repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/复习/光电子材料与器件复习/temple/main.typ | typst | #import "template.typ": *
// #import "@preview/big-todo:0.2.0": *
#let data=yaml("./data.yaml")
#import "@preview/tablex:0.0.8": tablex, rowspanx,
// 设置页面
// #set page(
// paper:"a4",
// margin: (
// top:23.5mm,
// bottom:25.4mm,
// left:20mm,
// right:20mm
// ),
// header:[
// #set text(10pt)
// #h(0mm)
// #image("./robomaster.png",width:100pt)
// #v(-0.8em)
// #line(length:100%,stroke:1pt)
// ],
// numbering:"1/1",
// number-align:center,
// )
// 标题编号
// 页眉
// 页脚
// import
// #show link: underline
#show: doc => conf(
linespacing: 1em,
outlinedepth: 3,
blind: false,
listofimage: true,
listoftable: true,
listofcode: true,
alwaysstartodd: true,
doc
)
// #align(center,[= 前言])
// #pagebreak()
// #todo_outline
// #pagebreak()
#import "@preview/colorful-boxes:1.3.1": *
= 知识速记
#v(-3em)
== 简述
#v(-3em)
=== 自然界中纳米材料
古代蜡烛燃烧后的炭黑,铜镜上的氧化锡 $"SnO"$薄膜,以及海龟的导航能力#footnote([与它自身组织内的纳米磁性物质有关,除海龟外,还有鸽子,海豚,蝴蝶,蜜蜂等动物。])。
=== 发展
1959年*理查德.费曼*最早提出*纳米尺度科学与技术*#footnote([于1959年他的一次著名的演讲中])。
1962年日本科学家*Kubo*提出*Kubo*理论,
1971年日本科学家唐古尼其最早提出用*纳米技术*一词来描述精细加工。
1981年,德国物理学家H.Gleiter提出了*固体纳米结构*的概念。
第一次国际纳米科技会议于1990年7月在美国巴尔的摩举行。
80年代初,人们发明了扫描隧道显微镜STM和原子力显微镜AFM。
=== 纳米材料新的物理化学特性
+ 小尺寸效应
+ 量子(尺寸)效应
+ 宏观量子隧道效应
+ 介电限域效应
#v(-1em)
==== 小尺寸效应
颗粒的尺寸比光波波长,德布罗意波长或者超导态的相干长度等相当或者更小的时候,晶体周期性特性被破坏,非晶态粒子*颗粒表面层*附近原子密度减小,导致声光电热磁力等特性发生变化。
*光学性质*: 所有超微颗粒都是黑色的,对光的反射率都很小,可以用于高效率光电光热转换材料,以及红外敏感元件和红外隐身技术。
*热学性质*:熔点降低,有些金属能够燃烧,Mg
// **
*磁学性质*:矫顽力先升高后降低
*力学性质*:人的牙齿是由*磷酸钙*等纳米材料组成的
- 量子效应
- 介电限域效应
- 宏观量子隧道效应
// 小尺寸,量子,介电限域,宏观量子隧道
// 小尺寸,量子,介电限域,宏观量子隧道
==== 量子效应
$ δ=(4E_f)/(3N) $
#h(2em)$δ$是能级之间的平均间距,对于宏观物质,$N-> infinity,δ-> 0$,能级是连续的,对于纳米例子,能级不再连续,*发生分裂*。
==== 宏观量子隧道效应
当微观例子总能量小于势垒高度的时候,粒子仍能通过这一势垒。近年来,人们发现一些宏观量,如微颗粒的磁化强度和量子相干器件的磁通量也有隧道效应。
研制的_*量子共振隧穿晶体管*_就是利用量子效应制成的新一代器件。
#v(-1em)
==== 介电限域效应
过渡族金属氧化物和半导体微粒都可能产生介电限域效应。
蓝移,量子尺寸效应。红移,小尺寸效应。
=== 纳米材料的应用
暂略。
= 非线性光学
== 非线性光学效应简述
// 非线性光学是研究*强光*与物质相互作用的规律,
是研究*激光*与物质相互作用的学科。激光的特性是:*高相干性,高单色性,高方向性和高亮度*。
非线性光学效应从和物质相互作用的角度可分为*主动非线性光学效应和非线性光学效应*。
*被动的非线性效应*(倍混参相)光和介质无能量交换,比如倍频,三波四波混频,参量过程,相位共轭。
*主动的非线性效应*(主吸这伞) 光和介质有能量交换,介质的物理量和光场强度有关如
- 非线性折射
- 自聚焦
- 自聚散
- 非线性散射
- 受激拉曼散射
- 受激布里渊散射
- 非线性吸收
- 饱和非线性吸收
- 共振
- 非共振
- 反饱和非线性吸收
- 激发态
- 多光子
- 单光子
- 光学吸收,光限幅
== 极化
根据极化强度和外界光强的分类,将极化分为下面两类,设外部光照强度为$E$,内部平均电场强度为$E'$,当
$ E/E'<<1 $
的时候,认为是弱光,线性极化。光的独立性和叠加原理都成立。
$ P=epsilon_0 chi *E $
当两者相当时,有非线性极化
$ P=sum_(i=1)^(n)epsilon_(i)chi^((i))*E^i $
对于同性介质,可以改为标量形式。
$chi^((3))$实部正比于$n$,虚部正比于吸收系数$alpha$。
// === 线性极化
== 典型的非线性光学效应
二次谐波SHG是*三波混频*的一种特例,是非线性介质在激光照射下的二阶非线性光学效应。
三次谐波THG是*四波混频*的一种特例,是非线性戒指在激光作用下的三阶非线性光学效应。
// #figure(
// align(center,
// image("img/1.png",width: 80%)
// )
// , caption: [产生二次谐波的装置]
// )
*匹配角* 入射光和非线性晶体光轴之间的夹角$theta$,应该满足如下的相位匹配条件(能量守恒和动量守恒)。
$ omega_1+omega_2=omega_3 , k_1+k_2=k_3 $
其中
$ k_i=(2 pi lambda_i)/n_i $
$ omega lambda=2 pi $
将(2.2)(2.3)代入得到
$n_omega=n_(2omega),k_(2omega)=2k_(omega)$
*相位匹配:*利用晶体的双折射特性来补偿晶体的色散效应,实现晶体的相位匹配主要有角度相位匹配和温度相位匹配两种方法。各有优缺点,总结如下
*角度匹配*:简单可行,但是会出现离散效应
*相位匹配*:没有离散效应,但是受温度影响。
*离散效应*:$theta!=0 | 90$ o光和e光(基频光和倍频光)会在空间上离散开来,从而使得转换效率下降。
== 光参量振荡器
= 非线性光学材料
== 分类
凡是能产生半导体效应,具有较高的二三阶非线性折射率。大多是不具有中心对称性的晶体,一类是盐类晶体,一类是半导体晶体。
按照非线性光学效应,分为二阶非线性光学材料和三阶非线性光学材料。
=== 二阶非线性光学材料
*二阶非线性光学材料*
大多是不具有中心对称性的晶体,常用于光学倍频混频和光参量震荡的晶体材料有两大类,盐类(KDP,ADP,工作在可见光和近红外),半导体类(淡红银矿,更适合工作在中红外波段)
*理想的二阶非线性光学材料应该具有(7)*
- 非中心对称结构
- 大的二阶非线性光学系数
- 容易实现*相位匹配*
- 材料的光学均匀性好,折射率均匀
- 高透明度,高透明波段
- 光损伤阈值高
- 容易长成大尺寸透明晶体
// - 非中心对称结构
// - 好的光学均匀性,折射率一致
// - 具有较大的二阶非线性系数
// - 具有较高的光损伤阈值
// - 能长成大尺寸的晶体
// - 透明度高,透明波段款
// - 容易实现相位匹配
=== 三阶非线性光学材料
#h(2em)
==== *特征参数*
- 三阶非线性系数
- 响应时间
- 光损伤阈值
// - 三阶非线性系数
// - 响应时间
// - 光损伤阈值
==== 产生三界非线性极化率的极致
- 原子和分子的电子跃迁和电子云形状的畸变
- 分子的转向和重新排列
- 固体能带之间和能带之内的的电子跃迁
- (来源于固体中的)各种元激发
// - 原子和分子的电子跃迁和电子云的即便
// - 分子的转向和重新排列
// - 固体中能带之内和能带之间的电子越前
// - 固体中的各种元激发
==== 三阶非线性光学材料包括(TODO)
#v(-2em)
== 按组成
按照组成分为有机,无机和有机无机杂化材料。
*无机*
容易相位匹配,高损伤阈值。
非线性系数不高,介电晶体无法与半导体集成,多数氧化物非线性系数不高。
// 有机,无机,有机无机杂化。
*有机*
非线性系数更高,光损伤与之更高,响应时间快$10^3$,来源于非定域的$pi$电子体系。可加工,可分子设计。
缺点:熔点低,机械性能差,不能长成大晶体,热稳定性和抗潮性能差
== 按折射率
- 激光频率转换
- 可到红
- 红
- 紫
- 非线性光学系数打,受晶体光学质量和尺寸大小的限制
- 电光晶体
- 光折变晶体
- 电光和光电一体
= 石墨烯和纳米薄膜
== 纳米薄膜的制备方法
- 微机械剥离法
- 化学气相沉积法
- 有机合成法
- 氧化还原氧化石墨法
- 生长外延法
#h(2em)石墨烯热导率是碳纳米管的2.5倍,是金刚石的三倍。
*如何测反射率那道题?*
设反射系数分别为$R_1,R_2$,$I_1$为第一次透射出去的光强,可得到
$ I_(n+1)=I_1(R_1R_2)^n exp(-2n alpha L)=I_1exp[n(ln(R_1R_2)-2 alpha L)] $
#h(2em) 在$t$时刻,循环次数为$ n=t/t_1,t_1=(2L)/c,n=(c t)/(2L) $
#h(2em)将(4.2)代入(4.1)
$ I(t)= I_1 exp[(c t)/(2L)(ln(R_1R_2)-2 alpha L)] $
$ I(t)=I_1 exp(-t/tau_0) $
#h(2em)所以可得
$ tau_0=-(2L)/(c[ln(R_1R_2)-2alpha L])=-(L)/(c[ln(sqrt(R_1R_2))-alpha L]) $
#h(2em)假设$alpha=0$,
$ R=R_1=R_2 $
#h(2em)将待测镜片放到折叠腔的折点处,以一定角度将直腔改变为
折叠腔,根据式(4.3)可得,
$ I(t)= I_1 exp[(c t)/(2L)(ln(R_1R_2R_x^2)-2 alpha L)] $
所以可得
$ tau=-(L)/(c[ln(sqrt(R_1R_2R_x^2))-alpha L])=-(L)/(c[ln(sqrt(R_1R_2))+ln(R_x)-alpha L]) $
#h(2em)所以
$ c/(tau L)-c/(tau_0 L)= -ln(R_x) => R_x=-exp[c/L (1/tau-1/(tau_0))] $
*开关那道题*
= 电磁波
影响人类的电磁波分为自然污染和人为污染,对人体的热效应和非热效应,具体可以采取电磁屏蔽,电磁吸收、个人防护、加强城市规划等措施。
=== *提高电磁波表面吸收性能*
+ 减小表面反射,阻抗匹配
+ 增加内部电磁波损耗-增加材料内部衰减电磁波的能力
拉曼-奈斯和布拉格衍射。
*4-f系统法*
+ 删除背景光
+ 能量校准
+ 提取线性、非线性、无样品光斑
+ 进行图像处理,数据处理,模拟实验结果,提取非线性参数
== 性能评价指标
#v(-3em)
=== 法拉第效率
越高,利用率越高,副产物越少。
=== 塔菲厄斜率
越小,催化越快
=== 转化效率
每个活性位点能转化为产物的比例
按照催化反应体系物相的均一性分类,包括( 均相 )、( 非均相 )和( 酶催化 )
*四种方法*
Z-扫描,荧光光谱,光电流,4f |
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/dialogues/cover-layouts/time-travel-edition.typ | typst | #import "@local/typkit:0.1.0": *
#let KacperStudent = (
grade: 6,
name: "<NAME>",
)
#let do-time-travel-sidebar-message(year) = {
let time-travel-text = pattern-text(
"TIME TRAVEL EDITION",
)
let year-text = bold("(" + str(year) + ")", size: 32pt, fill: blue)
let c = {
time-travel-text
h(20pt)
year-text
}
let c = box(centered(c), width: 100%, fill: patterns.dots, outset: 15pt)
return rotate(c, 270deg, reflow: true)
}
#let do-grade-level(grade) = {
let g6 = text(
"G" + str(grade),
size: 50pt,
weight: "bold",
font: "PT Sans",
)
return rect(centered(g6, true), fill: patterns.stripes, inset: 10pt)
}
#let do-title(season, year, subject, grade) = {
let a = {
bold(season, size: 26pt)
h(10pt)
pattern-text(year, style: "criss-cross", size: 26pt)
}
let b = bold(subject + " Workbook", size: 32pt)
centered({
b
v(-15pt)
a
})
// it doesnt look that good
// it looks squished together
// grid(
// rows: 2,
// columns: 2,
// row-gutter: 10pt,
// column-gutter: 20pt,
// grid.cell(
// rowspan: 2,
// align: center,
// fill: black,
// text(g6, fill: white)
// ),
// b,
// a,
// )
}
#let do-student(student) = {
return colon("For student", student.name, size: 18pt, font: "courier")
}
#let cover(
season: "Autumn",
year: 1991,
subject: "Math",
student: KacperStudent,
) = context {
let title = do-title(season, year, subject, student.grade)
let student-line = do-student(student)
let hmc-mark = [— Hammy Math Class ©#get-year() —]
let main-content = block(height: 100%, {
title
v(10pt)
// centered(student-line)
let pic = rect(width: 200pt, height: 200pt, fill: blue.transparentize(75%))
centered(pic)
// placed(pic, center + horizon)
// placed(grade-level, right + bottom)
})
// let time-travel = do-time-travel-sidebar-message(year)
let time-travel = do-time-travel-sidebar-message(year)
let width = measure(time-travel).width
let dots = rect(width: 100%, height: 100%, fill: yellow,
inset: 20pt, {
// text("HI")
// text("HI")
// text("HI")
// text("HI")
placed(time-travel, left)
})
let background = {
dots
}
let page-content = main-content
// let page-content = stacked(h(width), main-content)
page(
paper: "us-letter",
footer: {
placed(hmc-mark, bottom + center, inset: 20pt)
},
background: background,
page-content,
)
}
#cover()
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/touying-aqua/0.4.0/README.md | markdown | Apache License 2.0 | # [Touying](https://github.com/touying-typ/touying) 
[Touying](https://github.com/touying-typ/touying) (投影 in chinese, /tóuyǐng/, meaning projection) is a powerful and efficient package for creating presentation slides in Typst. Partial code is inherited from [Polylux](https://github.com/andreasKroepelin/polylux). Therefore, many concepts and APIs remain consistent with Polylux.
Touying provides an object-oriented programming (OOP) style syntax, allowing the simulation of "global variables" through a global singleton. This makes it easy to write themes. Touying does not rely on `counter` and `locate` to implement `#pause`, resulting in better performance.
If you like it, consider [giving a star on GitHub](https://github.com/touying-typ/touying). Touying is a community-driven project, feel free to suggest any ideas and contribute.
[](https://touying-typ.github.io/touying/)




## Document
Read [the document](https://touying-typ.github.io/touying/) to learn all about Touying.
This documentation is powered by [Docusaurus](https://docusaurus.io/). We will maintain **English** and **Chinese** versions of the documentation for Touying, and for each major version, we will maintain a documentation copy. This allows you to easily refer to old versions of the Touying documentation and migrate to new versions.
## Special Features
1. `#pause` and `#meanwhile` Marks [document](https://touying-typ.github.io/touying/docs/dynamic/simple)
```typst
#slide[
First
#pause
Second
#meanwhile
Third
#pause
Fourth
]
```

2. Dewdrop Theme Navigation Bar [document](https://touying-typ.github.io/touying/docs/themes/dewdrop)

3. `touying-equation` Math Equation Animation [document](https://touying-typ.github.io/touying/docs/dynamic/equation)

4. `touying-reducer` Cetz and Fletcher Animations [document](https://touying-typ.github.io/touying/docs/dynamic/other)

5. `#show: slides` Style and `#slide[..]` Style
6. Semi-transparent Cover Mode [document](https://touying-typ.github.io/touying/docs/dynamic/cover)

## Quick start
Before you begin, make sure you have installed the Typst environment. If not, you can use the [Web App](https://typst.app/) or the Tinymist Typst and Typst Preview extensions for VS Code.
To use Touying, you only need to include the following code in your document:
```typst
#import "@preview/touying:0.4.0": *
#let s = themes.simple.register(aspect-ratio: "16-9")
#let (init, slides) = utils.methods(s)
#show: init
#let (slide, empty-slide) = utils.slides(s)
#show: slides
= Title
== First Slide
Hello, Touying!
#pause
Hello, Typst!
```

It's simple. Congratulations on creating your first Touying slide! 🎉
**Tip:** You can use Typst syntax like `#import "config.typ": *` or `#include "content.typ"` to implement Touying's multi-file architecture.
## More Complex Examples
In fact, Touying provides various styles for writing slides. For example, the above example uses first-level and second-level titles to create new slides. However, you can also use the `#slide[..]` format to access more powerful features provided by Touying.
```typst
#import "@preview/touying:0.4.0": *
#import "@preview/cetz:0.2.2"
#import "@preview/fletcher:0.4.3" as fletcher: node, edge
#import "@preview/ctheorems:1.1.2": *
// cetz and fletcher bindings for touying
#let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide.with(bounds: true))
#let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide)
// Register university theme
// You can remove the theme registration or replace other themes
// it can still work normally
#let s = themes.university.register(aspect-ratio: "16-9")
// Set the numbering of section and subsection
#let s = (s.methods.numbering)(self: s, section: "1.", "1.1")
// Global information configuration
#let s = (s.methods.info)(
self: s,
title: [Title],
subtitle: [Subtitle],
author: [Authors],
date: datetime.today(),
institution: [Institution],
)
// Pdfpc configuration
// typst query --root . ./example.typ --field value --one "<pdfpc-file>" > ./example.pdfpc
#let s = (s.methods.append-preamble)(self: s, pdfpc.config(
duration-minutes: 30,
start-time: datetime(hour: 14, minute: 10, second: 0),
end-time: datetime(hour: 14, minute: 40, second: 0),
last-minutes: 5,
note-font-size: 12,
disable-markdown: false,
default-transition: (
type: "push",
duration-seconds: 2,
angle: ltr,
alignment: "vertical",
direction: "inward",
),
))
// Theroems configuration by ctheorems
#show: thmrules.with(qed-symbol: $square$)
#let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee"))
#let corollary = thmplain(
"corollary",
"Corollary",
base: "theorem",
titlefmt: strong
)
#let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em))
#let example = thmplain("example", "Example").with(numbering: none)
#let proof = thmproof("proof", "Proof")
// Extract methods
#let (init, slides, touying-outline, alert) = utils.methods(s)
#show: init
#show strong: alert
// Extract slide functions
#let (slide, empty-slide) = utils.slides(s)
#show: slides
= Animation
== Simple Animation
#slide[
We can use `#pause` to #pause display something later.
#pause
Just like this.
#meanwhile
Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously.
]
== Complex Animation
#slide(repeat: 3, self => [
#let (uncover, only, alternatives) = utils.methods(self)
At subslide #self.subslide, we can
use #uncover("2-")[`#uncover` function] for reserving space,
use #only("2-")[`#only` function] for not reserving space,
#alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives.
])
== Math Equation Animation
#slide[
Touying equation with `pause`:
#touying-equation(`
f(x) &= pause x^2 + 2x + 1 \
&= pause (x + 1)^2 \
`)
#meanwhile
Here, #pause we have the expression of $f(x)$.
#pause
By factorizing, we can obtain this result.
]
== CeTZ Animation
#slide[
CeTZ Animation in Touying:
#cetz-canvas({
import cetz.draw: *
rect((0,0), (5,5))
(pause,)
rect((0,0), (1,1))
rect((1,1), (2,2))
rect((2,2), (3,3))
(pause,)
line((0,0), (2.5, 2.5), name: "line")
})
]
== Fletcher Animation
#slide[
Fletcher Animation in Touying:
#fletcher-diagram(
node-stroke: .1em,
node-fill: gradient.radial(blue.lighten(80%), blue, center: (30%, 20%), radius: 80%),
spacing: 4em,
edge((-1,0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center),
node((0,0), `reading`, radius: 2em),
edge((0,0), (0,0), `read()`, "--|>", bend: 130deg),
pause,
edge(`read()`, "-|>"),
node((1,0), `eof`, radius: 2em),
pause,
edge(`close()`, "-|>"),
node((2,0), `closed`, radius: 2em, extrude: (-2.5, 0)),
edge((0,0), (2,0), `close()`, "-|>", bend: -40deg),
)
]
= Theroems
== Prime numbers
#definition[
A natural number is called a #highlight[_prime number_] if it is greater
than 1 and cannot be written as the product of two smaller natural numbers.
]
#example[
The numbers $2$, $3$, and $17$ are prime.
@cor_largest_prime shows that this list is not exhaustive!
]
#theorem("Euclid")[
There are infinitely many primes.
]
#proof[
Suppose to the contrary that $p_1, p_2, dots, p_n$ is a finite enumeration
of all primes. Set $P = p_1 p_2 dots p_n$. Since $P + 1$ is not in our list,
it cannot be prime. Thus, some prime factor $p_j$ divides $P + 1$. Since
$p_j$ also divides $P$, it must divide the difference $(P + 1) - P = 1$, a
contradiction.
]
#corollary[
There is no largest prime number.
] <cor_largest_prime>
#corollary[
There are infinitely many composite numbers.
]
#theorem[
There are arbitrarily long stretches of composite numbers.
]
#proof[
For any $n > 2$, consider $
n! + 2, quad n! + 3, quad ..., quad n! + n #qedhere
$
]
= Others
== Side-by-side
#slide[
First column.
][
Second column.
]
== Multiple Pages
#slide[
#lorem(200)
]
// appendix by freezing last-slide-number
#let s = (s.methods.appendix)(self: s)
#let (slide,) = utils.slides(s)
== Appendix
#slide[
Please pay attention to the current slide number.
]
```

## Acknowledgements
Thanks to...
- [@andreasKroepelin](https://github.com/andreasKroepelin) for the `polylux` package
- [@Enivex](https://github.com/Enivex) for the `metropolis` theme
- [@drupol](https://github.com/drupol) for the `university` theme
- [@pride7](https://github.com/pride7) for the `aqua` theme
- [@ntjess](https://github.com/ntjess) for contributing to `fit-to-height`, `fit-to-width` and `cover-with-rect`
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/互联网原理与技术/作业/实践4/main.typ | typst | The Unlicense | #import "../template.typ": *
#show: project.with(
title: "实践 4:Wireshark实验——IP",
authors: (
"absolutex",
)
)
= 内容
== 分析traceroute时的IP包格式。
运行 traceroute 并让它发送各种长度的数据报。Linux/Unix/MacOS : traceroute 用UDP 数据报
Traceroute指定包长度:一个长度 为 56 个字节,一个长度为 2000 个字节,另一个长度为 3500 个字节。
```
traceroute www.bilibili.com 56
traceroute to www.bilibili.com (192.168.3.11), 30 hops max, 56 byte packets
1 _gateway (192.168.1.1) 0.131 ms 0.125 ms 0.106 ms
2 254.111.165.61.dial.xw.sh.dynamic.163data.com.cn (172.16.58.3) 0.499 ms 0.480 ms 0.565 ms
3 192.168.243.1 (192.168.243.1) 3.604 ms 4.057 ms 4.521 ms
4 172.16.17.32 (172.16.17.32) 1.509 ms 192.168.3.11 (192.168.3.11) 1.656 ms 172.16.31.10 (172.16.31.10) 1.799 ms
5 192.168.3.11 (192.168.3.11) 3.082 ms 124.74.210.37 (124.74.210.37) 2.290 ms192.168.3.11 (124.74.210.69) 3.078 ms
6 192.168.127.12 (192.168.127.12) 2.886 ms 172.16.17.32 (172.16.17.32) 2.338 ms 192.168.3.11 (192.168.3.11) 3.551 ms
7 192.168.3.11 (192.168.3.11) 12.988 ms 172.16.58.3 (172.16.58.3) 8.141 ms *
8 * * *
9 * * *
10 * * *
11 * * *
12 * * 192.168.3.11 (192.168.127.1239) 9.660 ms
```
其他大小的输出类似。
#figure(
image("20231123-09.32.png", width: 100%),
)
=== 在 IP header 中,上层协议字段的值是多少?
Protocol: UDP (*17*)
=== IP header 有多少 bytes? IP datagram 的有效负载中有多少 bytes?
0101 = Header Length: *20 bytes* (5)
=== 此 IP 数据报是否已被分段(fragmented)?
010. .... = Flags: 0x2, Don't fragment
> .1.. .... = *Don't fragment: Set*
未被分段。
=== ID 字段和 TTL 字段的值是多少?
ID: 10755 TTL: 64
=== 将 pingplotter 数据包大小更改为 2000 后,查找计算机发送的第一个 ICMP Echo Request 消息。该消息是否已碎片化为多个 IP 数据报?
#figure(
image("20231123-12.15.png", width: 100%),
)
并没有被分段。
== 分析web(https和http)访问时的IP包格式
运行 web访问,分别查看http/https请求和响应。
#figure(
image("20231123-12.20.png", width: 80%),
caption: "http"
)
#figure(
image("20231123-12.27.png", width: 80%),
caption: "https"
)
=== 在 IP header 中,上层协议字段的值是多少?
6
=== IP header 有多少 bytes?
20
=== 查看响应数据包已碎片化为多个 IP 数据报?
没有
== 分析通过dhcp分配IP地址的过程,给出传输数据包的结构,包括源目的端口、IP、MAC地址、包的内容
`sudo dhclient -r`
#figure(
image("20231123-12.44.png", width: 100%),
)
客户端:192.168.1.106:68, mac: Clevo_15:76:cd (d4:93:90:15:76:cd)
服务端:192.168.1.1:67, mac: TpLinkTechno_01:5d:a0 (fc:d7:33:01:5d:a0)
内容:
#figure(
image("20231123-12.50.png", width: 100%),
) |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/metro/0.1.0/src/metro.typ | typst | Apache License 2.0 | #import "defs/units.typ"
#import "defs/prefixes.typ"
#import "impl/impl.typ"
// #import "parse_number.typ"
#import "utils.typ": combine-dict
#let _state-default = (
units: units._dict,
prefixes: prefixes._dict,
prefix-power-tens: prefixes._power-tens,
powers: (
square: impl.raiseto([2]),
cubic: impl.raiseto([3]),
squared: impl.tothe([2]),
cubed: impl.tothe([3])
),
qualifiers: (:),
// quantites
times: sym.dot,
// Unit
// Num
allow-breaks: false,
delimiter: " ",
)
#let _state = state("metro-setup", _state-default)
#let metro-reset() = _state.update(_ => return _state-default)
#let metro-setup(..options) = _state.update(s => {
return combine-dict(options.named(), s)
})
#let declare-unit(unt, symbol) = _state.update(s => {
s.units.insert(unt, symbol)
return s
})
#let create-prefix = math.class.with("unary")
#let declare-prefix(prefix, symbol, power-tens) = _state.update(s => {
s.prefixes.insert(prefix, symbol)
s.prefix-power-tens.insert(prefix, power-tens)
return s
})
#let declare-power(before, after, power) = _state.update(s => {
s.powers.insert(before, impl.raiseto([#power]))
s.powers.insert(after, impl.tothe([#power]))
return s
})
#let declare-qualifier(quali, symbol) = _state.update(s => {
s.qualifiers.insert(quali, impl.qualifier(symbol))
return s
})
#let unit(input, ..options) = _state.display(s => {
return impl.unit(input, ..combine-dict(options.named(), s))
})
#let num(number, e: none, pm: none, ..options) = _state.display(s => {
return impl.num(number, e: e, pm: pm, ..combine-dict(options.named(), s))
})
#let qty(
number,
units,
e: none,
pm: none,
..options
) = _state.display(s => {
return impl.qty(number, units, e: e, pm: pm, ..combine-dict(options.named(), s))
// assert(options.pos().len() == 0, message: "Unexpected positional arguments for qty()")
// let options = _combine-dict(options.named(), s)
// let result = {
// let number = num(number, e: e, pm: pm, ..options)
// if pm != none and e == none { number = $(number)$ }
// number
// sym.space.thin
// unit(units, ..options)
// }
// if not options.allow-breaks {
// result = $#result$
// }
// result
}) |
https://github.com/alberto-lazari/computer-science | https://raw.githubusercontent.com/alberto-lazari/computer-science/main/advanced-topics-cs/module-3/report.typ | typst | #set page(numbering: "1")
#set heading(numbering: "1.1.A.")
#set list(marker: ([•], [--]))
#let make_title(title: none, author: none, course: none, date: none) = {
align(center, text(size: 25pt, title))
align(center, text(size: 18pt, author))
align(center, text(size: 18pt, course))
align(center, text(size: 18pt, date))
}
#let unipd-red = rgb(160, 0, 0)
#show heading: set text(unipd-red)
#v(10em)
#figure(image("images/unipd-logo.png", width: 50%))
#v(3em)
#make_title(
title: "Advanced Topics in Computer Science\nTrustworthy AI report",
author: "<NAME> - 2089120",
course: "Computer Science – Other training activities",
date: "June 2023",
)
#pagebreak()
= Introduction
The aim of this report is to give a simple summary of the 2020 paper "Interpretable and Differentially Private Predictions", from <NAME>, <NAME> and <NAME>, and later make some considerations on the broader trustworthy AI context of the ideas proposed in the paper.
Finally, some personal critical thoughts on the topic are left.
= Paper
#include "paper.typ"
= About broader trustworthy AI context
#include "trustworthy-ai.typ"
= Personal evaluation
#include "personal.typ"
|
|
https://github.com/berceanu/activity-report | https://raw.githubusercontent.com/berceanu/activity-report/main/short_usage.typ | typst | BSD 3-Clause "New" or "Revised" License | #import "ultra-short-activity-report.typ": report, activities
#show: body => report(
month: "July, August, September 2023",
your_name: "<NAME>",
your_position: "CS-III",
sign_date: "17/10/2023",
department_head: "<NAME>",
group_leader: "<NAME>",
body,
)
#activities
- #lorem(40)
- #lorem(5) `openPMD-resampler` #lorem(10) $E = m c^2$ #lorem(20)
- #lorem(20) $attach(tl: 115m, bl:49, "In")$ #lorem(16)
- #lorem(27) $ B_(6 D) = I_P /
(epsilon_(n x) epsilon_(n y) sigma_gamma dot 0.1 %) $
|
https://github.com/fredguth/mwe-citation-quarto-typst | https://raw.githubusercontent.com/fredguth/mwe-citation-quarto-typst/main/article.typ | typst | // Some definitions presupposed by pandoc's typst output.
#let blockquote(body) = [
#set text( size: 0.8em )
#align(right, block(inset: (right: 5em, top: 0.2em, bottom: 0.2em))[#body])
]
#let horizontalrule = [
#line(start: (25%,0%), end: (75%,0%))
]
#let endnote(num, contents) = [
#stack(dir: ltr, spacing: 3pt, super[#num], contents)
]
#show terms: it => {
it.children
.map(child => [
#strong[#child.term]
#block(inset: (left: 1.5em, top: -0.4em))[#child.description]
])
.join()
}
// Some quarto-specific definitions.
#show raw.where(block: true): block.with(
fill: luma(230),
width: 100%,
inset: 8pt,
radius: 2pt
)
#let block_with_new_content(old_block, new_content) = {
let d = (:)
let fields = old_block.fields()
fields.remove("body")
if fields.at("below", default: none) != none {
// TODO: this is a hack because below is a "synthesized element"
// according to the experts in the typst discord...
fields.below = fields.below.amount
}
return block.with(..fields)(new_content)
}
#let empty(v) = {
if type(v) == "string" {
// two dollar signs here because we're technically inside
// a Pandoc template :grimace:
v.matches(regex("^\\s*$")).at(0, default: none) != none
} else if type(v) == "content" {
if v.at("text", default: none) != none {
return empty(v.text)
}
for child in v.at("children", default: ()) {
if not empty(child) {
return false
}
}
return true
}
}
// Subfloats
// This is a technique that we adapted from https://github.com/tingerrr/subpar/
#let quartosubfloatcounter = counter("quartosubfloatcounter")
#let quarto_super(
kind: str,
caption: none,
label: none,
supplement: str,
position: none,
subrefnumbering: "1a",
subcapnumbering: "(a)",
body,
) = {
context {
let figcounter = counter(figure.where(kind: kind))
let n-super = figcounter.get().first() + 1
set figure.caption(position: position)
[#figure(
kind: kind,
supplement: supplement,
caption: caption,
{
show figure.where(kind: kind): set figure(numbering: _ => numbering(subrefnumbering, n-super, quartosubfloatcounter.get().first() + 1))
show figure.where(kind: kind): set figure.caption(position: position)
show figure: it => {
let num = numbering(subcapnumbering, n-super, quartosubfloatcounter.get().first() + 1)
show figure.caption: it => {
num.slice(2) // I don't understand why the numbering contains output that it really shouldn't, but this fixes it shrug?
[ ]
it.body
}
quartosubfloatcounter.step()
it
counter(figure.where(kind: it.kind)).update(n => n - 1)
}
quartosubfloatcounter.update(0)
body
}
)#label]
}
}
// callout rendering
// this is a figure show rule because callouts are crossreferenceable
#show figure: it => {
if type(it.kind) != "string" {
return it
}
let kind_match = it.kind.matches(regex("^quarto-callout-(.*)")).at(0, default: none)
if kind_match == none {
return it
}
let kind = kind_match.captures.at(0, default: "other")
kind = upper(kind.first()) + kind.slice(1)
// now we pull apart the callout and reassemble it with the crossref name and counter
// when we cleanup pandoc's emitted code to avoid spaces this will have to change
let old_callout = it.body.children.at(1).body.children.at(1)
let old_title_block = old_callout.body.children.at(0)
let old_title = old_title_block.body.body.children.at(2)
// TODO use custom separator if available
let new_title = if empty(old_title) {
[#kind #it.counter.display()]
} else {
[#kind #it.counter.display(): #old_title]
}
let new_title_block = block_with_new_content(
old_title_block,
block_with_new_content(
old_title_block.body,
old_title_block.body.body.children.at(0) +
old_title_block.body.body.children.at(1) +
new_title))
block_with_new_content(old_callout,
new_title_block +
old_callout.body.children.at(1))
}
// 2023-10-09: #fa-icon("fa-info") is not working, so we'll eval "#fa-info()" instead
#let callout(body: [], title: "Callout", background_color: rgb("#dddddd"), icon: none, icon_color: black) = {
block(
breakable: false,
fill: background_color,
stroke: (paint: icon_color, thickness: 0.5pt, cap: "round"),
width: 100%,
radius: 2pt,
block(
inset: 1pt,
width: 100%,
below: 0pt,
block(
fill: background_color,
width: 100%,
inset: 8pt)[#text(icon_color, weight: 900)[#icon] #title]) +
if(body != []){
block(
inset: 1pt,
width: 100%,
block(fill: white, width: 100%, inset: 8pt, body))
}
)
}
#import "@preview/drafting:0.2.0": *
#let margincite(key, mode, prefix, suffix, noteNum, hash) = context {
if query(bibliography).len()>0 {
let supplement = suffix.split(",").filter(value => not value.contains("dy.")).join(",")
let dy = if suffix.contains("dy.") {
eval(suffix.split("dy.").at(1, default: "").split(",").at(0, default: "").trim())
} else {none}
cite(key, form: "normal", supplement: supplement)
if dy!=none {
set text(size: 8pt)
[#margin-note(dy:dy, dx:100%+.1em)[#block(width: 7cm, inset:1em)[#cite(key, form:"full", supplement: supplement)]]]
}
}
}
#let article(
title: none,
authors: none,
date: none,
abstract: none,
abstract-title: none,
cols: 1,
paper: "a4",
margin: (left: 1cm, right: 7cm, top: 2cm, bottom: 2cm),
lang: "en",
region: "US",
font: (),
fontsize: 11pt,
sectionnumbering: none,
toc: false,
toc_title: none,
toc_depth: none,
toc_indent: 1.5em,
bib: none,
doc,
) = {
set page(
paper: paper,
margin: margin,
numbering: "1",
)
set par(justify: true)
set text(lang: lang,
region: region,
font: font,
size: fontsize)
set heading(numbering: sectionnumbering)
if title != none {
align(center)[#block(inset: 2em)[
#text(weight: "bold", size: 1.5em)[#title]
]]
}
if authors != none {
let count = authors.len()
let ncols = calc.min(count, 3)
grid(
columns: (1fr,) * ncols,
row-gutter: 1.5em,
..authors.map(author =>
align(center)[
#author.name \
#author.affiliation \
#author.email
]
)
)
}
if date != none {
align(center)[#block(inset: 1em)[
#date
]]
}
if abstract != none {
block(inset: 2em)[
#text(weight: "semibold")[#abstract-title] #h(1em) #abstract
]
}
if toc {
let title = if toc_title == none {
auto
} else {
toc_title
}
block(above: 0em, below: 2em)[
#outline(
title: toc_title,
depth: toc_depth,
indent: toc_indent
);
]
}
show cite.where(form:"prose"): none
// set-page-properties() // I don't want it to calculate, I want to give my calculations
set-margin-note-defaults(
stroke: none,
side: right,
margin-right: 1cm, // 1cm is absurd.. just to show that it is being ignored!!!
margin-left: 1cm,
page-width: 21cm-8.25cm
)
// set-page-properties()
place(dx: 100%, dy: 3cm, block(width: 7cm, height: 7cm, fill: rgb("#dbdbc5"))[
#let n = 1
#set text(fill: gray)
#while n < 17 {
[Please do not put your citations here.]
n = n+1
}
]
)
if cols == 1 {
doc
} else {
columns(cols, doc)
}
if bib != none {
heading(level:1,[References])
bib
}
}
#set table(
inset: 6pt,
stroke: none
)
// Typst custom formats typically consist of a 'typst-template.typ' (which is
// the source code for a typst template) and a 'typst-show.typ' which calls the
// template's function (forwarding Pandoc metadata values as required)
//
// This is an example 'typst-show.typ' file (based on the default template
// that ships with Quarto). It calls the typst function named 'article' which
// is defined in the 'typst-template.typ' file.
//
// If you are creating or packaging a custom typst template you will likely
// want to replace this file and 'typst-template.typ' entirely. You can find
// documentation on creating typst templates here and some examples here:
// - https://typst.app/docs/tutorial/making-a-template/
// - https://github.com/typst/templates
#show: doc => article(
title: [Untitled],
toc_title: [Table of contents],
toc_depth: 3,
cols: 1,
doc,
)
= Task
<task>
I want to create citations like #margincite(<Tufte2001>, "AuthorInText", "", "p.30, dy.-3.5cm", none, none) and show it in the margin….
… done!!!
Another citation #margincite(<Labov1972>, "AuthorInText", "", "dy.-3.5cm", none, none) and #margincite(<Tufte>, "AuthorInText", "", "dy.7cm", none, none)
= Problems
<problems>
- #strike[linebreak: `#margincite` is breaking the line after the citation.]
- drafting/margin-note ignoring settings
- Supplements in bib entry: `p.30` should be part of the full citation text. Something like
```
[1] <NAME>, Visual Display of Quantitative Information, Second. Chesire, Con-
necticut: Graphics Press, 2001; p.30.
```
I guess for each CSL there is a correct way to include the supplement, but you get the idea.
#bibliography("references.bib")
|
|
https://github.com/N3M0-dev/Notes | https://raw.githubusercontent.com/N3M0-dev/Notes/main/ECON/Principles_of_Economics/ch1/note_ch1.typ | typst | #let authors=("Nemo",)
#let title="Ten Principles of Economics"
#let date="2023.9.11-"
#set document(author: authors, title: title)
#set page(numbering: "1", number-align: center)
#set heading(numbering: "1.1")
#let def_count=counter("Defininition")
#let th_count=counter("Theorem")
#let Upperfirst(in_str)={upper(in_str.at(0))+in_str.slice(1,in_str.len())}
// Title row.
#align(center)[
#block(text(weight: 700, 1.75em, title))
#v(1em, weak: true)
#date
]
// Author information.
#pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center, strong(author))),
),
)
// Main body.
#set par(justify: true)
#set text(12pt)
#outline(indent: true)
#pagebreak()
//
//
// = How People Make Decisions
//
// / Principle 1: People Face Trade-offs
//
// / Classic trade-offs::
// / Gun and Butter: The more a society spends on national defense(gun), the less it can spend on consumer goods(butter).
// / Efficiency and Equality: If the economic pie is distributed uniformly among society members, it reduces the reward for working hard, thus leading to the result of less efficiency.
// \
// / Principle 2: The Cost of Something Is What You Give Up to Get It
//
// Opportunity cost
//
// / Principle 3: Rational People think at the Margin.
//
// / Rational People: Rational people is who systematically and purposefully do the best they can to achieve their objectives.
//
// / Margin Change: Margin change is a small incremental adjustment to a plan of action.
//
// "#emph()[Rational people] often make decisions by comparing #emph()[marginal benefits] and #emph()[marginal costs]."
//
// / e.g.: Suppose an airline has a air route that costs \$100000 for 200 passengers per plane, so one may think the ticket price should never be below \$500. But suppose that there being a plane about to take off in 30 mins but with 10 empety seats. If we sell the ticket for \$300, the margin costs is quite low (probobly a bottle of soda), but the marginal benefit in \$300. The ticket price is below \$500, but now the margin benefit is greater than the marign cost, which means it's in general beneficial, though price below \$500.
//
// == test
//
// #let s=state("x",1)
//
//
#outline(indent: true)
#let prepro(con)={
if con.has("children"){
if con.children.len()==0 {return (con,)}
let search_colon(item)={
if item.has("text"){
if item.text==":" or item.text==":" {
return true
}
else{
return false
}}
else{
return false
}
}
let pos=con.children.position(item=>search_colon(item))
let name=[];let content=[]
if pos!=none {
name=[#con.children.slice(0,pos).join()];content=[#con.children.slice(pos+1).join()]}
return (name,content)
}
else{return (con,)}
}
#let def(body)={
if type(body)=="array"{
locate(loc=>{let levelin=counter(heading).at(loc).len()
let num=(query(selector(<def>).before(loc),loc).len()+1)
let i=0;
align(center)[#rect(width: 95%)[#align(start+horizon)[#pad(top: 5pt,bottom: 5pt)[
#for def in body{
[#heading(level: levelin+1, numbering: none)[#text(style: "italic")[Definition] #(num+i): #prepro(def).at(0)]<def>]
prepro(def).at(1)
i=i+1
}
]]]]
})
}
if type(body)=="content"{
locate(loc=>{let levelin=counter(heading).at(loc).len()
align(center)[#rect(width: 95%)[#align(start+horizon)[#pad(top: 5pt,bottom: 5pt)[
#heading(level: levelin+1, numbering: none)[#text(style: "italic")[Definition] #(query(selector(<def>).before(loc),loc).len()+1): #if prepro(body).at(0)==[] [#text(fill: gray,style: "italic")[Definition term here ...]]else[#prepro(body).at(0)]]<def>
#if prepro(body).len()>=2 [
#prepro(body).at(1)
]else[#text(fill: gray,style: "italic")[
Definition content here ...
]]
]]]]
})
}
}
#let theorem(body)={
if type(body)=="array"{
locate(loc=>{let levelin=counter(heading).at(loc).len()
let num=(query(selector(<th>).before(loc),loc).len()+1)
let i=0
align(center)[#rect(width: 95%)[#align(start+horizon)[#pad(top: 5pt,bottom: 5pt)[
#for def in body{
[#heading(level: levelin+1, numbering: none)[#text(style: "italic")[Theorem] #(num+i): #prepro(def).at(0)]<th>]
prepro(def).at(1)
i=i+1
}
]]]]
})
}
if type(body)=="content"{
locate(loc=>{let levelin=counter(heading).at(loc).len()
align(center)[#rect(width: 95%)[#align(start+horizon)[#pad(top: 5pt,bottom: 5pt)[
#heading(level: levelin+1, numbering: none)[#text(style: "italic")[Theorem] #(query(selector(<th>).before(loc),loc).len()+1): #if prepro(body).at(0)==[] [#text(fill: gray,style: "italic")[Theorem term here ...]]else[#prepro(body).at(0)]] <th>
#if prepro(body).len()>=2 [
#prepro(body).at(1)
]else[#text(fill: gray,style: "italic")[
Definition content here ...
]]
]]]]
})
}
}
#let note(name: [],body)={
align(center)[
#block(fill: luma(230),inset: 8pt,radius: 4pt, width: 95%)[
#align(start)[
*Note*: #name
#body
]]]
}
#let term_box(term,body)={
if type(body)=="array"{
locate(loc=>{let levelin=counter(heading).at(loc).len()
let num=(query(selector(label(term)).before(loc),loc).len()+1)
let i=0
align(center)[#rect(width: 95%)[#align(start+horizon)[#pad(top: 5pt,bottom: 5pt)[
#for def in body{
[#heading(level: levelin+1, numbering: none)[#text(style: "italic")[#term] #(num+i): #prepro(def).at(0)]#label(term)]
prepro(def).at(1)
i=i+1
}
]]]]
})
}
if type(body)=="content"{
locate(loc=>{let levelin=counter(heading).at(loc).len()
align(center)[#rect(width: 95%)[#align(start+horizon)[#pad(top: 5pt,bottom: 5pt)[
#heading(level: levelin+1, numbering: none)[#text(style: "italic")[#term] #(query(selector(label(term)).before(loc),loc).len()+1): #if prepro(body).at(0)==[] [#text(fill: gray,style: "italic")[term here ...]]else[#prepro(body).at(0)]]#label(term)
#if prepro(body).len()>=2 [
#prepro(body).at(1)
]else[#text(fill: gray,style: "italic")[
term content here ...
]]
]]]]
})
}
}
#pagebreak()
= show usage
#def()[]
#theorem()[]
#term_box("term name here")[]
== These Are Heading Level Sensitive
#def()[test def: test def content]
#theorem()[test theorem: test theorem content]
#term_box("your term name")[test term: test term content]
#def(([array form 1: content],[array form 2:content]))
#theorem(([array form 1: content],[array form 2: content]))
== Counter Numbering Issue Fixed
|
|
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/design/design_iteration_1_results.typ | typst | #import "../../../style.typ": include_section
= Conclusions <iteration-1-conclusion>
Based on the questionnaire answers for the first three designs, which can be
seen in @design_iteration_one_survey_results, it can be concluded that each
design received valid criticism.
== Flo-inspired Design
It is clear that the Flo-inspired design received the most negative feedback.
While this concept keeps blocks small due to blocks being connected through arrows, it quickly looks overloaded.
This is partly because the type annotations on the questionnaire images are visible for every block (these are only supposed to be visible when hovering over a block). Still, the main reason is the currying visualization.
By trying to visualize currying, the amount of blocks grows with every additional function parameter, leading to a high total number of blocks.
This problem could be improved by displaying functions as one block with multiple parameters, giving up the visualization of currying.
As suggested by <NAME>, an option could also be to offer the user the possibility to activate/deactivate currying in the function editor.
== Scratch-inspired Design
The Scratch-inspired design received the most positive feedback but also
some negative feedback.
The most consistent criticism was about the operator functions being aligned
in the middle, implying that the design accounts for infix application but
was written in parentheses (e.g., `(+)`), which in Haskell is a form of regular
function application of operators that would support an infix notation. This is
a very valid point and something the design wasn't supposed to imply.
It is fairly easy to fix by aligning the operators to
the left.
Another point of critique repeated by several participants was that
unapplied parameters are not used correctly and/or inconsistently and some felt
that the type holes were unintuitive.
Finally, all participants agreed that the design wouldn't scale, as it
requires a lot of horizontal space to grow.
Compared to the other designs, the Scratch-inspired design was praised for
its extensive use of coloring, and as the most easy to understand.
== Haskell Function Notation-inspired Design
The Haskell function notation-inspired design received the most mixed
feedback.
A common point of critique was that the design was too overloaded and
difficult to understand, especially for beginners.
But some participants like the design the most, as it is the most similar to
Haskell. Other participants disliked the design the most, maybe because
the relationship between the design and Haskell was not clear enough. Still, it
isn't a good sign if one needs to understand Haskell to
understand the concept, as that goes against the goals of VisualFP.
|
|
https://github.com/smorad/um_cisc_7026 | https://raw.githubusercontent.com/smorad/um_cisc_7026/main/lecture_10_autoencoders.typ | typst | #import "@preview/polylux:0.3.1": *
#import themes.university: *
#import "@preview/cetz:0.2.2": canvas, draw, plot
#import "common.typ": *
#import "@preview/algorithmic:0.1.0"
#import algorithmic: algorithm
#set math.vec(delim: "[")
#set math.mat(delim: "[")
#let ag = (
[Review],
[Unsupervised Learning],
[Compression],
[Autoencoders],
[Variational Models],
[World Models],
[Coding]
)
#show: university-theme.with(
aspect-ratio: "16-9",
short-title: "CISC 7026: Introduction to Deep Learning",
short-author: "<NAME>",
short-date: "Lecture 8: Autoencoders"
)
#title-slide(
title: [Autoencoders and Generative Models],
subtitle: "CISC 7026: Introduction to Deep Learning",
institution-name: "University of Macau",
)
#aslide(ag, none)
#aslide(ag, 0)
// TODO Review
#aslide(ag, 0)
#aslide(ag, 1)
#sslide[
#cimage("figures/lecture_8/supervised_unsupervised.png")
]
#sslide[
Unsupervised learning is not an accurate term, because there is some supervision #pause
"I now call it *self-supervised learning*, because *unsupervised* is both a loaded and confusing term. … Self-supervised learning uses way more supervisory signals than supervised learning, and enormously more than reinforcement learning. That’s why calling it “unsupervised” is totally misleading." - <NAME>, Godfather of Deep Learning
We will use the term *self-supervised* learning, although many textbooks still call it unsupervised learning #pause
]
#sslide[
In supervised learning, humans provide the model with a dataset containing inputs $bold(X)$ and corresponding outputs $bold(Y)$
$ bold(X) = vec(x_[1], x_[2], dots.v, x_[n]) quad bold(Y) = vec(y_[1], y_[2], dots.v, y_[n]) $
]
#sslide[
In self-supervised learning, the outputs (and sometimes inputs) are *not* provided by humans #pause
// TODO
The model learns without human supervision
]
#sslide[
Semi-supervised learning is responsible for today's most powerful models #pause
The models can learn from the entire internet, without needing humans to feed them data #pause
They can learn from datasets that would take decades for humans to create #pause
]
#sslide[
How do these models work? #pause
They learn the structure of the data #pause
If the structure of the data is every picture in the world, they learn about the structure of the world
// TODO GPT/DinoV2 images
] |
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/array/num-range/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": *
#set page(width: auto, height: auto, margin: 1cm)
#num-range(10, 30)
$numrange(10, 30)$
#num-range(5, 100)
#num-range(5, 100, range-phrase: sym.dash)
#num-range(10, 12)
$#num-range(10, 12, range-open-phrase: [from ])$
|
https://github.com/xkevio/parcio-typst | https://raw.githubusercontent.com/xkevio/parcio-typst/main/parcio-slides/template/parcio.typ | typst | MIT License | #import "@preview/polylux:0.3.1": *
#import "@preview/subpar:0.1.1"
#let extra-light-gray = rgb("#FFFFFF")
#let m-dark-teal = rgb("#23373b")
#let m-light-brown = rgb("#eb811b")
#let m-lighter-brown = rgb("#d6c6b7")
#let m-extra-light-gray = white.darken(2%)
#let ovgu-red = rgb("#D13F58")
#let ovgu-purple = rgb("#7A003F")
#let ovgu-blue = rgb("#0068B4")
#let ovgu-darkgray = rgb("#606060")
#let ovgu-lightgray = rgb("#C0C0C0").lighten(50%)
#let ovgu-orange = rgb("#F39100")
#let m-footer = state("m-footer", [])
#let m-cell = block.with(width: 100%, height: 120%, above: 0pt, below: 0pt, breakable: false)
#let m-pages = counter("m-page")
#let m-progress-bar = context {
let ratio = m-pages.get().first() / m-pages.final().first()
grid(
columns: (ratio * 100%, 1fr),
m-cell(fill: ovgu-purple),
m-cell(fill: m-lighter-brown),
)
}
// --- THEMING: Start of theme rules. ---
#let parcio-theme(aspect-ratio: "16-9", body) = {
set page(
paper: "presentation-" + aspect-ratio,
fill: extra-light-gray,
margin: 0em,
header: none,
footer: none,
)
set text(font: "Libertinus Sans")
// Make URLs use monospaced font.
show link: it => {
set text(font: "Inconsolata", 0.9em) if type(it.dest) == str
it
}
set list(indent: 20pt)
set footnote.entry(
indent: 2.5em,
separator: line(start: (2em, 0em), end: (40%, 0em), stroke: 0.5pt),
)
body
}
// Declare your title slide! OvGU logo to the right.
//
// title: Your presentation title.
// subtitle: (Optional) subtitle for more info.
// author: Consists of author.name and author.mail.
// date: (Optional) date of the presentation.
// extra: (Optional) info below the date, like your faculty.
#let title-slide(
title: [],
short-title: none,
subtitle: none,
author: (:),
date: none,
extra: none,
) = {
let content = {
set text(fill: m-dark-teal)
show raw: set text(font: "Inconsolata", 1.15em)
set align(horizon)
v(-1em)
block(width: 100%, inset: 2.5em, height: 100%, {
table(
columns: (auto, 1fr),
align: (left, right),
stroke: none,
inset: 0pt,
text(size: 1.3em, strong(title) + v(-0.25em) + text(0.85em, subtitle)),
image("ovgu.svg", width: 9.8cm),
)
v(-0.5em)
line(length: 100%, stroke: 1pt + ovgu-purple)
v(2em)
set text(size: .9em)
if author != none {
block(spacing: 1em)[
#author.name\
#link("mailto:" + author.mail, raw(author.mail))
]
}
if date != none {
block(spacing: 1em, date)
}
if extra != none {
block(spacing: 1em, extra)
}
})
}
m-footer.update(
grid(columns: 3 * (1fr,),
align(left, author.name),
align(center, if short-title != none { short-title } else { title }),
align(right)[#context m-pages.display("1 / 1", both: true)]),
)
polylux-slide(content)
}
// Basic slide function.
//
// title: (Optional) title of the slide, will be shown on the left in the header.
// new-section: (Optional) marks a new topic, adds it to the outline & on the right in the header.
// show-current-section: (default: true) if the current section should be displayed.
// show-footer: (default: true): if the footer should be displayed.
#let slide(
title: none,
new-section: none,
show-current-section: true,
show-footer: true,
_last: false,
body,
) = {
// Define header: [Subsection] --- [Section], incl. progress bar.
let header = {
set align(top)
if title != none {
// Register a new section if given.
if new-section != none {
utils.register-section(new-section)
}
// Step page counter when this is not set.
// ONLY for special slides like outline or references.
if not _last {
counter("m-page").step()
}
show: m-cell.with(fill: ovgu-lightgray, inset: 1em)
align(horizon)[
#text(fill: ovgu-blue, size: 1.1em)[*#title*]
#if show-current-section [
#h(1fr)
#text(fill: ovgu-blue, size: 0.9em)[*#utils.current-section*]
]
]
} else {
strong("Missing Headline")
}
block(height: 1pt, width: 100%, spacing: 0pt, m-progress-bar)
}
// Define footer: [author] - [title] - [page / total]
let footer = if show-footer {
show: pad.with(bottom: .25em, rest: 0.5em)
set text(size: 0.7em)
set align(bottom)
text(fill: m-dark-teal, context m-footer.get())
}
// Applies a similar theme with the ovgu colors using the tmTheme format.
// It is very limited; using Typst's own highlighting might be more expressive.
set raw(theme: "ovgu.tmTheme")
show raw: set text(font: "Inconsolata", 1.1em)
show raw: set par(leading: 0.75em)
// Add line numbers to code block.
show raw.where(block: true): r => {
show raw.line: l => {
box(table(
columns: (-1.25em, 100%),
stroke: 0pt,
inset: 0em,
column-gutter: 1em,
align: (x, y) => if x == 0 { right } else { left },
text(fill: ovgu-darkgray, str(l.number)),
l.body,
))
}
set align(left)
rect(width: 100%, stroke: gray + 0.5pt, inset: 0.75em, r)
}
// Display supplement in bold.
show figure.caption: c => [
*#c.supplement #context counter(figure.where(kind: c.kind)).display(c.numbering)#c.separator*#c.body
]
set page(
header: header,
footer: footer,
margin: (top: 3em, bottom: 1em),
fill: m-extra-light-gray,
)
let content = {
show: align.with(horizon)
show: pad.with(2em)
set text(fill: m-dark-teal)
body
}
polylux-slide(content)
}
// ------ HELPER FUNCTIONS ------
// Simple table design, similar to the existing ParCIO template.
// Custom ParCIO table as illustrated in the template.
#let parcio-table(max-rows, ..args) = table(
..args,
row-gutter: (2.5pt, auto),
stroke: (x, y) => (
left: 0.5pt,
right: 0.5pt,
top: if y <= 1 { 0.5pt },
bottom: if y == 0 or y == max-rows - 1 { 0.5pt }
)
)
// Subfigures.
#let subfigure = subpar.grid
// Simple orange TODO box.
#let todo = rect.with(fill: ovgu-orange, stroke: black + 0.5pt, radius: 0.25em, width: 100%)
// Shorthand for `slide` with shorthands for `title` and `new-section`.
#let s(t: none, ns: none, body) = slide(title: t, new-section: ns, body)
// Creates a clickable outline with a customizable title
// for each `new-section` entry.
#let outline-slide(title: "Outline") = {
slide(title: title, show-footer: false, _last: true)[
#set enum(numbering: n => [], tight: false, spacing: 3.5em)
#utils.polylux-outline()
]
}
// Creates a list of all references using the "apalike" style.
#let bib-slide(title: "References", bib) = slide(title: title, show-footer: false, show-current-section: false, _last: true)[
#bibliography(
bib,
style: "../bibliography/apalike.csl",
title: none,
full: true,
)
]
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/visualize/stroke-06.typ | typst | Other |
// Error: 29-55 expected "solid", "dotted", "densely-dotted", "loosely-dotted", "dashed", "densely-dashed", "loosely-dashed", "dash-dotted", "densely-dash-dotted", "loosely-dash-dotted", array, dictionary, dash pattern, or none
#line(length: 60pt, stroke: (paint: red, dash: "dash"))
|
https://github.com/FlixCoder/typst-slides | https://raw.githubusercontent.com/FlixCoder/typst-slides/main/metadata.typ | typst | MIT License | #let beamer_format = (16, 9)
#let theme_background = blue.darken(30%)
#let theme_text = white
#let font = "Open Sans"
#let presentation_title = "Creating Presentations"
#let presentation_subtitle = "Using Typst and this template"
#let author = "FlixCoder"
#let date = "2023-09-19"
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/035%20-%20Core%202019/009_Unbowed%2C%20Part%201.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Unbowed, Part 1",
set_name: "Core 2019",
story_date: datetime(day: 29, month: 08, year: 2018),
author: "<NAME>",
doc
)
"You speak with fish as well? Mademoiselle, your skills are without number."
The eels receded into the water at the sound of the man's voice, a lean baritone yet unused to manhood. Not that it'd ever have occasion to mature. Vivien raked a considered look across the new arrival's countenance, taking in the saturnine features, the boyish softness of his mouth, his bloodless complexion. Vampires were eternal, both in habit and biology.
Vivien unfolded to her feet. She was tall and brown and muscled in a way that compelled troubadours to think of knights in disguise, her dark hair held back in a pragmatic ponytail. If Vivien was beautiful, no one had yet thought to remark upon the fact, more concerned, perhaps, by her martial demeanor and the cold sated intensity of her regard.
The sea billowed and lapped at the ship, hurling jeweled foam into the air.
"I talk to fish as much as I talk to dinosaurs." Vivien adjusted the placement of the Arkbow, its ligature warm even through her doublet. Frederic, the vampire huntsman who'd elected himself her escort, spent a night and handfuls of a morning endeavoring to convince her the weapon needed to be stowed away: swaddled in oilpaper, kept safe from the abrasive salt air.
But Vivien refused. She would sooner be flayed than parted from the relic, crooked and bright as a spine sleeved in silver, the last piece of Skalla outside of her own skin and tendons.
"So, what you are saying is that you're versed in their every dialect, acquainted with their similes, and gifted at interpreting their native anecdotes?" Frederic beamed as though he expected to be rewarded for his grandiosity. He smelled of blood and brine and frankincense, a butcher at church, and even after days in his company, Vivien couldn't bring herself to untense in his presence. "I'm saying I don't 'speak' to fish."
One of the eels rose to interrogate her with a look, agate eye bisected by a rectangular pupil, goat-like and animate, only to be chased away by the lowing of the ship's prized captive: a juvenile brontodon. The dinosaur was too big for its prison. Both tail and throat tendrilled from portholes on each side of the vessel, endlessly beset by gulls and gulper-fish. As well as Vivien could infer, the creature did not sleep, only moaned and howled through the hours.
"You do, however, speak to dinosaurs?" A lascivious waggling of his brows. Behind him, Frederic's crew swarmed and seethed and shouted in a sublimely acrobatic creole; Vivien could only pick out one word in eight, the others too slang-tangled in lurid flourishes. But their excitement required no translation. Home was but a horizon away.
#figure(image("009_Unbowed, Part 1/04.jpg", width: 100%), caption: [Shadowed Caravel | Art by: <NAME>], supplement: none, numbering: none)
She plucked the last of the fruit from her bucket and flung it at the brontodon, succulent vegetal flesh dripping sugar like beads of buckwheat honey. The reptile snapped its mouth close around the morsel, guzzling a ragged scavenger-bird in the bargain. It gazed dolefully at her and trumpeted in misery again. "No."
"Then how do you explain what we saw? How do you explain the majesty of you standing there, a hand stretched to the beast? It takes Luneau entire expeditions to return with but one of these beasts. But you, #emph[you] sought them out alone! Mademoiselle, you are either gifted or magic or both!" Frederic twirled a hand upward and then paused, an anticipatory smile hunching his lips.
Unfortunately for the vampire, Vivien had ceased paying attention. "There will be medical attention waiting for the brontodon, I hope?"
"It will, like every new specimen, receive the finest attentions of the Royal Menagerie." Frederic palmed his breastbone and bowed low.
Vivien took note of how he abstained from a direct answer and how glibly he smiled, filing both observations away behind a grimace she, if questioned, would blame on the wind. The Planeswalker tired of the simpering, the subtle innuendos, the strata of meaning layered one over another, Frederic's every word weighted with a multiplicity of nuance.
Not for the first time, Vivien found herself regretting her decisions. She should have run them from the jungles. But Frederic, effete yet earnest, had so very many stories of a Royal Menagerie more impressive than myth, so enormous it held entire ecosystems behind its gilded teeth. What a trousseau of rarities, what treasures. Like nothing Vivien would ever see again this lifetime or the next.
The Planeswalker bent and scooped the bucket into the crook of an arm, wiping her fingers on her breeches. As skiffs, each the same tint of pearl as distant Luneau, came to circle the ship, the sailors began a lusty laughing chanty, one full of husbands and husbandry and what debaucheries can be achieved between the two. Frederic looked over his shoulder, smile as false as the words to follow.
"I should apologize for my men."
"No. That is quite all right." Vivien said. "It is about what I expect of civilized people."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
It took exactly twenty minutes for Luneau, all byzantine alleys and baroque balconies, to turn its stained sea-glass eyes on to Vivien and another ten for it to decide that the Planeswalker wasn't worth the trouble. Vivien pulled on the human pickpocket's hair until his neck bent like his scruples, until there was barely room for air to slick down his windpipe. Then and only then did Vivien lean down, teeth an inch from his ear.
"Do we understand each other?"
The pickpocket squeaked like the hinges of a rusted skeleton lock.
"Mercy, mistress. A cup of my blood as penance." His shoulders scissored back as Vivien gave another tug. Luneau, already bored with the spectacle, drowsed around them: its vampire dockhands and its sailors made conversation with the human fishermen while aproned women, each at least as tall and brawny as Vivien, gutted oversized sturgeons by the water. Save for Frederic, no one paid mind to the pickpocket's plight and even the vampire, a half-smile in its customary seat, seemed only amused.
"What is he talking about?" Vivien's flesh pimpled in the limp, listless breeze.
Frederic sank into a crouch and cupped the pickpocket's chin in one gloved hand. With the other, he brought forward a dirk. "This is the currency of Luneau, mademoiselle."
Vivien loosened her grip while keeping a knee wedged between the pickpocket's shoulders, eyes going wide. Her gaze flicked to the proffered weapon, held out to her hilt-first. "What do you expect me to do with this?"
"Did you not hear him?" Another of the vampire's easy, effervescent laughs. "He wishes to offer you a cup of blood—"
"No. I heard the boy." Vivien hissed. "What do you expect #emph[me] to do with his blood?"
"I suppose that would depend on the current exchange rate. But I imagine you'd at least be able to finance a new wardrobe. Your proletariat nature isn't without its charm. However, I think the royals would be flattered if you changed your manner of dress for them." He dragged the red wag of muscle that was his tongue over his teeth, and Vivien couldn't help but think of a leech, so blood-bloated it shone red as fresh paint. "Or if you are feeling generous, you could give him over to me. The Church espouses use of the criminal element."
The Planeswalker slapped the dirk away. "No."
"Mercy, mistress." The pickpocket panted like a dog forgotten on Death's door. "Mercy. I only wanted to leave Luneau."
"#emph[Leave] Luneau?" Frederic let go of the pickpocket's chin and stood, his silhouette bladed and burnished by the moonlight slanting through the alleys. A knot of nuns paused to review the tableau, the hems of their flowing mother-of-pearl habits teethed with gold. "And what will you do outside this island? Join the Brazen Coalition? Those ruffians don't allow for anything but the most competent sailors. Perhaps, you think to find a city yet civilized by the Church? I suppose you could. But there you would need to work. You would not be able to pay for your food and your housing with drops of ruby from your vein. No, monsieur. You will not leave Luneau. There is no space for you outside of these—"
Vivien lifted her voice over Frederic, not high enough for the timbre to hoarsen or hitch, but enough to signal she was glutted on the vampire's rhetoric. She rose, fingers gliding over the Arkbow. The pickpocket stayed wisely supine. "If I were a different woman, a more cynical one, I'd say you were bullying this boy into accepting his lot as livestock and that Luneau, pretty as a fresh-minted coin, is nothing but a glorified abattoir."
"You wound me, mademoiselle." His imperiousness dissipated, fat melting on an eager tongue. In its place, a new substrate of slyness, worse for its reprobate swagger. "Luneau is hardly a stockyard. If anything, I suppose you might call us a halfway house."
"Which takes payment in blood."
"Do you despise the lion as well? Do you take offense at the fact it will not eat grain but instead prefers the meat of the lamb? The Rite of Redemption isn't without its consequences. We drink blood because we must. But we aren't#emph[ barbaric] about it." Frederic cocked his head, the breeze coiling through his tiered curls. "A cup here, a portion there. Nothing that might kill the mortal citizenry. We have time tables."
And to Vivien's revulsion, he pouted.
"As for the matter of the boy," Frederic sighed. "I suppose I might have misstepped. But the Legion of Dusk does see itself as caretaker of Ixalan. Here in Luneau, we have the facilities to take care of people like him. But the rest of the world isn't so lucky, and what manner of gentry would we be if we did not do our part to protect these lands?"
"And the brontodon? The myriad wildlife you dragged across the water to Luneau? Is that for the same purpose?" Vivien tapped the pickpocket with the curved edge of the Arkbow. #emph[Go] , she mouthed, and the boy fled down the pier. Into Luneau proper where the buildings stood pale and lustrous as cream.
"Preservation, mademoiselle. You never know when a species might go extinct. Ixalan is such a savage, unforgiving place." That smile again. As though they were all accomplices to the same good-natured lie. "But please. We have wasted enough time. The wonders of Luneau cannot be encompassed by words. Let me show you my city and perhaps then, you will begin to see how wrong you were to assume poorly of us."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Vivien sat silent as Frederic unrolled reams of praise to Luneau, gesticulating and genuflecting at the splendor of both country and capitol. He narrated, with indecorous gusto, the preeminence of the sovereign couple, their virtues, the circumstances that precipitated such an exquisite union. Then he went on to alphabetize their accomplishments, chasing compliments with more of the same.
It was all, Vivien thought to herself, so gauche.
That there were lotus flowers laced through the balustrades of the city, gardens charting the plunge of its towers like the grasping hands of a desperate lover, trees parasitized by softly luminescent blossoms, was beside the point. At best, it only accented Vivien's disgust with the island nation. The air reeked of excess. Luneau was artifice and arrogance, its every last wonder a contrivance. Its buildings were white marble, all dainty cafes wherever Vivien turned, all museums and shopfronts showcasing rich gowns and towering wigs. Luneau resembled someone's dream of a city, clean and cultured and bereft of common things, things like butcher shops and bakers and bailiffs patrolling cracked-cobbled lanes. Only in the margins, only where Luneau could tuck such eyesores away, hidden behind alley or a crook in lanes, could Vivien see where humanity might toil.
If there was any true beauty here, it was a piteous thing, strangled and suffocated by the whimsy of its undead tenants.
But Vivien divulged nothing of her ruminations, only hooked fingers along the string of the Arkbow and smiled dispassionately, an expression her companion interpreted as invitation.
"What it is like where you come from?" Frederic traced a finger along the knob of bone that rose from Vivien's brown wrist, the motion precise as the pleating of his lace jabot, and turned her arm onto its back. His touch wandered up the tributaries of her veins, while Luneau, dusk-lit and haunting, flaunted itself through the window.
Vivien tried not to think of an antlered silhouette rising into the sky, tried not to think of the screaming, the #emph[pop] of skin as it crisps and breaks, tried not to think of how #emph[soundless] it became as the world burned to white. She tried not to think of fire.
"It was beautiful." she whispered.
The carriage rolled on.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
She counted the bodies on the wall until the numbers fled from her mind and then, Vivien murmured the numbers like a chant. For one terrible moment, the Planeswalker could understand <NAME>, the death of Skalla, the end of everything she'd known and loved.
Here, flanked by the corpses of a hundred extinct species, their bodies threaded with wires, fat-starched and stiffened by a taxidermist's concoctions, the antechamber gold and garish against the waxen sheen of fur, Vivien could think of nothing but the desire to see all this gone.
"Like nothing else, no?" Frederic's grasping hand on the crook of her elbow again, fingers locking around the joint. "The Hall of Treasures is a church onto itself, a worship of the natural world."
Vivien peeled herself from his grip. "Your idea of how to demonstrate reverence is very different from mine."
"As it should be. We are not creatures of the same world." Noblemen and their entourages drifted past the pair, effete and absurd in their towering wigs, minarets of hair teased into strange, unsubtle configurations. "And that is what is so beautiful about existence."
"Beauty isn't something to be pinned to a wall."
"Oh, absolutely not." Frederic smacked his lips. "Better if it is allowed to remain alive, beautifully framed by filigree. I remember when they brought home the monstrosaur breeding pair. What a joy that was. It was an #emph[event] , as they say. And they were such generous guests of the Royal Menagerie too. Some animals, they simply expire, unwilling to put up a show. But there was so much theatre with the pair. So much bombast. The male wasn't halfway as hardy as his counterpart. He died too quickly and she followed after, wasting away in a show of tragedy so profound, it was immortalized in a manuscript."
Vivien swallowed around her rage. "Show me more of Luneau."
#figure(image("009_Unbowed, Part 1/05.jpg", width: 100%), caption: [Charging Monstrosaur | Art by: <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The Perfumed Court lived up to its nickname: its aristocracy was anointed with ambergris and rose water, its knights dusted with salt and musk and holy incense. Even the supplicants and the servants, loose-wigged and cotton-garbed, stank of powders, always more powders, a glazing of particles that turned their skin nacreous in the evening's blue light.
Vivien pressed a handkerchief to her nose and choked on its odor. Gagging, she ran fingers along the edges, discovering too late the potpourri sewn into the hems. Nothing in Luneau was sacred. Nothing here was natural.
"<NAME>, are you all right?" Frederic extended his arm. In the half hour they were apart, he somehow found time to exchange his hunting attire for a more flamboyant display. Ruffles and stuffed breeches, rendered in lilac and cream-colored satin, made bulbous his silhouette.
"I'm fine." She threaded her arm through his, folding the handkerchief into quarters. "I suppose I was just dumbstruck by the glories of your homeland."
"In that case, do not let me distract you too much. Luneau demands worship. There is nothing else on Ixalan quite like her." He leaned in, voice sharpened to conspiracy. "The Baron of Vernot, he believes there are giants among the lizards we hunt. #emph[Gods] . Creatures bigger than even language can encompass. One day, we will have them for the Royal Menagerie and after that, history will never be able to name a rival."
"I see."
Frederic sniffed. Pigment stained his cheeks. Not pink, as was traditional, a rosy counterfeit of vitality, but a blush of turquoise which evoked in Vivien the memory of a crab-nibbled carcass she'd once fished from the sea. "Ah, mademoiselle. I'm sure you think the patriotism unwarranted, but you've seen the Royal Menagerie. Surely, you must understand."
Anger a frisson across her skin. The Arkbow seemed to thrum against the swoop of her spine, and for a moment, it subsumed her, a hunger like a well with no end. It wanted to be nocked—no, #emph[she ] wanted the relic's power nocked and angled at Luneau's heart. The Arkbow loathed this place. Vivien knew, the way the oak and the alder knew to rouse themselves in spring, the way fire knew to find the fat within one's flesh, there would be no walking away from Luneau. Together, they would see it gone.
But not yet.
Not yet.
They needed to wait.
Vivien schooled her voice for politeness, a smile tipped into place. Charm was too much to ask for. Their reflections regarded them from every angle of the high-ceilinged building. Where the architecture wasn't indigo stone, it was gold and shining metal, florid marquetry and grand stucco work, oil-lamps and mage-lights cunningly positioned to ensure no one might ever need squint against an unseemly glare.
It held, in Vivien's opinion, all the tenderness and compassion absent from certain other elements of Luneau.
"Forgive me, but all I saw were cages full of sick and dying animals and a hall resplendent with a circus of cadavers." Her mouth pinched. "If that was your pride and joy, you may wish to consider investing in another."
To her surprise, Frederic laughed, gauzy and unperturbed by the warning grooved in her tone. "Mademoiselle, if we turned ourselves inside out to keep everything alive, where would we put them all? The Royal Menagerie is the largest of its kind in Ixalan, but it is not #emph[magic] . Besides, how would the baron pursue his science if there were no bodies to use in an autopsy?"
#figure(image("009_Unbowed, Part 1/06.jpg", width: 100%), caption: [Pride of Conquerors | Art by: <NAME>], supplement: none, numbering: none)
The corridor spread into a palatial lobby. Above them, a vaulted ceiling frescoed with ships in conflict with a kraken. Waitstaff ferried brass plates laden with goblets through a growing crowd of courtiers, their corpuses doubled in the mirror-plated floor.
#emph[The clothes do not make the monk, ] Vivien thought to herself#emph[. ] No matter how they primped and perfumed themselves, no matter how many acres of crushed velvet they draped over bodies embalmed in dark magic, how they played at refinement, these creatures were still corpses. Frederic patted Vivien's hand, and it took all of her to not slap his fingers away.
"By the way," Frederic said, exchanging air kisses with a pale woman who barely deigned to glance at Vivien, her cleavage frosted with diamond dust. "I must congratulate you on your sense of timing. You chose the perfect occasion to visit Luneau."
"And why is that?"
The woman turned, snapping open a fan. Lace foamed at her collar and down along the ends of her sleeves, wove into the gaudy edifice of her alabaster wig. She alone of the attendees smelled of nothing but mausoleums and marrow and bone and dirt. "Poor thing. Do they teach you nothing from where you come from, mademoiselle? Tonight's festivities are famous across Ixalan. It is—"
A sigh, as if to broadcast the burden that was translation.
"—the #emph[Tourdion with the Truculent Thunder] . Did I say that correctly, Frederic? No. No, don't tell me. I don't care enough." She pumped her fan slowly. A beauty mark punctuated her philtrum. "Just know that you are #emph[unbearably ] fortunate, mademoiselle. There are rurals in Luneau who would hawk their firstborns to attend this gala. Honestly, Frederic, why did you even bring her?"
"For novelty, I imagine." Vivien's attention made an orbit of the space. Too many of them, and too little known of what they were capable. She would have to wait and watch and wonder for the time being. "Like everything else in this place."
Tittering greeted Vivien's riposte, high-pitched and theatrical, while Frederic looked on like an indulgent uncle. "Sweet mercies, this one has teeth! What a delight, my dear."
Before Vivien could marshal her rage, double doors creaked apart, admitting first a straight-backed couple in gaudily elaborate regalia, their skulls crested with ivory wigs. Of the two, the woman, severe and slim, appeared less comfortable with the finery: she had a hunter's stalk, the gait of someone more accustomed to leathers and the thump of a sword against her hip. Despite that faint air of unease, her expression was beatific, as was the look worn by her partner, a gaunt-faced man with immaculate facial hair, shoulders stooped as though weighed down by the crown he wore like a burden.
"King Lucard and <NAME>," Frederic murmured into Vivien's ear, his breath cold on the lobe. "You should bow to them."
She flicked a look behind her. "No."
The sovereign rulers of Luneau tipped their heads, and the crowd responded in kind: the women curtseyed, the men bowed, the heels of their palms pressed to their hearts. Alone of them, Vivien stood unbowed, chin tipped up. The assembled gentry straightened as the royals drifted past, children in teal frocks coming to take hold of their trains. If any of them took notice of her impudence, they did not think it fit to comment.
"Audacious," murmured Frederic's pale acquaintance as she rose again to her full height. "You have such interesting tastes in friends."
"Only the finest."
The doors opened again. A hush ran through congregation. From the penumbra emerged a rangy fellow clad simply in a cassock, white hands steepled at his sternum. His manner exuded a choreographed austerity, every motion imbued with purpose. He raised his head, and the crowd sighed at the sight of him, an ecstatic noise.
Vivien cocked her head. "And who is he?"
"The Baron of Vernot." The woman sighed, fanning herself, tongue wrapping about the honorific, cradling it like a newborn messiah. "<NAME>. He rules over the Royal Menagerie and the wonders in the Hall of Treasures."
"<NAME>." His ophidian gaze found Vivien through the press of bodies, lidded and lazy, held her, golden sap hoping to drown an unsuspecting insect. "#emph[Special ] guests. We are ready for you."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The opening act spoiled the breath in Vivien's lungs, left her panting, and she sat, blood seeping from where her nails gouged half-moons into her palms, as a man wafted a torch beneath a lizard's belly. It shrilled while its hide blackened in the fire, splotches of color radiating from the burns. Arabesques of puce and orange, venous trails of fading blue: its terror coaxed into an art.
The show only grew worse thereon.
The performers brought forward bears in ill-fitting frocks and absurd panniers, raptors dressed as marquises, viscountesses incarnated as knock-kneed cranes, waltzing across hot coals in halting leaps. Each was tortured, tormented, teased in turn, while the audience howled song titles to a brass cabaret in the pit, and the monarchs of Luneau conversed with their ministers.
#figure(image("009_Unbowed, Part 1/07.jpg", width: 100%), caption: [Anointed Deacon | Art by: <NAME>], supplement: none, numbering: none)
"This is cruelty," Vivien hissed, half-risen from her seat, voice coarsened by rage.
"No, this is entertainment." Frederic sucked at his teeth and clinched fingers around her wrist. "Now, sit down, <NAME>.#emph[ Please] ."
The crowd roared as the band laid down a triumphant anthem, brass scaffolding a rolling, rippling drumbeat. Something was happening. Vivien jerked her attention toward the stage, a finger hooked over the Arkbow's bowstring.
"Ladies and gentlemen." There he was once more: the priest of this place. The man stood alone, no accoutrement or accessory, no chains of office. Black robes, calcium-pale hands raised to the masses. The music dimmed to a shiver of a flute, like some lonely thing dying in the dark. "I thank you for your patience, your tolerance of the lesser acts. We know why you are here."
Silence washed over the coliseum, taut. The man commanded their gazes, hallowed in his pulpit of light. He lowered his voice as Vivien took aim, his voice a holy hush.
"Our finest spend their months in the savage wilderness, stalking through the undergrowth. They wage war against nature. They die in droves, all in service to your pleasure." Here, his tone warmed and the crowd murmured in pleasure. "All in the pursuit of the grandest of prizes, the finest of monsters to bring home to you. Tonight's specimen is particularly intriguing, a behemoth even the Golden City fears. Ladies and gentlemen, let me introduce you to this evening's most special#emph[ guest.] "
And the curtains drew back, red velvet pulled away by lush ropes of braided gold. The spotlights abandoned the man in black and joined like hands laced in prayer, illuminating a route for whatever would soon emerge. From the dark, something screamed its rage.
"A new monstrosaur from the depths of the Ixalan jungles," whispered the baron, his voice carrying like a curse. "More impressive even than our breeding pair. Fiercer, still full of that primal fire."
That #emph[sound.] It wasn't the brontodon. It couldn't be. Vivien #emph[knew] ruminants. They did not have the throat for such sounds. There wasn't space in a body like that, no room with the multiplicity of stomachs, the knowledge of death riding low in their bellies. This was something else. Something bigger, angrier, something that'd eat up the world if it was given half the chance and judging by that call, it wanted nothing less. It #emph[ached] to swallow them whole.
But the shambling, sad thing that emerged from the gloom could barely hold itself upright, let alone put up a fight. Vivien forgot herself at the horror that stumbled into view, a gasp rasping up her throat. The creature was #emph[once] massive, majestic even, but now it stood stooped and sunken, starved of everything but fury. Someone had tortured it. Someone, Vivien realized with a pang of horror, had plucked the largest teeth from its head.
"I am done." The Arkbow sang out at the downward stroke of Vivien's finger, suddenly lambent with power, and Skalla as it was, as it should have been, as it should have#emph[ stayed] , was alive again, if only for that moment.
The audience did not care. Not for Vivien, or for the plight of the monstrosaur. And why would they? Vivien thought. Nothing mattered to these vampires but their games, their posturing and preening jibes. Soldiers advanced on the creature, a flashing half-circle of steel and plumed hats. Their caution was performative. There was no way it could have retaliated. Not like this, not with manacles on every limb, its hide stippled with scars, two men at each end, tugging its hunched body down low. Nonetheless, that didn't make its suffering less of a sport for its audience. If anything, it seemed to delight the crowd. #emph[This ] way, the soldiers had space for invention.
What misery those soldiers brought to being. They worked holes through the monstrosaur's hide with their pike tips, constellations of new wounds amid a patchwork nebulae of scars. They scratched at its eyes, one already filmed with milk, the other jaundiced and rolling in its socket. They worried at its body like crows, or dogs, or spoiled children drunk on the absence of consequence.
"Madame, #emph[please] —" Before Frederic could speak another word, Vivien notched an arrow. Before Frederic could breathe out, she let go.
The wood blazed green as the projectile sang through the air. It hit the floor beside where the man in black stood, shaft trembling from the impact. And Vivien had enough time to salute him, two fingers to smiling lips, before the seething, glimmering green outline of a hydra wrenched itself from the arrowhead and howled its hunger for the world to see.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Luneau did not know how to contend with hydras.
It had, over the years, learned to accommodate dinosaurs and megafauna of comparable size, but these were separate taxonomies of dangers. The wildlife of Ixalan, while ferocious, responded to decapacitation in the traditional fashion: they laid down and died. The hydra, however, did not.
#figure(image("009_Unbowed, Part 1/08.jpg", width: 100%), caption: [Hungering Hydra | Art by: Daarken], supplement: none, numbering: none)
The fact it was made of magic didn't help either.
Two of its heads, shimmering and green, took hold of a screaming noble: one dug its jaws into his shoulder, the other latched onto a calf. They pulled and he came apart.
Vivien loped down through the stands and into the stampede of evacuating guests, guards racing behind her, shouting for the Planeswalker to stop.
The Planeswalker continued to run; she vaulted over a duke who'd dropped to his knees, wig clinging to his skull by a strip of sweat-soaked prayer; she ran as the monstrosaur, forgotten by its handlers, roared in defiance. In the chaos that had ensued, the beast had snapped a leg, trying and failing to snare one of the fleeing performers. Bone protruded from the rags of its knee, but that wasn't enough to dissuade it. It screamed. For retribution, for rage, for whatever ineffable hope that dragged it forward, inch by inch, toward the guards advancing on the hydra.
The dinosaur swung its head; teeth found flesh, the hollow of a poorly armored hip. It bit down. Crippled, it had no way to stand. But it could still pendulate its skull, still crush its quarry against the mortar and the marquetry of the stage, the body inside the ornate armor rendering to bone-bitten mush. And as it did, it screamed and this time, there was triumph in the noise.
Vivien swiveled, fell to a knee, took aim, and let fly an arrow. The Pelakka wurm launched itself forward, all mouth and sinuous body, glowing green. The guards paused, dumbstruck by the sight. Vivien did not wait for the aftermath. She stood instead and renewed her sprint toward the stage, even as screaming rose up at her back, the sound quickly muffled by the#emph[ snap ] of the wurm's jaws. She didn't have to look. She knew what'd follow. As was often the case with the wurm's victims, they likely died with astonishment on their faces. No one ever expects to be perfectly bite-sized.
#figure(image("009_Unbowed, Part 1/09.jpg", width: 100%), caption: [Pelakka Wurm | Art by: <NAME>], supplement: none, numbering: none)
Vivien leapt onto a railing and allowed the momentum to carry her down. She nocked an arrow, fired again. On this occasion, it was an herbivore that burst from the point of impact, staggering colt-legged onto an uneven canter, the stag—body a carapace like a pangolin, spade-shaped antlers swept back from its skull like raised wings—making several orbits around the arena before at last it took notice of the guards.
Startled by its appearance, someone had flung a pike at the animal. Their throw was perfect. It sailed through the green glimmer of the stag's muscled shoulder, but the ethereal creature #emph[bucked ] like it'd been hit, kicking out both sets of legs before at last rearing onto its hind hooves. The guards had accounted for dumb instinct, animal reflexes tethered to the trigger-points of pain and rapture. But Skalla, beautiful and voracious, Skalla of the mangrove-strangled monsoons and the fireflies and the wildfires that sang giddily of new seasons, Skalla's wildlife, down to the last coral-striped ant, was cannier than that.
The stag did not panic. It barreled down on its assailant, shimmering antlers bent at a ninety-degree angle, rage in its eyes and in the set of its expression. The guard had enough time to inhale before the stag, taller than Luneau's finest by several hands, scooped him up and flung him into a wall. A crack: short and sudden and sickening. His body wrinkled to a heap as he slid down onto the floor.
Vivien landed delicately beside the stage, Arkbow still at ready.
The Pelakka wurm's last triumphant bellow shuddered through the arena, its percussions amplified by the acoustics of the theatre, so loud that it thinned the world in Vivien's ears to a whine. It was followed by shouting. She snapped a look across the coliseum, gaze walking up the tiered seats to where the Baron of Vernot stood in the aisles, ringed by men with crossbows. Her surviving pursuers stood with them.
"You." His voice, oratorical, carried easily to where Vivien crouched.
The Planeswalker bared a snarl. "This place is an abomination."
Something flared in the baron's gaze, a look not unlike recognition, half-smile fixing itself in place as he descended the steps. Only a handful more arrows. Vivien narrowed her eyes at the crossbows, wondering which of her magical menagerie to call: the wasps or the rainbow-breasted birds with the scimitar beaks, the devouring wurm, the grizzly bear from her earliest memories, smelling of cold water and mountains and animal spoor.
"You rurals are always the same, always so sure of the shape of the world." The words spilled like oil, slick. "Always so#emph[ frightened ] of the idea of change. Do you have any idea as to how many of you I have seen? How many of you I have dealt with?"
#figure(image("009_Unbowed, Part 1/10.jpg", width: 100%), caption: [Vivien of the Arkbow | Art by: Magali Villeneuve], supplement: none, numbering: none)
Half of the baron's entourage poured past him and down, down into the fray where corpses lay, gleaming slickly. They broke into two rows: the first went down to their knees, while the second stood braced. They took aim at the hydra as it began to come apart in a convulsion of emerald sparks.
"Speeches are such a thing with tyrants, aren't they?" Vivien freed another arrow from her quiver. The wasps, she decided. "People like you are so in love with your voice."
"Tyrant?" His laughter was effervescent. "Please, mademoiselle, I am nothing but a humble researcher. Even my barony was forced upon me. A gift from her Royal Highness."
Vivien thought back to her first glimpse of the queen, of the sharp-featured face beneath its stiff crown of marble curls, that unsmiling mouth and abstracted gaze, attention already elsewhere. She had sat slumped at her throne, chin held in the cup of her palm, bored with the tableau, bored with the cruelty. Such a woman wouldn't play at favorites. But the baron did not look like a man who cared.
"Whatever the case," Vivien nocked her arrow, every motion deliberate. The crossbowmen rallied around the baron. "I will see Luneau pay for what it has done to this world."
This time, they did not hesitate. They released their crossbow bolts, only to see their assault sail harmlessly through the hydra, even as it finally dissipated.
"I'm sure you'd like that. But what I would like is to know more about that bow of yours." The baron's gaze ticked to the Arkbow in Vivien's grip. "What a #emph[fascinating ] weapon. How do you use it? Where do your creatures come from?"
In answer, Vivien let fly her arrow. Wasps corkscrewed from the ensuing contrails, translucent wings iridescent for a moment before they shook loose of the enchantment, the insects coalescing into a swarm so thick, it darkened the air. Vivien sprinted forward in their wake, feeling every copper-banded body thrum beneath her thoughts. The lambent wasps were the size of hounds, of horses, all with appetites to match. No queen in sight, no nest, but that hardly mattered: hunger was even older than the memory of them.
"Skalla." Vivien panted as she traded the Arkbow for her daggers. The wasps parted, revealing the baron, hands pressed together as though in prayer, his smile serene. "We are the dead of Skalla."
She brought her blades down. #emph[Twisted. ] Felt steel slot between ribs, felt the iron catch in soft tissue. Vivien jerked her wrists, and the daggers sliced through membrane. But the baron's placid expression did not change. He only looked up, and when he smiled, full-teethed, Vivien had a moment to think on how red his tongue was, how plump his mouth, and how much he reminded her of a sated lamprey. His fingers closed around Vivien's own, almost tender, his touch scorching.
"My turn."
The baron backhanded Vivien, a blow so casual, so artless that Vivien found herself surprised by its force. She skidded backward, away from the point of impact. A wet heat dribbled along the corner of her jaw. Vivien mopped at her chin with the back of a hand and snarled.
"Ah, were you expecting a dandy then?" The baron's voice stayed mild. He wrenched Vivien's daggers from his chest and flung them onto the floor. "I'm afraid I'd have to disap—"
"I'll manage." You couldn't rely on weapons alone in Skalla. Nature did not wait for duels, for rituals, for men to unsheathe their swords. Often, it was nothing but tooth and talon and tendon. Vivien spun into a roundhouse kick, stopping the baron mid-sentence, hooked a leg along his shoulder, and allowed momentum to pull them both down onto the ground.
Pain burst along her shoulder; the fall hadn't gone quite right. She had taken too much of the baron's weight on her, but Vivien refused to be deterred. She reared up, bringing the Arkbow down like a bludgeon, taking aim at the baron's temple. Vivien managed three sharp shots to her quarry's head before his minions arrived to drag her away.
Vivien fought. Rabidly, and with the bitter abandon of someone who had run out of things to lose. She took two guards to unconsciousness with her: the first with a strategic kick to the head, the other with a blow from an elbow, one so forceful that Vivien heard the small bones of the man crack in the recoil. It was, she decided as awareness bled from her, at least a decent last stand.
|
|
https://github.com/hugoledoux/msc_geomatics_thesis_typst | https://raw.githubusercontent.com/hugoledoux/msc_geomatics_thesis_typst/main/template.typ | typst | MIT License |
//-- my local cover
#import "cover/cover_template.typ": cover
//-- subfigure
#import "@preview/subpar:0.1.1"
//-- admonitions
#import "@preview/gentle-clues:1.0.0": *
//-- pseudo-code
#import "@preview/lovelace:0.3.0": *
//-- for the fancy headers
#import "@preview/hydra:0.5.1": hydra
//-- TODO
#import "@preview/dashy-todo:0.0.1": todo
#let msc-geomatics-tudelft(
title: "",
author: "",
advisors: (),
graduation-year: "",
graduation-month: "",
supervisor1: "",
supervisor2: "",
coreader : "",
graduation-group: "",
body,
) = {
set page(
margin: auto,
// margin: (left: 25mm, right: 25mm, top: 40mm, bottom: 30mm),
)
set par(justify: true)
let serif-fonts = ("TeX Gyre Pagella", "Palatino", "New CM") //-- https://www.1001fonts.com/tex-gyre-pagella-font.html
let sans-fonts = ("TeX Gyre Heros", "Source Sans Pro", "Calibri") //-- https://www.1001fonts.com/texgyreheros-font.html + https://github.com/adobe-fonts/source-sans-pro
let math-font = ("Stix Two Math", "New CM Math") //-- free: https://github.com/stipub/stixfonts
let mono-font = ("Consolas")
set text(
font: serif-fonts,
size: 11pt,
)
show heading: set text(font: sans-fonts)
// show heading: set text(font: title-font, fill: primary-color)
show heading.where(level:1): it => text(font: sans-fonts, 1.3em, it) + v(1.5em)
//-- math
show math.equation: set text(font: math-font)
/// author: laurmaedje
// set heading(numbering: "1.")
// reset counter at each chapter
show heading.where(level:1): it => {
counter(math.equation).update(0)
it
}
set math.equation(numbering: n => {
let h1 = counter(heading).get().first()
numbering("(1.1)", h1, n)
})
//-- raw font
show raw: set text(font: mono-font)
// Set link style
show link: it => text(fill: rgb("#3087b3") , it)
set list(indent: 1em)
set enum(indent: 1em)
// set page(footer: locate(
// loc => if calc.even(loc.page()) {
// align(right, counter(page).display("1"));
// } else {
// align(left, counter(page).display("1"));
// }
// ))
// show figure.caption: emph
show figure.caption: it => [
#text(font: sans-fonts)[
#it.supplement
#context it.counter.display(it.numbering). #h(0.3em)
#it.body
]
]
// show figure: set figure.caption(separator: [.#h(0.5em)])
//-- cover pages
cover(
title: title,
author: author,
graduation-year: graduation-year,
graduation-month: graduation-month,
supervisor1: supervisor1,
supervisor2: supervisor2,
coreader : coreader,
graduation-group: graduation-group,
serif-fonts: serif-fonts,
sans-fonts: sans-fonts,
)
// #show math.equation: set text(weight: 400)
show heading.where(level: 1): it => pagebreak(weak: true, to: "odd") + it
body
pagebreak()
align(bottom)[
This document was typeset using #link("https://typst.app")[Typst]. The main font is Palatino.
The figures and diagrams were mostly drawn using IPE, PGF/Ti\emph{k}z and Omnigraffle.
]
}
//-- natbib
#let citet= cite.with(form: "prose")
#let citep = cite
//-- for outline of figures
// -- TODO: DOESN'T WORK FOR SHORT FIGURE TITLES
#let in-outline = state("in-outline", false)
#show outline: it => {
in-outline.update(true)
it
in-outline.update(false)
}
#let flex-caption(long, short) = context {
if in-outline.at(here()) { long } else { short }
}
//-- default for pseudo-code/lovelace
#let my-lovelace-defaults = (
booktabs: true,
booktabs-stroke: 1pt + black,
)
#let pseudocode-list = pseudocode-list.with(..my-lovelace-defaults) |
https://github.com/dashuai009/dashuai009.github.io | https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/blog/036.typ | typst |
#let date = datetime(
year: 2022,
month: 10,
day: 2,
)
#metadata((
title: "梅森素数与完全数",
subtitle: [数论],
author: "dashuai009",
description: "什么是梅森素数,欧几里得完全数公式,$delta$函数的定义,欧拉完全数定理",
pubDate: date.display(),
))<frontmatter>
#import "../__template/style.typ": conf
#show: conf
== 引入梅森素数
<引入梅森素数>
#quote[
对于整数$a gt.eq 2 , n gt.eq 2$, 若$a^n - 1$ 是素数,则$a = 2 , n$
为素数。
]
注意反之不一定成立。
注意到,几何级数求和公式
$ a^n - 1 = (a - 1) (a^(n - 1) + a^(n - 2) + dots.h + a + 1) $
若a\>2,则$a - 1 > 1 , a - 1 \| (a^n - 1)$,与$a^n - 1$是素数冲突。
若n为合数,假设$n = m k$,由上式,
$
a^n - 1 & = (a^m)^k - 1\
& = ((a^m) - 1) ((a^m)^(k - 1) + dots.h + a^m + 1)
$
所以$a^m - 1 > 1 , a^m - 1 \| (a^n - 1)$,冲突。
得证。
#quote[
对于整数$a gt.eq 2 , n gt.eq 2$, 若$a^n + 1$ 是素数,则$n$ 为2的幂次。
]
证明类似,用到a^n+1的公式。
== 梅森素数
我们将形容如$a^p - 1$的素数称为梅森素数。
- 有无穷多个梅森素数吗?现在仍不知道
== 什么是完全数
#quote[
真因数之和等于他本身。
]
比如6=1+2+3,28=1+2+4+7+14
== 欧几里得完全数公式
#quote[
如果$2^p - 1$是素数 , 则$2^(p - 1) (2^p - 1)$是完全数
]
== $sigma$函数
=== 定义
$ sigma (n) = n 的 所 有 因 数 之 和 ( 包 括 1 和 n ) $
=== 性质
<性质>
- 如果p是素数,$k gt.eq 1$,则
$ sigma (p^k) = sum_(i = 0)^n p^i = frac(p^(k + 1) - 1, p - 1) $
- 如果$gcd (m , n) = 1$,则$sigma (m n) = sigma (n) sigma (m)$
=== 证明
瞪眼法
== 欧拉完全数定理
<欧拉完全数定理>
如果n是偶完全数,则n形如$n = 2^(p - 1) (2^p - 1)$,其中
$2^p - 1$是梅森素数。
=== 证明
<证明>
将偶数中的2都分解出来,则$n = 2^k m$,其中$k gt.eq 1$且m是奇数。则
$
sigma (n) = & sigma (2^k m)\
= & sigma (2^k) sigma (m)\
= & (2^(k + 1) - 1) sigma (m)
$
又n为完全数,则$sigma (n) = 2 n = 2^(k + 1) m$。所以,
$ 2^(k + 1) m = (2^(k + 1) - 1) sigma (m) $
即$2^(k + 1) \| (2^(k + 1) - 1) sigma (m)$,
即$2^(k + 1) \| sigma (m)$。
也就是说存在整倍数c,使得$sigma (m) = 2^(k + 1) c$。
#set math.equation(numbering: "(1)")
即 $
2^{k+1}m=(2^{k+1}-1)\\sigma(m)=(2^{k+1}-1)2^{k+1}c
$
即
$ m = (2^(k + 1) - 1) c med 且 med sigma (m) = 2^(k + 1) c $
下面,我们来证明c=1.反证法,先假设c\>1。
则m至少有三个不同的因数$1 , c , m$。
$ sigma (m) gt.eq 1 + c + m = 1 + c + (2^(k + 1) - 1) c = 1 + 2^(k + 1) c $
又由(1)得, $ 2^(k + 1) c gt.eq 1 + 2^(k + 1) c $
显然,这是荒谬的。故假设不成立,c因该等于1 。 这样,我们得知
$ m = (2^(k + 1) - 1) , 且 sigma (m) = 2^(k + 1) = 1 + m $
后半部分说明m为质数(因数只有1,m)。 所以,如果n为偶完全数,则
$ n = 2^k (2^(k + 1) - 1) , 其 中 2^(k + 1) - 1 是 素 数 。 $
。再由梅森素数的定义,原定理得证。
== 奇完全数
存在吗?现在不知。
|
|
https://github.com/LDemetrios/Conspects-4sem | https://raw.githubusercontent.com/LDemetrios/Conspects-4sem/master/typst/styles/theme.typ | typst | #import "/typst/styles/theme-dispatch.typ": *
#let decide(on, whatif) = if (on == none) { body => body } else { whatif }
#let either(..a) = if (a.pos().contains(none)) { none } else { 1 }
#let showtheme(
base: none,
fill: none,
surface: none,
high: none,
subtle: none,
overlay: none,
iris: none,
foam: none,
fnote: none,
) = body => [
#show: decide(base, (body) => { set page(fill: base); body })
#show: decide(fill, (body) => { set text(fill: fill); body })
#show:decide(subtle, (body) => { set line(stroke: subtle); body })
#show : decide(either(subtle, overlay), (body) => {
set circle(stroke: subtle, fill: overlay)
set ellipse(stroke: subtle, fill: overlay)
set path(stroke: subtle, fill: overlay)
set polygon(stroke: subtle, fill: overlay)
set rect(stroke: subtle, fill: overlay)
set square(stroke: subtle, fill: overlay)
body
})
#show : decide(high, (body) => { set highlight(fill: highlight.high); body })
#show : decide(
either(surface, high),
(body) => { set table(fill: surface, stroke: highlight.high); body },
)
#show link: decide(iris, (body) => { set text(fill: iris); body })
#show ref: decide(foam, (body) => { set text(fill: foam); body })
#show footnote: decide(fnote, (body) => { set text(fill: fnote); body })
#body
]
#let lucid(lightness) = color.mix((foreground, (255 - lightness)), (background, lightness))
#let theme-show-rule = (rest) => [
#show : showtheme(
base:background,
fill:foreground,
)
#show : decide(pagewidth, body => { set page(width:pagewidth); body } )
#show : decide(pageheight, body => { set page(height:pageheight); body } )
#rest
]
|
|
https://github.com/DrakeAxelrod/cvss.typ | https://raw.githubusercontent.com/DrakeAxelrod/cvss.typ/main/cvss/0.1.0/src/main.typ | typst | MIT License | #import "cvss.typ": score, severity, parse, metrics, verify, re, NONE, LOW, MEDIUM, HIGH, CRITICAL
|
https://github.com/The-Notebookinator/notebookinator | https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/internals.typ | typst | The Unlicense | #import "./globals.typ"
#import "./themes/themes.typ"
/// Internal function used by the template to print out all of the entries
///
/// - theme (theme):
/// -> content
#let print-entries(theme: (:)) = {
let print-helper(section, state) = context {
for entry in state.final() {
let entry-func = theme.at(section + "-entry")
entry-func(entry.body, ctx: entry.ctx)
}
}
print-helper("frontmatter", globals.frontmatter-entries)
print-helper("body", globals.entries)
print-helper("appendix", globals.appendix-entries)
}
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/game-theoryst/0.1.0/doc/gtheoryst-manual.typ | typst | Apache License 2.0 | #set page("us-letter", header: align(right)[_Manual_])
#set text(12pt)
#import "../src/lib.typ": *
#show <title>: it => {
set align(center)
set text(1.75em)
it
}
#show <author>: it => {
set align(center)
set text(1.25em)
it
}
#heading(outlined: false)[Game-Theoryst] <title>
#heading(level: 3, outlined: false)[<NAME>] <author>
#set list(indent: 1.2em, body-indent: 0.4em)
// Display inline code in a small box
// that retains the correct baseline.
#show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 2pt),
radius: 2pt,
)
// Display block code in a larger block
// with more padding.
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 5pt,
radius: 2pt,
)
#show heading.where(level: 1): it => {
set text(1.25em)
underline(offset: 4pt)[#it]
}
#show heading.where(level: 2): it => {
set text(1.25em)
underline(offset: 4pt)[#it]
}
#show heading.where(level: 3): it => {
set text(1.2em)
it
}
#show heading.where(level: 4): it => {
set text(1em)
[_ #it _]
}
#set outline(indent: 1em, depth: 3)
#show outline.entry.where(level: 2): it => {
v(12pt, weak: true)
strong(it)
}
#show link: lnk => {set text(fill: blue); underline(lnk)}
#show grid: gr => {
block(breakable: false, gr)
}
#outline()
#pagebreak()
== Overview
==== Full Example
```typ
#nfg(
players: ([A\ Joe], [Bas Pro]),
s1: ([$x$], [a]),
s2: ("x", "aaaa", [$a$]),
pad: ("x": 12pt, "y": 10pt),
eliminations: ("s11", "s21", "s22"),
ejust: (
s11: (x: (0pt, 36pt), y: (-3pt, -3.5pt)),
s22: (x: (-10pt, -12pt), y: (-10pt, 10pt)),
s21: (x: (-3pt, -9pt), y: (-10pt, 10pt)),
),
mixings: (hmix: ($p$, $1-p$), vmix: ($q$, $r$, $1-q-r$)),
custom-fills: (hp: maroon, vp: navy, hm: purple, vm: fuchsia, he: gray, ve: gray),
[$0,vul(100000000)$], [$0,1$], [$0,0$],
[$hul(1),1$], [$0, -1$], table.cell(fill: yellow.lighten(30%), [$hful(0),vful(0)$])
)
```
#nfg(
players: ([A\ Joe], [Bas Pro]),
s1: ([$x$], [a]),
s2: ("x", "aaaa", [$a$]),
pad: ("x": 12pt, "y": 10pt),
eliminations: ("s11", "s21", "s22"),
ejust: (
s11: (x: (0pt, 36pt), y: (-3pt, -3.5pt)),
s22: (x: (-10pt, -12pt), y: (-10pt, 10pt)),
s21: (x: (-3pt, -9pt), y: (-10pt, 10pt)),
),
mixings: (hmix: ($p$, $1-p$), vmix: ($q$, $r$, $1-q-r$)),
custom-fills: (hp: maroon, vp: navy, hm: purple, vm: fuchsia, he: gray, ve: gray),
[$0,vul(100000000)$], [$0,1$], [$0,0$],
[$hul(1),1$], [$0, -1$], table.cell(fill: yellow.lighten(30%), [$hful(0),vful(0)$])
)
=== Importing
#strike[Simply insert the following into your Typst code:] (_Coming soon_)
```typ
#import "@preview/game-theoryst:0.1.0": *
```
This imports the `nfg()` function as well as the underlining methods.
If you want to tweak the helper functions for generating an `nfg`, import them explicitly through the `utils/` directory. The package's repository is located at #link("https://github.com/connortwiegand/game-theoryst").
#pagebreak()
==== Example
The main function to make strategic (or *normal*) form games is `nfg`. For a basic 2x2 game, you can do
#grid(
columns: (1fr, 1fr), [
```typc
#nfg(
players: ("Jack", "Diane"),
s1: ($C$, $D$),
s2: ($C$, $D$),
[$10,10$], [$2,20$],
[$20,2$], [$5,5$],
)
```
], [
#nfg(
players: ("Jack", "Diane"),
s1: ($C$, $D$),
s2: ($C$, $D$),
[$10,10$], [$2,20$],
[$20,2$], [$5,5$],
)
])
All of `<players>`, `<s1>`, and `<s2>` have defaults for convenience sake. Payoffs (table entries) are provided via unamed arguments after all other payoff matrix options have been set.
=== Color
By default, player names, mixed-strategy parameters (called _mixings_), and elimination lines are shown in color. These colors can be turned off at the method-level by passing `bw: true`, or at the document level by running the state helper-function `#colorless()`.
`nfg` accepts custom colors for all of the aforementioned parameters by passing a `dictionary` of colors to the `custom-fills` arg. The keys for this dictionary are as follows (`<defaults>`):
- `hp` -- "horizontal player" (#text(red)[red])
- `vp` -- "vertical player" (#text(blue)[blue])
- `hm` -- "hor. mixing" (#text(rgb("#e64173"))[`#e64173`])
- `vm` -- "ver. mixing" (#text(eastern)[eastern])
- `he` -- "hor. elimination" line (#text(orange)[orange])
- `ve` -- "ver. elimination" line (#text(olive)[olive])
== Cell Customization
Since the payoffs are implemented as argument sinks (`..args`) which are passed directly to Typst's `#table()`, underlining of non-math can be accomplished via the standard `#underline()` command. Similarly, any of the payoff cells can be customized by using `table.cell()` directly. For instance, `table.cell(fill: yellow.lighten(30%), [$1,1$])` can be used to highlight a specific cell.
=== Padding
There are edge cases where the default padding may be off. These can be mended by passing the optional `pad` argument to `nfg()`. This should represent how much *_additional_* padding you want. The `pad` arg. is interpreted as follows:
- If a `length` is provided, it assumes you want that much length added to all cell walls
- If an array of the form `(L1, L2)` is provided, it assumes you want padding a horizontal (`x`) padding of `L1` and a vertical padding (`y`) of `L2`
- If a `dictionary` is provided, it operates identically to that of the array, but you must specify the `x`/`y` keys yourself
=== Automatic Cell Sizing
Cell are automatically sized to equal heights/widths according to the longest/tallest content. If you want to avoid this behavior, pass `lazy-cells: true` to `nfg`. This behavior can be combined with the custom `padding` argument.
== Semantic Game Styling
=== Underlining
The package imports a small set of underlining utility functions.
The primary functions for underlining are
- `hul()` -- _Horizontal Underline_
- `vul()` -- _Vertical Underline_
- `bul()` -- _Black Underline_
These can be wrapped around values in math-mode (`$..$`) within the payoff matrix. The underlines for `hul` and `vul` are colored by default according to the default colors for names, but they accept an optional `col` parameter for changing the color of the underline. `bul()` produces a black underline.
#grid(
columns: (1fr, 1fr), [
```typ
#nfg(
players: ("Jack", "Diane"),
s2: ($x$, $y$, $z$),
s1: ($a$, $b$),
[$hul(0),vul(0)$], [$1,1$], [$2,2$],
[$3,3$], [$4,4$], [$5,5$],
)
```
], [
#nfg(
players: ("Jack", "Diane"),
s2: ($x$, $y$, $z$),
s1: ($a$, $b$),
[$hul(0), vful(0)$], [$1,1$], [$2,2$],
[$3,3$], [$4,4$], [$5,5$],
)
])
By default, these commands leave the numbers themselves black, but boldfaces them. _Full Color_ versions of `hul` and `vul`, which color the numbers and under-lines identically, are available via `hful()` and `vful()`. Like their counterparts, they accept an optional `col` command for the color.
Both of the colors can be modified individually via the general `cul()` command, which takes in content (`cont`), an underline color (`ucol`), and the color for the text value (`tcol`). For instance,
```typ
#let new-ul(cont, col: olive, tcol: fuchsia) = { cul(cont, col, tcol) }
```
will define a new command which underlines in olive and sets the text (math) color to fuchsia.
=== Mixed Strategies
You can optionally mark mixed strategies that a player will in a `nfg` using the `mixing` argument. This can be a `dictionary` with `hmix` and `vmix` keys, or an `array`, interpreted as a dictionary with the aforementioned keys in the `(hmix, vmix)` order. The values/entries here should be arrays which mimic `s1` and `s2` in size, with some parameter denoting the proportion of time the relevant player uses that strategy. If you would like to omit a strategy from this markup, pass `[]` in it's place.
For example, in a 2x3 game, the following dictionary would add mixing parameters to both of player 1's strategies and player 2's first and third strategies:
```typ
(hmix: ($p$, $1-p$), vmix: ($q$, [], $1-q$))
```
==== Example
#grid(columns: (1fr, 1fr), [
```typ
#nfg(
players: ("Chet", "North"),
s1: ([$F$], [$G$], [$H$]),
s2: ([$X$], [$Y$]),
mixings: (
hmix: ($p$, $1-p$),
vmix: ($q$, [], $1-q$)),
[$7,3$], [$2,4$],
[$5,2$], [$6,1$],
[$6,1$], [$5,4$]
)
```
], [
#nfg(
players: ("Chet", "North"),
s1: ([$F$], [$G$], [$H$]),
s2: ([$X$], [$Y$]),
mixings: (vmix: ($q$, $1-q$), hmix: ($p$, [], $1-p$)),
[$7,3$], [$2,4$],
[$5,2$], [$6,1$],
[$6,1$], [$5,4$]
)
])
=== Iterated Deletion (Elimination) of Dominated Strategies
You can use the `pinit` package to cross out lines, semantically eliminating strategies. `pinit` comes pre-imported with `game-theoryst` by default.
```typ
#let directions = ([$N$], [$S$], [$E$], [$W$])
#let elements = ([$W$], [$E$], [$F$], [$A$])
#let domd = ("s12", "s13", "s14", "s21", "s22", "s23")
```
#let directions = ([$N$], [$S$], [$E$], [$W$])
#let elements = ([$W$], [$E$], [$F$], [$A$])
#let domd = ("s12", "s13", "s14", "s21", "s22", "s23")
#grid(columns: (2fr, 1fr), align: horizon, [
```typ
#nfg(
players: ("A", "B"),
s1: directions,
s2: elements,
eliminations: domd,
ejust:(
"s12": (x: (0pt, 10pt), y: (-3pt, -3pt)),
"s13": (x: (0pt, 10pt), y: (-3pt, -3pt)),
"s14": (x: (0pt, 10pt), y: (-3pt, -3pt)),
"s21": (x: (-6pt, -8pt), y: (3pt, 8pt)),
"s22": (x: (-4pt, -8pt), y: (3pt, 8pt)),
"s23": (x: (-4pt, -8pt), y: (3pt, 8pt)),
),
[$6,4$], [$7,3$], [$5,5$], [$6,6$],
[$7,3$], [$2,7$], [$4,6$], [$5,5$],
[$8,2$], [$6,4$], [$3,7$], [$2,8$],
[$3,7$], [$5,5$], [$4,6$], [$5,5$],
)
```
], [
#nfg(
players: ("A", "B"),
s1: directions,
s2: elements,
eliminations: domd,
ejust:(
"s12": (x: (0pt, 10pt), y: (-3pt, -3pt)),
"s13": (x: (0pt, 10pt), y: (-3pt, -3pt)),
"s14": (x: (0pt, 10pt), y: (-3pt, -3pt)),
"s21": (x: (-6pt, -8pt), y: (3pt, 8pt)),
"s22": (x: (-4pt, -8pt), y: (3pt, 8pt)),
"s23": (x: (-4pt, -8pt), y: (3pt, 8pt)),
),
[$6,4$], [$7,3$], [$5,5$], [$6,6$],
[$7,3$], [$2,7$], [$4,6$], [$5,5$],
[$8,2$], [$6,4$], [$3,7$], [$2,8$],
[$3,7$], [$5,5$], [$4,6$], [$5,5$],
)
])
You can tell `nfg` which strategies to eliminate with the `eliminations` argument and the corresponding `ejust` helper-argument. The `eliminations` argument is simply an `array` of `strings` of the form `"s<i><j>"`, where `<i>` is the player -- 1 or 2 -- and `<j>` is player `i`'s `<j>`th strategy (in left-to-right / top-to-bottom order _starting from 1_). These strategy strings represent the rows/columns which you want to eliminate. For instance, `("s12", "s21")` denotes an elimination of player 1's second strategy as well as player 2's first strategy.
Due to `context` dependence, the lines typically need manual adjustments, which can be done via the `ejust` arg. `ejust` needs to be a dictionary with keys of matching those strings present in `eliminations` (`s11`, `s21`, etc.). The values of one of these dictionary entries is itself a dictionary: one with `x` and `y` keys. Each of these keys needs an array consisting of 2 lengths, corresponding to the starting/ending `dx/dy` adjustments from `pinit-line`.
==== Example
Here is the previous game with no `ejust` options included. As you can see, even similar lines may need different adjustments.
#align(center, block(breakable: false)[
#nfg(
players: ("A", "B"),
s1: ([$N$], [$S$], [$E$], [$W$] ),
s2: ([$W$], [$E$], [$F$], [$A$]),
eliminations: ("s12", "s13", "s14", "s21", "s22", "s23"),
[$6,4$], [$7,3$], [$5,5$], [$6,6$],
[$7,3$], [$2,7$], [$4,6$], [$5,5$],
[$8,2$], [$6,4$], [$3,7$], [$2,8$],
[$3,7$], [$5,5$], [$4,6$], [$5,5$],
)
])
For example, one such `ejust` argument could be `("s12": (x: (5pt, -5pt), y: (-10pt, 3pt)))`. This says to adjust the "s12" elimination line by `5pt` in the x direction and `-10pt` in the y direction for the starting (strategy-) side of the line, and adjust by `-5pt` in x and `3pt` in y on the ending (payoff-) side of the line.
==== Pin modifications
If you would like to modify the pins and/or lines in any way, there are easy-to-follow naming conventions for the pins. The name of every pin is `<prefix-id>-s<i><j>--<start/end suffix>`.
#underline[_Prefix ID_]
To prevent confusion of `pinit-lines` across games within a document, there is a counter called `_nfg-counter` which steps every time `nfg` is called. The counter begins from 0. By default, this counter is used to define the start of every pin; if the value of `_nfg-counter` is `<c>`, then the start of the pin label is "nfg<c>-".
You may change the starting prefix of the elims within a game by passing a `string` to the `gid` argument of `nfg`. _No additional `-` will be added_. Note that the `_nfg-counter` will still incrememnt for every game in the document.
#underline[_Strategy_]
The strategy portion of the pin name is identical to the strategy being crossed out; see above for explanation.
#underline[_ Start/End Suffix_]
For the suffix, the rule is as follows:
- The starting pin -- e.g., strategy-side pin -- is labelled with the suffix `"--start"`
- The ending pin -- e.g., payoff-side pin -- is labelled with the suffix `"--end"`
For example, consider an elimination line in the 1st game within a document which eliminates player 2's 1st strategy. This `pinit-line` would connect the pins `nfg0-s21--start` with `nfg0-s22--end`.
== Debugging
If you want to see all of the lines for the table, including the ones for a players, strategies, and mixings, set the following at the top of your document.
```typ
#set table.cell(stroke: (thickness: auto))
```
Note that cells are always present for mixings, they just have 0 width/height when no mixings of a specific variety are provided.
|
https://github.com/An-314/Notes-of-Probability_and_Stochastic_Processes | https://raw.githubusercontent.com/An-314/Notes-of-Probability_and_Stochastic_Processes/main/chap2.typ | typst | #import "@local/mytemplate:1.0.0": *
#import "@preview/physica:0.9.2": *
= 离散型随机变量
== 随机变量
=== 随机变量的概念
设随机试验的样本空间为$Ω$,如果对于每一个可能的试验结果(样本点) $omega in Ω$,都唯一地存在一个实数值$X(omega)$与之对应,则称$X(omega)$为一个*随机变量*,简记为$X$。
随机变量的概念是对概率空间概念的进一步发展。它将随机实验的结果数量化,从而可以用简洁的数学语言描述繁杂的随机问题,并而提高处理相关问题的效能和效率。随机变量的引入使概率论的研究前进了一大步。
随机变量是一个函数,它的定义域是样本空间,值域是实数集。它的值是随机的,但是它的取值是有规律的。随机变量是对随机现象的数量化描述。
设$X$是一个离散型随机变量,它可能取到的值为$x_1, x_2, dots $(有限个或可数个),称
$
p_k = P({omega in Ω | X(omega) = x_k}) = P(X = x_k), k = 1, 2, dots
$
为$X$的*概率分布律*,简称为*分布律*。
分布律满足下列性质:
- $p_k >= 0, k = 1, 2, dots$
- $sum p_k = 1$
=== 常见的离散型随机变量
==== 两点分布(Bernoulli分布)
设随机变量$X$的分布律为
$
P(X = 0) = p, P(X = 1) = 1 - p
$
其中$0 < p < 1$,则称$X$服从参数为$p$的*两点分布*,记为$X ~ B(1, p)$。
Bernoulli试验:只有两种可能结果的随机试验称为*Bernoulli试验*。
==== 二项分布
二项分布的概率分布律为
$
P(X = k) = binom(n, k) p^k (1 - p)^(n - k), k = 0, 1, dots, n
$
其中$0 < p < 1$,则称$X$服从参数为$n, p$的*二项分布*,记为$X ~ B(n, p)$。
$n$重Bernoulli试验中事件$A$发生的次数为$X$,则$X$服从二项分布。
直接计算$P(X = k)$非常复杂,下面考虑一种极端情况:
当$n$充分大,$p$充分小时二项分布的近似公式。
*Poisson定理*:设$lambda > 0$为给定常数,$n$为任意正整数,$p_n = lambda / n$,则对任意固定的非负整数$k$,有
$
lim_(n -> ∞) binom(n, k) p_n^k (1 - p_n)^(n - k) = (e^(-lambda) lambda^k )/ k!
$
注:这里有一个重要假定,即$n times p_n = λ$为常数。它可以理解成:一段时间内的独立重复试验可以发生无穷次,但出现某一特定结果的平均次数是确定的。上面近似公式的右端项,给出了非常重要的泊松分布!
==== 泊松分布
设随机变量$X$的分布律为
$
P(X = k) = (e^(-lambda) lambda^k) / k!, k = 0, 1, 2, dots
$
其中$lambda > 0$,则称$X$服从参数为$lambda$的*泊松分布*,记为$X ~ "Po"(lambda)$。
根据Poisson定理,Poisson分布可以描绘成大量试验$n -> oo$中稀有事件$p -> 0$出现$k$次的概率分布的数学模型。由Poisson分布引起的Poisson信号流是随机过程的一个重要分支。
设$X ~ "Po"(lambda)$,使得$P(X = k)$取到最大值的$k$称作$X$的*最大可能出现次数*。
- 当$lambda$为正整数时,$P(X = lambda) = P(X = lambda - 1)$取到最大值,此时$X$的最大可能出现次数为$lambda$和$lambda - 1$。
- 当$lambda$为非整数时,$P(X = [lambda])$取到最大值,此时$X$的最大可能出现次数为$[lambda]$。
==== 几何分布
设随机变量$X$的分布律为
$
P(X = k) = (1 - p)^(k - 1) p, k = 1, 2, dots
$
其中$0 < p < 1$,则称$X$服从参数为$p$的*几何分布*,记为$X ~ "Ge"(p)$。
几何分布描述的是在Bernoulli试验中,第一次成功所需的试验次数。相当于连续独立的投掷一面不规则硬币,直到出现正面时停止。
上例中,如果我们已经投掷n次,且始终背面朝上,则有
$
P(X = k + n | X > n) = P(X = k), k = 1, 2, dots
$
这是几何分布一个极其特殊的性质:*无记忆性*。它表示未来发生的事情与过去无关。
*定理:*设$X$为取正整数值的随机变量,则下列命题等价:
- $X$服从几何分布
- $P(X > k + n | X > n) = P(X > k), k = 0, 1, 2, dots$
- $P(X = k + n | X > n) = P(X = k), k = 1, 2, dots$
上面的定理不仅说明了*几何分布具有无记忆性*;也说明这一性质是几何分布所特有的。
_证明:_
- $(1) => (2)$:$P(X > k + n | X > n) = P(X > k + n, X > n) / P(X > n) = q^k = P(X > k)$
- $(2) => (3)$:_显然_
- $(3) => (1)$:_递推即可_
==== 超几何分布
设随机变量$X$的分布律为
$
P(X = k) = (binom(m, k) binom(n - m, s - k)) / binom(n, s), k = max(0, s - n + m), ...,min(m, s)
$
其中$0 <= m <= n, 0 <= s <= n$,则称$X$服从参数为$n, m, s$的*超几何分布*,记为$X ~ "Sg"(n, m, s)$。
*二项分布可以看做是有放回的抽样,而超几何分布则可看成是无放回的抽样。*
$n -> oo$时,$m/n -> p$,则从中抽取$s$个元素,其中$m$个元素的概率分布趋近于二项分布:
$
(binom(m, k) binom(n - m, s - k)) / binom(n, s) -> binom(s, k) p^k (1 - p)^(s - k)
$
== 数学期望和方差
=== 数学期望
设离散型随机变量$X$的分布律为
$
P(X = x_k) = p_k, k = 1, 2, dots
$
若级数
$
E(X) = sum x_k p_k
$
绝对收敛#footnote[定义中的绝对收敛是对X可以取到无穷可数个值而言的,
它保证级数的收敛性与项的顺序无关。],则称级数$E(X)$收敛,称$E(X)$为$X$的*数学期望*,简称*期望*。数学期望就是(加权)平均值,在统计学中也称为均值。
==== 常见离散型随机变量的数学期望
*两点分布的期望:*
$
E(X) = 1 times p + 0 times (1 - p) = p
$
#newpara()
*二项分布的期望:*
$
E(X) = sum_(k = 0)^n k binom(n, k) p^k (1 - p)^(n - k) = sum_(k = 1)^n n binom(n - 1, k - 1) p^k (1 - p)^(n - k) =^("显然") n p
$
#newpara()
*泊松分布的期望:*
$
E(X) = sum_(k = 0)^∞ k (e^(-lambda) lambda^k) / k! = lambda e^(-lambda) sum_(k = 1)^∞ lambda^(k - 1) / (k - 1)! = lambda e^(-lambda) e^lambda = lambda
$
#newpara()
*几何分布的期望:*
$
E(X) &= sum_(k = 1)^∞ k (1 - p)^(k - 1) p = p (1-p)^(-1) sum_(k = 1)^∞ sum_(l = 1)^(k) q^k \
&= p (1 - p)^(-1) sum_(l = 1)^∞ sum_(k = l)^∞ q^k \
&= 1 / p
$
#newpara()
*超几何分布的期望:*
$
E(X) = sum_(k = max(0, s - n + m))^min(m, s) k (binom(m, k) binom(n - m, s - k)) / binom(n, s) = (s m) / n sum_(k = 1)^min(m, s) (binom(m-1, k-1) binom(n - m, s - k)) / binom(n-1, s-1) = (s m) / n
$
#newpara()
==== 与函数复合的数学期望
设离散型随机变量$X$的分布律为$P(X = x_k) = p_k; k = 1, 2, ... $,考虑函数$phi : {x_1, x_2, · · · } -> RR$,即它是定义域包含$X$的取值范围的一个实函数。因此$Y = φ(X)$也是一个随机变量,它的分布律由$X$的分布律完全确定
$
P({omega in Omega | phi(X(omega)) = y}) = sum_(k: phi(x_k) = y) p_k, y in {phi(x_1), phi(x_2), · · · }
$
若$sum_k phi(x_k) p_k$绝对收敛,则称$E(φ(X)) = sum_k phi(x_k) p_k$为$φ(X)$的数学期望。
==== 矩
$n$阶原点矩和$n$阶中心矩:
$
E(X^n) &= sum x_k^n p_k\
E(X - E(X))^n &= sum (x_k - E(X))^n p_k
$
#newpara()
有Vandermode等式:
$
mat(
1, 1, 1, dots, 1 ;
x_1, x_2, x_3, dots, x_n ;
x_1^2, x_2^2, x_3^2, dots, x_n^2 ;
dots ;
x_1^(n - 1), x_2^(n - 1), x_3^(n - 1), dots, x_n^(n - 1)
)
mat(
p_1;
p_2;
p_3;
dots;
p_n
)
=
mat(
1;
E(X);
E(X^2);
dots;
E(X^(n - 1))
)
$
事实上前$n$阶矩和概率分布律是一一对应的。
=== 数学期望的性质
设$X, Y$是两个随机变量,若$E(X), E(Y)$存在,则有
- $|E(X)| <= E(|X|)$
- 对实数$a < b$,若$a <= X <= b$,则$a <= E(X) <= b$
- 若$X <= Y$,则$E(X) <= E(Y)$
- 对实数$a, b$,有$E(a X + b Y) = a E(X) + b E(Y)$
- 若$X,Y$相互独立,则$E(X Y) = E(X) E(Y)$
- 【Schwarz不等式】$|E(X Y)|^2 <= E(X^2) E(Y^2)$
这些证明都是显然的,只需要用定义写出即可。
这就意味着:可以将随机变量$X$分解成若干个随机变量(这些随机变量是否独立和相关,并不重要)之和,通过求这若干个随机变量的期望而求得$X$的期望。
这样我们可以重新计算二项分布的期望:
$
E(X) = E(sum_(i = 1)^n X_i) = sum_(i = 1)^n E(X_i) = n p
$
事实上,对于样本空间Ω中的随机事件A,我们可以定义相应的*示性函数*$I_A: Ω -> {0, 1}$:
$
I_A(omega) = cases(
1 quad &omega in A ,
0 quad &omega in.not A
)
$
则$I_A$是一个随机变量,且$E(I_A) = P(A)$。这意味着:*事件的概率都可以写成它的示性函数的数学期望*。换句话说,数学期望是概率的一种推广。
=== 方差及其性质
考虑离散型随机变量$X$,若$E((X - E(X))^2)$存在,则称$E((X - E(X))^2)$为$X$的*方差*,记为$D(X)$或$"Var"(X)$:
$
D(X) = E((X - E(X))^2) = E(X^2) - (E(X))^2
$
方差刻画了$X$的分散程度,因为X越分散,用一个实数去代表它的误差就越大。
==== 方差的性质
*平均平方误差*:任取$a in RR$,我们有
$
E((X - a)^2) &= E(((X - E(X)) + (E(X) - a))^2) \
&= E((X - E(X))^2) + 2(E(X) - a) E(X - E(X)) + (E(X) - a)^2 \
&= D(X) + (E(X) - a)^2 >= D(X)
$
上式表明,若用一个实数去表示一个随机变量$X$, 数学期望$E(X)$表示使平均平方误差最小的实数,而最小的平均平方误差就是方差$D(X)$。
*两个随机变量的方差*:考虑离散型随机变量$X,Y$,若$D(X), D(Y)$存在,则有
- 对实数$a, b$,有$D(a X + b) = a^2 D(X)$
- 若$X,Y$相互独立,则$D(X + Y) = D(X) + D(Y)$
- $D(X) = 0$当且仅当$P(X = E(X)) = 1$,即$X$几乎必然是一个常数
前两个证明显然,第三个的必要性考虑一定有正部分即可。
==== 常见离散型随机变量的方差
*二项分布的方差:*
$
D(X) = E(X^2) - (E(X))^2 = n p (1 - p)
$
#newpara()
*泊松分布的方差:*
$
D(X) = E(X^2) - (E(X))^2 = lambda
$
==== Chebyshev不等式
*Chebyshev不等式*:设$X$是一个随机变量,$E(X)$和$D(X)$存在,则对任意实数$epsilon > 0$,有
$
P(|X - E(X)| >= epsilon) <= D(X) / epsilon^2
$
_证明:_
记离散型随机变量$X$可能取到的值为${x_i}$他们相应的概率为${p_i}$。为简化,我们记
$
Lambda = {x_i}, macron(x) = E(X), Gamma = { i | x_i in Lambda, |x_i - macron(x)| >= epsilon }
$
从而
$
P(|X - E(X)| >= epsilon) = sum_(i in Gamma) p_i <= sum_(i in Gamma) p_i (x_i - macron(x))^2 / epsilon^2 <= sum_(i in Lambda) p_i (x_i - macron(x))^2 / epsilon^2 = D(X) / epsilon^2
$
Chebyshev不等式说明了一个随机变量$X$远离期望$E(X)$的概率被方差$D(X)$的大小和距离$epsilon$的大小所控制。这是一个比较松的不等式。
== 条件分布
=== 随机变量的条件分布
给定样本空间$Ω$,考虑定义在其上的离散型随机变量$X,Y$,则称$vec(X,Y)$为*2维离散型随机向量*。进一步的,若$vec(X,Y)$可能的取值为$vec(x_i,y_j)$,则称
$
p_(i j) = P(X = x_i, Y = y_j)
$
为$vec(X,Y)$的*联合分布律*,简称分布律。我们称
$
P(X = x_i) = sum_(j) p_(i j), P(Y = y_j) = sum_(i) p_(i j)
$
为$X,Y$的*边缘分布律*。进一步的,我们可以定义$X$关于$Y = y_j$的*条件分布律*为
$
P(X = x_i | Y = y_j) = P(X = x_i | Y = y_j) / P(Y = y_j)
$
这里$P(Y = y_j) > 0$。这个条件分布律的物理意义是:在给定$Y = y_j$的条件下,$X$的取值概率。而$Y$关于$X = x_i$的条件分布律为
$
P(Y = y_j | X = x_i) = P(X = x_i | Y = y_j) / P(X = x_i)
$
=== Markov链
考虑离散型随机变量序列${X_n}_(n = 1)^oo, X_n in S$,其中$S$是一个有限或者可数集(称为此*Markov链的状态空间*)。若对任意$i_1, ...,i_n,i,j$,有
$
P(X_(n + 1) = j | X_1 = i_1, ..., X_(n-1) = i_(n-1), X_n = i) = P(X_(n + 1) = j | X_n = i)
$
则称其为*Markov序列(或Markov链)*,其条件概率
$
hat(p)_(i j) (n)= P(X_(n + 1) = j | X_n = i)
$
称为*转移概率*。若$hat(p)_(i j) (n)$与$n$无关,称此Markov链为*时间齐次*的。
*Markov链的性质是:未来的状态只与当前状态有关,而与过去的状态无关。* 如果过程在$n$时刻处于状态$i$,那么不管它以前处于什么状态,它在$n + 1$时刻处于状态$j$的条件概率都是$hat(p)_(i j) (n)$。换句话说,在已知“现在”的条件下,“将来”与“过去”无关。
对于时间齐次的Markov链,我们可以将转移概率写成矩阵形式
$
PP = mat(
hat(p)_(1 1), hat(p)_(1 2), dots, hat(p)_(1 s) ;
hat(p)_(2 1), hat(p)_(2 2), dots, hat(p)_(2 s) ;
dots ;
hat(p)_(s 1), hat(p)_(s 2), dots, hat(p)_(s s)
)
$
称为*转移概率矩阵*,是一个$|S| times |S|$的矩阵。
_例如:将一枚均匀硬币投掷无穷次,记$X_n$为前$n$次投掷中正面出现的次数,易见_
$
P(X_(n + 1) = j | X_n = i) = cases(
1/2 quad &j = i + 1 ,
1/2 quad &j = i ,
0 quad &"others"
)
$
_这就是一个Markov链。对应的转移概率矩阵为_
$
PP = mat(
1/2, 1/2, 0, , ;
0, 1/2, 1/2, 0 ,;
"", 0, 1/2, 1/2, 0 ;
"", "", dots.down, dots.down, dots.down ,dots.down;
)
$
_Google搜索引擎的核心技术是通过PageRank对多达30亿个网页进行重要性分析。PageRank利用网络链接结构对网页进行组织管理,原理是,如果网页A链接到网页B,Google就认为“网页A投网页B一票”。_
_考虑Google数据库中网页全体组成的集合为$S$(状态空间) ,其元素个数为$n ∼ 10^10$。定义一个$n$阶矩阵$G$:如果从页面$i$到页面$j$有超链接,则$g_(i j) = 1$,否则为$0$。易见$G$是巨大的且非常稀疏的矩阵。令_
$
c_j = sum_i g_(i j), r_i = sum_j g_(i j)
$
_分别给出每个页面链入和链出的数目。由此给出Markov链的转移概率矩阵$PP = (hat(p)_(i j))$:第一项表示用户链接到其它网页是等可能的(其概率为$0.85/r_i$);第二项表示用户有可能不选择网页提供的链接方案(其概率为$0.15/n$)_
$
hat(p)_(i j) = tau g_(i j) / r_i + delta, delta = (1 - tau)/n
$
_其中$PP$的最大特征值为1,对应的特征向量即为PageRank_
$
pi PP = pi, sum_i pi_i = 1
$
_这里$π$就是*Markov链的平稳分布*。因此,计算PageRank的问题,本质上是大规模矩阵特征值问题。_
=== 随机变量的独立性
称离散型随机变量$X$和$Y$是相互独立的,如果
$
P(X = x_i, Y = y_j) = P(X = x_i) P(Y = y_j) , i,j = 1, 2, dots
$
由定义,若$X,Y$相互独立,则有
$
P(X = x_i | Y = y_j) = P(X = x_i)\
P(Y = y_j | X = x_i) = P(Y = y_j)
$
*一个随机向量的联合分布唯一的确定了作为其分量的随机变量的边缘分布。*但是,仅有边缘分布的信息对于确定他们的联合分布是不够的。*只有在独立性假设下,才可以由边缘分布唯一确定其联合分布。*
若离散型随机变量$X,Y$相互独立,且$E(X),E(Y)$存在,则$E(X Y) = E(X)E(Y)$。若$X,Y$相互独立,且$D(X),D(Y)$存在,则$D(X + Y) = D(X) + D(Y)$。
_证明:_
$
E(X Y) = sum_(i,j) x_i y_j p_(i j) = sum_(i,j) x_i y_j p_i p_j = sum_i x_i p_i sum_j y_j p_j = E(X) E(Y)
$
$
D(X + Y) &= E((X + Y) - (E(X + Y))^2) = E(((X - E(X)) + (Y - E(Y)))^2) \
&= E((X - E(X))^2) + 2 E((X - E(X))(Y - E(Y))) + E((Y - E(Y))^2) \
&= #text(fill:red)[$D(X) + D(Y) + 2 E((X - E(X))(Y - E(Y)))$] \
&= D(X) + D(Y) + 2 E(X Y) - 2 E(X) E(Y) = D(X) + D(Y)
$
#newpara()
如果$X$和$Y$是相互独立的整数值随机变量,其分布为
$
P(X = i) = p_i, P(Y = j) = q_j; i,j = 0 plus.minus 1, plus.minus 2, dots
$
则$X + Y$的分布为
$
P(X + Y = k) = sum_(i = -oo)^oo p_i q_(k - i)
$
此分布称为$X$的分布律与$Y$的分布律的*卷积*。
设$X_i$为离散型随机变量,如果对于$X_k$任意的可能取值$x_k$,都有
$
P(X_1 = x_1, X_2 = x_2, dots, X_n = x_n) = P(X_1 = x_1) P(X_2 = x_2) dots P(X_n = x_n)
$
则称$X_1, X_2, dots, X_n$是*相互独立*的。我们称随机变量序列${X_n, n>=1}$为相互独立的,如果对任意的$n$有$X_1, X_2, ... , X_n$相互独立。
一些性质:
- 相互独立的随机变量$X_1, X_2, ... , X_n$的任一部分随机变量$X_(j_1), X_(j_2), ... , X_(j_k)$也是相互独立的。
- 若$X_1, X_2, dots, X_n$相互独立,而
$
Y_1 = g_1(X_1, X_2, dots, X_k), Y_2 = g_2(X_(k+1), X_(k+2), dots, X_n)
$
则$Y_1, Y_2$也是相互独立的。
若离散型随机变量$X, Y$的取值均为${a_i}$,且对任意的$i$
$
P(X = a_i) = P(Y = a_i)
$
则称$X$和$Y$是*同分布*的。
如果${X_n, n ≥ 1}$是一个独立的随机变量序列,并且他们是同分布的,则称${X_n, n ≥ 1}$是一个*独立同分布的随机变量序列*,简记为i.i.d(independent and identically distributed)。
=== 协方差和相关系数
设$X,Y$是两个随机变量,有
$
D(X + Y) = D(X) + D(Y) + 2 E((X - E(X))(Y - E(Y)))
$
如果$X, Y$独立,则最后一项为$0$; 如果$X, Y$不独立,则最后一项在一定程度上刻画了$X, Y$的相关性。
设$vec(X,Y)$是一个二维随机向量,若$E((X - E(X))(Y - E(Y)))$存在,则称
$
"Cov"(X,Y) = E((X - E(X))(Y - E(Y)))
$
为$X,Y$的*协方差*。若$D(X)D(Y)!=0$,则称
$
rho_(X Y) = "Cov"(X,Y) / sqrt(D(X) D(Y))
$
为$X,Y$的*相关系数*。
有
$
"Cov"(X,X) = D(X), rho_(X X) = 1
$
#newpara()
*协方差具有如下性质:*
- $"Cov"(X,Y) = E(X Y) - E(X) E(Y)$
- $"Cov"(X,Y) = "Cov"(Y,X)$
- $"Cov"(a_1 X_1 + b_1, a_2 X_2 + b_2) = a_1 a_2 "Cov"(X_1,X_2)$
- $"Cov"(a_1 X_1 + a_2 X_2, Y) = a_1 "Cov"(X_1,Y) + a_2 "Cov"(X_2,Y)$
- $|"Cov"(X,Y)|^2 <=D(X) D(Y)$【Schwarz不等式】
- 若$X,Y$相互独立,则$"Cov"(X,Y) = 0$
*相关系数具有如下性质:*
- $-1 <= rho_(X Y) <= 1$
- $rho_(X Y) = 1$当且仅当$X$和$Y$以概率为$1$线性相关,即
$
P(Y = a X + b) = 1
$
其中$a,b$是常数,且$a != 0$
当$a_(X Y) != 0$时,根据其符号是正或负,分别称$X, Y$具有*正相关或负相关*。
*用随机变量逼近随机变量:*
方差:$D(X)$, 如果用一个实数$b in RR$去逼近随机变量$X$,数学期望$E(X)$表示使平均平方误差最小的实数,而这个最小的平均平方误差就是方差$D(X)$。
$
E((X - b)^2) >= E((X - E(X))^2) = D(X)
$
基于上述思路,我们希望引入一个新的随机变量$Y$,用它的线性函数$a Y + b$,去逼近随机变量$X$,使其平均平方误差最小。
下证:
$
E((X - (hat(a) Y + hat(b)))^2) = min_(a,b) E((X - a Y - b)^2) = D(X)(1 - rho_(X Y)^2)
$
其中$hat(a) = rho_(X Y) sqrt(D(X) /D(Y)), hat(b) = E(X) - hat(a) E(Y)$。
_证明:_
$
E((X - a Y - b)^2) &= E(((X - E(X)) - a(Y - E(Y)) + (E(X) - a E(Y) - b))^2) \
&= D(X)+ a^2 D(Y) + (E(X) - a E(Y) - b)^2 - 2 a E((X - E(X))(Y - E(Y))) \
&= D(X) + a^2 D(Y) + (E(X) - a E(Y) - b)^2 - 2 a "Cov"(X,Y) \
&>= D(X) + a^2 D(Y) - 2 a "Cov"(X,Y) \
""^("关于a的二次函数") &>=D(X) - "Cov"(X,Y)^2 / D(Y) = D(X)(1 - rho_(X Y)^2)
$
等号成立的条件为$a = rho_(X Y) sqrt(D(X) /D(Y))$与$b = E(X) - a E(Y)$。
该定理说明相关系数$ρ_(X Y)$刻画了$X, Y$之间的线性相关关系。如果$ρ_(X Y) = 0$,即$hat(a) = 0$,用$Y$去近似$X$的最佳情形是只用常数,而与$Y$无关。此时称$X$与$Y$线性不相关,简称*不相关*。
如果$ρ_(X Y)$越大,用随机变量$Y$的线性函数去近似随机变量X的最佳近似的均方误差越小。 当 $ρ_(X Y) = 1$时,以概率1,随机变量$X$是随机变量$Y$的线性函数。上述性质正是将$ρ_(X Y)$称为$X$与$Y$的*线性相关系数*的原因,即相关系数是刻画$X$和$Y$的线性相关程度的数字特征。
*独立一定不相关,但不相关不一定独立。*独立性是更强的条件。
如果随机变量$X$是有度量的单位,例如米,那么方差$D(X)$的单位就是平方米,而标准差$σ_X = sqrt(D(X))$与$X$具有同样的度量单位米。为了使随机偏差摆脱度量单位的影响,我们给出随机变量$X$的*标准化*
$
X^* = (X - E(X)) / σ_X
$
这样
$
E(X^*) = 0, D(X^*) = 1, "Cov"(X^*,Y^*) = rho_(X^* Y^*)
$
#newpara()
*一个恒等式:*设${X_i}$为$n$维随机向量,则
$
D(sum_(i = 1)^n X_i) = sum_(i = 1)^n D(X_i) + 2 sum_(i < j) "Cov"(X_i, X_j)
$
证明是显然的。
设$X,Y$是随机变量,则有:
- 若$E(X^n)$存在,则称为$X$的$n$阶*原点矩*
- 若$E((X - E(X))^n)$存在,则称为$X$的$n$阶*中心矩*
- 若$E(X^n Y^m)$存在,则称为$X,Y$的$n+m$阶*混合矩*
- 若$E((X - E(X))^n (Y - E(Y))^m)$存在,则称为$X,Y$的$n+m$阶*中心混合矩*
期望$E(X),E(Y)$是一阶原点矩,方差$D(X),D(Y)$是二阶中心矩,协方差$"cov"(X, Y)$是二阶中心混合矩。
随机变量可以是无穷维的,但是矩一般只考虑有限个。用有限的信息(矩)去刻画无穷维的随机变量,这是非常有价值的事情。
*协方差矩阵:*设$vec(X)$是一个$n$维随机向量,其分量为$X_1, X_2, ... , X_n$,则称
$
Sigma = mat(
"Cov"(X_1, X_1), "Cov"(X_1, X_2), dots, "Cov"(X_1, X_n) ;
"Cov"(X_2, X_1), "Cov"(X_2, X_2), dots, "Cov"(X_2, X_n) ;
dots ;
"Cov"(X_n, X_1), "Cov"(X_n, X_2), dots, "Cov"(X_n, X_n)
)
$
为$vec(X)$的*协方差矩阵*。协方差矩阵是一个对称矩阵,且对角线上的元素是各个随机变量的反差,非对角线上的元素是各个随机变量之间的协方差。
有这样的性质:
- $Sigma$是对称的
- $sigma_(i j)^2 <= sigma_(i i) sigma_(j j)$
- $Sigma$是非负定的,即对任意非零向量$bold(a)$,有$bold(a)^T Sigma bold(a) >= 0$
_证明:_
$
bold(a)^T Sigma bold(a) = sum_(i,j) a_i a_j "Cov"(X_i, X_j) = "Cov"(sum_i a_i X_i, sum_j a_j X_j) >= 0
$
=== 分布的熵
Shannon引进熵的概念作为刻画一个离散分布或一个离散随机变量的不确定性的指标。熵是目前信息科学中最重要的概念之一。
离散分布$bold(p)(X = x_i) = p_i, i = 1, 2, ... , n$的熵定义为
$
H(bold(p)) = - sum p_i log p_i
$
再定义分布$bold(p)$关于分布$bold(q)$的*Kullback-Leibler相对熵*为
$
h(bold(p), bold(q)) = sum p_i log (p_i / q_i)
$
这个相对熵刻画了两个分布之间的差异。
相对熵$h(bold(p), bold(q))$是非负的,当且仅当$bold(p) = bold(q)$时取到最小值$0$。这个性质是由Jensen不等式保证的。
相对熵在相当程度上表达了$bold(p)$和$bold(q)$的差别,当$p_i$和$q_i$都接近时,显然$h(bold(p), bold(q))$会小,因此可以看成$bold(p)$和$bold(q)$之间的准距离。#footnote[它不满足对称性,也不满足三角不等式,因此不是数学中的距离。]
*有限个值的分布的熵:*分布$bold(p)$的熵满足
$
H(bold(p)) = - sum p_i log p_i <= log N
$
其中$N$是分布$bold(p)$可能取到的值的个数。等号成立当且仅当$bold(p)^* = (1/N, 1/N, ... , 1/N)$,即所有可能取到的值的概率相等时。
*数学期望固定条件下的最大熵:*假设存在实数$alpha$,使得$x_i >= alpha$。对于固定的$(x_i)$和$mu$,在满足
$
P(xi = x_i)= p_i, E(X) = mu
$
的条件下,熵$H(bold(p))$的最大的分布为
$
p_i^* = C e^(-lambda x_i), C = 1 / (sum e^(-lambda x_i))
$
其中$lambda$满足
$
mu sum e^(-lambda x_i) = sum x_i e^(-lambda x_i)
$
这个最大熵是
$
H(bold(p)^*) = lambda mu - log C
$
=== 条件数学期望
设$X,Y$是两个随机变量,定义$E(X|Y=y)$是在$Y=y$的条件下$X$的数学期望,定义为
$
E(X|Y=y) = sum x_i P_(X|Y)(x_i|y)
$
$E(X|Y=y)$可以看作关于$y$的函数。记作$phi(y)$,则随机变量$phi(Y(omega))$是一个随机变量,称为$X$关于$Y$的*条件数学期望*,记作$E(X|Y)$。
$X$对$Y$的条件数学期望$E(X|Y)$是随机变量$Y$的一个函数,因此$E(X|Y)$是随机变量。
*全期望公式:*对随机变量$X,Y$,若$E(X)$存在,并且$P(Y = y_j) > 0$,则有
$
E(X) = E(E(X|Y)) = sum E(X|Y = y_j) P(Y = y_j)
$
_证明:_
$
E(E(X|Y)) &= E(phi(Y)) = sum phi(y_j) P(Y = y_j) \
&= sum E(X|Y = y_j) P(Y = y_j)\
&= sum sum x_i P_(X|Y)(x_i|y_j) P(Y = y_j) \
&= sum sum x_i P(X = x_i, Y = y_j)\
&= sum x_i P(X = x_i) = E(X)
$
由于数学期望可以看作是概率的推广,全期望公式也可以看作是全概率公式的推广。
*平均平方误差估计:*对随机变量$X,Y$,若$E(X^2),E(Y^2)$均存在,则有
$
E((X - E(X|Y))^2) min_phi E((X - phi(Y))^2)
$
_证明:_
由于$E(X|Y)$是关于随机变量$Y$的函数,不妨记其为$g(Y)$,则有
$
cal(J) = E((X - g(Y))^2) = E(X-g(Y))^2 = E(E((X-g(Y))^2|Y))
$
上式最后一步利用了全期望公式。这里的$E((X-g(Y))^2|Y)$是关于$Y$的函数,记作$h(Y)$,则有
$
cal(J) = E(h(Y)) = sum h(y_j) P(Y = y_j) = sum E((X-g(Y))^2|Y = y_j) P(Y = y_j)
$
对于任意函数$phi$有
$
E((X - phi(Y))^2|Y=y_j) =& E((X - g(Y) + g(Y) - phi(Y))^2|Y=y_j) \
=& E((X - g(Y))^2|Y=y_j) + 2 E((X - g(Y))(g(Y) - phi(Y))|Y=y_j) \
&+ E((g(Y) - phi(Y))^2|Y=y_j) \
=& E((X - g(Y))^2|Y=y_j) + (g(y_j) - phi(y_j))^2 + 2 (g(y_j)\
&- phi(y_j)) E((X - g(Y))|Y=y_j)\
=& E((X - g(Y))^2|Y=y_j) + (g(y_j) - phi(y_j))^2\
>=& E((X - g(Y))^2|Y=y_j)
$
上式最后一步利用了$E((X - g(Y))|Y=y_j) = 0$。因此
$
cal(J) &= E((X - g(Y))^2) \
&= E(E((X - g(Y))^2|Y)) \
&= sum E((X - g(Y))^2|Y = y_j) P(Y = y_j) \
&<= sum E((X - phi(Y))^2|Y = y_j) P(Y = y_j)\
&= E((X - phi(Y))^2)
$
在用可观测的$Y$去估计$X$时,条件期望$E(X|Y)$是所有估计中最佳的。
*条件期望的性质:*若随机变量$E(X|Y)$存在,则它满足以下性质:
- 若$a <= X <= b$,则$a <= E(X|Y) <= b$
- 若$E(X_1|Y)$和$E(X_2|Y)$均存在,则$E(a_1 X_1 + a_2 X_2|Y) = a_1 E(X_1|Y) + a_2 E(X_2|Y)$
- 若$X$和$Y$相互独立,则$E(X|Y) = E(X)$
- 设$(X,Y)$是一个二维随机向量,$g,h$是两个实函数,则$E(g(X)h(Y)|Y) = h(Y)E(g(X)|Y)$
- 若$Phi$是定义在${y_1, y_2, ... , y_n, ...}$上的函数,则$Phi(Y) = E(X|Y)$当且仅当对任意定义在${y_1, y_2, ... , y_n, ...}$上的函数$phi$,有$E((X - Phi(Y))phi(Y)) = 0$
= 随机徘徊、泊松过程
== 随机徘徊
不停的投掷一枚硬币,其正面朝上的概率为$p$。现有一个粒子,初始位置为0,根据投掷结果在直线上移动:如投正面,粒子向右走1步;如投反面,粒子向左走1步。
根据上述描述,我们可以给出这个试验的样本空间
$
Omega = {bold(omega) = (omega_1, omega_2, ... , omega_n, ...)}
$
我们还可以给出相应的概率空间$(Omega, cal(F), P)$。由此,我们定义随机变量的序列
$
Y_n(bold(omega)) = omega_n\
Z_n(bold(omega)) = 2 Y_n(bold(omega)) - 1\
X_n(bold(omega)) = sum_(i = 1)^n Z_i(bold(omega)) + X_0
$
其中$Y_n$表示第$n$次投掷的结果,$Z_n$表示第$n$次投掷的结果对应的粒子移动的方向,$X_n$表示第$n$次投掷后粒子的位置。
这样的独立同分布随机序列${Z_n,n ≥ 1}$称为Bernoulli序列,它是一个最简单的随机过程。
*状态空间:*$S_z = {-1, 1},S_x = ZZ$。称每一个固定的$bold(omega) = (omega_1, omega_2, ... , omega_n, ...)$为一个*样本轨道*。
下面导出$X$的有限个随机变量的联合分布律。设$X_0 = 0$,则有
$
P(X_n = s) = cases(
binom(n, (n + s) / 2) p^((n + s) / 2) (1 - p)^((n - s) / 2) quad &n>=|s| n+s"为偶数",
0 quad &"others"
)
$
再讨论$(X_n, X_m)$的联合分布,这里$m > n$,则有
$
P(X_n = i, X_m = j) &= P(X_n = i, X_m - X_n = j - i) = P(sum_(i = 1)^n Z_i = i, sum_(i = n+1)^m Z_i = j - i)\
&= P(sum_(i = 1)^n Z_i = i) P(sum_(i = n+1)^m Z_i = j - i)\
&= binom(n, (n + i) / 2) p^((n + i) / 2) (1 - p)^((n - i) / 2) binom(m - n, (m - n + j - i) / 2) p^((m - n + j - i) / 2) (1 - p)^((m - n - j + i) / 2)
$
面是多个时刻$(X_(n_1), X_(n_2), ... , X_(n_k) n_1 < n_2 < ... < n_k$的联合分布,则有
$
P(X_(n_1) = i_1, X_(n_2) = i_2, ... , X_(n_k) = i_k) &= product_(j = 1)^k P(X_(n_j) = i_j | X_(n_(j-1)) = i_(j-1))\
$
可以计算出$X_n$的数学期望和方差
$
E(X_n) = 2 n p - n\
D(X_n) = 4 n p (1 - p)
$
最后计算$(X_n, X_m)$的协方差
$
"Cov"(X_n, X_m) = 2 min(n, m) p (1 - p)
$
#newpara()
*带吸收壁的随机徘徊*: 考虑粒子从0出发,走到$a$或$-b$处则结束$(a, b > 0)$,问粒子走到$a$处或$-b$处的概率分别有多大。
*首次到达问题*:考虑粒子从0出发,记
$
T_(0a) = min{t >= 0 | X_0 = 0,X_t = a}
$
表示首次到达$a$的时刻。如果
$
{t>=0|X_0 = 0, X_t = b} = emptyset
$
则粒子无法到达$b$,记$T_(0b) = +oo$。特别地,$T_(00)$表示首次返回原点的时刻。
=== 随机过程
对于概率空间$(Omega, cal(F), p)$,一簇依赖于参数$t in T$的随机变量$X_t$,称为*随机过程*,记作${X_t, t in T}$。其中$T$是*指标集*,通常表示时间。
随机过程${X_t, t in T}$的*样本轨道*是指对于每一个固定的$omega in Omega$,$t -> X_t(omega)$是一个函数,称为*样本轨道*。
我们常把$t$解释为时间。一般来说,$T$是一个无限集合。如果它是可数集合,如$T = ZZ$,则称$X$为*离散参数的随机过程*或*随机序列*,即
$
X = {X_n, n in ZZ}
$
如果$T = RR$,则称$X$为*连续参数的随机过程*。
#figure(
tablem[
| $t$取值\\$X$取值 | 连续 | 离散 |
| ----------------- | ---- | ---- |
|连续 | Brown运动 | Poisson过程 |
|离散 | Markov链 | 随机徘徊 |
],
caption: [
随机过程的分类
],
kind: table
)
设$X = {X_t : t in T}$是一个随机过程,若它在任意$s$个互不相交的区间
$
[m_i , n_i] sect [m_j , n_j] = emptyset, i != j
$
上的增量$X_(n_i) - X_(m_i)$是相互独立的,则称$X$是*独立增量过程*。
若对于$n>0$,$X_(t + n) - X_t$的分布对一切$t in T$都是相同的,则称$X$是*时齐的独立增量过程*。
一维和二维随机过程都是时齐的独立增量过程。
== 泊松过程
=== 泊松分布的性质
泊松分布:
设$X$是一个随机变量,如果它的概率分布为
$
P(X = k) = (lambda^k e^(-lambda))/k!, k = 0, 1, 2, ...
$
则称$X$服从参数为$lambda$的泊松分布,记作$X ~ P(lambda)$。
泊松分布的期望和方差为
$
E(X) = D(X) = lambda
$
==== 可加性
设$X_1, X_2, ... , X_n$是$n$个独立的服从参数为$lambda_i$的泊松分布的随机变量,则$Y = sum_(i = 1)^n X_i$服从参数为$sum_(i = 1)^n lambda_i$的泊松分布。
_证明:_
由于$X_i$是独立的,我们线计算$n=2$的情况,后面归纳即可。
对于$n=2$,$Y$的分布律为
$
P(Y = k) &= sum_(i = 0)^k P(X_1 = i) P(X_2 = k - i) = sum_(i = 0)^k (lambda_1^i e^(-lambda_1))/i! (lambda_2^(k-i) e^(-lambda_2))/(k-i)!\
&= sum_(i = 0)^k binom(k, i) lambda_1^i lambda_2^(k-i) e^(-lambda_1 - lambda_2)/k! = (lambda_1 + lambda_2)^k e^(-(lambda_1 + lambda_2))/k!\
&= (lambda_1 + lambda_2)^k e^(-(lambda_1 + lambda_2))/k!
$
==== 随机选择下的不变性
从$X ~ P(lambda)$个人中,以保留概率$p$的概率随机选择$Y$个人,则$Y ~ P(lambda p)$。
_证明:_
$
P(Y = k) &= sum_(n=k)^oo P(Y = k | X = n) P(X = n) = sum_(n=k)^oo binom(n, k) p^k (1-p)^(n-k) (lambda^n e^(-lambda))/n! \
&= (lambda e^(-lambda)) / k! sum_(n=k)^oo binom(n, k) p^k (1-p)^(n-k) lambda^n = (lambda e^(-lambda)) / k! sum_(n=k)^oo binom(n, k) (lambda p)^k (1-p)^(n-k) lambda^(n-k) \
&= (lambda p)^k e^(-lambda p)/k!
$
这种性质也可以理解成一种继承性质。
=== 母函数
设$X$为非负整数值随机变量,其分布为$P(X = k) = p_k, k = 0, 1, 2, ...$,则称
$
G(s) = E(s^X) = sum p_k s^k
$
为$X$的*概率母函数*,简称为*母函数*或者*生成函数*。相当于把$X=n$的概率放在多项式的$n$次项上。可以理解成一个Laplace变换。
==== 一些常见分布的母函数
- 二项分布$B(n, p)$的母函数为
$
G(s) = E(s^X) = sum_(k = 0)^n binom(n, k) p^k (1-p)^(n-k) s^k = (p s + 1 - p)^n
$
- 泊松分布$P(lambda)$的母函数为
$
G(s) = E(s^X) = sum_(k = 0)^oo (lambda^k e^(-lambda))/k! s^k = e^(lambda(s-1))
$
- 几何分布$G(p)$的母函数为
$
G(s) = E(s^X) = sum_(k = 0)^oo p (1-p)^k s^k = (p s) / (1 - (1-p)s)
$
==== 母函数的性质
- $p_k = 1/k! G^(k)(0)$
- 设非负整数值随机变量$X_1, X_2, ... , X_n$*相互独立*(不一定同分布),它们的母函数分别为$g_1, g_2, ... , g_n$,则$Y = sum_(i = 1)^n X_i$的母函数为
$
G(s) = product_(i = 1)^n g_i(s)
$
这就是Laplace变换乘法与卷积的关系。
母函数唯一的确定相应随机变量的概率分布律。从而可知概率分布律和母函数是一一对应的。
下面用一些基本的分布来说明母函数的性质。
考虑$X_k tilde B(1,p)$,其母函数为
$
G(s) = E(s^X) = p s + 1 - p
$
如果$X_i$互相独立,则$Y = sum_(i = 1)^n X_i$的母函数为
$
G(s) = (p s + 1 - p)^n
$
从而$Y ~ B(n,p)$。
考虑$X_k tilde B(n_k, p)$,其母函数为
$
G(s) = E(s^X) = (p s + 1 - p)^(n_k)
$
如果$X_i$互相独立,则$Y = sum_(i = 1)^n X_i$的母函数为
$
G(s) = product_(i = 1)^n (p s + 1 - p)^(n_i)
$
从而$Y ~ B(sum_(i = 1)^n n_i, p)$。
考虑$X_k tilde "Ge"(p)$,其母函数为
$
G(s) = E(s^X) = (p s )/ (1 - (1-p)s)
$
如果$X_i$互相独立,则$Y = sum_(i = 1)^n X_i$的母函数为
$
G(s) = product_(i = 1)^n (p s )/ (1 - (1-p)s) = (p^n s^n) / (1 - (1-p)s)^n
$
幂级数展开
$
G(s) &= p^n s^n (1- (1-p)s)^(-n) = p^n s^n sum_(k = 0)^oo binom(n+k-1, k) (1-p)^k s^k \
&= p^n (1-p)^n sum_(k = n)^oo binom(n-1, k-n) (1-p)^k s^k
$
从而
$
P(Y = k) = binom(n-1, k-1) p^n (1-p)^(k-n)
$
这是超几何分布的概率分布律。
可以证明Poisson分布的可加性:考虑$X_k tilde P(lambda_k)$,其母函数为
$
G(s) = E(s^X) = e^(lambda_k(s-1))
$
如果$X_i$互相独立,则$Y = sum_(i = 1)^n X_i$的母函数为
$
G(s) = product_(i = 1)^n e^(lambda_i(s-1)) = e^(sum_(i = 1)^n lambda_i(s-1))
$
从而$Y ~ P(sum_(i = 1)^n lambda_i)$。
- 母函数与期望和方差的关系
$
E(X) = G'(1)\
D(X) = G''(1) + G'(1) - (G'(1))^2
$
母函数的本质是期望,我们可以用全期望公式来求解母函数,进一步求解分布。
== 泊松过程
=== 泊松过程
若非负整数取值随机过程${N_t, t >= 0}$满足以下性质:
- $N_0 = 0$
- *增量独立性*:对于任意$0 <= t_1 < t_2 < ... < t_n$,$N_(t_2) - N_(t_1), N_(t_3) - N_(t_2), ... , N_(t_n) - N_(t_(n-1))$相互独立。#footnote[一般来说,总样本量很大的情况下才能满足]
- *增量平稳性*:对于任意$s, t >= 0$,$N_(t+s) - N_t$的分布与$N_s$的分布相同。
- *普通性*:对于任意$t>0$和充分小的$h>0$,有
$
P(N_(t+h) - N_t = 1) = lambda h + o(h)\
P(N_(t+h) - N_t >= 2) = o(h)
$
其中$lambda$是常数,称为*强度*。
则称其为强度为$lambda$的*泊松过程*。
增量独立性是最重要的性质,在互不重叠的时间区间上信号发生数相互独立,这是后续导出常微分方程的关键。
增量平稳性意味着在$(s, s + t]$内信号发生数的概率只与时间间隔长短$t$有关,而与起点$s$无关。
在充分小的时间间隔$h$中,最多发生一个信号,发生两个(或以上)信号的概率是$h$的高阶无穷小,且信号发生的概率与$h$成正比。普通性的本质是局部线性化。
普通性蕴含了另一个关系,由概率的规范性,有
$
P(N_(t+h) - N_t = 0) = 1 - lambda h + o(h)
$
另外,普通性可以拓展:
$
P(N_(t+h) - N_t = k) = lambda_k + o(h)\
P(N_(t+h) - N_t >= k) = o(h)
$
这允许了泊松过程的泊松分布的推广。
=== 泊松过程的性质
如果$N_t$是强度为$lambda$的泊松过程,那么对于任意$s, t >= 0$,有
$
P(N_(t+s) - N_t = k) = (lambda s)^k e^(-lambda s) / k!
$
即$N_(t+s) - N_t ~ "Po"(lambda s)$。
_证明:_
令$p_k (t) = P(N_(t+s) - N_t = k)$,根据增量平稳性,有$p_k (t) = p_k (N_s)$。
先考虑$k = 0$的情况,有$p_0 (t + h)$
若非负整数值随机过程${N_t : t ≥ 0}$满足下面$3$条性质:
1. $N_0 = 0$;
2. 增量独立性;
3. $N_(s+t) - N_s tilde "Po"(λ t)$,则它是强度为$λ$的泊松过程。
该定理和上面性质结合起来,说明在条件1、2的情况下, 条件3和增量平稳性+普通性等价。*该定理也可以看成是泊松过程的另一定义。*
${N_t : t ≥ 0}$是强度为$λ$的泊松过程,则有
$
P(N_s = k | N_t = n) = binom(n, k) (s/t)^k (1-s/t)^(n-k)
$
该定理揭示了泊松过程和二项分布的关系。另外,它可以推广到多个时刻的条件概率情形,从而得到多项分布。
对于强度为$λ$泊松过程${N_t : t ≥ 0}$,我们有如下性质:
$
E(N_t) = λ t; D(N_t) = λ t; "Cov"(N_s, N_t) = λ(s and t)
$
#newpara()
*泊松过程的相加不变*
令$X_t$和$Y_t$为泊松过程$X = {X_t : t ≥ 0}$和$Y = {Y_t : t ≥ 0}$的强度分别$λ_1$和$λ_2$。$N_t = X_t + Y_t$,由于$X$和$Y$相互独立,容易验证$N_t$满足上面定理的第(1)、(2)条。再根据定理2.1,可知
$
N_(s+t) - N_s tilde "Po"((λ_1 + λ_2)t)
$
因此$N = {N_t : t ≥ 0}$是强度为$λ = λ_1 + λ_2$的泊松过程。
*泊松过程的选择不变*
$N_t$是强度为$λ$的泊松过程,
=== Poisson过程的推广
==== 非时齐泊松过程
若非负整数值随机过程${N_t : t ≥ 0}$满足下面3条性质,则称其为强度函数为$λ(t)$的非时齐泊松过程:
==== 复合泊松过程
==== 更新过程
= 连续型随机变量
== 连续型随机变量
=== 概率分布函数及概率密度函数
设X是一个随机变量,函数
$
F(x) = P(X ≤ x), x in RR
$
称为$X$的*概率分布函数*(简称分布函数)。
设随机变量$X$的分布函数为$F(x)$,如果存在非负可积函数$f(x)$,使得
$
F(x) = integral_(-oo)^x f(s) dd(s)
$
则称$X$为*连续型随机变量*,称$f(x)$为$X$的概率密度函数(简称概率密度)。
考虑离散型随机变量$X$,其概率分布律为
$
p_k = P(X = a_k), k = 1, 2, ...
$
其中$a_1 < a_2 < ... < a_n$,则$X$的分布函数为
$
F(x) = sum_(a_k <= x) p_k
$
因此$F(x)$是分段常值函数,$x = a_1,a_2, ...,a_n$是$F(x)$的跳跃点,其跳跃的高度为$p_1, p_2, ..., p_n$。
随机变量$X$的分布函数$F(x)$有如下性质:
- $0 ≤ F(x) ≤ 1, x in RR$
- $F(x)$是非减函数:如$x_1 < x_2$,则$F(x_1) ≤ F(x_2)$
- $lim_(-oo) F(x) = 0$ ,$lim_(+oo) F(x) = 1$
- $F(x)$右连续,即$lim_(x→x_0+) F(x) = F(x_0)$
- $P(X = x) = F(x) - F(x^-)$,其中$F(x^-) = lim_(x→x_0-) F(x)$
连续型随机变量X的概率密度f(x)有如下性质:
- $f(x) ≥ 0, x in RR$
- $integral_(-oo)^oo f(x) dd(x) = 1$
- $P(a ≤ X ≤ b) = integral_a^b f(x) dd(x)$
- 若$f(x)$在$x_0$处连续,则$F'(x_0) = f(x_0)$
=== 数学期望和方差
设连续型随机变量$X$的概率密度为$f(x)$,若积分
$
E(X) = integral_(-oo)^oo x f(x) dd(x)
$
绝对收敛,则称$E(X)$为$X$的*数学期望*。
设连续型随机变量$X$的概率密度为$f(x)$,函数$phi : RR -> RR$连续,则$Y = φ(X)$也是一个随机变量,若积分
$
E(Y) = integral_(-oo)^oo φ(x) f(x) dd(x)
$
绝对收敛,则称$E(Y)$为$Y$的*数学期望*。
设连续型随机变量X的概率密度为$f(x)$,若$E ((X - E(X))^2)$存在,则称为$X$的方差,即
$
D(X) = E((X - E(X))^2) = integral_(-oo)^oo (x - E(X))^2 f(x) dd(x)
$
称$sqrt(D(X))$为X的标准差。
考虑随机变量$X,Y$,若期望$E(X),E(Y)$均存在,则有
- $|E(X)| <= E(|X|)$
- 对实数$a < b$,若$a <= X <= b$,则$a <= E(X) <= b$
- 若$X <= Y$,则$E(X) <= E(Y)$
- 对实数$a, b$,有$E(a X + b Y) = a E(X) + b E(Y)$
- 若$X,Y$相互独立,则$E(X Y) = E(X) E(Y)$
- 【Schwarz不等式】$|E(X Y)|^2 <= E(X^2) E(Y^2)$
若方差$D(X),D(Y)$均存在,则有
- 对实数$a, b$,有$D(a X + b) = a^2 D(X)$
- 若$X,Y$相互独立,则$D(X + Y) = D(X) + D(Y)$
- $D(X) = 0$当且仅当$P(X = E(X)) = 1$,即$X$几乎必然是一个常数
也有Chebyshev不等式:
$
P(|X - E(X)| >= epsilon) <= D(X) / epsilon^2
$
_证明:_
$
P(|X - E(X)| >= epsilon) &= integral_(|X - E(X)| >= epsilon) f(x) dd(x) \
&<= integral_(|X - E(X)| >= epsilon) (x - E(X))^2 / epsilon^2 f(x) dd(x) \
&= 1/epsilon^2 integral_(|X - E(X)| >= epsilon) (x - E(X))^2 f(x) dd(x) \
&= <= 1/epsilon^2 integral_(-oo)^oo (x - E(X))^2 f(x) dd(x) = D(X) / epsilon^2
$
若取$epsilon = k sqrt(D(X))$,则有
$
P(|X - E(X)| >= k sqrt(D(X))) <= 1/k^2
$
可以让我们从另一个角度观察随机变量值远离其数学期望的概率。
考虑强度为$λ$的泊松过程${N_t : t ≥ 0}$。相应的,我们可以导出另一组随机过程${X_n : n = 1, 2...}$,它给出泊松过程中第$n$个信号的发生时间。求$E(X_n)$和$D(X_n)$。
对$t > 0$,先求$X_n$对应的分布函数$F_n (t)$和概率密度$f_n (t)$。由于$X_n$是第$n$个信号的发生时间,有
$
F_n (t) = P(X_n <= t) = P(N_t >= n) = 1 - P(N_t < n) = 1 - sum_(k = 0)^(n-1) e^(-λ t) (λ t)^k / k!
$
对应的概率密度为
$
f_n (t) = F_n'(t) = λ e^(-λ t) (λ t)^(n-1) / (n-1)!
$
对$t<=0$时,$F_n (t) = 0$,$f_n (t) = 0$。从而得到
$
E(X_n) = integral_0^oo t f_n (t) dd(t) = n/λ\
E(X_n^2) = integral_0^oo t^2 f_n (t) dd(t) = n(n+1)/λ^2\
D(X_n) = E(X_n^2) - (E(X_n))^2 = n/λ^2
$
== 常见的连续型随机变量
=== 均匀分布
如果连续型随机变量$X$的概率密度为:
$
f(x) = 1/(b-a) I_[a,b]
$
则称$X$服从$(a,b)$上的均匀分布,记作$X ~ U(a,b)$。
均匀分布的数学期望和方差为
$
E(X) = (a+b)/2\
D(X) = (b-a)^2 / 12
$
=== 指数分布
如果连续型随机变量$X$的概率密度为:
$
f(x) = λ e^(-λ x) I_[0, +oo)
$
则称$X$服从参数为$λ$的指数分布,记作$X ~ "Exp"(λ)$。
指数分布的数学期望和方差为
$
E(X) = 1/λ\
D(X) = 1/λ^2
$
和Poisson过程的联系:指数分布是泊松过程的等待时间分布。
*指数分布的无记忆性*:若$X ~ "Exp"(λ)$,则对任意$s, t > 0$,有
$
P(X > s + t | X > s) = P(X > t)
$
_证明:_
$
P(X > s + t | X > s) &= P(X > s + t, X > s) / P(X > s) \
&= P(X > s + t) / P(X > s) = e^(-λ(s+t)) / e^(-λ s) = e^(-λ t) = P(X > t)
$
#newpara()
*指数分布的无老化性*:$X$是取值非负的随机变量,则$X ~ "Exp"(λ)$当且仅当对任意$t > 0$和充分小的$h > 0$,有
$
P(t < X < t + h | X > t) = λ h + o(h)
$
_证明:_
先证明必要性
$
P(t < X < t + h | X > t) &= P(t < X < t + h) / P(X > t) = (e^(-λ t) - e^(-λ (t+h))) / e^(-λ t) = λ h + o(h)
$
再证明充分性
$
(F(x + h) - F(x)) / (1 - F(x)) = λ h + o(h)\
(F(x + h) - F(x)) / h = λ (1 - F(x)) + o(1 - F(x))\
$
令$h -> 0$,有
$
f(x) = λ e^(-λ x)
$
从而$X ~ "Exp"(λ)$。
=== 正态分布
如果连续型随机变量$X$的概率密度为:
$
f(x) = 1/(sqrt(2π) σ) e^(-(x-μ)^2 / 2σ^2)
$
则称$X$服从参数为$μ, σ^2$的*正态分布*,记作$X ~ N(μ, σ^2)$。特别地,若$μ = 0, σ = 1$,则称$X$服从*标准正态分布*,记作$X ~ N(0, 1)$。
下面证明$integral_(-oo)^oo e^(-x^2) dd(x) = sqrt(π)$。
$
integral_(-oo)^oo e^(-x^2) dd(x) &= integral_(-oo)^oo u^(-1/2) e^(-u) dd(u) = Gamma(1/2) = sqrt(π)
$
#newpara()
正态分布的数学期望和方差为
$
E(X) = μ\
E(X^2) = μ^2 + σ^2\
D(X) = σ^2
$
若$X$服从标准正态分布,习惯上人们用$φ(x)$和$Φ(x)$分别表示概率密度和分布函数,即
$
φ(x) = 1/√(2π) e^(-x^2 / 2)\
Φ(x) = integral_(-oo)^x φ(t) dd(t)
$
$φ(x)$和$Φ(x)$具有下面性质:
- $φ(-x) = φ(x)$
- $x =0$时,$φ(x) = 1/√(2π)$取到最大值
- $Φ(-x) = 1 - Φ(x)$
- 若$X ~ N(μ, σ^2)$,则$F(x) = Φ((x-μ)/σ)$。任何正态分布都可以通过一个线性变化转化为标准正态分布,此过程也称为对随机变量$X$进行标准化。
#grid(columns: (1fr,1fr),
[#figure(
image("pic/2024-05-07-11-55-47.png", width: 80%),
caption: [
正态分布的概率密度函数
],
)],
[#figure(
image("pic/2024-05-07-11-56-05.png", width: 80%),
caption: [
正态分布的分布函数
]
)]
)
概率密度$f(x)$有下面性质:
- 关于$x = µ$对称;
- 当$x = µ$时, $f(x)$取最大值 $1/(√(2π) σ)$;
- $f(x)$在$x = µ ± σ$处有拐点;
- $σ$越大,$f(x)$的图像越“胖”,取值越分散,$σ$越小,$f(x)$的图像越“瘦”,取值越集中;
- $f(x)$存在任意阶连续导数。
== 二维连续型随机变量
=== 二维连续型随机变量
设随机试验的样本空间为$Ω$,$X$和$Y$是定义在$Ω$上的两个随机变量,我们称向量$(X, Y)$为二维随机变量或二维随机向量。
设$(X, Y)$的联合概率密度为$f(x, y)$,若对任意$D ⊆ RR^2$,有
$
P((X, Y) ∈ D) = integral.double_D f(x, y) dd(x) dd(y)
$
= 布朗运动和极限定理
== 特征函数和高斯分布
|
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/chained-call-compileable.typ | typst | Apache License 2.0 | #{
((1,2),2,3).rev().rev().at(0).rev().rev().rev()
}
#{
("a": ("b": (1,2))).a.b.rev().rev().rev().len()
}
#((1,2),2,3).rev().rev().at(0).rev().rev().rev()
#("a": ("b": (1,2))).a.b.rev().rev().rev().len()
|
https://github.com/jamesrswift/pixel-pipeline | https://raw.githubusercontent.com/jamesrswift/pixel-pipeline/main/src/primitives/position.typ | typst | The Unlicense | #let position(
space: "canvas", // Which coordinate system
relative: none,
name: none,
coord
) = {
(:
position: coord,
space: space
)
if relative != none {(: relative: relative)}
if name != none {(: name: name)}
} |
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/09-layout/bidi-embedding.typ | typst | Other | #import "/lib/draw.typ": *
#import "/template/lang.typ": arabic, greek
#import "bidi-unembedded.typ": example, make-arrow
#let start = (0, 0)
#let end = (1000, 160)
#let graph = with-unit((ux, uy) => {
// mesh(start, end, (100, 20), stroke: 1 * ux + gray)
txt(example, (20, 20), size: 30 * ux, anchor: "lb")
let arrow = make-arrow(ux)
arrow((20, 120), (990, 120))
arrow((970, 90), (380, 90))
arrow((710, 60), (840, 60))
txt([从左向右(0级)], (20, 120), size: 20 * ux, anchor: "lb", dy: 2)
txt([从右向左(1级)], (970, 90), size: 20 * ux, anchor: "rb", dy: 2)
txt([从左向右(2级)], (710, 60), size: 20 * ux, anchor: "lb", dy: 2)
})
#canvas(end, start: start, width: 100%, graph)
|
https://github.com/diquah/OpenBoard | https://raw.githubusercontent.com/diquah/OpenBoard/main/example-exam.typ | typst | MIT License | #import "openboard.typ": *
#show: doc => template(
paper: "us-letter",
doc,
)
#title(
title: "Example Exam",
subtitle: "Using OpenBoard and Typst",
organization: "University of the Internet",
class: "Typography 101",
collect_info: ("Name", "ID"),
exam_version: "A",
)
#instruct[
== Initial Instructions Before Exam
#lorem(50)
#lorem(50)
This exam consists of three parts:
#pad(left: 2em)[
- *MCQ*: Multiple Choice Questions.
- *FRQ*: Free Response Questions.
- *DBQ*: Document Based Questions (essay response).
]
\
You will have a total of *45 minutes* to complete all sections.
]
#pagebreak()
#section_header("MCQ", info: [*Scientific Calculator Permitted*])
#prompt[
This is an example of a *multiple choice* question. #lorem(20)
#mcq(
[#lorem(10)],
[#lorem(21)],
[#lorem(7)],
[#lorem(9)],
)
]
#prompt[
Multiple choice questions can have *any amount of options*. #lorem(20)
#mcq(
[#lorem(10)],
[#lorem(21)],
[#lorem(7)],
[#lorem(9)],
[#lorem(6)],
[#lorem(8)],
[...]
)
]
#prompt[
#lorem(5) $x_A (t) = -3t^2+t+4$. #lorem(12)
#mcq(
[3.2],
[4.7],
[5.2],
[None of the above.],
)
]
#prompt[
#lorem(20)
#mcq(
[#lorem(10)],
[#lorem(7)],
[#lorem(9)],
[#lorem(8)],
)
]
#prompt[
#lorem(20)
#mcq(
[#lorem(10)],
[#lorem(7)],
[#lorem(9)],
[#lorem(8)],
)
]
#pagebreak()
#section_header("FRQ", info: [*Calculators are not permitted.*\ #lorem(20) Show all work. ])
#prompt[
This is an example of a *free response* question. They can have any number of sub-questions. #lorem(20)
#frq(
[
*Contemplate* this empty space.
#space(1)
],
[
*Explain* on these ruled lines.
#ruled(5)
],
[
*Draw* on this graph-ruled section.
#graph(22, 10)
],
)
]
#pagebreak()
#section_header("DBQ")
#custom_prompt(
"Document 1.",
[
#lorem(100)
#lorem(70)
]
)
#custom_prompt(
"Document 2.",
[
#lorem(50)
#lorem(25)
#lorem(30)
]
)
#prompt(allow_overrun: true)[
#lorem(30)
#ruled(52)
] |
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/160.%2095.html.typ | typst | 95.html
Let the Other 95% of Great Programmers In
December 2014American technology companies want the government to make immigration
easier because they say they can't find enough programmers in the
US. Anti-immigration people say that instead of letting foreigners
take these jobs, we should train more Americans to be programmers.
Who's right?The technology companies are right. What the anti-immigration people
don't understand is that there is a huge variation in ability between
competent programmers and exceptional ones, and while you can train
people to be competent, you can't train them to be exceptional.
Exceptional programmers have an aptitude for and
interest in
programming that is not merely the product of training.
[1]The US has less than 5% of the world's population. Which means if
the qualities that make someone a great programmer are evenly
distributed, 95% of great programmers are born outside the US.The anti-immigration people have to invent some explanation to
account for all the effort technology companies have expended trying
to make immigration easier. So they claim it's because they want
to drive down salaries. But if you talk to startups, you find
practically every one over a certain size has gone through legal
contortions to get programmers into the US, where they then
paid them the same as they'd have paid an American. Why would they
go to extra trouble to get programmers for the same price? The
only explanation is that they're telling the truth: there are just
not enough great programmers to go around.
[2]I asked the CEO of a startup with about 70 programmers how many
more he'd hire if he could get all the great programmers he wanted.
He said "We'd hire 30 tomorrow morning." And this is one of the
hot startups that always win recruiting battles. It's the same all
over Silicon Valley. Startups are that constrained for talent.It would be great if more Americans were trained as programmers,
but no amount of training can flip a ratio as overwhelming as 95
to 5. Especially since programmers are being trained in other
countries too. Barring some cataclysm, it will always be true that
most great programmers are born outside the US. It will always be
true that most people who are great at anything are born outside
the US.
[3]Exceptional performance implies immigration. A country with only
a few percent of the world's population will be exceptional in some
field only if there are a lot of immigrants working in it.But this whole discussion has taken something for granted: that if
we let more great programmers into the US, they'll want to come.
That's true now, and we don't realize how lucky we are that it is.
If we want to keep this option open, the best way to do it is to
take advantage of it: the more of the world's great programmers are
here, the more the rest will want to come here.And if we don't, the US could be seriously fucked. I realize that's
strong language, but the people dithering about this don't seem to
realize the power of the forces at work here. Technology gives the
best programmers huge leverage. The world market in programmers
seems to be becoming dramatically more liquid. And since good
people like good colleagues, that means the best programmers could
collect in just a few hubs. Maybe mostly in one hub.What if most of the great programmers collected in one hub, and it
wasn't here? That scenario may seem unlikely now, but it won't be
if things change as much in the next 50 years as they did in the
last 50.We have the potential to ensure that the US remains a technology
superpower just by letting in a few thousand great programmers a
year. What a colossal mistake it would be to let that opportunity
slip. It could easily be the defining mistake this generation of
American politicians later become famous for. And unlike other
potential mistakes on that scale, it costs nothing to fix.So please, get on with it.
Notes[1]
How much better is a great programmer than an ordinary one?
So much better that you can't even measure the difference directly.
A great programmer doesn't merely do the same work faster. A great
programmer will invent things an ordinary programmer would never
even think of. This doesn't mean a great programmer is infinitely
more valuable, because any invention has a finite market value.
But it's easy to imagine cases where a great programmer might invent
things worth 100x or even 1000x an average programmer's salary.[2]
There are a handful of consulting firms that rent out big
pools of foreign programmers they bring in on H1-B visas. By all
means crack down on these. It should be easy to write legislation
that distinguishes them, because they are so different from technology
companies. But it is dishonest of the anti-immigration people to
claim that companies like Google and Facebook are driven by the
same motives. An influx of inexpensive but mediocre programmers
is the last thing they'd want; it would destroy them.[3]
Though this essay talks about programmers, the group of people
we need to import is broader, ranging from designers to programmers
to electrical engineers. The best one could do as a general term
might be "digital talent." It seemed better to make the argument a
little too narrow than to confuse everyone with a neologism.
Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading
drafts of this.Spanish Translation
|
|
https://github.com/jrihon/multi-bibs | https://raw.githubusercontent.com/jrihon/multi-bibs/main/chapters/01_chapter/discussion.typ | typst | MIT License | #import "../../lib/multi-bib.typ": *
#import "bib_01_chapter.typ": biblio
== Conclusion
#lorem(20)
|
https://github.com/liuguangxi/suiji | https://raw.githubusercontent.com/liuguangxi/suiji/main/tests/test-normal-f.typ | typst | MIT License | #set document(date: none)
#import "/src/lib.typ": *
#let print-arr(arr) = {
if type(arr) != array {
[#raw(str(arr) + " ")]
} else {
[#raw(arr.map(it => str(it)).join(" "))]
}
}
#{
let rng = gen-rng-f(42)
let arr = ()
(rng, arr) = normal-f(rng)
raw(repr(arr)); parbreak()
(rng, arr) = normal-f(rng, size: 1)
raw(repr(arr)); parbreak()
(rng, arr) = normal-f(rng, size: 0)
raw(repr(arr)); parbreak()
(rng, arr) = normal-f(rng, size: 100)
print-arr(arr); parbreak()
let n = 10000
[Generate #n normal numbers $~ N(5.0, 10.0^2)$. \ ]
(rng, arr) = normal-f(rng, loc: 5.0, scale: 10.0, size: n)
let mean = 0
let std = 0
for i in range(n) {mean += arr.at(i)}
mean /= n
for i in range(n) {std += calc.pow(arr.at(i) - mean, 2)}
std = calc.sqrt(std / n)
[*mean* = #mean \ *std* = #std]; parbreak()
}
|
https://github.com/albanie/typst2mathjax | https://raw.githubusercontent.com/albanie/typst2mathjax/main/README.md | markdown | # Typst2MathJax
A simple [streamlit](https://streamlit.io/) app that converts [typst](https://typst.app/docs) to [mathjax](https://www.mathjax.org/).
## Use the app
Web app available [here](https://albanie-typst2mathjax-main-dgpnp0.streamlit.app/).
You can also run the app locally via:
```bash
streamlit run main.py
```
Looks like this:

## Testing
```bash
python -m unittest test.py
```
## Notes
This is a minimalist tool that I use to help with conversion. It uses a (very) lightweight parsing process that will likely fail on complex uses of Typst. |
|
https://github.com/ns-shop/ns-shop-typst | https://raw.githubusercontent.com/ns-shop/ns-shop-typst/main/readme.md | markdown | # NS Shop Report
---
## Bibliography
- [Hayagriva](https://github.com/typst/hayagriva/blob/main/docs/file-format.md)
## Commands
- Install packages: `yarn`
- Watching for exporting PDF: `yarn watch`
- Update latest Typst: `yarn tupdate`
|
|
https://github.com/pride7/Typst-callout | https://raw.githubusercontent.com/pride7/Typst-callout/main/example/example.typ | typst | #import "../callout.typ": callout
#set heading(numbering: "1")
#set text(font:"LXGW WenKai")
#align(
center
)[
#text(size: 2em)[Test for Callout]
]
= Basic Callout
#callout(
title: [笔记]
)[
有一伟大的男子站在我面前,美丽,慈祥,遍身有大光辉,然而我知道他是魔鬼。
]
#callout(
title:[警告],
type:"warning"
)[
#lorem(20)
]
#callout(
title:[核对],
type:"check"
)[
#lorem(20)
]
#callout(
title: [总结],
type:"summary"
)[
人类的悲欢并不相通,我只觉得他们吵闹。
]
#callout(
title: [问题],
type:"question"
)[
#lorem(20)
]
#callout(
title:[例子],
type:"example"
)[
#lorem(20)
]
#callout(
title:[引用],
type:"quote"
)[
我愿意真有所谓鬼魂,真有所谓地狱,那么,即使在孽风怒吼之中,我也将寻觅子君,当面说出我的悔恨和悲哀,祈求她的饶恕;否则,地狱的毒焰将围绕我,猛烈地烧尽我的悔恨和悲哀。
]
= Non-title Callout
#let c1 = callout.with(type:"note")
#let c2 = callout.with(type:"warning")
#let c3 = callout.with(type:"check")
#let c4 = callout.with(type:"summary")
#let c5 = callout.with(type:"question")
#let c6 = callout.with(type:"example")
#let c7 = callout.with(type:"quote")
#c1[
#lorem(20)
]
#c2[
#lorem(20)
]
= Other Layout
#grid(
columns: 4,
callout(
title:[笔记],
type:"note"
)[
#lorem(15)
],
callout(
title:[警告],
type:"warning"
)[
#lorem(15)
],
callout(
title:[核对],
type:"check"
)[
#lorem(15)
],
callout(
title:[总结],
type:"summary"
)[
#lorem(15)
],
)
#callout(
title:[1st Callout],
type:"note"
)[
#grid(
columns: 2,
column-gutter: 5pt,
callout(
title:[2nd Callout],
type:"summary",
height:20%,
)[
#lorem(15)
],
grid(
columns:1,
callout(
title:[3rd Callout],
type:"check"
)[
#lorem(15)
],
callout(
title:[4th Callout],
type:"warning"
)[
#lorem(15)
]
)
)
]
#callout(
title:[无icon的标题],
icon:false)[
记录一点点东西
] |
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/control-flow-if-content.typ | typst | Apache License 2.0 | #if 1
#if [] 1
#if [] else [] 1
#if 1 [] else [] 1
#if {} [] else [] #1
#if [] [] else [] []
#if () [] else [] # a
#if () [] else []
1
#if () [] else []
[]
#if () [] else []
{
#if () [] else []
1
# if () [] else []
1
A#if false {} else thing
|
https://github.com/Shuenhoy/modern-zju-thesis | https://raw.githubusercontent.com/Shuenhoy/modern-zju-thesis/master/utils/fonts.typ | typst | MIT License | #let 字号 = (
初号: 42pt,
小初: 36pt,
一号: 26pt,
小一: 24pt,
二号: 22pt,
小二: 18pt,
三号: 16pt,
小三: 15pt,
四号: 14pt,
中四: 13pt,
小四: 12pt,
五号: 10.5pt,
小五: 9pt,
六号: 7.5pt,
小六: 6.5pt,
七号: 5.5pt,
小七: 5pt,
)
#let 字体 = (
宋体: ("Times New Roman", "SimSun"),
黑体: ("Arial", "SimHei"),
// 楷体
楷体: ("Times New Roman", "KaiTi"),
// 仿宋
仿宋: ("Times New Roman", "FangSong",),
等宽: ("Courier New", "Menlo", "IBM Plex Mono", "Source Han Sans HW SC", "Source Han Sans HW", "Noto Sans Mono CJK SC", "SimHei", "Heiti SC", "STHeiti"),
)
#let songti(s) = {
set text(font: 字体.宋体)
s
}
#let heiti(s) = {
set text(font: 字体.黑体)
s
}
#let kaiti(s) = {
set text(font: 字体.楷体)
s
}
#let fangsong(s) = {
set text(font: 字体.仿宋)
s
}
|
https://github.com/txpipe-shop/sundae-swap | https://raw.githubusercontent.com/txpipe-shop/sundae-swap/main/src/templates/report.typ | typst | // severity colors
#let critical = rgb("#EB6F92")
#let major = rgb("#EA9A97")
#let minor = rgb("#F6C177")
#let info = rgb("#e0def4")
// status colors
#let resolved = rgb("#73D480")
#let acknowledged = rgb("#F1A03A")
#let identified = rgb("#ED706B")
// other colors
#let table_header = rgb("#E5E5E5")
// table cells
#let cell = rect.with(
inset: 10pt,
fill: rgb("#F2F2F2"),
width: 100%,
height: 50pt,
radius: 2pt
)
#let tx_link(url, content) = {
link(url, underline(text(fill: rgb("#007bff"), content)))
}
// The project function defines how your document looks.
// It takes your content and some metadata and formats it.
// Go ahead and customize it to your liking!
#let report(
client: "",
title: "",
authors: (),
date: none,
repo: "",
body,
) = {
// Set the document's basic properties.
let title = client + " - " + title
set document(author: authors, title: title)
set text(font: "Linux Libertine", lang: "en")
set heading(numbering: "1.a -")
// Title page.
// The page can contain a logo if you pass one with `logo: "logo.png"`.
v(0.6fr)
align(right, image("img/txpipe.png", width: 50%))
v(9.6fr)
text(1.1em, date)
v(1.2em, weak: true)
text(2em, weight: 700, title)
// Author information.
if authors.len() > 0 {
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()
set page(numbering: "1", number-align: center, fill: none)
// Table of contents.
outline(depth: 2, indent: true)
pagebreak()
// Main body.
set par(justify: true)
body
[
= Appendix
#v(1em)
== Disclaimer
#v(1em)
This report is governed by the terms in the agreement between TxPipe (*TXPIPE*) and #client (*CLIENT*). This report cannot be shared, referred to, altered, or relied upon by any third party without TXPIP's written consent. This report does not endorse or disapprove any specific project, team, code, technology, asset or similar. It provides no warranty or guarantee about the quality or nature of the technology analyzed.
*TXPIPE DISCLAIMS ALL WARRANTIES, EXPRESSED OR IMPLIED*, related to this report, its content, and the related services and products. This report is provided as-is. TxPipe does not take responsibility for any product or service advertised or offered by Client or any third party. *TXPIPE IS NOT RESPONSIBLE FOR MONITORING ANY TRANSACTION BETWEEN YOU AND CLIENT AND/OR ANY THIRD-PARTY PROVIDERS OF PRODUCTS OR SERVICES.*
This report should not be used for making investment or involvement decisions with any project, services or assets. This report provides general information and is not a form of financial, investment, tax, legal, regulatory, or other advice.
TxPipe created this report as an informational review of the due diligence performed on the Client's smart contract. This report provides no guarantee on the security or operation of the smart contract on deployment or post-deployment. *TXPIPE HAS NO DUTY TO MONITOR CLIENT'S OPERATION OF THE PROJECT AND UPDATE THE REPORT ACCORDINGLY.*
The information in this report may not cover all vulnerabilities. This report represents an extensive assessment process intended to help increase the quality of the Client's code. However, blockchain technology and cryptographic assets present a high level of ongoing risk, including unknown risks and flaws.
TxPipe recommends multiple independent audits, a public bug bounty program, and continuous security auditing and monitoring. Errors in the manual review process are possible, and TxPipe advises seeking multiple independent opinions on critical claims. *TXPIPE BELIEVES EACH COMPANY AND INDIVIDUAL IS RESPONSIBLE FOR THEIR OWN DUE DILIGENCE AND CONTINUOUS SECURITY.*
#pagebreak()
== Issue Guide
=== Severity
#v(1em)
#grid(
columns: (20%, 80%),
gutter: 1pt,
cell(fill: table_header, height: auto)[
#set align(horizon + center)
*Severity*
],
cell(fill: table_header, height: auto)[
#set align(horizon + center)
*Description*
],
cell(fill: critical)[
#set align(horizon + center)
Critical
],
cell()[
#set align(horizon)
Critical issues highlight exploits, bugs, loss of funds, or other vulnerabilities
that prevent the dApp from working as intended. These issues have no workaround.
],
cell(fill: major)[
#set align(horizon + center)
Major
],
cell()[
#set align(horizon)
Major issues highlight exploits, bugs, or other vulnerabilities that cause unexpected
transaction failures or may be used to trick general users of the dApp. dApps with Major issues
may still be functional.
],
cell(fill: minor)[
#set align(horizon + center)
Minor
],
cell()[
#set align(horizon)
Minor issues highlight edge cases where a user can purposefully use the dApp
in a non-incentivized way and often lead to a disadvantage for the user.
],
cell(fill: info)[
#set align(horizon + center)
Info
],
cell()[
#set align(horizon)
Info are not issues. These are just pieces of information that are beneficial to the dApp creator. These are not necessarily acted on or have a resolution, they are logged for the completeness of the audit.
],
)
#v(1em)
=== Status
#v(1em)
#grid(
columns: (20%, 80%),
gutter: 1pt,
cell(fill: table_header, height: auto)[
#set align(horizon + center)
*Status*
],
cell(fill: table_header, height: auto)[
#set align(horizon + center)
*Description*
],
cell(fill: resolved)[
#set align(horizon + center)
Resolved
],
cell()[
#set align(horizon)
Issues that have been *fixed* by the *project* team.
],
cell(fill: acknowledged)[
#set align(horizon + center)
Acknowledged
],
cell()[
#set align(horizon)
Issues that have been *acknowledged* or *partially fixed* by the *project* team. Projects
can decide to not *fix* issues for whatever reason.
],
cell(fill: identified)[
#set align(horizon + center)
Identified
],
cell()[
#set align(horizon)
Issues that have been *identified* by the *audit* team. These
are waiting for a response from the *project* team.
],
)
#pagebreak()
== Revisions
#v(1em)
This report was created using a git based workflow. All changes are tracked in a github repo and the report is produced
using #tx_link("https://typst.app")[typst]. The report source is available #tx_link(repo)[here]. All versions with downloadable PDFs can be found on the #tx_link(repo + "/releases")[releases page].
#v(1em)
== About Us
#v(1em)
TxPipe is a blockchain technology company responsible for many projects that are now a critical part
of the Cardano ecosystem. Our team built #tx_link("https://github.com/oura")[Oura], #tx_link("https://github.com/txpipe/scrolls")[Scrolls], #tx_link("https://github.com/txpipe/pallas")[Pallas], #tx_link("https://demeter.run")[Demeter], and we're the original home of #tx_link("https://aiken-lang.org")[Aiken]. We're passionate
about making tools that make it easier to build on Cardano. We believe that blockchain adoption can be accelerated by improving developer experience. We develop blockchain tools, leveraging the open-source community and its methodologies.
#v(1em)
=== Links
#v(1em)
- #tx_link("https://txpipe.io")[Website]
- #tx_link("<EMAIL>")[Email]
- #tx_link("https://twitter.com/txpipe_tools")[Twitter]
]
}
#let files_audited(items: ()) = {
grid(
columns: (auto),
gutter: 1pt,
cell(fill: rgb("#E5E5E5"), height: auto)[*Filename*],
..items.map(
row => cell(height: auto)[#row]
)
)
}
#let titles = ("ID", "Title", "Severity", "Status")
#let finding_titles = ("Category", "Commit", "Severity", "Status")
#let findings(items: ()) = {
grid(
columns: (1fr, 46%, 1fr, 1fr),
gutter: 1pt,
..titles.map(t => cell(fill: table_header, height: auto)[
#set align(horizon + center)
*#t*
]),
..items
.map(
row => (
cell()[
#set align(horizon + center)
*#row.id*
],
cell()[
#set align(horizon)
#row.title
],
cell(
fill: if row.severity == "Critical" {
critical
} else if row.severity == "Major" {
major
} else if row.severity == "Minor" {
minor
} else {
info
}
)[
#set align(horizon + center)
#row.severity
],
cell(
fill: if row.status == "Resolved" {
resolved
} else if row.status == "Acknowledged" {
acknowledged
} else {
identified
}
)[
#set align(horizon + center)
#row.status
]
)
)
.flatten()
)
pagebreak()
for finding in items {
[
= #finding.id #finding.title
#v(1em)
#grid(
columns: (1fr, 48%, 1fr, 1fr),
gutter: 1pt,
..finding_titles.map(t => cell(fill: rgb("#E5E5E5"), height: auto)[
#set align(horizon + center)
*#t*
]),
cell(height: auto)[
#set align(horizon + center)
#finding.category
],
cell(height: auto)[
#set align(horizon + center)
#finding.commit
],
cell(
height: auto,
fill: if finding.severity == "Critical" {
critical
} else if finding.severity == "Major" {
major
} else if finding.severity == "Minor" {
minor
} else {
info
}
)[
#set align(horizon + center)
#finding.severity
],
cell(
height: auto,
fill: if finding.status == "Resolved" {
resolved
} else if finding.status == "Acknowledged" {
acknowledged
} else {
identified
}
)[
#set align(horizon + center)
#finding.status
]
)
#v(1em)
== Description
#v(1em)
#finding.description
#v(1em)
== Recommendation
#v(1em)
#finding.recommendation
#v(1em)
== Resolution
#v(1em)
#finding.resolution
]
pagebreak()
}
}
|
|
https://github.com/curvenote-templates/ncssm | https://raw.githubusercontent.com/curvenote-templates/ncssm/main/README.md | markdown | MIT License | # The Morganton Scientific
A typst template for NCSSM Morganton Scientific journal using MyST Markdown.

|
https://github.com/Lucas-Wye/tech-note | https://raw.githubusercontent.com/Lucas-Wye/tech-note/main/src/Python.typ | typst | = Python
#label("python")
- Python 是一种解释型、面向对象、动态数据类型的高级程序设计语言。
- Python 由 <NAME> 于 1989 年底发明,第一个公开发行版发行于
1991 年。 像 Perl 语言一样, Python 源代码同样遵循 GPL(GNU General
Public License) 协议。
== Install
#label("install")
从#link("https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/")[清华镜像源]下载对应平台的
anaconda/miniconda 安装即可。
== conda创建python虚拟环境
#label("conda创建python虚拟环境")
```sh
# 查看当前存在哪些虚拟环境
conda env list
## or
conda info -e
# 创建虚拟环境
conda create -n your_env_name python=X.X # 版本选择:2.7、3.6等
# 激活环境
conda activate your_env_name
# 关闭虚拟环境
conda deactivate
# 安装package到your_env_name
conda install -n your_env_name package_name
# 删除环境中的某个包
conda remove --name your_env_name package_name
# 删除虚拟环境
conda remove -n your_env_name --all
```
== 常用包安装方法
#label("常用包安装方法")
```sh
# tensorflow
conda install tensorflow
# pytorch(CPU)
conda install pytorch torchvision cpuonly -c pytorch
```
=== conda导出环境依赖
#label("conda导出环境依赖")
```sh
conda list -e > requirements.txt
```
=== Jupyter notebook
#label("jupyter-notebook")
访问远程服务器的notebook配置:
```sh
# 生成一个 notebook 配置文件
jupyter notebook --generate-config
# 生成密码
jupyter notebook password
```
修改配置文件 ~/.jupyter/jupyter\_notebook\_config.py
```python
c.NotebookApp.ip = '*' # 允许任何IP访问
c.NotebookApp.password = u'sha:...' # 密码的哈希值
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888 # 自行指定一个端口
```
=== PyPy
#label("pypy")
https://www.pypy.org \
https://github.com/rvianello/conda-pypy
=== Cython
#label("cython")
https://cython.org
=== 镜像源
#label("镜像源")
`cat ~/.condarc`
```
channels:
- defaults
- ric/channel/pypy
show_channel_urls: true
default_channels:
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
custom_channels:
conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
envs_dirs:
- ~/pypy-envs
```
== pip
#label("pip")
```sh
# 导入依赖包
pip install -r requirements.txt
# 只导出项目依赖包
pip install pipreqs
pipreqs ./
# 导出依赖包
pip freeze > requirements.txt
# 离线下载
pip download -d [DIR] -r requirements.txt
# 离线安装
pip install --no-index --find-links=[DIR] -r requirements.txt
```
=== 镜像源
#label("镜像源-1")
`cat ~/.pip/pip.conf`
```
[global]
index-url = http://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host = mirrors.aliyun.com
```
== More
#label("more")
#link("http://nbviewer.jupyter.org/")[ipynb文件在线查看工具]
|
|
https://github.com/ukihot/igonna | https://raw.githubusercontent.com/ukihot/igonna/main/articles/shell-work/cui.typ | typst | #import "@preview/colorful-boxes:1.2.0": *
== コンソール
コンソールとは、OSを搭載したコンピュータに接続されたディスプレイおよびキーボードである。
コンピュータとの対話を可能にするための物理ハードウェア、入出力システムともいえる。
「文字だけの黒い画面」というキーワードで一般に想起される画面は、仮想コンソールである。
これは入出力を仮想的な空間に提供するものであり、この環境はCUI(Character-based User Interface)ともいう。
CUIは、我々が日々利用するGUI(Graphical User Interface)と対をなす存在であり、文字に基づいたユーザーインターフェースを提供する。
#colorbox(
title: "インターフェース",
color: "blue",
radius: 2pt,
width: auto
)[
"Interface"という語はハードウェアでもソフトウェアでも登場する。主に情報産業では、異なる二つのモノ(人間や機器)を接触させるための境界面として用いられる語である。
]
== ターミナルとシェル
仮想コンソール(CUI)を提供するアプリケーションは一般に*ターミナル*と呼ばれる。
Windowsにおけるコマンドプロンプトや、MacOSにおけるiTerm2やWarpなどがターミナルにあたる。
これらはGUI上でCUIを操作するための窓口になる。
本題となるコンピュータへの命令は*コマンド*という。
コマンドを解釈し、実行する仕組みをシェルという。
シェルの役割はコンピュータとの対話を実際に担うアプリケーションであり、Bashやzsh、fishなど種類が存在する。
#colorbox(
title: "シェル",
color: "blue",
radius: 2pt,
width: auto
)[
エンジニアでない一般ユーザがOSと対話するためのシェルに、Windowsのエクスプローラーなどがある。CUIのシェルとGUIのシェル、操作しやすいユーザ層は当然異なる。
]
要するに、エンジニアがコンピュータへ命令するためには基本的に「ターミナルを起動し(シェルを介して)コマンドを入力」する。
また、コマンドを入力する行のことをコマンドラインという。
単語が重要なのではなく、このCUI構成を理解することは今後役に立つ。
|
|
https://github.com/maantjemol/Aantekeningen-Jaar-2 | https://raw.githubusercontent.com/maantjemol/Aantekeningen-Jaar-2/main/Machine%20Learning/mock-exam.typ | typst | = Mock exam:
== Question 1:
Which of the following is NOT a type of machine learning task according to "samenvatting.pdf"?
*a)* Predictive tasks
*b)* Descriptive tasks
*c)* Analytical tasks
*d)* Supervised learning
== Question 2:
What is the primary goal of probabilistic models in machine learning, as described in "samenvatting.pdf"?
*a)* To represent complex relationships using geometric functions.
*b)* To reduce uncertainty by utilizing probability distributions.
*c)* To create flowchart-like structures for decision-making.
*d)* To group data points based on distance metrics.
== Question 3:
According to "samenvatting.pdf," which of the following is an example of a grading model?
*a)* Tree model
*b)* Naive Bayes model
*c)* Linear model
*d)* Decision tree model
== Question 4:
Which feature transformation technique involves converting numerical features into categorical features, as explained in "samenvatting.pdf"?
*a)* Feature construction
*b)* Discretisation
*c)* Feature selection
*d)* Feature transformation
== Question 5:
In the context of binary classification, what does the True Negative Rate (TNR) or Specificity measure?
*a)* The proportion of correctly identified positive instances out of all positive instances.
*b)* The proportion of correctly identified negative instances out of all negative instances.
*c)* The proportion of incorrectly identified positive instances out of all negative instances.
*d)* The proportion of incorrectly identified negative instances out of all positive instances.
== Question 6:
What is the purpose of using a validation set in machine learning model development, as described in "samenvatting.pdf"?
*a)* To train the initial model parameters.
*b)* To fine-tune the model's hyperparameters.
*c)* To evaluate the final model's performance.
*d)* To identify and handle missing data points.
== Question 7:
What does the area under the ROC curve (AUC) represent in machine learning model evaluation?
*a)* The accuracy of the model on the training dataset.
*b)* A measure of the model's performance, with values closer to 1 indicating better
performance.
*c)* The degree of overfitting present in the trained model.
*d)* The computational cost of training the machine learning model.
== Question 8:
According to "samenvatting.pdf", what is the primary difference between inherently binary and inherently non-binary algorithms for multi-class classification?
*a)* Inherently binary algorithms are more computationally expensive than inherently non-binary algorithms.
*b)* Inherently non-binary algorithms are specifically designed to handle more than two classes, while inherently binary algorithms need adaptation.
*c)* Inherently binary algorithms are more prone to overfitting than inherently non-binary algorithms.
*d)* Inherently non-binary algorithms require a larger amount of training data compared to inherently binary algorithms.
== Question 9:
What is the purpose of the "One-vs-One" approach in adapting a binary classifier for multi-class classification?
*a)* It trains a single classifier to distinguish all classes simultaneously.
*b)* It trains separate binary classifiers for each possible pair of classes.
*c)* It converts the multi-class problem into a regression task.
*d)* It reduces the number of features used to simplify the classification process.
== Question 10:
How does "samenvatting.pdf" define residuals in the context of regression analysis?
*a)* The difference between the predicted values and the actual (true) values.
*b)* The variance of the data points around the regression line.
*c)* The slope of the regression line representing the relationship between
variables.
*d)* The coefficient of determination (R-squared) of the regression model.
== Question 11:
What is the key characteristic of distance-based algorithms in machine learning, as explained in "samenvatting.pdf"?
*a)* They utilize probability distributions to model uncertainty.
*b)* They classify instances by calculating distances to stored exemplars.
*c)* They build tree-like structures to partition data based on feature values.
*d)* They rely on finding linear relationships between variables for prediction.
== Question 12:
What is the "curse of dimensionality" as described in "samenvatting.pdf" in the context of distance-based models?
*a)* The phenomenon where distances become less meaningful and informative as the
number of dimensions increases.
*b)* The exponential increase in computational cost with the growth of data features.
*c)* The difficulty in visualizing high-dimensional data for model interpretation.
*d)* The problem of overfitting when the number of features exceeds the number of data points.
== Question 13:
What is the function of a linkage function in hierarchical clustering, as described in "samenvatting.pdf"?
*a)* It assigns data points to the nearest cluster centroid.
*b)* It determines the distance between two clusters.
*c)* It calculates the silhouette score for cluster evaluation.
*d)* It visualizes the clusters in a scatter plot.
== Question 14:
How does "samenvatting.pdf" define regularization in the context of linear models?
*a)* A technique to normalize feature values into a standard range.
*b)* A method to handle missing data points in the dataset.
*c)* A technique to prevent overfitting by adding a penalty term to the loss
function.
*d)* An approach to transform non-linear data into a higher-dimensional space.
== Question 15:
According to "samenvatting.pdf", what is the primary goal of a Support Vector Machine (SVM)?
*a)* To minimize the sum of squared errors between predicted and actual values.
*b)* To find the hyperplane that maximizes the margin between different classes.
*c)* To cluster data points based on their distances from each other.
*d)* To build a tree-like structure for hierarchical classification.
== Question 16:
Which statistical measure is less sensitive to outliers in a dataset: the mean or the median?
*a)* Mean
*b)* Median
== Question 17:
What does a positive skewness value indicate about the distribution of a dataset, as explained in "samenvatting.pdf"?
*a)* The data is skewed to the right, with a longer tail on the right side of the distribution.
*b)* The data is skewed to the left, with a longer tail on the left side of the
distribution.
*c)* The data is symmetrically distributed around the mean.
*d)* The data has high kurtosis, indicating heavy tails.
== Question 18:
According to "samenvatting.pdf," what is the primary purpose of one-hot encoding in feature engineering?
*a)* To normalize numerical feature values to a standard scale.
*b)* To convert categorical data into a numerical representation using binary
vectors.
*c)* To reduce the number of features by selecting the most relevant ones.
d) To handle missing data points using imputation techniques.
== Question 19:
In the context of evaluating multiple machine learning algorithms on a single dataset, what statistical test is recommended in "samenvatting.pdf"?
*a)* Paired t-test
*b)* Wilcoxon's signed-rank test
*c)* Friedman test
*d)* Nemenyi test
== Question 20:
What is the primary goal of AutoML (Automated Machine Learning), as described in "samenvatting.pdf"?
*a)* To develop new machine learning algorithms from scratch.
*b)* To interpret and explain the predictions of black-box models.
*c)* To automate the process of applying machine learning to real-world problems.
*d)* To collect, clean, and prepare data for machine learning tasks.
#pagebreak()
== Answer Sheet:
1. *c)* Analytical tasks
2. *b)* To reduce uncertainty by utilizing probability distributions.
3. *c)* Linear model
4. *b)* Discretisation
5. *b)* The proportion of correctly identified negative instances out of all negative instances.
6. *b)* To fine-tune the model's hyperparameters.
7. *b)* A measure of the model's performance, with values closer to 1 indicating better performance.
8. *b)* Inherently non-binary algorithms are specifically designed to handle more than two classes, while inherently binary algorithms need adaptation.
9. *b)* It trains separate binary classifiers for each possible pair of classes.
10. *a)* The difference between the predicted values and the actual values.
11. *b)* They classify instances by calculating distances to stored exemplars.
12. *a)* The phenomenon where distances become less meaningful and informative as the number of dimensions increases.
13. *b)* It determines the distance between two clusters.
14. *c)* A technique to prevent overfitting by adding a penalty term to the loss function.
15. *b)* To find the hyperplane that maximizes the margin between different classes.
16. *b)* Median
17. *a)* The data is skewed to the right, with a longer tail on the right side of the distribution.
18. *b)* To convert categorical data into a numerical representation using binary vectors.
19. *a)* Paired t-test
20. *c)* To automate the process of applying machine learning to real-world problems
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion/complete_purely_label.typ | typst | Apache License 2.0 | // contains:test
// compile:true
#set heading(numbering: "1.1")
= H <t>
== H2 <test>
aba aba
#<t> /* range -3..-2 */
|
https://github.com/eduardz1/Bachelor-Thesis | https://raw.githubusercontent.com/eduardz1/Bachelor-Thesis/main/chapters/overview-of-the-greenhouse.typ | typst | #import "../utils/common.typ": *
= Overview of the Greenhouse
The specific greenhouse we're working on has the following characteristics:
- It is divided into two shelves
- Each shelf is composed of two groups of plants
- Each group of plants is watered by a single water pump
- Each group of plants is composed of two plants
- Each plant is associated with a pot
#_content(
[
== Assets
=== Sensors
The following sensors, each associated with a specific asset, are used to
monitor the environmental conditions of the greenhouse and the plants:
#set par(justify: true, first-line-indent: 0em) // FIXME: workaround for https://github.com/typst/typst/issues/1050
/ Greenhouse: one webcam used to measure the light level, can be replaced with
a light sensor that would also provide an accurate lux measurement.
/ Shelves: one `DHT22` sensor is used to measure the temperature and humidity.
/ Pots: each pot has one capacitive soil moisture sensor used to measure the
moisture of the soil.
/ Plants: one `Raspberry Pi Camera Module v2` `NoIR` is used to take pictures of the
plants and measure their growth by calculating the `NDVI` (see @ndvi).
#set par(justify: true, first-line-indent: 1em)
=== Actuators
There is one pump for watering but a second bucket is also present as it enables
us to add a second pump for liquid fertilizers.
#text( // FIXME: too hacky and ugly
fill: white,
)[
.\ \ \ \
]
#figure(
block(
radius: 4pt,
stroke: 0pt + red,
clip: true,
image("../img/greenhouse.jpeg"),
),
caption: [
the bottom shelf of our greenhouse, not in the picture the router, host, and
lights
],
)
],
)
|
|
https://github.com/typst-community/valkyrie | https://raw.githubusercontent.com/typst-community/valkyrie/main/tests/types/tuple/test.typ | typst | Other | #import "/src/lib.typ" as z
#set page(height: 1cm, width: 1cm)
#{
let test-tuple = (
"123",
"<EMAIL>",
1.1
)
z.parse(
test-tuple,
z.tuple(
z.string(),
z.email(),
z.floating-point(),
),
)
}
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/bytefield/0.0.4/lib/asserts.typ | typst | Apache License 2.0 | #import "@preview/oxifmt:0.2.0": strfmt
// fail if field is not a bf-field
#let assert_bf-field(field) = {
assert.eq(type(field),dictionary, message: strfmt("expected field to be a dictionary, found {}", type(field)));
let bf-type = field.at("bf-type", default: none)
assert.eq(bf-type, "bf-field", message: strfmt("expected bf-type of 'bf-field', found {}",bf-type));
let field-type = field.at("field-type", default: none)
assert.ne(field-type, none, message: strfmt("could not find field-type at bf-field {}", field));
}
// fail if field is not a bf-field of type data-field
#let assert_data-field(field) = {
assert_bf-field(field);
let field-type = field.at("field-type", default: none)
assert.eq(field-type, "data-field", message: strfmt("expected field-type == data-field, found {}",field-type))
let size = field.data.size;
assert(type(size) == int, message: strfmt("expected integer for parameter size, found {} ", type(size)))
}
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/034%20-%20Dominaria/011_Return%20to%20Dominaria%3A%20Episode%2011.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Return to Dominaria: Episode 11",
set_name: "Dominaria",
story_date: datetime(day: 23, month: 05, year: 2018),
author: "<NAME>",
doc
)
The sun was close to setting when the #emph[Weatherlight] left the ocean and crossed over the coast into Urborg.
Gideon stood on the bridge with Liliana while Jhoira guided the ship over a swampland of bogs and weed-choked waterways bordered by thick green vegetation. Old ruins were buried under the vines and moss, some indication of the long history of this land.
They had already passed near an outer island, where Jhoira had sent her owl off on a brief scouting mission. When it returned, she explained grimly, "The monument to the fallen of the Phyrexian invasion was there. People used to go on pilgrimages to it, as a symbol of hope in terrible times. Rumor said Belzenlok had the Cabal deface it and from what my owl saw, the rumor is true."
"I heard about that, too." Teferi stood on the far side of the bridge, his arms folded and his gaze on the jungle swampland below. His mouth twisted in contempt. "Apparently the Cabal calls it the Fools' Tomb."
Liliana grimaced. "Well, my symbol of hope is that when the Blackblade rips Belzenlok apart and drains his life, the pain is unimaginable and everlasting."
Jhoira smiled. Teferi laughed and said, "I like the way you think, Liliana."
Liliana eyed him. "Don't make a habit of it; I'm a terrible person to know."
Gideon sighed, and she glared at him.
As the #emph[Weatherlight] flew inland, the light gradually failed. The sky was dark with ash clouds from the volcanoes, and Jhoira turned the ship's running lights down to bare sparks. Gideon managed to spot the heavy shapes of monolithic Thran structures, but most of the ruins had the spiky organic look of Phyrexian remnants.
#figure(image("011_Return to Dominaria: Episode 11/01.jpg", width: 100%), caption: [Swamp | Art by <NAME>], supplement: none, numbering: none)
Some rose above the trees in great circular shapes, others had sharp lines left barely discernible under the vegetation. The broken walls and an occasional tower marked the sites of more recent cities and towns, destroyed and reclaimed by the plant growth. But for all the ruins, Urborg was far from uninhabited. Lights of all sizes gleamed under the trees and vines, flitting rapidly or moving with slow deliberation. Every clump of vegetation seemed to be a home for creatures constantly in motion.
The mood on the ship was sober as they passed over the dark landscape. Teferi and the others went below, though Karn remained out on the bow deck, keeping watch. Gideon stayed on the bridge with Liliana and Jhoira. He knew he should be resting in anticipation of their battle tomorrow, but he couldn't imagine trying to sleep right now. They were so close to their goal, so close to this last effort before they could turn all their attention to <NAME>.
"You're sure these friends of yours will help us?" Liliana asked Jhoira, just a little skeptically. Earlier, Jhoira had sent her mechanical owl flying off across the swamps to deliver a message to her contacts here. "And not try to sell us to the Cabal as soon as they see us?"
Jhoira lifted a brow, but was clearly too used to Liliana by now to take offense. "I'm certain. I've been in contact with them since I decided to destroy the Cabal. There are plenty of humans living here who submit to the Cabal as a way to survive. But many others have fought and died trying to drive Belzenlok's forces off the islands. Now the resistance is concentrated in a secret hiding place. The people we'll be speaking to come from there."
"I'd heard something about the changes here, when I was making my own plans. Seeing it in person is quite different," Liliana admitted. "Of course, the more armies that died on this ground, the better. At least for our purposes."
"There's been so much death in Urborg. The panther warriors have been almost completely wiped out." Jhoira's expression was tinged with sadness. "And spirits and liches have built their own cities and towns throughout the swamps now."
"Spirits?" Gideon frowned. "Of the dead?"
"Yes, and pure manifestations of dark magic," Jhoira explained. "The number and variety of undead here are almost infinite."
"Then I should feel right at home," Liliana said drily.
Jhoira's ironic expression showed she knew that wasn't a joke. She added, "Most don't care for the Cabal any more than we do, and they have to defend themselves against the nightmares created by the Cabal's dementia magic—and other threats." She leaned forward, peering into the mist and darkness. "My owl's coming back." Her expression went still as she communicated with her familiar. "And the resistance has agreed to meet with us."
#figure(image("011_Return to Dominaria: Episode 11/02.jpg", width: 100%), caption: [Jhoira's Familiar | Art by <NAME>], supplement: none, numbering: none)
"Good," Gideon said. He was ready to have this over and done with, and leave this strange land behind.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
It was full dark when the #emph[Weatherlight] came to a stop near a small city at the edge of a bog, half-buried under moss and overgrown trees. It had a stone wall and heavy gates, and was lit by a variety of colored lights. What Gideon could glimpse of the interior from the #emph[Weatherlight] 's deck was odd in the extreme, with bridges stretching between strange architectural shapes and what looked like the campanile of a tower, lying on its side and forming part of a new structure.
The others stayed onboard while Gideon and Jhoira climbed down a ladder to the small clearing just outside the gates. Once they were down, a young Jamuraan man slipped out of the shadows. "This way," he said, and led the way back through the brush.
Gideon was wary of going too far from the #emph[Weatherlight] , but they only went a short distance to a shelter. It had been built where a large tree had fallen onto the curve of an old Phyrexian structure.
Four people waited there, sitting on a ground cloth in the light of a small cloud of glowing mist that floated nearby. Two were human, but the other two were panther warriors. They were tall, leanly muscled, with the heads and faces of the sleek predator cats they were named after. Everyone was heavily armed, and dressed in a mix of ordinary leather or metal armor and dark spike-covered garments obviously looted from the Cabal.
The female panther warrior motioned for them to come closer. "Jhoira. I'm Sayrah. You asked for our help."
Gideon stayed on his feet, keeping guard like their guide, who put his back to the group and kept watch on the shadows under the trees. Jhoira took a seat and said, "Thank you for meeting with us."
Sayrah tilted her head, and said with a touch of irony, "When we heard that Jhoira was here with a fabled skyship, it was hard to stay away."
Jhoira didn't waste time. "We've come here to attack the Stronghold."
#figure(image("011_Return to Dominaria: Episode 11/03.jpg", width: 100%), caption: [Cabal Stronghold | Art by <NAME>], supplement: none, numbering: none)
Startled, Sayrah lifted one broad clawed hand. "If you're here for warriors, there are too few of us to help you."
"No, we won't ask anyone else to fight this battle." Jhoira leaned forward. "There are only two things I need. First, the clothing of a Cabal scout or fighter, someone who would be hunting Urborg for captives to take to the Stronghold's fighting pit."
"That we can easily do." Sayrah gestured to the others, and one of the humans stood and slipped away through the dark. "And the other thing?"
"Information. Can you show us on a map where some of the last great battles were fought in Urborg?"
"Again, simple enough." Sayrah opened her belt pouch and drew out a much-folded map.
Something moved in the brush and Gideon reached for his sword hilt. But the Jamuraan man said, "It's all right. It's a spirit from the town. They hate the Cabal and won't betray us."
The figure that moved out of the shadows was short and bulbous, with a flattened head and dark gray skin. It seemed to roll rather than walk, but Gideon could clearly see it had at least three legs. One eye swiveled to regard him as it passed by.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Slimefoot told its sprouts to stay below. This place was strange and in its own way even more threatening than the vast expanse of water they had just passed over. But there was something about it that seemed to call to Slimefoot, and it reluctantly climbed the steps to the deck. Arvad and Tiana stood near the ladders attached to the railing and the other humans were up on the bow deck.
Slimefoot stayed in the shadows near the bridge but edged over to the railing, drawn there by some strange impulse. It stretched to look down at the tangled greenery below.
In the darkness, glowing shapes moved through the undergrowth. Something said, #emph[Who are you and where do you come from?]
Slimefoot replied, #emph[I am Slimefoot, I come from the ] Weatherlight#emph[. Who are you?]
#emph[Yxarit and Iyrgth and Syl-Stalker and] —Slimefoot was overwhelmed by a torrent of names. #emph[But what are you? ] the voices asked.#emph[ You are like] —The words turned into images, scents. Bright green leaves warmed by a hot sun, flowers, rich damp earth.
Slimefoot said, #emph[Yavimaya] . Raff had said that Slimefoot was from Yavimaya, and that it and its sprouts should go back there after they killed Belzenlok. Slimefoot wasn't sure about that. The #emph[Weatherlight] was all it knew.
Iyrgth said, #emph[There is Yavimaya here, woven into the ground, from long ago. It came to fight] .
#emph[We came to fight the demon] , Slimefoot said.
#emph[The demon, the demon] , the voices whispered to each other, passing the word along. #emph[Fight the demon] .
#figure(image("011_Return to Dominaria: Episode 11/04.jpg", width: 100%), caption: [Fungal Plots | Art by Even Amundsen], supplement: none, numbering: none)
Slimefoot settled in against the railing to talk to its new friends. It was good to be understood like this.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Before dawn the next morning, Gideon ducked his head into the open door of Chandra's compartment. "How is it going?"
"Almost ready," Raff said. He was seated at the desk, paging through the arcane text he usually kept chained to his belt. He hadn't bothered to remove the spell that made it weightless, so it was floating even with his face. On the far side of the room, Liliana and Shanna stood, contemplating Chandra critically.
Liliana said thoughtfully, "Maybe you should shave your head."
Chandra scratched her scalp vigorously. "I kind of want to right now, after all the dirt you put in my hair." She was in her disguise as a Cabal bounty hunter, wearing dark-colored pants and a tunic under black leather armor. The outfit had obviously come from a dead cultist, and was stained with blood and dirt.
Shanna disagreed. "Clerics shave their heads, we don't want to draw that kind of attention. But she does need those scars."
Raff pushed to his feet. "I'm ready, just had to check a few things. I learned this spell in the Academy, but I haven't done it in a while. It's an advanced exercise for illusionists."
For once, Gideon didn't think Raff was bragging. His expression was too intent, too preoccupied. Raff stepped close to Chandra and added, "Just hold still and look straight ahead."
A faint light sparked around Raff's fingers as he drew them down Chandra's face. Her skin puckered and pulled, creating a sword scar that ran from one side of her forehead to her jaw. Gideon was impressed with the transformation. Raff stepped back and said, "How's that?"
Liliana nodded in approval. "Perfect. She looks delightfully roguish."
Shanna clapped Raff on the back. "Very good."
Chandra touched the scar gingerly. "Whoa, that feels weird."
Gideon said, "We need to get moving." His own disguise had been much easier. He had taken off his armor and weapons, torn his clothes, rolled in the dirt at their last stop, and had Shanna punch him in the face a couple of times.
"Be right there," Chandra said, as she wiggled into her weapons harness.
Gideon headed up the passage toward the stairs to the deck, Liliana following him. He asked her, "You're ready as well?"
"More than ready." She scrubbed her face with her hands. "I want this pact off my body. I want Belzenlok in pieces."
"It'll be over soon." Gideon tried to sound reassuring.
Liliana's expression was ironic. "One way or another."
They climbed the stairs to the open deck, and a view of Urborg by dawn light.
#figure(image("011_Return to Dominaria: Episode 11/05.jpg", width: 100%), caption: [Swamp | Art by <NAME> Ro], supplement: none, numbering: none)
The sky was still clouded with ash and it made the morning light dim and gray. The misty copse of swampy forest beneath the #emph[Weatherlight] seemed uninhabited, except for a half-buried ring-shaped Phyrexian structure. Gideon stepped to the railing where Karn stood beside Teferi, who watched something with a spyglass. Teferi lowered the glass and jerked his chin. "There it is."
Gideon had seen the shape of the volcano last night, outlined against the dark sky, but now the walls of the Stronghold were visible as it stretched up from the caldera. It had been created as a Phyrexian base, then had been partially destroyed by an eruption when the Phyrexians were defeated. "Belzenlok has done some rebuilding," Teferi commented. "Most of the tower was gone the last time I saw it."
Gideon gauged the distance. "We've got a long walk ahead of us, but Shanna's right, I wouldn't want to risk taking the ship any closer."
Gideon couldn't read Karn's expression, but somehow he didn't think Karn was regarding the place with any concern. Karn said, "We should get started."
Chandra and the others had come up on deck with Jhoira. Chandra now wore a Cabal sword across her back, with a long knife strapped to each thigh. "You look terribly frightening," Teferi assured her.
"Thanks," Chandra told him, smiling. "I know I smell terribly frightening."
Teferi laughed. "I wasn't going to mention that part."
Jaya gave Chandra a clap on the shoulder. "Just remember, you're prepared, and you can do it."
Chandra grinned. "Thanks to you."
As the others gathered, Jhoira said, "Be ready for our diversion. If it works, you should know immediately."
"Oh, it'll work all right," Liliana said. She hesitated, regarding Gideon and Chandra. "Don't get killed," she said finally. "It'd ruin everything."
Chandra snorted but Gideon told Liliana seriously, "We'll be fine." He knew her well enough by now to see she was genuinely worried, though her feelings were buried under layers of defensive sarcasm. She wanted to be rid of her pact, she wanted vengeance against Belzenlok, but she also didn't want to see Gideon and Chandra hurt.
Arvad dropped one of the ladders over the side for them. Karn climbed down first and Gideon followed him, dropping the last few feet down to the soft moss-covered mud. It was warmer on the ground even though the ash-filled sky made the sunlight dim and gray. The high grass and vine-covered trees blocked the breeze, and insects buzzed around the mud and weed-choked pools.
Gideon stood beside Karn and kept watch until Teferi and Chandra climbed down to join them. As Karn took the lead and started away through the trees, Chandra said, "Well, here we go."
Gideon squeezed her shoulder reassuringly. "It will work," he said. It had to work.
She looked up at him worriedly. "So . . . you really think Liliana has changed?"
"I do," Gideon said honestly. He shrugged and smiled a little. "I'm just not sure she knows it."
Chandra's expression said she thought he was out of his mind.
As they wove their way through scattered ruins, Gideon thought the landscape seemed even stranger than it had at night. Karn pushed a path through clinging vines and thorny brush, testing the ground with his weight. With the sky so overcast, shadows clung to the undergrowth and little sparks of light fled away through the high grass as they passed.
After they had been walking some time, the ground dipped into a grotto and they spotted several of the spirit creatures gathered there, apparently having a meeting. With a gesture Teferi slowed time around the spirits, holding the group all but frozen until Gideon and the others were through the grotto and out of sight again. Jhoira had said the spirits didn't support the Cabal, but they had decided not to take chances. Little, glowing, flitting things, bigger than insects, followed them for a time, but nothing attacked.
#figure(image("011_Return to Dominaria: Episode 11/06.jpg", width: 100%), caption: [Swamp | Art by <NAME>], supplement: none, numbering: none)
They encountered an old tumbled-down stone wall and had to climb over it. As Gideon reached the top he spotted the outline of something that looked like a single great claw, buried in vines and roots, a remnant of whatever Phyrexian weapon had destroyed the stone structure.
"There sure are a lot of ruins," Chandra said as she jumped down. "How many people lived here?"
"A great many," Karn said, glancing down at her as he circled around the claw. "Our friend Venser lived here once."
"The friend who gave you his spark?" Chandra asked, then winced. "Jhoira said—I know he died. I'm sorry."
Teferi's expression was sober. Karn nodded and said, "He was a good friend."
Now that the silence was broken, Gideon decided to ask the question he had been thinking about since Yavimaya. "After Belzenlok is dead, will you—both of you—come with us to fight Bolas?"
Teferi glanced at him with a quizzical smile. "Into the trap, you mean?"
Before Gideon could reply, Chandra said, "Hey, at least this time we know it's a trap!"
Teferi inclined his head, conceding the point. "I've fought <NAME> before."
Gideon was startled. "You did?"
"It was a very long time ago," Teferi explained. "I lost spectacularly."
"So did we, the last time we fought him," Chandra admitted.
"That is not encouraging information," Karn told her, but his voice held a trace of amusement.
Gideon said, "With Liliana at her full power, unrestrained by her pact, we can turn it into a trap for Bolas. We hope."
Teferi shrugged. "One of the reasons I took my spark back was to come with you. I know Bolas, and I know his plans will include my home, sooner or later. And now that I have a daughter and grandchildren and great-grandchildren to worry about, I find my perspective has changed." He clapped Karn on his metal shoulder. "What about you, my friend? Will you come with us?"
Karn said, "I need to take the Sylex to destroy New Phyrexia before the Phyrexians return to Dominaria."
"The Phyrexians are trapped there," Teferi pointed out. "You have all the time in the Multiverse to destroy them. As I—"
Karn interrupted, "Don't make a time-related pun, please."
Teferi chuckled. "All right, but you see my point."
Gideon noted that Karn hadn't said no. He prompted, "We could use your help, Karn. One more fighter might make the difference for us."
Karn was silent for a time, as he made a path for them through some thick brush. "You believe the threat he presents is this urgent?"
Chandra wiped sweat off her forehead. "He did terrible things on Amonkhet. I don't want to see that happen again anywhere. We've got to stop him."
#figure(image("011_Return to Dominaria: Episode 11/07.jpg", width: 100%), caption: [Damnation | Art by <NAME>], supplement: none, numbering: none)
Gideon agreed. "I'm not sure what his plans are, but I know we're running out of time. And I know our next encounter with him has to be decisive."
Teferi lifted his brows. "One way or another?"
"Unfortunately, yes," Gideon said.
Karn seemed to ponder it for a moment, then said, "I'll consider your invitation."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
With a quick break for food and water from the pack Gideon carried, it took them the better part of the day to reach the approach to the Stronghold.
They stopped on high ground, where dirt and vegetation had partially covered the rubble of a huge ruined wall that was tall enough to give them a concealed vantage point. The sky was getting darker, a storm threatening somewhere above the ash clouds. But it was still light enough for a good view of the Stronghold.
It was as the Cabal agent in Tolaria West had described it. A long stone walkway bridged the old canals and moats that terraced the sloped ground in front of the volcano. The canals were now filled with muddy water and some extremely hungry scaled creatures, and the walkway was interrupted by walls with heavy gates, all well guarded by armored grimnants and robed clerics, where passwords and other proof of identity would be asked for. One side of the volcano had been carved down smooth, and the walkway led up to the towering half-circle wall built out from it. The gate through that wall was round, still bearing the spiked shape of some hopefully defunct Phyrexian weapon.
With the bulk of the black tower looming over them and the sky even darker with ash and smoke, the scene was daunting. Gideon was glad they didn't have to fight their way through these defenses.
Gideon handed their supply pack to Karn, who shouldered it as Teferi said, "The spell should last more than long enough to get you through the gates. Once you're where you need to be, find a place out of sight, or at least in the shadows. When the spell ceases, there may be a pop of displaced air that could attract attention."
"Got it," Chandra said. She looked at Gideon. "Are we ready?"
Gideon thought they were as ready as they could get. After the long sweaty walk, they both looked even more the part of Cabal hunter and prisoner than they had on the #emph[Weatherlight] . He asked Teferi, "Will we be able to see the spell from the inside?"
Teferi stepped back, smiling wryly. "Don't worry, its effect will be obvious. Now, hold still."
He held out a hand. Gideon instinctively braced himself, but he felt nothing. Then he realized Teferi and Karn had seemed to freeze in place, that the sound of the breeze through the leaves, the buzz of insects and birdcalls, had all abruptly stopped. Gideon looked at the Stronghold again and saw that all the armored figures at the various checkpoints now stood like statues.
Chandra met his gaze, brows lifted. "Wow, this is weird."
Gideon had to agree. Then, though Teferi still appeared to be frozen, they heard his voice say, "Go now. A quick but even pace is best."
"Right, let's go," Gideon said. Chandra took hold of his arm, and, careful to stay even with her, Gideon started down the slope. It took effort to step out of the tall grass and reeds, out into the open and the full view of the grimnants atop the low outer wall. But as Gideon and Chandra moved across the open ground toward the walkway, the world was silent and unmoving.
Teferi had explained the spell would create a zone of slowed time all around them, so, walking normally, they would be moving too fast for anyone inside the zone to see them. They reached the end of the walkway, the packed dirt turning to smooth dark paving stones under their feet.
The first wall was a Phyrexian structure that looked like the teeth of some large creature, so organic in appearance that it might have grown up out of the ground. It was draped with the Cabal's red banners and the large metal gate across the walkway was at least twelve feet high.
Gideon and Chandra paused. "We can't just open it, I guess," Chandra said. "It's bigger than our time bubble."
Gideon wasn't sure what would happen if they tried to push it open. Better not to find out. "We'll climb it," he said.
Careful to stay close together, they climbed the gate, the broad crosspieces making a good ladder. It was awkward, but Gideon reminded himself it would have been much harder with the Cabal grimnants shooting poison-tipped arrows at them. On the far side, they edged around the still forms of the guards and a scatter of floating dark orbs, the manifestation of a spell to trap intruders. "This could take longer than we thought," Chandra said grimly, as they carefully picked their way across two trapdoors covered with metal spikes. "I hope Teferi gave us enough time. Ugh, I didn't mean to make a pun."
#figure(image("011_Return to Dominaria: Episode 11/08.jpg", width: 100%), caption: [Stronghold Confessor | Art by <NAME>], supplement: none, numbering: none)
"I know," Gideon said. "Just keep moving."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
On the #emph[Weatherlight] 's bridge, Liliana stood beside Jhoira while Tiana steered them low over the swamp. They headed to the area where one of the last battles between the panther warriors and the Cabal had taken place. "Though it was more like a massacre than a battle, from what I've been told," Jhoira had said.
Liliana had told her, "For our purposes, a massacre is better."
Now Jhoira leaned forward and told Tiana, "There's a spirit town to the south, we want to be sure to avoid it."
Jhoira didn't want the Cabal to know the #emph[Weatherlight] was here until they were ready. But Liliana could sense the presence of death ahead. Old death and cold rage. Many had died here, turning the trees and thick greenery into a charnel house, the plants feeding off the remains long ago rotted into the soil. The bones left behind cried out for vengeance. Liliana was more than willing to give it to them. She said, "We're close enough. Stop here."
Already reaching out to the unquiet dead below the #emph[Weatherlight] , Liliana turned away to climb down the stairs to the deck.
She walked out into rising wind, heavy with the scent of ash and rainwater and incipient lightning. This undead army would be a distraction, an attack to disrupt the Stronghold while Gideon and Chandra searched for the Blackblade and used it to destroy Belzenlok. But if Liliana had her way, her army would also break the Cabal's back in Urborg. The clerics and their death cultists would never recover from the blow dealt to them today.
She strode to the bow and stepped up onto the raised deck. As she lifted her arms, the lines of her pact glowed purple against her skin. "Hear me," she whispered. "I call you to me, to lead you to revenge and the destruction of the Cabal." The Onakke spirits in the Chain Veil whispered in her mind.
And in the grass and reeds and brush below, the dead stirred.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
It seemed to take forever, but Gideon and Chandra made it past each checkpoint without having to open a gate or move anything that might betray their existence. It wasn't so much being caught that worried Gideon, since he knew they appeared to be moving far too rapidly for a cleric to even think about performing a spell to attack them. But he didn't want anyone to find altered doors or gates and decide to search the Stronghold for intruders.
As they finally walked through the open doors to the first hall, Chandra said in exasperation, "That was way harder than it looked like it would be."
"If you hadn't realized we could walk on the water in that third trap, we'd never have made it," Gideon told her.
"I wish I'd thought of it quicker," Chandra admitted as they stopped to get their bearings. The hall was huge and shadowy, the pillars supporting the ceiling curved inward so it was like walking into a giant's ribcage. Red banners had been hung from the ceiling and Cabal cultists slumped on the floor in huddled groups. A haze of smoke from incense burners hung unmoving in the air with the floating torches that inadequately lit the space. It was still easy to tell this huge chamber was alien, something created by the Phyrexians and repurposed by the Cabal. Chandra added, "We'd better get out of sight. Teferi's spell can't last for much longer."
#figure(image("011_Return to Dominaria: Episode 11/09.jpg", width: 100%), caption: [Cabal Ritual | Art by <NAME>], supplement: none, numbering: none)
"Let's try to get further down, toward the fighting pit." Gideon led the way toward one of the openings at the side of the chamber, between two of the curving pillars. From questioning the Cabal agent, they knew roughly that the pit should be a few levels below this hall, and that the treasure vaults were near it. With Chandra disguised as a Cabal hunter and Gideon as her prisoner, brought to fight in the pit for the glory of Belzenlok and the entertainment of the cultists, they should be able to move relatively easily around the area. Once Liliana and the others arrived with their undead army, most of the Cabal forces would leave the Stronghold to fight, and Gideon and Chandra would have a chance to find the Blackblade and get to Belzenlok.
At least, that's how they hoped it would happen.
Past the hall they found a large corridor supported by the curved riblike pillars. #emph[An esophagus rather than a ribcage] , Gideon thought wryly. It was lit by more torches floating in the air, but its twists and turns made for many shadowy alcoves. They found one near a broad staircase leading down, temporarily empty of any Cabal cultists or guards. Gideon thought the light from the nearest torch might be starting to flicker. He turned to Chandra and held out his arms. "Hurry, I think the spell is nearly finished."
Chandra fastened the chains around Gideon's wrists. "Does that hurt?" she asked him worriedly.
"It's fine," he assured her. The light flickered again, and they both braced themselves.
Slowly, the silence around them filled like water poured into a bowl. Voices first, echoing in from the entry, chanting Belzenlok's titles over and over again. #emph[Demonlord, King of Urborg, Lord of the Wastes, Scion of Darkness] . Then distant moans, screams, metal banging, shouts. The torches flickered and black-robed Cabal cultists ran down the hall, armored grimnants following them.
Gideon and Chandra exchanged a grim look, then started toward the stairway.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Jhoira came up on deck with Shanna to watch Liliana raise the army of undead.
The ash-choked sky was even lower, thunder rumbling somewhere distant. Below the #emph[Weatherlight] , figures stirred in the grass and brush. They were the remnants of panther warriors, their bones clothed with shadows of the flesh they had once inhabited. Their weapons were rusted swords and spears that had been left buried under the mud, or clubs and rocks gathered from the ground. They formed groups, clusters, recreating the formations they had used to fight their last battle. They had fought the Cabal as long as they were able, and this swamp was a mass grave of their army.
"There are hundreds of them," Shanna said, leaning over the railing. Raff and Arvad stood on the other side of the deck with Jaya, watching warily. The thallid came up the stairs, stood there a moment, then sent its babies hurriedly back down the steps.
A dozen dark shapes appeared over the bow rail and Shanna reached for her sword. Jhoira caught her arm. "No, I think they're liches, called by Liliana."
As they crouched on the rail, their forms solidified into panther warriors. They still bore the wounds that had killed them, great bloodless slashes that had cut through their armor into their chests and arms. Shanna let go of her sword hilt but watched them warily. "This is strange," she commented.
"It'll get stranger before we're done," Jhoira told her.
Liliana spoke to the undead warriors in a soft tone, and the panthers replied. Jhoira could hear the words, but it was like listening to a language she couldn't understand. Then Liliana turned to say, "They're ready. They'll follow the ship into battle."
"Good," Jhoira breathed. She pushed back from the rail. The long wait was finally over; they would face the Cabal head on. "Raff, go tell Tiana to take us—"
"Jhoira!" Arvad called out.
Jhoira turned, and her eyes widened. Rising out of the swamp in the distance was a huge creature. A mottled dark green, its head was easily half the size of the #emph[Weatherlight] , surely too big for the distorted, long-limbed body clawing out of the mud and trees. The wide slash of its mouth opened to split the head in half and reveal a fanged maw like a cavern.
Shanna shouted, "Liliana, is that thing yours?"
In the bow, Liliana cursed, sounding more annoyed than startled. "I didn't call that thing! And whatever it is, it's not dead."
Jhoira murmured, "When I said it would get stranger, I didn't mean this." She drew on her power, pulling defensive spells together out of light and air.
Raff ran to her side, staring at the creature. "Uh. If we knew what it was, maybe—"
Jhoira glanced back. "Liliana—"
The panther liches had leaned down to whisper to Liliana again. She translated, "It's called Yargle. It was created when Belzenlok transformed some idiot called Yar-Kul into a maggot, which was eaten by a frog, which turned into that." She waved a hand in frustration. "And that was not at all helpful!"
"Do they know how to kill it?" Shanna asked.
Liliana grimaced. "No. It's what killed all of them."
#figure(image("011_Return to Dominaria: Episode 11/10.jpg", width: 100%), caption: [Yargle, Glutton of Urborg | Art by Jehan Choo], supplement: none, numbering: none)
Jhoira set her jaw. "This thing is not going to stop us." But it was going to delay them. Gideon and Chandra would be trapped in the Stronghold expecting the #emph[Weatherlight] to arrive at any moment.
Then Yargle roared and flung itself at the #emph[Weatherlight] .
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Gideon was tense with waiting. He and Chandra stood just outside the arena around the fighting pit. Through the huge curved archways, the chanting praises to Belzenlok grew louder and louder, almost drowning out the clash of weapons and screams from the pit.
"They should have been here by now," Chandra said under her breath. "Something's gone wrong."
That was what Gideon was afraid of. They had moved twice, trying to find inconspicuous places to wait, but the corridors and halls around the arena were becoming more crowded with cultists and clerics as they flooded in to watch their prisoners murder each other in the fighting pit. The entrance to the Cabal's treasure vaults, where their information said the Blackblade was kept, was nearby, so Gideon didn't want to retreat. But it was becoming harder not to get swept up in the crowd and pulled into the arena.
Either something had gone wrong with Liliana's attempt to raise an undead army, or worse, something had attacked them. #emph[They could be here any moment] , Gideon reminded himself. Then the cultists would be called to arms and the whole place would clear out as they ran to the outer defenses. #emph[All we have to do is wait] —
A crowd of cultists surged into the corridor and Chandra was shoved forward. Gideon tried to use his chains to brace her, but hands pushed him from behind and they stumbled into the arena with the crowd.
They came out onto a broad open walkway that ran along the edge of the pit. The screams and clashing of arms were much louder, though Gideon couldn't see into the pit from here. Hundreds of cultists stood on the ledges around the huge chamber, chanting a hymn. Torches floated above the pit and red banners hung from the curved ceiling. Chandra looked around for a way out, but Gideon was tall enough to see the path to the nearest archway was blocked by the crowd.
"Whisper comes," the cultists around them were chanting. "Whisper calls us to the pit."
A red-robed cleric swept in as the crowd parted for her. Cultists dropped to the floor so she could use their backs to step up to a raised platform. Evil radiated off her like a miasma as she raised her arms, letting her robe drop back. "The Demonlord approaches!"
Gideon swore under his breath. The chanting intensified and huge doors rumbled at the far end of the arena. The torches flared, and out of the shadows appeared a massive demonic shape. Belzenlok. He spread his wings and basked in the chants and screams of the cultists, the firelight glinting off his pale skin. His body was strong and muscular, his head heavy with curving horns. He strode forward and sat on the throne-like stone structure at the end of the arena. He gestured and Whisper bowed deeply to him. As she straightened up, she shouted, "Into the pit, for the glory of Belzenlok!"
#figure(image("011_Return to Dominaria: Episode 11/11.jpg", width: 100%), caption: [Whisper, Blood Liturgist | Art by <NAME>], supplement: none, numbering: none)
All around the arena, hunters and cultists shoved captives over the edge into the pit. As Whisper turned, her gaze fell on Gideon and Chandra. "You, send him in! Unless you want to die here with him?"
Chandra started to look up at Gideon, and he knew that was a mistake they couldn't make. He jerked away from her and said under his breath, "Push me into the pit."
"Gideon—" she protested.
"Do it. We need to buy more time." Whisper was watching them like a predator scenting prey. "Now!"
Chandra shoved him, and Gideon pretended to stagger, then tumbled backward into the pit.
|
|
https://github.com/vEnhance/1802 | https://raw.githubusercontent.com/vEnhance/1802/main/r12.typ | typst | MIT License | #import "@local/evan:1.0.0":*
#show: evan.with(
title: [Notes for 18.02 Recitation 12],
subtitle: [18.02 Recitation MW9],
author: "<NAME>",
date: [16 October 2024],
)
#quote(attribution: [<NAME> in the author notes for the Mystery Hunt puzzle \
#link("https://puzzles.mit.edu/2023/puzzlefactory.place/puzzles/5d-barred-diagramless-with-multiverse-time-travel")[5D Barred Diagramless with Multiverse Time Travel]])[
At some points, I was not convinced this puzzle should even exist,
but editors and testsolvers encouraged me to finish it, saying it was
"exactly the bullshit I expect to see in Mystery Hunt".
(The lucky postprodder for the puzzle would also like to voice his support.)
Hope you had fun! Really, it could have been much worse.
]
This handout (and any other DLC's I write) are posted at
#url("https://web.evanchen.cc/1802.html").
= Announcements and the like
Welcome back from the long weekend!
- *Midterm 2* is probably up to Lagrange multipliers but not including tomorrow's class.
- *Midterm 2 review session* is scheduled 3pm-5pm in 4-370.
- It will be a mock exam 3pm-4pm then solution presentation by me for 4pm-5pm.
- I will post the exam beforehand, so if you can only make
4pm-5pm you can try the mock yourself and then come to solutions. Solutions posted later too.
- *LAMV* is updated in preparation for Midterm 2, corresponds to Parts Delta, Echo, Foxtrot.
(This is the mega-file titled "Linear Algebra and Multivariable Calculus" on my page.)
- Part Delta has all the parametric stuff, it's about halfway written.
- Part Echo has all the partial derivative and gradient material and is essentially done.
- Part Foxtrot has all the critical point and Lagrange multipliers stuff and is essentially done.
= Highlights from LAMV
Again, see the full book at #url("https://web.evanchen.cc/upload/1802/lamv.pdf") for full exposition ---
(much more than I can fit on one printed page!
But here is a quick cheat sheet.
For every region, you care about what LAMV calls *boundary*, *limit case*, and *dimension*.
#recipe(title: [Recipe: The rule of thumb for regions])[
- The dimension is probably $n$ minus the number of $=$ constraints.
- The limit cases are obtained by turning $<$ and $>$ into limits,
and considering when any of the variables can go to $pm oo$.
- The boundary is obtained when any $<=$ and $>=$ becomes $=$.
]
#figure(
table(
columns: 4,
align: left,
table.header([Constraint], [Boundary], [Limit case], [Dimension]),
[$<=$ or $>=$], [Change to $=$ to get boundary], [No effect], [No effect],
[$<$ or $>$], [No effect], [Approach for limit case], [No effect],
[$=$], [No effect], [No effect], [Reduces dim by one],
),
kind: table,
caption: [Rules of thumb.]
)
For 18.02, we say region $cal(R)$ is compact if there are no limit cases.
That is, all the constraints are $=$, $<=$, or $>=$ (no $<$ or $>$)
and none of the variables can go to $pm oo$.
#tip(title: [Tip: Compact optimization theorem])[
If $cal(R)$ is a compact region,
and $f$ is a function to optimize on the region which is continuously defined everywhere,
then there must be at least one global minimum, and at least one global maximum.
(Works in both no-LM and LM case.)
]
#recipe(title: [Recipe for optimization without Lagrange Multipliers])[
Suppose you want to find the optimal values of $f : RR^n -> RR$ over a region $cal(R)$,
and $cal(R)$ has dimension $n$.
1. Evaluate $f$ on all the *critical points* of $f$ in the region $cal(R)$.
2. Evaluate $f$ on all the *boundary points* of $f$ in the region $cal(R)$.
3. Evaluate $f$ on all the *limit cases* of $f$ in the region $cal(R)$.
4. Output the points in the previous steps that give the best values,
or assert the optimal value doesn't exist (if points in step 3 do better than steps 1-2).
]
#recipe(title: [Recipe for Lagrange multipliers])[
Suppose you want to find the optimal values of $f : RR^n -> RR$ over a region $cal(R)$,
and $cal(R)$ has dimension $n-1$ due to a single constraint $g = c$ for some $g : RR^n -> RR$.
1. Evaluate $f$ on all the *LM-critical points* of $f$ that lie on the region $cal(R)$.
2. Evaluate $f$ on all the *boundary points* of $f$ of the region $cal(R)$.
3. Evaluate $f$ on all the *limit cases* of $f$ of the region $cal(R)$.
4. Output the points in the previous steps that give the best values,
or assert the optimal value doesn't exist (if points in step 3 do better than steps 1-2).
]
If there are any points at which $nabla f$, $nabla g$ are undefined,
you should check those as well. (Rare.)
= Recitation questions from official course
(Exercise before you start: which of these questions does
compact optimization theorem apply?)
/ 1.: Consider the function $f (x, y) = x^3 − 3 x y + y^3$.
Find the critical points of the function and use the second derivative test to classify them.
/ 2.: Find the maximum and minimum values of $x^3 + y^3$ on the region given by
$x^2 + 2y^2 <= 36$.
/ 3.: Find the maximum and minimum of $x^2 + x + 3y^2 + 2z^2$ on the unit sphere $x^2 + y^2 + z^2 = 1$.
|
https://github.com/voXrey/cours-informatique | https://raw.githubusercontent.com/voXrey/cours-informatique/main/typst/17-algorithmes-de-recherche.typ | typst | #import "@preview/codly:0.2.1": *
#show: codly-init.with()
#codly()
#set text(font: "Roboto Serif")
= Problèmes de Recherche et d’optimisation <problèmes-de-recherche-et-doptimisation>
== I - Problèmes de Recherche <i---problèmes-de-recherche>
On dispose d’un ensemble S de "candidats" et on souhaite savoir si l’un d’eux vérifie une certaine propriété, un tél élément est alors appelé solution.
#strong[Exemples]
+ Étant donnés $a lt.eq b in N$, existe-t-il un nombre premier dans $\[ a , b \]$ ?
+ Etant donné a un tableau d’entiers et $T in N$, existe-t-il une tranche du tableau qui somme à T ? Autrement dit, a-t-on :
$exists 0 lt.eq i lt.eq j lt.eq "len"\(a) : T \= sum\(a\[i:j\])$
+ Subset Sum :
Étant donné E un ensemble d’entiers et $T in Z$, existe-t-il un sous-ensemble $F subset.eq E : T = sum_(x in F) x$
+ Problème des N-dames :
Soit $n in N$, on souhaite placer N dames sur un échiquier $N times N$ de façon à qu’aucune ne puisse en prendre une autre, c’est-à-dire qu’aucune ne puisse se voire verticalement, horizontalement, ou en diagonal. Est-ce possible ?
+ Problème du cavalier :
Soit $n in N$, un cavalier partant du coin inférieur gauche (ou une autre position fixe) peut-il se rendre une unique fois sur chaque case de l’échiquier ?
+ Existence d’un colloscope :
Étant donné un EDT, des créneaux de colle, des groupes de colle, avec des contraintes (LV1, LV2, option SI…) et une contrainte de discipline par semaine, comment diable construire un colloscope ?
== II - Problèmes d’optimisation <ii---problèmes-doptimisation>
On a un espace de candidats S et une fonction `f` "score" qui va de S dans $R$.
Objectif : Optimiser f, c’est-à-dire trouver $x in S : x = m i n_S lr((f))$
#strong[Exemples]
+ Étant donné $a lt.eq b in N$, trouver le plus petit nombre premier dans $lr([a , b])$.
+ Tranche optimale : Étant donné un tableau a d’entiers, trouver i et j tels que $sum_(k = i)^(j - 1) a lr([k])$ soit le plus grand possible.
+ Problème du sac à dos :
On dispose de N objets de poids respectifs $p_1 , . . . p_N$ et de valeurs $v_1 , . . . v_N$. Notre sac de peut supporter plus qu’un poids P. Maximiser la valeur du sac, c’est-à-dire choisir un sous-ensemble $F subset.eq lr([1 , N]) : sum_(i in F) p_i lt.eq P$ et $sum_(i in F) v_i = m a x_(G subset.eq lr([1 , N])) { sum_(i in G) v_i \| sum_(i in G) }$
+ Problème du rendu de monnaie :
On dispose d’une liste $S = lr([1 , S lr([1]) , . . . S lr([k]) , . . .])$ triée qui représente un système monétaire. Étant donné $x in N$, en souhaitant donner $x$ euros à une personne en minimisant le nombre de pièces/billets, c’est-à-dire trouver une liste R de longueur $"len"(S)$ :
$
sum_(i\=0)^("len"(S)-1)R[i]S[i] = x "et" sum_(i=0)^(n)R[i]
$
soit minimale.
|
|
https://github.com/Jollywatt/typst-wordometer | https://raw.githubusercontent.com/Jollywatt/typst-wordometer/master/tests/all-tests.typ | typst | MIT License | // Use this to preview tests in real time
// typst watch --root . tests/all-tests.typ
#include "word-count-of/test.typ"
#include "word-count/test.typ"
#include "word-count-callback/test.typ"
#include "word-edge-cases/test.typ"
#include "sentences/test.typ"
#include "where-selectors/test.typ"
#include "text-extraction/test.typ"
#include "custom-counters/test.typ"
#include "exclude/test.typ"
#include "issues/test.typ"
#include "concat-adjacent-text/test.typ"
|
https://github.com/gdahia/typst-ams-fullpage-template | https://raw.githubusercontent.com/gdahia/typst-ams-fullpage-template/main/example.typ | typst | #import "template.typ": *
#let log = $upright(log)$
#let exp = $upright(exp)$
#let max = $upright(max)$
#let Gamma = $upright(Gamma)$
#show: ams-article.with(
title: "On discrete Fourier analysis
and applications",
short-title: "On discrete Fourier analysis and applications",
authors: (
(
name: "<NAME>",
organization: [IMPA],
location: [Rio de Janeiro, RJ, Brasil],
email: "<EMAIL>",
),
// (
// name: "Second author",
// organization: [University],
// location: [Brazil],
// email: "email",
// ),
// (
// name: "Third author",
// organization: [University],
// location: [Brazil],
// email: "email",
// ),
// (
// name: "Fourth author",
// organization: [University],
// location: [Brazil],
// email: "email",
// )
),
abstract: [In this short note we introduce a few tools in discrete Fourier analysis and prove Meshulam and Roth's theorem. These notes are based on a minicourse given by <NAME> at IMPA, summer 2024.],
bibliography-file: "refs.bib",
)
#show: ams-stmt-rules
#show: ams-general-rules
= Lecture 1: Fourier analysis and arithmetic progressions
<introduction>
Let $(G,dot)$ be a finite abelian group. A 3-AP in $G$ is simply a set of the form ${x,x+y,x+2y} subset.eq G$ with $x eq.not y$.
Let $S subset.eq G$ be a finite subset. We define
$ r_3(S) = max {A subset.eq S: A "is 3-AP free"}. $
The main question we are interested in is: what is the size of $r_3([N])$?
In 1953, Roth proved that that dense enough sets $A subset.eq [N]$ must
contain 3-AP, for density threshold $ delta approx frac(1,log log N)$.
In the late 1980's, this was improved by
Heath--Brown and Szemerédi to $delta approx 1/ (log N)^c$, for some small $c>0$.
This bound was further refined in the works of Bourgain in 1999 and 2008, and Sanders in 2012 where it is shown that one can take $c = 1 slash 2$, $c = 2 slash 3$, and then $c = 3 slash 4$.
In 2011, Sanders then obtained a density-threshold of the form $delta approx frac((log log N)^6,log N)$.
In 2016, this was further sharpened by a factor $(log log N)^2$
by Bloom and then in 2020 again by another factor $log log N$ by Schoen.
A bit later, Bloom and Sisask showed that a set $A subset.eq [N]$ with no
3-progressions must have density
$ delta = O (frac(1,(log N)^(1+c))) $
for some small $c>0$.
== Behrend's construction
In the other direction, it was shown by Behrend in 1946
that for infinitely many values $N$ there are indeed subsets $A subset.eq [N]$ of density roughly $delta approx 2^(-sqrt(log N))$ which are 3-AP free.
Behrend's major idea is that if we were looking for a progression-free sets in $RR^d$, then we could use spheres. So, consider an $d$-dimensional cube $[0,n]^d sect ZZ^d$ and family of spheres $x_1^2+x_2^2+...+x_d^2 = t$ for $t=1,...,d n^2$.
Each point in the cube is contained in one of the spheres, and so at least one of the spheres contains $n^d slash (d n^2)$ lattice points. Let us call this set $A$.
Since spheres do not contain arithmetic progressions, $A$ does not contain any progressions either.
Now let $f$ be a Freiman isomorphism from $A$ to a subset of $ZZ$ defined as follows.
If $x = (x_1,x_2,...,x_d)$ is a point of $A$, then $f(x) = x_1 + x_2 (2 n) + x_3 (2 n)^2 + ... + x_d (2 n)^(d-1)$
That is, we treat $x_i$ as $i$'th digit of $f(x)$ in base $2 n$.
Observe that this base was chosen so that $f$ is a Freiman isomorphism of order 2.
Note that $f(A) subset.eq {1,2,...,N = (2 n)^d}$ and that $f(A)$ is a progression-free set of size at least $n^d slash (d n^2)$.
Moreover, the density of $f(A)$ in the interval $[1,N]$ is at least
$ frac(n^d, d n^2 N) = frac(1, d 2^(d) n^2) approx frac(1, 2^d n^2) approx frac(1,2^d N^(2/d)). $
The last approximation follows from the fact that $N = (2 n)^d$.
the expression $2^d N^(2/d)$ is minimized when $d = sqrt(log N)$, and so we get that the density of $f(A)$ is at least $2^(-Omega(sqrt(log N))).$
In a major breakthrough, Kelley and Meka showed that Behrend's construction is essentially optimal. More precisely, they proved the following theorem.
#theorem[
Let $N$ be a large integer. Then, there exists a subset $A subset.eq [N]$ of size at least $N e^(-(log N)^(1/11))$ which has no nontrivial 3-progressions.
]<kelley-meka>
== A bit of discrete Fourier analysis
Let $G$ be a finite abelian group and let $A subset.eq G$ be an arbitrary subset. Define the indicator function of $A$ as
$ 1_A = cases(1 "if" x in A, , 0 "otherwise".) $
We denote by $L_2(G)$ the space of complex-valued functions on $G$ with the usual inner product, namely
$ angle.l f,g angle.r = frac(1,|G|) sum_(x in G) f(x) overline(g(x)) = EE_(x in G) f(x) overline(g(x)). $
Observe that $L_2(G)$ is a $CC$-vector space of dimension $|G|$.
The *Physical space basis* is the set of functions $delta_z: G -> CC$ defined by
$ delta_z (x) = cases(1 "if" x in A, , 0 "otherwise".) $
#definition[
A character of $G$ is a group homomorphism $chi: G -> CC^*$. In other words, a character is a function $chi$ such that $chi(x+y) = chi(x) chi(y)$ for all $x,y in G$.
]
The set of characters also defines a group, called the *dual group* of $G$ and denoted by $hat(G)$.
A special character is the identity function $chi_0(x) = 1$ for all $x in G$.
Now, our next goal is to prove the following theorem.
#theorem[
The set of characters of $G$ forms an orthonormal basis of $L_2(G)$.
]<characters-basis>
The first step is to show that the characters are indeed orthonormal is to prove the following lemma.
#lemma[
Let $chi eq.not chi_0$ be a character of $G$. Then,
$ EE_(x in G) chi(x) = 0. $
]<characters-orthonormal>
#proof[
Let $chi$ be a character of $G$ different from $chi_0$. As $chi eq.not chi_0$, there exists $y in G$ such that $chi(y) eq.not 1$.
Then, we have
$ EE_(x in G) chi(x) = EE_(x in G) chi(x+y) = chi(y) dot EE_(x in G) chi(x). $
Since $chi(y) eq.not 1$, we conclude that $EE_(x in G) chi(x) = 0$.
]
Now we are ready to prove @characters-basis.
#block[#emph[Proof of @characters-basis .] First, we observe that all characters have norm 1, since
$ angle.l chi,chi angle.r = EE_(x in G) chi(x) overline(chi(x)) = EE_(x in G) |chi(x)|^2 = 1. $
Now, we show that they form an orthonormal set. Let $chi,chi'$ be two characters of $G$. If $chi eq.not chi'$, then we have]
#v(5cm)
|
|
https://github.com/ymgyt/techbook | https://raw.githubusercontent.com/ymgyt/techbook/master/programmings/js/typescript/specification/any.md | markdown | # any type
* 何でもassignできる
```typescript
let x: any;
x = 1; // OK
x = "string"; // OK
x = { name: "オブジェクト" }; // OK
```
## implicit any
```typescript
function ok(arg) { }
```
* `arg`の型は`any`になる
* tsconfig.jsonの`noImplicitAny: true`を指定すると、compile時にerrorにできる
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1F700.typ | typst | Apache License 2.0 | #let data = (
("ALCHEMICAL SYMBOL FOR QUINTESSENCE", "So", 0),
("ALCHEMICAL SYMBOL FOR AIR", "So", 0),
("ALCHEMICAL SYMBOL FOR FIRE", "So", 0),
("ALCHEMICAL SYMBOL FOR EARTH", "So", 0),
("ALCHEMICAL SYMBOL FOR WATER", "So", 0),
("ALCHEMICAL SYMBOL FOR AQUAFORTIS", "So", 0),
("ALCHEMICAL SYMBOL FOR AQUA REGIA", "So", 0),
("ALCHEMICAL SYMBOL FOR AQUA REGIA-2", "So", 0),
("ALCHEMICAL SYMBOL FOR AQUA VITAE", "So", 0),
("ALCHEMICAL SYMBOL FOR AQUA VITAE-2", "So", 0),
("ALCHEMICAL SYMBOL FOR VINEGAR", "So", 0),
("ALCHEMICAL SYMBOL FOR VINEGAR-2", "So", 0),
("ALCHEMICAL SYMBOL FOR VINEGAR-3", "So", 0),
("ALCHEMICAL SYMBOL FOR SULFUR", "So", 0),
("ALCHEMICAL SYMBOL FOR PHILOSOPHERS SULFUR", "So", 0),
("ALCHEMICAL SYMBOL FOR BLACK SULFUR", "So", 0),
("ALCHEMICAL SYMBOL FOR MERCURY SUBLIMATE", "So", 0),
("ALCHEMICAL SYMBOL FOR MERCURY SUBLIMATE-2", "So", 0),
("ALCHEMICAL SYMBOL FOR MERCURY SUBLIMATE-3", "So", 0),
("ALCHEMICAL SYMBOL FOR CINNABAR", "So", 0),
("ALCHEMICAL SYMBOL FOR SALT", "So", 0),
("ALCHEMICAL SYMBOL FOR NITRE", "So", 0),
("ALCHEMICAL SYMBOL FOR VITRIOL", "So", 0),
("ALCHEMICAL SYMBOL FOR VITRIOL-2", "So", 0),
("ALCHEMICAL SYMBOL FOR ROCK SALT", "So", 0),
("ALCHEMICAL SYMBOL FOR ROCK SALT-2", "So", 0),
("ALCHEMICAL SYMBOL FOR GOLD", "So", 0),
("ALCHEMICAL SYMBOL FOR SILVER", "So", 0),
("ALCHEMICAL SYMBOL FOR IRON ORE", "So", 0),
("ALCHEMICAL SYMBOL FOR IRON ORE-2", "So", 0),
("ALCHEMICAL SYMBOL FOR CROCUS OF IRON", "So", 0),
("ALCHEMICAL SYMBOL FOR REGULUS OF IRON", "So", 0),
("ALCHEMICAL SYMBOL FOR COPPER ORE", "So", 0),
("ALCHEMICAL SYMBOL FOR IRON-COPPER ORE", "So", 0),
("ALCHEMICAL SYMBOL FOR SUBLIMATE OF COPPER", "So", 0),
("ALCHEMICAL SYMBOL FOR CROCUS OF COPPER", "So", 0),
("ALCHEMICAL SYMBOL FOR CROCUS OF COPPER-2", "So", 0),
("ALCHEMICAL SYMBOL FOR COPPER ANTIMONIATE", "So", 0),
("ALCHEMICAL SYMBOL FOR SALT OF COPPER ANTIMONIATE", "So", 0),
("ALCHEMICAL SYMBOL FOR SUBLIMATE OF SALT OF COPPER", "So", 0),
("ALCHEMICAL SYMBOL FOR VERDIGRIS", "So", 0),
("ALCHEMICAL SYMBOL FOR TIN ORE", "So", 0),
("ALCHEMICAL SYMBOL FOR LEAD ORE", "So", 0),
("ALCHEMICAL SYMBOL FOR ANTIMONY ORE", "So", 0),
("ALCHEMICAL SYMBOL FOR SUBLIMATE OF ANTIMONY", "So", 0),
("ALCHEMICAL SYMBOL FOR SALT OF ANTIMONY", "So", 0),
("ALCHEMICAL SYMBOL FOR SUBLIMATE OF SALT OF ANTIMONY", "So", 0),
("ALCHEMICAL SYMBOL FOR VINEGAR OF ANTIMONY", "So", 0),
("ALCHEMICAL SYMBOL FOR REGULUS OF ANTIMONY", "So", 0),
("ALCHEMICAL SYMBOL FOR REGULUS OF ANTIMONY-2", "So", 0),
("ALCHEMICAL SYMBOL FOR REGULUS", "So", 0),
("ALCHEMICAL SYMBOL FOR REGULUS-2", "So", 0),
("ALCHEMICAL SYMBOL FOR REGULUS-3", "So", 0),
("ALCHEMICAL SYMBOL FOR REGULUS-4", "So", 0),
("ALCHEMICAL SYMBOL FOR ALKALI", "So", 0),
("ALCHEMICAL SYMBOL FOR ALKALI-2", "So", 0),
("ALCHEMICAL SYMBOL FOR MARCASITE", "So", 0),
("ALCHEMICAL SYMBOL FOR SAL-AMMONIAC", "So", 0),
("ALCHEMICAL SYMBOL FOR ARSENIC", "So", 0),
("ALCHEMICAL SYMBOL FOR REALGAR", "So", 0),
("ALCHEMICAL SYMBOL FOR REALGAR-2", "So", 0),
("ALCHEMICAL SYMBOL FOR AURIPIGMENT", "So", 0),
("ALCHEMICAL SYMBOL FOR BISMUTH ORE", "So", 0),
("ALCHEMICAL SYMBOL FOR TARTAR", "So", 0),
("ALCHEMICAL SYMBOL FOR TARTAR-2", "So", 0),
("ALCHEMICAL SYMBOL FOR QUICK LIME", "So", 0),
("ALCHEMICAL SYMBOL FOR BORAX", "So", 0),
("ALCHEMICAL SYMBOL FOR BORAX-2", "So", 0),
("ALCHEMICAL SYMBOL FOR BORAX-3", "So", 0),
("ALCHEMICAL SYMBOL FOR ALUM", "So", 0),
("ALCHEMICAL SYMBOL FOR OIL", "So", 0),
("ALCHEMICAL SYMBOL FOR SPIRIT", "So", 0),
("ALCHEMICAL SYMBOL FOR TINCTURE", "So", 0),
("ALCHEMICAL SYMBOL FOR GUM", "So", 0),
("ALCHEMICAL SYMBOL FOR WAX", "So", 0),
("ALCHEMICAL SYMBOL FOR POWDER", "So", 0),
("ALCHEMICAL SYMBOL FOR CALX", "So", 0),
("ALCHEMICAL SYMBOL FOR TUTTY", "So", 0),
("ALCHEMICAL SYMBOL FOR CAPUT MORTUUM", "So", 0),
("ALCHEMICAL SYMBOL FOR SCEPTER OF JOVE", "So", 0),
("ALCHEMICAL SYMBOL FOR CADUCEUS", "So", 0),
("ALCHEMICAL SYMBOL FOR TRIDENT", "So", 0),
("ALCHEMICAL SYMBOL FOR STARRED TRIDENT", "So", 0),
("ALCHEMICAL SYMBOL FOR LODESTONE", "So", 0),
("ALCHEMICAL SYMBOL FOR SOAP", "So", 0),
("ALCHEMICAL SYMBOL FOR URINE", "So", 0),
("ALCHEMICAL SYMBOL FOR HORSE DUNG", "So", 0),
("ALCHEMICAL SYMBOL FOR ASHES", "So", 0),
("ALCHEMICAL SYMBOL FOR POT ASHES", "So", 0),
("ALCHEMICAL SYMBOL FOR BRICK", "So", 0),
("ALCHEMICAL SYMBOL FOR POWDERED BRICK", "So", 0),
("ALCHEMICAL SYMBOL FOR AMALGAM", "So", 0),
("ALCHEMICAL SYMBOL FOR STRATUM SUPER STRATUM", "So", 0),
("ALCHEMICAL SYMBOL FOR STRATUM SUPER STRATUM-2", "So", 0),
("ALCHEMICAL SYMBOL FOR SUBLIMATION", "So", 0),
("ALCHEMICAL SYMBOL FOR PRECIPITATE", "So", 0),
("ALCHEMICAL SYMBOL FOR DISTILL", "So", 0),
("ALCHEMICAL SYMBOL FOR DISSOLVE", "So", 0),
("ALCHEMICAL SYMBOL FOR DISSOLVE-2", "So", 0),
("ALCHEMICAL SYMBOL FOR PURIFY", "So", 0),
("ALCHEMICAL SYMBOL FOR PUTREFACTION", "So", 0),
("ALCHEMICAL SYMBOL FOR CRUCIBLE", "So", 0),
("ALCHEMICAL SYMBOL FOR CRUCIBLE-2", "So", 0),
("ALCHEMICAL SYMBOL FOR CRUCIBLE-3", "So", 0),
("ALCHEMICAL SYMBOL FOR CRUCIBLE-4", "So", 0),
("ALCHEMICAL SYMBOL FOR CRUCIBLE-5", "So", 0),
("ALCHEMICAL SYMBOL FOR ALEMBIC", "So", 0),
("ALCHEMICAL SYMBOL FOR BATH OF MARY", "So", 0),
("ALCHEMICAL SYMBOL FOR BATH OF VAPOURS", "So", 0),
("ALCHEMICAL SYMBOL FOR RETORT", "So", 0),
("ALCHEMICAL SYMBOL FOR HOUR", "So", 0),
("ALCHEMICAL SYMBOL FOR NIGHT", "So", 0),
("ALCHEMICAL SYMBOL FOR DAY-NIGHT", "So", 0),
("ALCHEMICAL SYMBOL FOR MONTH", "So", 0),
("ALCHEMICAL SYMBOL FOR HALF DRAM", "So", 0),
("ALCHEMICAL SYMBOL FOR HALF OUNCE", "So", 0),
("LOT OF FORTUNE", "So", 0),
("OCCULTATION", "So", 0),
("LUNAR ECLIPSE", "So", 0),
(),
(),
(),
(),
("HAUMEA", "So", 0),
("MAKEMAKE", "So", 0),
("GONGGONG", "So", 0),
("QUAOAR", "So", 0),
("ORCUS", "So", 0),
)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/features_08.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 26-31 expected integer or none, found boolean
// #set text(stylistic-set: false) |
https://github.com/ivaquero/scibook | https://raw.githubusercontent.com/ivaquero/scibook/main/0.1.0/scibook.typ | typst | // multi-languages
#import "@preview/linguify:0.4.1": *
// indent
#import "@preview/indenta:0.0.3": fix-indent
// header-footer
#import "@preview/hydra:0.5.1": *
// chemistry
#import "@preview/whalogen:0.2.0": ce
// physics
#import "@preview/physica:0.9.2": *
// theorems
#import "@preview/ctheorems:1.1.3": *
// banners
#import "@preview/gentle-clues:1.0.0": *
// figures
#import "@preview/subpar:0.1.1": grid as sgrid
// wrap
#import "@preview/wrap-it:0.1.0": wrap-content
// diagram
#import "@preview/fletcher:0.5.0": diagram, node, edge
// numbering
#import "@preview/i-figured:0.2.4"
// index
#import "@preview/in-dexter:0.4.2": *
#let conf(
title: none,
author: (),
header-cap: [],
footer-cap: [],
outline-on: true,
eqnumstyle: "1",
eqnumsep: ".",
eqnumlevel: 1,
par-leading: 1em,
list-indent: 1.2em,
block-above: 1em,
block-below: 0.5em,
figure-break: false,
lang: "zh",
doc,
) = {
set page(
paper: "a4",
numbering: "1",
header: context {
set text(size: 8pt)
if calc.odd(here().page()) {
align(right, [#header-cap #h(6fr) #emph(hydra(1))])
} else {
align(left, [#emph(hydra(1)) #h(6fr) #header-cap])
}
line(length: 100%)
},
footer: context {
set text(size: 8pt)
let page_num = here().page()
if calc.odd(page_num) {
align(
right,
[#footer-cap #datetime.today().display("[year]-[month]-[day]") #h(6fr) #page_num],
)
} else {
align(
left,
[#page_num #h(6fr) #footer-cap #datetime.today().display("[year]-[month]-[day]")],
)
}
},
)
set heading(numbering: "1.1")
set par(
first-line-indent: 2em,
justify: true,
leading: par-leading,
linebreaks: "optimized",
)
set block(above: block-above, below: block-below)
set list(indent: list-indent)
set enum(indent: list-indent)
let fonts = toml("fonts.toml")
set text(
font: fonts.at(lang).context,
size: 10.5pt,
lang: lang,
)
let lang_data = toml("lang.toml")
set-database(lang_data)
set ref(supplement: it => {
if it.func() == heading {
linguify("chapter")
} else if it.func() == table {
it.caption
} else if it.func() == image {
it.caption
} else if it.func() == figure {
it.supplement
} else if it.func() == math.equation {
linguify("eq")
} else { }
})
show heading: i-figured.reset-counters.with(level: 2)
show math.equation: i-figured.show-equation
set figure.caption(separator: " ")
show figure: it => align(
center,
block(breakable: figure-break)[
#it.body#it.caption
],
)
show raw.where(block: true): block.with(
fill: luma(240),
inset: .8em,
radius: 5pt,
width: 100%,
)
align(
center,
text(size: 20pt, font: fonts.at(lang).title)[
*#title*
],
)
if outline-on == true [
#outline(
title: linguify("content"),
indent: auto,
depth: 2,
)
#pagebreak()
]
show link: underline
show: thmrules
show: fix-indent()
doc
}
// text
#let fonts = toml("fonts.toml")
#let ctext(body) = text(body, font: fonts.at("zh").math)
// tables
#let frame(stroke) = (
(x, y) => (
top: if y < 2 {
stroke
} else {
0pt
},
bottom: stroke,
)
)
#let ktable(data, k, inset: 0.3em) = table(
columns: k,
inset: inset,
align: center + horizon,
stroke: frame(rgb("000")),
..data.flatten(),
)
// codes
#let code(text, lang: "python", breakable: true, width: 100%) = block(
fill: rgb("#F3F3F3"),
stroke: rgb("#DBDBDB"),
inset: (x: 1em, y: 1em),
outset: -.3em,
radius: 5pt,
spacing: 1em,
breakable: breakable,
width: width,
raw(
text,
lang: lang,
align: left,
block: true,
),
)
// theorems
#let definition = thmbox(
"definition",
text(linguify("definition"), font:""),
base_level: 1,
separator: [#h(0.5em)],
padding: (top: 0em, bottom: 0em),
fill: rgb("#FFFFFF"),
// stroke: rgb("#000000"),
inset: (left: 0em, right: 0.5em, top: 0.2em, bottom: 0.2em)
)
#let theorem = thmbox(
"theorem",
text(linguify("theorem"), font:""),
base_level: 1,
separator: [#h(0.5em)],
padding: (top: 0em, bottom: 0.2em),
fill: rgb("#E5EEFC"),
// stroke: rgb("#000000")
)
#let lemma = thmbox(
"theorem",
text(linguify("lemma"), font: ""),
separator: [#h(0.5em)],
fill: rgb("#EFE6FF"),
titlefmt: strong,
)
#let corollary = thmbox(
"corollary",
text(linguify("corollary"), font:""),
// base: "theorem",
separator: [#h(0.5em)],
titlefmt: strong
)
#let rule = thmbox(
"",
text(linguify("rule"), font: ""),
base_level: 1,
separator: [#h(0.5em)],
fill: rgb("#EEFFF1"),
titlefmt: strong,
)
#let algo = thmbox(
"",
text(linguify("algorithm"), font: ""),
base_level: 1,
separator: [#h(0.5em)],
padding: (top: 0em, bottom: 0.2em),
fill: rgb("#FAF2FB"),
titlefmt: strong,
)
// banners
#let tip(title: text(linguify("tip"), font: ""), icon: emoji.lightbulb, ..args) = clue(
accent-color: yellow,
title: title,
icon: icon,
..args,
)
#let alert(title: text(linguify("alert"), font: ""), icon: emoji.excl, ..args) = clue(
accent-color: red,
title: title,
icon: icon,
..args,
)
|
|
https://github.com/Loosetooth/next-rehype-typst-mdx | https://raw.githubusercontent.com/Loosetooth/next-rehype-typst-mdx/main/README.md | markdown | A small test to get markdown formulas working using [Typst](https://typst.app) in [MDX](https://mdxjs.com/).
This uses Next.js and [rehype-typst](https://github.com/Myriad-Dreamin/typst.ts/tree/main/projects/rehype-typst) under the hood.
---
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/polygon_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 10-17 point array must contain exactly two entries
// #polygon((50pt,)) |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/titleize/0.1.0/README.md | markdown | Apache License 2.0 | # titleize
Small wrapper around the [titlecase](https://crates.io/crates/titlecase) library to convert text to title case.
It follows the [rules defined by <NAME>](https://daringfireball.net/2008/05/title_case).
For more details, refer to the library.
```typst
#import "@preview/titleize:0.1.0": titlecase
#set page(width: auto, height: auto, margin: 1cm)
#for s in (
"Being productive on linux",
"Finding an alternative to Mac OS X — part 2",
"an example with small words and sub-phrases: \"the example\"",
) [
#s => #titlecase(s) \
]
```
 |
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/let_fn.typ | typst | Apache License 2.0 | #let f() = 1;
#let f(a) = 1;
#let f(a, b: none) = 1;
#let f(a, (b, c)) = 1;
#let f(a, (b, c: d)) = 1;
#let f((a, b)) = 1;
#let f((a, (c: (b: e)))) = 1;
#let f((a, ..)) = 1;
#let f((.., a)) = 1; |
https://github.com/MattiaOldani/Informatica-Teorica | https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/calcolabilità/08_richiami_matematici.typ | typst | #import "../alias.typ": *
#import "@preview/lemmify:0.1.5": *
#let (
theorem, lemma, corollary,
remark, proposition, example,
proof, rules: thm-rules
) = default-theorems("thm-group", lang: "it")
#show: thm-rules
#show thm-selector("thm-group", subgroup: "theorem"): it => block(
it,
stroke: red + 1pt,
inset: 1em,
breakable: true
)
= Richiami matematici: chiusura
== Operazioni
Dato un insieme $U$, si definisce *operazione* su $U$ una qualunque funzione $ "op": underbracket(U times dots times U, k) arrow.long U. $
Il numero $k$ indica l'*arietà* (o _arità_) dell'operazione, ovvero la dimensione del dominio dell'operazione.
== Proprietà di chiusura
L'insieme $A subset.eq U$ si dice *chiuso* rispetto all'operazione $"op": U^k arrow.long U$ se e solo se $ forall a_1, dots, a_k in A quad "op"(a_1, dots, a_k) in A. $ In poche parole, _se opero in A rimango in A_. In generale, se $Omega$ è un insieme di operazioni su $U$, allora $A subset.eq U$ è chiuso rispetto a $Omega$ se e solo se $A$ è chiuso per *ogni* operazione in $Omega$.
== Chiusura di un insieme
Siano $A subset.eq U$ insieme e $"op" : U^k arrow.long U$ un'operazione su esso, vogliamo espandere l'insieme $A$ per trovare il più piccolo sottoinsieme di $U$ tale che:
+ contiene $A$;
+ chiuso per $"op"$.
Quello che vogliamo fare è espandere $A$ il minimo possibile per garantire la chiusura rispetto a $"op"$.
Due risposte ovvie a questo problema sono:
+ se $A$ è chiuso rispetto a $"op"$, allora $A$ stesso è l'insieme cercato;
+ sicuramente $U$ soddisfa le due richieste, _ma è il più piccolo?_
#theorem(numbering: none)[
Siano $A subset.eq U$ insieme e $"op" : U^k arrow.long U$ un'operazione su esso. Il più piccolo sottoinsieme di $U$ contenente $A$ e chiuso rispetto all'operazione $"op"$ si ottiene calcolando la *chiusura di $A$ rispetto a $"op"$*, e cioè l'insieme $A^"op"$ definito *induttivamente* come:
+ $forall a in A arrow.long.double a in A^"op"$;
+ $forall a_1, dots, a_k in A^"op" arrow.long.double "op"(a_1, dots, a_k) in A^"op"$;
+ nient'altro sta in $A^"op"$.
]
Vediamo una definizione più _operativa_ di $A^"op"$:
+ metti in $A^"op"$ tutti gli elementi di $A$;
+ applica $"op"$ a una $k$-tupla di elementi in $A^"op"$;
+ se trovi un risultato che non è già in $A^"op"$ allora aggiungilo ad $A^"op"$;
+ ripeti i punti (2) e (3) fintantoché $A^"op"$ cresce.
Siano $Omega = {"op"_1, dots, "op"_t}$ un insieme di operazioni su $U$ di arietà rispettivamente $k_1, dots, k_t$ e $A subset.eq U$ insieme. Definiamo *chiusura di $A$ rispetto a $Omega$* il più piccolo sottoinsieme di $U$ contenente $A$ e chiuso rispetto a $Omega$, cioè l'insieme $A^Omega$ definito come:
- $forall a in A arrow.long.double a in A^Omega$;
- $forall i in {1,dots,t} quad forall a_1, dots, a_(k_i) in A^Omega arrow.long.double "op"_i (a_1, dots, a_(k_i)) in A^Omega$;
- nient'altro è in $A^Omega$.
|
|
https://github.com/PeiPei233/typst-template | https://raw.githubusercontent.com/PeiPei233/typst-template/main/README.md | markdown | # typst-template
My Typst Template
|
|
https://github.com/cran/tinytable | https://raw.githubusercontent.com/cran/tinytable/master/NEWS.md | markdown | # News
## 0.5.0
New:
* `output="html_portable"` returns a portable HTML file, where `plot_tt()` encodes and embeds the images directly in the HTML code, rather than link to external images. Thanks to @J-Moravec for implementing this nice feature!
* `format_tt()` gets a `math` argument to wrap cell content in $...$ math mode.
* `group_tt(i = vec)` accepts a vector of labels of length equal to the number of rows in the dataset.
* `tt()` gets an `escape` argument. Thanks to <NAME> for the feature request.
* The `i` argument in `style_tt()` now accepts a logical matrix of same dimensions as `x`, to style specific cells, rather than all combinations of `i` and `j` vectors. Thanks to @dhicks for the feature request #329.
* `style_tt()` gets new `output` argument for conditional styling based on output format.
* `names()` method now supported for both returning column names and re-assingning them. Issue #332.
Typst:
* Table code is much more concise and efficient.
* Fix indexing bug for groups. Issue #323 and #343.
* `style_tt()` can override cell styling with successive calls, and the call order is respected.
* `options(tinytable_quarto_figure = FALSE)` wraps Typst tables in a `figure` environment in Quarto documents.
Bugs:
* `theme_tabular()` is no longer greedy in replacing `cmidrule`. Thanks to @jsr-p for code submission #349.
## 0.4.0
### Breaking change
HTML tables no longer insert MathJax scripts by default. This behavior could enter in conflict with other MathJax scripts loaded explicitly by the user or automatically by Quarto. Users can revert to the previous behavior by setting a global option:
`options(tinytable_html_mathjax = TRUE)`
Alternatively, users can insert appropriate scripts directly in their HTML document or as a Quarto literal chunk:
````
```{=html}
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']]
},
svg: {
fontCache: 'global'
}
};
</script>
```
````
* Option `tinytable_markdown_hlines` has been removed. To get a more minimal looking markdown table, use output "gfm" which is gfm compliant.
### General
* Global options are more consistent and better documented. Thanks to @kylebutts for PR #313.
* Support Viewer Pane in Positron IDE. Thank to @kylebutts for code contribution in PR #299.
* Improved documentation.
* `format_tt(markdown=TRUE)` escapes groups and notes when `i` and `j` are `NULL`.
* `plot_tt()`: The `height` argument is now respected in Markdown and Word documents.
* `group_tt()` allows 0 and duplicates in `i` argument for labels in the first row and consecutive labels.
* Headers are now styled and formatted when `i=NULL`.
* `colnames(x)<-NULL` works on a `tinytable` object.
* `format_tt(num_big_mark)` applies to integer columns.
* Use `getOption("viewer")` instead of `rstudioapi::viewer()` for positron support
* `glue::glue()` string is accepted by `format_tt()`. Thanks to @LukasWallrich for report #792 on the `modelsummary` repository.
* Support Github Flavored Markdown (`gfm`) output. Thanks to @kylebutts for contribution #315.
* `theme_tt("rotate")` to rotate tables in LaTeX or Typst.
* `save_tt("/path/to/file")` returns the file path invisibly. Thanks to @yjunechoe for issue #328.
### HTML
* Simplify JS functions in HTML documents. Avoid nesting full HTML documents inside Quarto output.
* Remove polyfill JS because of security issues.
* Avoid error in interactive use in Positron.
### LaTeX
* `theme_tt("tabular")` no longer uses `tabularray` or `booktabs`. Only relies on basic LaTeX packages.
* `theme_tt("tabular", style = "tabularray")` does the same as above, but keeps the `\begin{tblr}` environment.
### Typst
* `style_tt()` supports `align` for different rows and cells, rather than just whole columns.
* `style_tt()` supports `indent` argument.
* `group_tt()` supports `indent` argument.
* No more gutters when `group_tt(j)` and `style_tt(background)`
* `theme_tt(x, horizontal = "l")` can left, center, or right-align a table in the page.
### Global options
* `save_tt("pdf")`:
- `options(tinytable_save_pdf_clean = TRUE)`
- `options(tinytable_save_pdf_engine = "xelatex")`
* `options(tinytable_tt_rownames=TRUE)`: Print row names in the first column by calling. Thanks to @rsbivand for Issue #264.
* EXPERIMENTAL: `options(tinytable_html_mathjax = TRUE)`. Inserts MathJax scripts in the HTML file. This may cause conflicts if MathJax is otherwise loaded in the document.
### Bugs
* Footnotes were center-aligned in some Quarto chunks. Thanks to @andrewheiss for report #303.
* `replace` does not work in LaTeX with `format_tt(quarto=TRUE)`. Thanks to @cbgoodman for Issue #263.
* `style_tt(indent)` works for LaTeX
* Notes were hard-coded to 5 colspan. We now use the actual number of columns in the table. Thanks to @DominikVogel for report #788.
* Do not suppress labels when inserting notes. Thanks to @cportner for Issue #290.
* `format_tt()` on a table without column names. Thanks to @andrewheiss for report #306.
* \cmidrule[lr] requires [] in tabularray but () otherwise. Thanks to @andrewheiss for report #307.
## 0.3.0
Breaking change:
* The `width` argument is moved from `style_tt()` to `tt()`.
`tt()`:
* `width` argument now accepts a vector of numeric values to control the width of each column, as a proportion of the total linewidth.
`format_tt()`:
* New `quarto` argument enables Quarto data processing for the whole table and marks specific cells as containing Quarto content. This is especially useful to include @Citation1981 in a table. Thanks to @andrewheiss for issue #215 and @giabaio for further discussion and debugging.
* New `replace` argument which accepts a single logical, a single string, or a named list to specify multiple replacements.
* `replace=TRUE` by default replaces `NA` by an empty string. `FALSE` prints "NA" as string.
* `replace_na` is deprecated in favor of `replace`. Backward compatibility is maintained and a warning is issued.
* All arguments can now be set using global options.
`theme_tt()`:
* "void" is now supported for Typst tables. Thanks to @marcboschmatas for PR #223.
`style_tt()`:
* No longer keep many versions of the same data frame, which could increase memory use. Thanks to @MarcoPortmann for the report.
`save_tt()`:
* Do not change working directory when saving to file raises an error. Thanks to @etiennebacher for report #225.
Typst:
* Better compatibility with Quarto captions. Recommended strategy is to *not* use the `caption` argument, and rather to define *both* the `label` and `tbl-cap` chunk options in Quarto. This is a breaking change, as Typst tables are no longer enclosed in a `#figure` environment in Quarto documents when both `tbl-cap` and `label` chunk options are defined.
* `format_tt(escape=TRUE)` escapes square brackets.
* Tables are centered by default.
Misc:
* Support `beamer_presentations`, but see: https://github.com/vincentarelbundock/tinytable/issues/244
* Table objects can be modified and printed several times ---with styling--- in a single HTML document like a ReavealJS slideshow. Thanks to @kazuyanagimoto for report #759.
* Global option to enable Quarto data processing: `options(tinytable_quarto_disable_processing = FALSE)`. Thanks to @andrewheiss for issue #215.
Bug fixes:
* Data frames without column headers could be displayed as "c(1,2,3,3)". Bug in `format_tt()`. Issue #230.
* `save_tt()` can now save to PDF when the table includes a caption. Thanks to @etiennebacher for report #224.
* `group_tt(i)` inserted an extra latex column, which made horizontal lines stop to early. Thanks to @andrewheiss for report #235.
* Multiple unnamed footnotes allowed in LaTeX tabularray. Issue #242.
## 0.2.1
* RStudio displays table in HTML viewer by default when the `rstudioapi` package is available.
* `colnames` and `colnames<-` are now exported functions.
* `tt()` supports data.frame-like objects which also inherit from other classes, ex: `marginaleffects::slopes()`
* Bug: `options(tinytable_tt_print)` is respected in `print()` without argument.
## 0.2.0
New features:
* `rbind()` and `rbind2()` can be used to stack `tinytable` objects. `rbind2()` is more flexible than `rbind()`. See `?tinytable::rbind2`
* New output format in `print()`: "dataframe"
* Rename table headers: `colnames(tab) <- c("a", "b", "c")`
* `theme_tt("resize")` gets a `direction` argument with "up", "down", "both" options. Thanks to @MarcoPortmann for feature request #207
Minor:
* Informative error message when no default browser is selected via global options.
* Fix CRAN errors on Mac old releases.
Bugs:
* `theme_tt()` resize issue with `talltblr` environment and notes in LaTeX. Thanks to @MarcoPortmann for reporting issue #206
## 0.1.0
New function `theme_tt()`:
* Function to apply collections of transformations to a `tinytable`.
* Visual themes:
- grid, void, striped, bootstrap, default
* `resize`: Insert a LaTeX table in a `resizebox` environment to ensure a table fits the page, or to scale it to a fraction of `\linewidth`
* `placement`: Determine where a LaTeX table float is positioned. Ex: `[H]`, `[htbp]`
* `multipage`: Split long LaTeX tables across multiple pages with (optional) repeated headers/footers. Uses the `longtblr` environment from `tabularray`.
`format_tt()`:
* New `i` argument to format subsets of rows.
* New `fn` argument which accepts an arbitrary function to format table content.
* `num_fmt="significant_cell"` rounds significant digits on a cell-by-cell basis rather than for full columns (as is default in base R `format()`).
* Numeric formatting options can be set via global options, defined in the function signature.
* `num_mark_big` and `num_mark_dec` require an explicit `digits`. We now raise an informative error.
* `escape = TRUE` now escapes captions, notes, and spanning cells created by `group_tt()` when `i` and `j` are both `NULL`. To avoid escaping group labels, users can specify `i` and/or `j` explicitly.
Typst format:
* Support for row headers with `group_tt(i)`
* Supports images and inline plots with `plot_tt()`. Thanks to @aghaynes for contribution #155.
* "kind: tinytable" parameter is now added to all figures enclosing a `tinytable`. This allows users to apply targeted show rules. For example, in a table of contents: `outline(target: figure.where(kind: "tinytable"))`
Misc:
* `style_tt()` gains a `finalize` argument. This accepts functions to be applied to the table object at the very end of the building process, to programmatically change its content. For example, this can be used with regular expressions to modify the text version of the table hosted in `tab@table_string`, or the function could programmatically modify the caption in `tab@caption`.
* `style_tt()`: LaTeX format supports decimal alignement with `align="d"`. The width of columns is determined by the maximum number of digits to the left and to the right in all cells specified by `i`, `j`.
* Support RevealJS slides in Quarto documents.
* Improved support for `tibble`. ANSI characters (ex: fancy `pillar` formatting) are stripped automatically or converted to HTML when the `fansi` package is installed. `fansi` is a dependency of `tibble`, so it should often be installed.
* New `tinytable_tt_digits` global option can set the default number of digits in the `tt()` function.
* Refactor: `tinytable` objects are now S4 class objects, with slots to hold data about the content and structure.
* `as.character()` now works on `tinytable` objects, returning a string in the output format specified by the `@output` slot of the `tinytable` object (markdown by default).
* LaTeX code in captions no longer requires double escaping, allowing: `tt(x, caption = "Blah blah \\label{tab:blah})`
Breaking changes:
* In some cases, `format_tt()` could be use sequentially to apply two formats to the same cell. Now, multiple calls to `format_tt()` can still be make chained with pipes, but they must apply to different cells with `i`, `j`, otherwise only the last change is respected. One exception is the `escape` argument which can be applied to pre-formatted cells.
* `tinytable` objects no longer have a `meta_tinytable` attribute. Use S4 slots instead.
* `placement` argument in `tt()` is removed in favor of `theme_tt("placement")`.
Bugs:
* `format_tt()` did not work on factor vector.
## 0.0.5
* `format_tt()` escapes <> tags in Typst.
* Bug introduced in 0.0.4 prevented `group_tt(i)` in HTML.
## 0.0.4
New:
- `j` argument in `style_tt()` and `format_tt()` now accepts a string vector to match columns. Issue #122
- Line plots: `plot_tt(fun = "line")`
- `format_tt(j=NULL, escape=TRUE)` now escapes column headers in addition to all cells.
- `format_tt()` gains a `replace_na` argument to replace missing values.
- `style_tt()`: `rowspan` and `colspan` arguments are now supported in all formats except Typst. In markdown and Word, we get "pseudo-spans" with empty cells around the main cell, instead of true merged cells.
- `style_tt()`: `alignv` argument is now supported for LaTeX and HTML
Bugfix:
- Markdown group columns when labels are wider than columns. Thanks to @etiennebacher for report #127.
- Markdown group rows broke indexing when using `style_tt()`. Thanks to @strengejacke for report #133.
## 0.0.3
New:
- `Typst` tables are now supported using the `tablex` extension:
- https://typst.app/
- https://github.com/PgBiel/typst-tablex
- `escape` argument in `format_tt()` escapes or substitutes special characters in LaTeX or HTML output to prevent compilation and rendering errors.
- `notes` argument in `tt()` can insert superscript markers inside cells to refer to notes at the bottom of the page.
- `tt(x, notes = list("*" = list(i = 0:1, j = 2, text = "Hello world)))`
- `notes` agument in `tt()` now works wth Markdown and Word, but must be a single string.
- `group_tt()` can be called multiple times to create mult-row headers.
## 0.0.2
Improvements:
- Rules and cell borders: `line`, `line_width`, and `line_color` arguments.
- Enhanced knitr output detection.
- New themes.
- Caption argument support for Markdown tables.
- Defensive programming enhancements.
- plot_tt() regular expression column selection.
- Header/footer are no longer indented by group_tt(i).
Bug fixes:
- Inline plots visibility in RStudio viewer pane.
- Bug in group_tt(i) for markdown and docx output.
- Resolved style_tt resetting issue.
- Bug fix for column alignment in markdown affecting docx output.
Documentation:
- Improved vignette on the package website.
- Various documentation updates.
- Math in $$ is the new recommendation.
## 0.0.1
Initial package release. Yay!
|
|
https://github.com/jijinbei/typst_template | https://raw.githubusercontent.com/jijinbei/typst_template/main/report/template.typ | typst | #import "@preview/showybox:2.0.1": showybox
#let custom_outline() = locate(loc => {
heading(numbering: none)[目次]
let headings = query(heading, loc)
let toc = ()
let _ = headings.remove(0)
for h in headings {
let padd = h.level * 1em - 1em
let page = counter(page).at(h.location())
let ch = if h.level == 1 {
strong(counter("h").display("1."))
} else {
counter("h").display("1.")
}
let heading = if h.level == 1 {
strong(h.body)
} else {
h.body
}
toc.push(
{
if h.level == 1 [
#v(1.2em)
] else [
#v(0.7em)
]
} +
box[#pad(left: padd)[#link(h.location())[#{counter("h").step(level: h.level)}#ch#sym.space.third#heading]]] +
" " +
box(width: 1fr)[
#if h.level != 1 [
#repeat(" .")
]
] +
[ #page.join()]
)
}
stack(dir: ttb, ..toc)
})
#let set_date(is_date, fontsize) = {
if is_date == true {
align(
center,
text(
size: fontsize,
datetime.today().display("[year]年[month]月[day]日")
)
)
}
}
#let set_author(authors, fontsize) = {
pad(
top: 1em,
bottom: 0em,
left: 4em,
right: 4em,
grid(
columns: (1fr,) * calc.min(2, authors.len()),
gutter: 1%,
..authors.map(author =>
align(
center,
text(size: fontsize, author)
)),
),
)
}
#let project(
title: "",
authors: (),
date: false,
titlepage: false,
bibfile: "",
body
) = {
let body_font = (
"Latin Modern Roman",
"<NAME>"
)
let math_font = ("Latin Modern Math")
set document(author: authors, title: title)
set page(
margin: (
left: 25mm,
right: 25mm,
top: 30mm,
bottom: 30mm
),
numbering: "1",
number-align: center,
)
set text(
font: body_font,
lang: "ja",
region: "JP"
)
set figure(supplement: it => {
if it.func() == table {
"表"
} else if it.func() == image {
"図"
} else {
"図" // どうしよ
}}
)
show math.equation: set text(
weight: 400,
font: math_font,
)
set math.equation(
supplement: "式",
numbering: "(1)",
)
// Start of document
if titlepage == true {
v(0.4fr)
align(center)[
#block(
text(size: 2.5em, weight: 600, title)
)
]
v(0.05fr)
set_author(authors, 1.6em)
v(0.05fr)
set_date(date, 1.4em)
v(0.6fr)
pagebreak()
custom_outline()
pagebreak()
} else {
// Title
align(center)[
#block(
text(size: 2.0em, weight: 600, title)
)
]
set_author(authors, 1.5em)
set_date(date, 1.4em)
h(4em)
}
// Spacing between Japanese and English text
show regex(
"[\\P{latin}&&[[:^ascii:]]][\\p{latin}[[:ascii:]]]|[\\p{latin}[[:ascii:]]][\\P{latin}&&[[:^ascii:]]]"
) : it => {
let a = it.text.match(regex("(.)(.)"))
a.captures.at(0)+h(0.25em)+a.captures.at(1)
}
show par: set block(
above: 0.5em,
below: 1em,
)
show math.equation: set block(
above: 1.5em,
below: 1.5em,
)
show heading: set block(
above: 0.5em,
below: 0.5em,
)
show enum: set block(
above: 1.05em,
below: 1.05em,
)
show list: set block(
above: 1.05em,
below: 1.05em,
)
show math.equation: it => {
h(0.2em) + it + h(0.2em)
}
show figure: set block(
above: 1em,
below: 1.5em,
)
// Set heading styles.
set heading(numbering: "1.1 ")
show heading: set text(
weight: 640,
)
// Set 字下げ
set par(
first-line-indent: 1em,
justify: true,
leading: 1em,
)
show heading: it => {
it
par(text(size: 0pt, ""))
}
body
if bibfile != "" {
heading([参考文献])
bibliography(bibfile, title: none)
}
}
// box
#let cbox(title,txt) = showybox(
title-style: (
weight: 800,
color: red.darken(15%),
sep-thickness: 0pt,
align: center
),
frame: (
title-color: red.lighten(80%),
border-color: red.darken(30%),
thickness: (left: 1pt),
radius: 2pt
),
title: title,
)[
#txt
]
#let LaTeX = text(
font: "Latin Modern Roman",
[
L#h(-0.35em)#text(size: 0.725em, baseline: -0.25em)[A]#h(-0.125em)T#h(-0.175em)#text(baseline: 0.225em)[E]#h(-0.125em)X
]
)
// convert csv to table
//
// example
// #csv2table(csv("data/Pb_data.csv"), [鉛の厚みとエネルギースペクトルの関係], label: ("厚さ(cm)",$A$,$mu "(keV)"$,$sigma$,$I$))
//
#let csv2table(csv, caption, label: none, digits: 2) = {
let csv_label = csv.first()
let len = csv_label.len()
let csved =()
for row in csv.slice(1) {
for s in row {
if regex("\d+\.\d+") in s {
let n = float(s)
let round_n = calc.round(n, digits: digits)
let str_n = str(round_n)
csved = csved + (str_n,)
} else {
csved = csved + (s,)
}
}
}
let labeled = ()
if label == none {
for csv_l in csv_label {
labeled = labeled + (strong(csv_l),)
}
figure(
table(
columns: (1fr, ) * len,
..labeled,
..csved,
),
caption: caption,
)
} else {
for l in label {
labeled = labeled + (strong(l),)
}
figure(
table(
columns: (1fr, ) * len,
..labeled,
..csved,
),
caption: caption,
)
}
}
|
|
https://github.com/Servostar/dhbw-abb-typst-template | https://raw.githubusercontent.com/Servostar/dhbw-abb-typst-template/main/template/abstract.typ | typst | MIT License |
// English summary "abstract" is content of this block:
#let abstract = [
#lorem(100)
]
// Other languages abstract translation is content of this block:
// NOTE: An abstract is required in case the thesis is not written primarily in english
// if writing in english (and the language is set to "en") this can be let empty or set to none
#let summary = [
#lorem(100)
]
|
https://github.com/lvignoli/typst-action-example | https://raw.githubusercontent.com/lvignoli/typst-action-example/main/README.md | markdown | # Example using [typst-action](https://github.com/marketplace/actions/github-action-for-typst)
Using the action at [`.github/workflows/build.yml`](.github/workflows/build.yml), file `main.typ` is compiled using [lvignoli/typst-action](https://github.com/marketplace/actions/github-action-for-typst) to a PDF, which is uploaded as an artifact in the action workflow and released, for a tagged commit, with the build timestamp.
|
|
https://github.com/htlwienwest/da-vorlage-typst | https://raw.githubusercontent.com/htlwienwest/da-vorlage-typst/main/lib/pages/deckblatt.typ | typst | MIT License | #import "../assertions.typ": *
#import "../settings.typ" as settings
#let deckblatt(title, abteilung, schuljahr, teilnehmer) = {
set page(margin: (left: 3cm, bottom: 3cm, top: 1cm))
let gutter = 3mm
let img_height = 3.81cm
let headline = grid(
columns: (1fr, auto, auto),
align: (right),
column-gutter: gutter,
{
set text(16pt, hyphenate: false)
set par(leading: 12pt, justify: false)
v(1mm)
grid(
row-gutter: 6mm,
[
HÖHERE TECHNISCHE\
BUNDESLEHRANSTALT WIEN 16
],
block(width: 100% + 0.5cm,
text(font: settings.FONT_ACCENT)[
Abteilung für #abteilung
]
)
)
},
line(length: img_height, angle: 90deg, stroke: 0.8pt),
image("../images/HTLWienWest.png", height: img_height)
)
headline
set align(center)
v(3cm)
text(36pt)[DIPLOMARBEIT]
v(2cm)
block(
width: 12cm,
par(leading: 20pt, justify: false,
text(36pt, title)
)
)
v(0.5cm)
text(18pt)[Ausgeführt im Schuljahr #schuljahr]
set text(11pt)
place(bottom,
grid(
columns: (1fr, 1fr),
align: (left, right),
row-gutter: 0.5cm,
..teilnehmer
.map((e) => {
let betreuer_suffix = if e.betreuer.geschlecht == "female" {
"In"
} else {
""
}
([#e.vorname #e.nachname (#e.klasse)], [Betreuer#betreuer_suffix: #e.betreuer.name])
})
.flatten(),
)
)
}
|
https://github.com/Quaternijkon/Typst_USTC_CS | https://raw.githubusercontent.com/Quaternijkon/Typst_USTC_CS/main/mycontent.typ | typst | #import "config.typ": *
#outline-slide()
//第三步
//从这里开始 |
|
https://github.com/chilingg/kaiji | https://raw.githubusercontent.com/chilingg/kaiji/main/part1/chapter2.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)[
// 612 漢字活字書体の源流
= 汉字活字字体的源流
// ■漢字の構成は建築的である。その一書体は秩序ある体系美を備えている。それを量的に追求すると,内在する数学的バターンがとらえられそうな姿をしている(こういう姿は說文解字(AD100年)ができたころの小篆で,一応の完成を見せている)。にもかかわらず,それを数量的に分析しようという試みが今までとんどなされていないのはなぜであろうか。書道では,根本にある原型を重んじながらも,直接の関心事は表現の変化相の方にあったからであろうか。活字は,書道的表現にくらべてより没個性的な,より平均値的な,より静止的な姿で文字を固定する。そこで変化相の基盤にある〔原型〕,あるいは〔典型〕に迫らざるをえない。
■汉字的构成是建筑性的,其字体拥有着一种有序的体系美。从量上考究它,似乎能捕捉到其内在呈现出的数学性的形象(这种形象在说文解字(AD100年)中形成当时的小篆,已表现出初步的完善)。然而,为什么很少有人尝试对它们从数值上进行分析呢?是否是因为在书法中,在重视原型的基础上,人们直接关心的是作为表达的变化相呢?活字与书法相比,以更没有个性、更平均值、更静止的形式固定文字。因此,我们不得不面对变化的基础〔原型〕,或者说〔典型〕。
// 「活字は死んでいるものだ」という書道の教師もいる。それでいながら,一般日常用の手紙やメモに書く人それぞれのひとりよがりな筆記体は,わかればよい程度の〔仮のもの〕で,活字こそ〔正書法〕である。活字を正書としてイメージしながら,その略体を書いている。書道は字の変化相に芸術を求めるために、ますます当代の〔正書〕からは遠い姿になっている。それについて会津八一の卓見を読んだのはだいぶ昔のことになる。——机上の字引きをぱっと開いて親字を見る。たとえ,不出来の活字でも明朝体の姿は私に漢字構成のギリギリのバランスを教えてくれる。私の書くのは躍動した姿だが,躍動させる前の基本構成を学ぶことが欠かせぬ勉強になるのだ——。
「活字是死的。」也有书法老师是这么说。然而,日常书信和笔记中使用的个性化的手写体,只要了解就可以了,活字才是〔正字法〕。把活字想象成正书,依此写着它的简体。书法是追求字的变化相的艺术,其变得越来越远离当代的正书。很久以前,我曾读到会津八一对此的卓見。——翻开桌上的辞典看亲字。即使是不好的活字,明朝体的样子也告诉我汉字构成的最佳平衡。我写的是跃动的姿态,但学习跃动之前的基本结构是必不可少的功课——。
// 612 1 書における漢字の構成
== 书法中汉字的构成
// ■漢字の構成を理解するために〔書〕から入ろう。活字はすべての漢字をなるべく正方形に押し込めようとする。したがって固有の形・リズム感・運動感などが失われやすい。活字を設計する場合,それらを殺し去らずに,どこかに与えなければならない。
■从〔书法〕开始理解汉字的构成。活字要把所有的汉字尽量挤成正方形,因此容易丢失其原有的形态、韵律、动感等。设计活字时,需要为这些特点保留一定余地,不能把它们全部扼杀。
// ここには〔書〕の特色を強く出している褚遂良の楷書を例として分析を進める。それを見て感じることは,文字がーつーつ別の形と大きさを持っていることである。
这里以具有强烈〔书法〕特色的褚遂良楷书为例进行分析。可以看到,这些字的形状和大小各不相同。
#set enum(indent: 1em, numbering: n => [#parenthese_numbers.at(n - 1)])
// + それぞれの字は正方形から遠い固有な形を持っている。
+ 每个字都有一个独特的形状,绝非统一的正方形。
// + その形にはリズム感や運動感がある。
+ 其形状具有韵律和动感。
// それは,(a)ユニットの片側強調が強い張力をあらわしている。(b)部分の構成に突出部を作ることによって,全体の形に旋回する偶力を与えている。
(a)单元的单侧强调表现出很强的张力。(b)通过在部分的结构上做突出部分,给整体的形状提供了盘旋的力偶。
// ●⑴の説明——正方形から遠ざかった漢字,たとえば〔寺〕などは◇型をしている。一番長い横線と次の長さの線との差が大きい。図501の実例について横線の長さを測ると,それはだいたい4階級のグループに分かれ,最長の階級(第1位)の平均の長さを100とすれば,下表のような数列となる。(p.561図561,p.115図563)。この比が小さいとは,字の形が正方形から遠ざかり,内部構造をそのまま輪郭にあらわすことになる。
●⑴说明——远离正方形的汉字,如〔寺〕等呈◇型。其最长的横线和次长横线差距很大。对图501中的示例进行横线长度测量,它大致分为4个级别,最长级别(第1位)的平均长度为100,得到下表的数列。(图561,图563 track_page)。比例小意味着字的形状会偏离正方形,其内部结构直接在轮廓上体现。
#colbreak()
// 縦組にした場合,右図1のa(横最長線)に対して,b(字の本体)の幅が狭いことを意味する。字の中央にあるフトコロが狭いということでもある。
纵向排列时,相对于右图1的a(横最长线),b(字的本体)的宽度较窄。字中央的字怀也很窄。
#v(1em)
// 書における字配り 言うまでもなく縦組用に発遣した構成である。見て気がつくことは縦4本のラインの中に置かれていることである。外侧(図中a)を100とすれば内側(b)は45となる。字の本体は図中bにあって,ところどころから外に向って突出部があると見なすことができる。それは英文の小文字のボディ・アッセンダー・ディッセンダーの関係に似ている。
书法上的字配<sans_font>
这是为竖排而设计的结构。注意看,它被置于4条竖线内。若外侧(图中a)为100,则内侧(b)为45。字的主体在图中的b处,可以看作处处有向外突出的部分。这类似于英文小写中的x-height(x字高)、ascender(升部)、descender(降部)的关系。
// 活字書体になると,この内側のラインが外側のラインに近づき,かつ存在が不明瞭となる。以上を念頭において,次章からの活字書体の構成を研究すれば,両者に共通の部分と異なった部分が明確に理解されるであろう。
如果是活字字体,内侧的线会更接近外侧的线,其存在感被掩盖。有鉴于此,研究下一章的字体构成,将有助于明确两者的共同点和不同点。
#v(1em)
// ■書と活字の最大の違いは,活字のサイズが小さく,そして小さくても読みやまいことが要求される。次にどの字が隣に来てもバランスしなければならない。これらの理由によって,漢字は小さい面積の正方形の活字表面の中にいっぱいに設計される。したがって外形は正方形に近づき,個々の字の固有の姿は弱められる。書では画数の多い字は大きくして密度のバランスをとっているが,活字では画数の少ない字も多い字もあまりかわらぬ大きさになるので,線幅によってウエイトの調整をしなくてはならない。
■书法和活字最大的区别在于活字的尺寸较小,即使活字的尺寸很小,它也必须易于阅读。其次,无论哪个字在其前后,都要保持平衡。由于这些原因,汉字被设计在小面积的正方形活字表面中,因此外形趋近正方形,各个字的固有面貌被削弱。在书法中,笔画多的字要加大以保持密度平衡,但在活字中,字的笔画多少不会对字的大小造成太大影响,所以必须使用线宽来调整字重。
#v(1em)
// === 唐時代の碑文の字配り
=== 唐代碑文的字配
// ■欧陽詢の九成宮醴泉銘(632年楷書)について分析する。
■分析欧阳询的九成宫醴泉铭(632年楷书)。
// ●字間・行間の距離はほば等しく,行間と字間の比1:0.9である。この時代,本文の横組は考えられないので,字間·行間がほば等しくても縦に読まれる。
●字距、行距几乎相等,其比值为1:0.9。在那个时代是不考虑横排正文的,所以即使字距、行距相等,也是竖着读。
// 平均値mm 平均値mm
// ⑴ 字高 18.6
// ⑵ 字間 14.4
// ⑶ 重心間的距離 33.0
// 字幅
// ⑷ 最大幅 21.0
// ⑸ 最小幅 12.6
#text(tracking: 0em)[
#tablex(
columns: (1fr, auto, auto, auto, auto),
stroke: thin_line,
map-cells: cell => {
if cell.x == 1 or cell.x == 4 {
cell.align = center
}
cell
},
auto-lines: false,
[], text(font_size_list.at(3))[
平均值mm
], [], [], text(font_size_list.at(3))[
平均值mm
],
hlinex(),
[⑴字高], [18.6], rowspanx(2)[
#set align(horizon)
字宽\{
], [⑷最大宽], [21.0],
[⑵字距], [14.4], (), [⑸最小宽], [12.6],
[⑶重心间距], [33.0], [], [], [],
hlinex(),
)
]
// ⑴⑵⑶のうちで字高のブレがもっとも激しく,重心間距離がもっとも少ない。字間アキを充分広くとることで(平均字高の0.77),重心間距離をだいたい揃えている。つまり重心等距離システムである。
⑴⑵⑶中,字高的波动幅度最大,重心间距变化最少。由于字距的范围足够宽(平均字高的0.77),重心之间的距离大体一致。也就是重心等距离体系。
// ●行の正中線上に字の重心が乗っていて,左右のブレはきわめて少ない。しかし字高の変化は激しく(注1),水平方向のならびは同一線上にない。
●字的重心处于行的正中线上,左右晃动极少。但是字高的变化很大(注1),水平方向的排列则不在同一线上。
#v(1em)
// 注1 横線数と字高 横線の数と字高の関係は次の式のように,横線数と比例している。h=6.3+2.1m h=字高 m=横線数
// 全体として縦長の字が多いように感じられる。最大幅平均は21mmで平均字高よりも広いのだが,字の胴幅の細いところは平均13mmぐらいである。つまり文字の縦10,幅7の胴中の両側に腕が伸びていて,その長さは11という比である(p.6, p.66-68)。
#let page_504 = locate(loc => query(<横线数与字高>, loc).at(0).location().page())
注1 横线数与字高<sans_font>
横线数与字高成正比关系,其公式:h=6.3+2.1m h=字高 m=横线数。
整体而言竖长字居多。最大宽平均值为21mm,比平均字高长,但字身最细处仅平均为13mm。
也就是说,在文字高10、宽7的身躯两侧延申,其长度为11。(p.#page_504, p.66\~68 track_page)
]
#v(1em)
#columns(2)[
// 長さの平均
// 上位に対する比
// 差
#align(center)[
#set text(tracking: 0em)
#tablex(
columns: 5,
stroke: thin_line,
auto-lines: false,
(), vlinex(), (), (), (), (),
hlinex(),
[], [第1位], [第2位], [第3位], [第4位],
hlinex(),
[平均长度], [100], [58], [39], [28],
[与上位之比], [], [0.57], [0.69], [0.72],
[差], [], [42], [19], [11],
hlinex(),
)
]
#colbreak()
// 実物mm(p.6図503)
// 角寸法3cmの実寸mm
#tablex(
columns: 5,
stroke: thin_line,
auto-lines: false,
(), vlinex(), (), vlinex(), (),
hlinex(end: 4),
[], [王], [麗], [比], [],
hlinex(end: 4),
[欧阳询], [13.5], [28], [2.07], text(font_size_list.at(3))[
#let page_504 = locate(loc => query(<横线数与字高>, loc).at(0).location().page())
实物mm(图504 p.#page_504)
],
[正楷字体], [21.5], [28], [1.3], rowspanx(2)[
#set text(font_size_list.at(3))
#set align(horizon)
字身框3cm\
实际尺寸mm
],
[细明朝体], [31], [35.6], [1.14], (),
hlinex(end: 4),
)
]
#pagebreak()
#gridx(
columns: (9fr, 4fr, 12fr),
rowspanx(3)[
// 褚遂良〔雁塔聖教序〕(654年)の楷書
#figure(
image("img/501-1.jpg"),
caption: [褚遂良的楷书雁塔圣教序(654年)]
)
],
rowspanx(2)[
#image("img/501-2-1.jpg")
],
[#image("img/501-2-2.jpg")],
(), (), [
// ■外形を大別すると,1ボディがbの幅で両側にa幅の突出部がある。主として縦横の線でできている。5同じくボディがbでa幅の突出部があるが,斜め方向の線が強い。2.は平体,幅がa,3.は長体で幅がb。4.は幅がbで小さい字。
■外形大致可分为:1躯体宽度为b,两侧各有宽度a的突出部。主要由纵横线组成。5同样是b身宽,有a宽度的突出部分,但斜向线条较强。2.是平体,宽a, 3.是长体,宽b。4.是宽度为b的小字。
],
(), colspanx(2)[
#set align(center + horizon)
#image("img/501-3.jpg")
], (),
)
#columns(2)[
// ■上の2行は勝手に選んだ字を組んでみた実験。似た字がつづくとつまらない。大小,粗密,太細,濃淡,平長,いろいろなりんかくの形,水平垂直線と斜線ことに波勢を持った払いなどのコントラストとバランスの微妙さに美しさの秘密がある。
■上面的两行是挑选的字进行排列的实验。毕竟,相似的字接连不断很无趣。大小,粗密,纤细,浓淡,平长,各种各样的轮廓形状,水平垂直线和斜线以及波浪形笔触等的对比和平衡的微妙,才是美感的秘密。
// ■上図右で分析した5種類のほかに,右の〔斯〕のような種類——ボディの矩形から四方にはり出しが出ていて,旋回するような動きを感じさせるものがある。活字になると,この突出部,いわば手足をもぎとってしまうことになる。実験として活字の〔詩〕について,逆に突出部をのばしてみたのが下図右である。
■除了上图右边分析的5种以外,还有像右边的〔斯〕一样的种类——从字身的矩形向四周突出,给人以盘旋的感觉。如果变成活字,这个突出的手脚部分都会被去掉。作为实验,对活字的〔诗〕,试着反过来拉长突出部,如下图右侧。
// 活字設計の場合といえども,書におけるこうした豊かな表情,線やその構成から感じられる運動感などをまったく殺してしまっては,漢字の持つ生命感が失われるだろう。極めて限られた状況の中でも何とかしてこれを最少限に維持しなければならない。
即使是活字设计,如果完全抹杀了书法中这种表现力丰富的线条,以及其构成所带来的动感,那么汉字所具有的生命感就会消失。在空间极其有限的情况下也必须设法将其维持在最低限度。
#align(center, image(width: 90%, "img/501-4.jpg"))
// ■横綴りに調和する字を選んでならべてみた。何となく英文のような漠然としたラインがあり,ボディはd,アッセンダー,デッセンダーを含めて全字高がc。扁額ならば伝統に従い右から左へ書く。
■匾额的话按照传统从右向左书写。试着选择了与横排相协调的字排列。总觉得有像英文一样模糊的线条,字躯(x-height)d,加上ascender、descender为全字高c。
#image("img/501-5.jpg")
]
#pagebreak()
#box()[
#columns(2)[
// === 字配りと字の構成との関係
=== 字配与字的结构间的关系
#set enum(numbering: "1")
#let page_508 = locate(loc => query(<欧阳询楷书放大>, loc).at(0).location().page())
// ■p.7図508(拓本×1.4倍の拡大)は大きさのほぼ揃った字を選び,字間行間を拓本と同じ比例にして,字配りと字の構成との関係を分析したものである。
■p.#page_508 图508(拓本×1.4倍放大)选择大小基本一致的字,字、行间距与拓本成相同比例,分析了字配与字的结构之间的关系。
// + ●破線は字の外接円で(注2),ここにある8字は同じ半径。
+ ●虚线是字的外接圆(注2),这里的8个字半径相同。
// + ●それらの字の重心(注3)を目測によって決めた(〇印)。
+ ●这些字的重心(注3)是通过目测决定(画〇)。
// + ●重心を中心にして,その中に点画の密集部が含まれるように適宜の半径で実線の小円を書いた。
+ ●以重心为中心,以适当的半径画实线的小圆将笔画密集的部分包含在其中。
// + ●以上のように字配りした結果,縦の正中線の中央部(スクリーンの帯)に〔筋の通ったところ〕が発見される。〔則〕の左端縦線,〔起〕の〔己〕の右側,〔微〕のギョウニンベンの縦線,ノブンの左ハライの始筆部,〔斯〕の左端縦線と〔斤〕の右側縦線,これらがスクリーンの帯の両侧と一致している。
+ ●如上所述排列字形后,在竖正中线的中央部(网线带)发现了〔有条理的地方〕。〔则〕的左端纵线,〔起〕的〔己〕的右侧,〔微〕的〔彳〕的纵线,〔攵〕的左撇的起笔部,〔斯〕的左端纵线和〔斤〕的右侧纵线,这些与线条带两侧一致。
// + ●外侧の縦線は左右の端をつらねた線であるが,スクリーン帯はその中央に位置する。
+ ●外侧的纵线是连接左右边缘的线,网线带位于其中央。
// + ●重心は外接円(破線)に対して左寄りにあって,その周囲に点画密集部(実線小円)がある。そこから外接円までの伸びている部分(注4)は右が長くたっぶりとってある。この碑文の字の特長的な輪郭は図505のような上辺右上り,下辺右下りの四角となる。
+ ●重心相对于外接圆(虚线)偏左,其周围是笔画密集部分(实线小圆)。从那里延伸到外接圆的部分(注4)在右边很长。这个碑文的特征轮廓是图505那样的上边右侧上升,下边右侧下降的四方形。
#v(1em)
// ■名人が1字1字を書いていく瞬間瞬間にこれら多方面の要因(上記6項目)を同時に満足させるポイントをおさえ,しかも豊かな表情を盛り上げていく。字配りシステムと,個々の字の構成の内面的統一は強固に結びついている。また同じ字はいつも同じに書かれていることを12個の〔之〕で示す。
■名人在书写每一个字的瞬间,抓住并同时满足这些多方面因素(上述6项)的要点,使其表现力丰富活跃起来。
字配和每个字结构的内在是紧密联系在一起的。另外,同样的字总是写得一样,用12个〔之〕表示。
#colbreak()
// 注2 外接円半径rと点画の複雑さ 外接円の半径をrとし,点画の長さの合計をlとすれば,
注2 外接圆半径r与笔画的复杂性 <sans_font>
设外接圆的半径为r,笔画的长度之和为l,则
// 欧陽詢
// 正楷書
#align(center)[
#block(
width: 85%,
grid(
columns: (auto, 1fr, auto),
gutter: 0.8em,
[欧阳询], [$3 log(r) = log(l) + 2.7$], [$r = root(3, 500l)$],
[正楷书], [$5 log(r) = log(l) + 2.5$], [$r = root(5, 280l)$],
))
]
// 点画密度を表現するl(点画の長さの合計)の増加に対するr(外接円の半径)の増加は,正楷書の方がはるかに少ない。明朝体では特別に小さい〔口・日・月〕など以外は,同じ基準ワクに内接するようになっていて,字の大小の差は極力少なくしてある。
表现笔画密度的l(笔画的长度之和)增加,则r(外接圆的半径)也增加,这种增加在正楷书中要少得多。明朝体除了特别小的字(口、日、月)以外,都内接在同一个基准框内,尽量减少字的大小之差。
#v(1em)
// 注3 重心の判定 字配りに際して重心の修正を行なった(×印)。
注3 重心的判定 <sans_font>
字配时进行了重心的校正(画×)。
#set enum(numbering: "(a)")
// + 隣の行の字〔楽・郡〕の上下位置を調整して,〔郡〕の〇印重心を×印に移した。〇印の重心は点画の密集部だけを意識して,最終画の突出部に対する関心が少なかったことが,×印に修正された理由である。
+ 调整相邻行字〔楽、郡〕的上下位置,把〔郡〕的〇重心移到×上。〇的重心只注意到点画的密集部分,而对最终画的突出部分的关注较少,这就是被修改为×的原因。
// + 〔則〕の重心は始め右端の縦線を強く意識しすぎていた(〇印)。修正された重心(×印)は〔貝〕の囲まれた部分をより重要視した結果である。
+ 〔则〕的重心一开始过于强烈地意识到右端的垂线(画〇)。修改后的重心(画×)是更加重视被〔貝〕包围的部分的结果。
// 以上のように重心の目測判定には,字の全体を前後左右の字と比較しながらする場合と,1字1字の部分に関心を寄せる場合とではかなり判定に違いができる。
如上所述,对重心进行目测判定时,比较字的整体和前后左右的字,与关心每个字的个别部分,两者之间可能会有很大的差异。
#v(1em)
// 注4 このような楷書と比较すると,明朝体では全部が充実したスクリーン部分に相当し,内円と外円の間にはさまれた領域が極端に縮められている。そういう書体が明朝体である。
注4 <sans_font>
与上述楷书相比,明朝体完全对应网线带部分,内圆和外圆之间夹着的区域极度缩小。这样的字体就是明朝体。
]
#v(1em)
#box()[
#gridx(
columns: (3fr, 1fr, 2fr),
figure(
image("img/502.svg"),
caption: [
// 字間·字高·重心間距離のバラツキじ
字间·字高·重心的分布
]
),
colspanx(2)[
#figure(
image("img/504.jpg"),
caption: [
// 同じ字は一定の大きさ·形に書かれている
同样的字按同样的大小、形状书写
]
)
],(),
colspanx(2)[
#figure(
image("img/503.jpg"),
caption: [
// 橫綫数と字高(拓本の大きさ——実物の大きさと思われる)
横线数与字高(拓本的大小——与实物大小相同)
]
) <横线数与字高>
],(),
figure(
image("img/505.svg"),
caption: [外接圆·轮廓·重心]
),
)
]
]
#pagebreak()
#columns(2)[
// 注5 字の輪郭と引込み線
// 上辺・下辺の右上り,右下り,中央部の凹凸のあらゆる組合せは多様となるが目につく形を選んでみると図506,507のようになる。
// 水平線が右上りであるから,基本的には四隅の位置が右図aのようになるが,bのように下辺が右下りの字が意外に多い。中央縦線の突出があればaはc,bはdのようになる。またeのように中央がえぐれている字も多い。
// 図507の最上段と第2段はもっとも平凡な右上りの矩形・台形だが,変化を求めて〔雖〕のように下に突出させる。
// 明朝体では下辺が水平で2点以上で支える字も(肌・神・顕)も右下りである。
// 第3段の〔分〕は下を一点支えとし,〔南〕の中央線を下にのばして変化をつける。
// 第4段の右ハライ・ソリハネは右下りを極端に強調してある。左右合成でヘンの短い字(p.58第21類),ヘンとツクリのずれる字(第22類)では,左右の差を強調し右下りを激しくしている。
// 明朝体では〔勤・観・動・新〕など左辺をならべて同じ高さとし,下辺は2点以上で支える。楷書体では上下辺ともに左右の字高・位置の差を激しくし,また上下とも突出部を極端に長くするなど,すべてに変化を求めている。
注5 字的轮廓和参考线 <sans_font>
上、下边的右上、下升降,中央部的凹凸,其不同情况可以组成各种各样的组合,试着选取最醒目的形状,如图506,507所示。
由于水平线是右侧上升的,所以基本上四个角的位置如右图a所示,但像b这样下边右侧下降的字却意外地多。
如果有中央纵线的突出,a就是c, b就是d。另外,像e这样中央凹陷的字也很多。
图507的最上段和第2段是最普通的右侧上升矩形、梯形,第2段为了求变化,如〔雖〕一样向下突出。
在明朝体中,下方水平支撑两点以上的字(肌、神、顕)都是右下降。
第3段的〔分〕下面作为一点支撑,〔南〕的中央线向下延伸以增加变化。
第4段的捺钩极端强调了右下降。在左右结构中,部首短的字(track_page第21类),偏旁间错位的字(第22类),强调左右的差别,使右下降变得激烈。
#colbreak()
在明朝体中,〔勤・観・動・新〕等左边并列为同一高度,下面用两点以上支撑。楷书上下边都使左右的字高、位置差剧烈,而且上下都使突出部极长,一切都力求变化。
#v(1em)
#align(center)[
#block(width: 80%)[
#set align(start)
#figure(
image("img/506.svg"),
caption: [
// 輪郭の形
轮廓形状
]
)
]
]
]
#v(1em)
#columns(2)[
#figure(
image(height: 68%, "img/507.jpg"),
caption: [
// ロ507 欧陽詢の楷書(縮小×約0.9)(分類はp.53参照)
欧阳询的楷书(缩小×约0.9)
#text(font_size_list.at(3))[(参照track_page分类)]
]
)
#figure(
image(height: 68%, "img/508.jpg"),
caption: [
// ロ508 欧陽詢の楷書(拡大×約1.4)
欧阳询的楷书(放大×约1.4)
]
) <欧阳询楷书放大>
]
#pagebreak()
#box()[#columns(2)[
// 活字書体設計のための〔書〕の研究
=== 活字字体设计中〔书法〕的研究
// ■楷書が明朝体になったとき,捨てて来たのは何か?捨てることが絶対に必要であったのか,捨てなくてもよいものまで捨てて来たのか?——こうした問いに答えるためには,〔書〕と活字の本質論から,細部の技法に至るまでの深い研究を必要とする。
■丛楷书到明朝体,其舍弃的是什么?是绝对有必要舍弃的,还是连不必要的都扔了呢?——为了回答这样的问题,需要深入研究〔书法〕和活字的本质,直至技法的细枝末节。
// 書道関係の研究は,技法上の問題を除いては書家個人の生涯や人格と書との接点などに触れたものが多い。時代の流れの中に,名家の書は〔典型〕として把握されていることは,結構なのであるが,個人を離れた様式の抽出——殊に数量的なとらえ方がほとんど見られない。質を量に転化すると生命を失うという怖れによるのかもしれないが,数量化することで,そのデザインに内在する美の急所などが,より明らかになることもありうる。一見異なったものと思われる書と活字を共通の解剖台の上に乗せてメスをとるには,死体にすることも止むをえない。もっとも,あくまで生きた姿を正しく理解するための手段であることを忘れてはなるまい。
书法相关的研究中,除了技法上的问题外,多涉及到书法家个人的身世、个性与书法之间的联系。
随着时代的进步,名家书法被当作〔典型〕来研究是没有问题的,但几乎看不到对个人风格的提炼——尤其是量化的数值。也许是害怕量化会使其丢失生命,但量化也有可能使我们更加明确其内在设计的美的关键之处。
把看似不同的书法和活字放在共同的解剖台上用手术刀解剖,难免使其变为死物。但我们不要忘记,这终究是正确理解生命姿态的手段。
#v(1em)
// ■世人がテキストとしている古来の名筆には,その時代と書家の個性の密着した状況での典型的な造形である。創作があり発見がある。紙や筆などの物的条件の発達も見逃すことができない。とにかくそれらの総合から生まれた名筆は,今になってもなお生き生きとわれわれの心の中に生きつづけている典型である。漢字がかって持っていた豊かな表現・久しい間祖先が親しんできたイメージには,何か人間とのつながりの上で捨てがたいものがあるのではないか?
■世人所说的古代名笔,是那个时代与书法家的个性紧密结合所形成的经典造型。同时纸笔等物质条件的发展也不容忽视。总之,在这些因素的综合作用下诞生的名笔,至今仍是我们心中鲜活生动的经典。汉字所具有的丰富的表现形式,以及我们祖先长久以来所熟悉的形象,其与人的联系中是不是存在某种难以舍弃的东西呢?
// 再び新しい生命をふきこむことのできるデザインの急所がかくされているのではあるまいか?
是否隐藏着能够再次赋予汉字新生命的设计关键点呢?
// ノートから見つけた資料の2例を示そう。そのーつは,〔口〕の下辺の扱い方を歴史的に採取した資料である。もう一つは,楷書の構成様式にある〔背勢・向勢〕を取り出してみたもので,これを明朝体の中で表現すると,どういう姿になるか——と考えてみる。
这是我在笔记上找到的两个例子。其一是收集的历史上对〔口〕下边处理方案的资料。其二是在明朝体中表现出楷书风格的〔背势・向势〕的尝试。
#v(1em)
// 〔口〕の下辺(図509)
=== 〔口〕的下边(图510)
// ■2世紀隷書では水平で下図1型がほとんどであったのが,楷書となると3,5型が多くなり,明朝体になると突如として6型が現われてきた。これはハライの左右関係について述べる(p.60)ことと同様逆字を彫刻したために始まったことかもしれない。現在の明朝体では全面的に6型にする習慣がある。しかしそれは絶対的な必要事かどうか疑問をさしはさむ余地があろう。
■公元2世纪隶书中,几乎都是如下图1型所示的水平,楷书则多为3、5型,到了明朝体突然出现了6型。也许与撇捺的左右关系中(track_page)所描述的原因一样,是因雕刻了倒字而开始的。现在的明朝体习惯全面变成6型。这是否是绝对必要还有待商榷。
// 510 背勢(褚遂良)と向勢(顔真卿)
#figure(
caption: [背势(褚遂良)与向势(颜真卿)],
kind: image,
grid(
columns: (auto, auto),
text(tracking: 0em)[褚遂良〔雁塔聖教序〕654年],
text(tracking: 0em)[顔真卿〔顏勤礼碑〕753年],
image("img/509-1.jpg"),
image("img/509-2.jpg"),
)
)
#v(1em)
// 背勢と向勢(図510)
=== 背势与向势(图509)
// ■唐時代の楷書でも褚遂良(596~658)と顔真卿(707~787)では構成のスタイルが大いに違う。これは個人の性格にもよるし,各々の時代の要求の違いもあったのだろう。前者は腰幅(フトコロ幅)を思い切ってしばったのに対して,後者は中央から両側に張り出す感じである。これらを背勢・向勢と言っている。背勢は上品で優美,向勢は力強く親しみがある。明朝体でこれを表現すると次のようになるだろう。
■唐代楷书中褚遂良(596\~658)和颜真卿(707\~787)的结构风格也大不相同。这与个人的性格有关,也与他们各自时代的要求不同有关。前者腰部(字怀宽)捆得很紧,而后者感觉从中间向两侧伸展出来。这就是所谓的背势、向势。背势高雅优美,向势有力亲切。用明朝体来表现这点的话,大概是下面这样的吧。
#v(1em)
// 写研細明朝体
// モトヤ特太明朝体M8
#align(center)[
#grid(
columns: (auto, auto),
gutter: 0.5em,
[写研細明朝体 <sans_font>], [モトヤ特太明朝体M8 <sans_font>],
image("img/510-1.jpg", width: 70%),image("img/510-2.jpg", width: 70%)
)
]
]
#set text(tracking: 0em)
// 〔口〕の下辺の歷史的変化
#figure(
caption: [〔口〕的下边的历史变化],
kind: image,
tablex(
columns: (auto, ..(1fr,)*6, auto, auto, auto),
align: center,
stroke: thin_line,
rows: (auto, auto, 1.6em, ..(auto,)*5),
inset: 0.7em,
auto-lines: false,
vlinex(start:3), ..(vlinex(),)*7, (),(),vlinex(start:2),
hlinex(start:1, end:7),
[],[1型],[2型],[3型],[4型],[5型],[6型],[],[],[],
hlinex(start:1, end:7),
[],
rowspanx(2, image("img/510-3.jpg")),
rowspanx(2, image("img/510-4.jpg")),
rowspanx(2, image("img/510-5.jpg")),
rowspanx(2, image("img/510-6.jpg")),
rowspanx(2, image("img/510-7.jpg")),
rowspanx(2, image("img/510-8.jpg")),
colspanx(3)[
#set align(bottom + left)
单位 %
],
(),(),
hlinex(start:7),
[],(),(),(),(),(),(),[水平],[右升],[左升],
hlinex(),
align(start)[隶书 2c],[45],[40],[15],[0],[0],[0],[85],[15],[0],
align(start)[欧阳询 6\~7c],[11],[17],[45],[10],[17],[0],[28],[45],[27],
align(start)[活字字体 楷·宋 20c],[6],[8],[42],[16],[28],[0],[14],[42],[44],
hlinex(),
align(start)[木板明朝体 18c],[6],[0],[36],[0],[25],[33],[6],[69],[25],
align(start)[初期活字明朝体 1891],[0],[0],[0],[0],[0],[100],[0],[100],[0],
hlinex(),
)
)]
#columns(2)[
// 活字書体の定型化
== 活字字体的定型化
// ■種字を原寸手彫りしていた頃は,同じ彫師が自作を写すにしても,寸分ちがわぬ物はできなかった。べントン時代となって,同じ拡大原図から写真でパターンが写しとれるようになれば,殆どちがわぬ物が得られる。そうした技法上の問題とは別に,早くから標準書体を求める気運はあった。評判の良い書体を模作したい要求はそれ以上に強い。しかし道義上模作はできないとなると,似たものを別に作り,とにかく「うちで職人をやとって作らせたものです」という言いわけを確保する。要するに,より一層の優良書体を独自に開発しようという計画がない。メーカーとしては職人に頼るほかなく,社長の気づいた一つ二つの方針を既成書体に加味するよう注文する。職人の資格は,よいテキストを知っていて,それを適当に変形することに尽きる場合が多い。それでも,長年の経験によって彫師中の名人は独自のイメージをさぐりあてる。ひらがなデザインはそうして発展した。漢字については,ことに明朝体については明治6年以来築地活版が連続開発し,明治30年代にほぼ完成した〔築地型〕をあえて乗りこえようとしたのは,秀英舎(大日本印刷の前身)以外にはなかった。——というのが昭和37年頃までの実状である。以下の研究は,わずか3字をとって,その細部(6項目)を比較してみると,どうやら上記の二系統の名残りが跡づけられるというものである。
■手工雕刻原寸种字时,即使是雕刻师自己复刻自己的作品,也无法做到分毫不差。到了宾得时代,
当可以通过照片从同一放大原稿中复制图案时,几乎就不会出现差异了。
除了技法上的问题之外,人们很早以前就出现了追求标准字体的风气。想仿制评价好的字体的要求则更为强烈。
但道义上不能模仿,只能另做相似的东西,总之要确保「我们雇用自己的工匠制作的字体」这个借口。
总而言之,没有独自开发更优良字体的计划。作为制造商只能依靠工匠,要求在现有字体上添加一两个他们注意到的方针。
工匠的资质大多是来自于知道好的文本,并能对其进行适当地改造变形。
尽管如此,凭借多年的经验,雕刻师中的名人还是能摸索出自己的独特造型。平假名设计就是这样发展起来的。
关于汉字,特别是关于明朝体,自明治6年起由築地活版连续开发明治30年代基本完成的〔築地型〕,能超越它的,只有秀英舍(大日本印刷的前身)。——这就是昭和37年前后的真实情况。以下的研究,仅取三个字,比较其细部(6项)来追溯上述两种体系的残余。
// ■活字であることによって,下記のような過酷な条件をつきつけられる。また〔活字は正書法〕の資任も負わきれる。それに加えて工業化一辺倒の風潮は,活字設計100年の歩みをもっばら機械化の方向に押しやった。楷書体·明朝体·ゴシック体とならべると,歴史的変遷にそれが明らかである。そして今や再検討の時に至ったのではあるまいか。
■由于是活字,所以有如下苛刻的条件。同时还要担负起〔活字是正字法〕的职责,加之工业化一边倒的风潮,活字设计的百年历程走到了机械化的方向。楷书·明体·黑体,历史变迁显而易见。现在已经到了重新审视的时候了。
#v(1em)
#line(length: 100%)
#set enum(numbering: "1.", indent: 0em)
#set list(marker: "●", indent: 0em)
// ●グループ全体がよく揃っていること <sans_font>>
// + どんな顺序に組まれても隣の字と調和し,相互の間隔·位置・サイズ・ウエイトなどが揃うこと。
// + 全体の(1行または数行,ひらがなと混植)テクスチャーが適切であること。
// + 漢字とひらがなの調和と,適切な違い。これは弁別のために必要。など
- 整体之间必须规整一致 <sans_font>
+ 无论按什么顺序排列,都与相邻的字协调,相互的间隔、位置、尺寸、字重等都要规整。
+ 整体的(一行或几行,和平假名混排)组织应适当。
+ 汉字与平假名之间应保持和谐并适当区分。这是辨别的必要条件。等等
// ●一つーつの字が他の字とたやすく弁別できるように,その特長を失わず,独自性を持ちながら,他の字と調和していること <sans_font>>
// + 一つの漢字の特長とは,まず字体の違い,ウエイトとサイズの違い。
// + 字体の違いはまず格子構造・曲線構造その他などの大きな区別。それから特にその字の輪郭の形・特長あるエレメントなどで弁別される。この特長を必要以上に弱めることは,可読性を低下させる。
// + 1行のライン(縦組の場合は中央縦線が重要,横組の場合は文字の上下の水平線が重要)の中でのその文字の位置関係,輪郭と重心の有り方。
// + 構造の中で,主導的立場を持っているのが格子構造の漢字である。曲線構造の字は〔ハライ・そりハネ〕等で,その書体の特長·デザイナーの個性を強く表現する。
- 每个字之间应易于区分,要保持其特点,有其独特性,又与其他字协调一致 <sans_font>
+ 一个汉字的特征,首先是字形的不同,其次是字重和尺寸的不同。
+ 字形的不同主要是网格结构、曲线结构等有很大差异。此外,依据字形的轮廓形状、特征元素等进行分辨。过分削弱这一点会降低可读性。
+ 一行的基线(竖组时中央纵线重要,横组时文字上下的水平线重要)中文字的位置关系,轮廓和重心所在。
+ 在结构中,具有主导地位的是网格结构的汉字。曲线结构的字如〔撇捺・弯钩〕等,强烈地表现出字体的特点和设计者的个性。
#line(length: 100%)
#figure(
caption: [明朝体分类的Key],
image("img/511.jpg")
)
#v(3em)
// 図512の26書体分類のKey
图512的26字体分类的Key <sans_font>
// ■はじめに直感的に分類し,同時にそれを裏づけるデザインの細部のちがいを探し,この両面から分類をまとめた。実際上の歴史的知識もいくらか参考にしている。事実はどうかと,今になってメーカーに問合わせても回答は得られるはずもない。さて,26書体をA型6種,B型5種に分類した。分類をするためのkeyは6項目さがし当てたが,それで必要にして充分である。グループの全員にその特長を認め,他に一切ないのは確実性の高いkeyである(◉印とした)。B型の2,3,4グループには共通な特長が多く独立性は乏しい。
■首先直观地分类,同时寻找印证其设计细节的差异,从这两方面总结分类。另外也参考了一些历史知识。事实是如何,事到如今再去问制造商也得不到答复了。将26种字体分为A型6种、B型5种。做分类用的key有6个项目,已经足够需求了。关键是确定度最高的(◉),因为该组的所有成员都拥有该特征。B型的2、3、4组有很多共同的特征,缺乏独立性。
#v(2em)
#set text(size: font_size_list.at(3))
#tablex(
columns: (..(1fr,)*3,1.3cm,..(1fr,)*11),
align: horizon,
stroke: thin_line,
auto-lines: false,
vlinex(),(),(),(),vlinex(),(),(),(),(),(),vlinex(),(),(),(),(),vlinex(),
hlinex(),
[],[],[],[],colspanx(6)[
#align(center, text(size: font_size_list.at(2), tracking: 1em, [A 型]))
],(),(),(),(),(),colspanx(5)[
#align(center, text(size: font_size_list.at(2), tracking: 1em, [B 型]))
],(),(),(),(),
colspanx(4)[↓分类的Key],(),(),(),[0],[1],[2],[3],[4],[5],[0],[1],[2],[3],[4],
hlinex(),
[a],colspanx(3)[45%以上],(),(),[],[],[],[],[],[],[◉],[◉],[◉],[◉],[◉],
rowspanx(2)[b\{],[1],[离],image("img/511-1.jpg"),[●],[●],[],[●],[●],[●],[],[],[],[],[],
(),[3],[着],image("img/511-2.jpg"),[],[],[◉],[],[],[],[],[],[◉],[◉],[◉],
[e-],[2],[],image("img/511-3.jpg"),[],[],[],[◉],[],[],[],[],[◉],[◉],[◉],
rowspanx(2)[c\{],[2],[],image("img/511-4.jpg"),[],[],[],[],[],[],[●],[],[●],[],[●],
(),[1],[],image("img/511-5.jpg"),[],[],[],[],[◉],[],[],[],[],[],[],
[d-],[3],[],image("img/511-6.jpg"),[●],[],[],[],[●],[],[●],[],[●],[●],[],
hlinex(),
) <明朝体分类Key>
]
#pagebreak()
#columns(2)[
// ■資料は《季刊プリント巻1,1962印刷出版研究所》による。9pt.細明朝体27社を角寸法3cmに拡大した。No.1だけは歴史上の書体で明朝5号。
■资料来源于《季刊プリント巻1,1962印刷出版研究所》。将27个9pt细明朝体的字身框扩大到3cm。只有No.1明朝5号是历史上的字体。
#let page_511 = locate(loc => query(<明朝体分类Key>, loc).at(0).location().page())
// ■次の設計項目について测定し,比較した(p.9参照)。
■对下列设计项目进行了测定和比较(p.#page_511 参照)。
#set enum(numbering: "第a项目:", indent: 0em)
// 第a項目:〔行〕の中央フトコロ幅。角寸法の44%以下をA系,45%以上をB系とすると,Aは築地,Bは秀英にほぼー致するらしい。
+ 〔行〕的中间宽度,如果按照其与字身框的百分比分类,44%以下为A系,45%以上为B系的话,A是築地,B几乎都是秀英。
// 第b項目:〔発〕カシラの左右ハライの離れ方。
// 1.離れる,2.接触する,3,接合する
+ #box([
〔発〕头部的撇捺的分离方式。\
1.远离,2.接触,3.接合。
])
// 第c項目:〔発〕カシラの左ハライの末端が第2横線の左端とほぼ同じ高さに接近しているのをc-1とする。残りのうち,最上の横線の長さが角寸法の30%以上をc-2とする。
+ 〔発〕头部的左侧末端与其第2横线的左端,高度几乎相同的为c-1。剩下的部分中,最上面的横线长度在字身框的30%以上为c-2。
// 第d項目:〔新〕のヘンの〔立〕と〔木〕の接触するところについて図のように横線と縦線の関係を3種にする。
+ 〔新〕的偏旁的〔立〕和〔木〕的接触点,如图所示,将横线和竖线的关系分为3种。
// 第e項目:〔行〕の右側ハネ棒のハネの形によって2種にする。
+ 〔行〕的右侧根据〔亍〕的勾画形状分为两种。
#v(1em)
#figure(
caption: [正文用明朝体的体系],
image("img/512-1.jpg")
)
#colbreak()
#v(1fr)
#image("img/512-2.jpg")
]
#pagebreak()
#columns(2)[
// 第f項目:縦線幅3字で7本の平均值。グループごとに数値は近似していた。線幅は製作年代の新しいほど細くなっているらしい。
#list(marker: [第f项目:])[3字7条纵线宽度的平均值。每组的数值都很接近。制作年代越新,线宽越细。]
// 以上の6項目中,第a項目でA・Bの2型に大分けし,その中を第b\~f項目が同じようなものをまとめた。その結果A型5グループ,B型4グループとなった。同じグループは製作上何らかの関係があるものと思われる。
以上6个项目中,从第a项目区分A、B两种类型,其中又按第b\~f项目结果分组。最后A型为5组,B型为4组。同一组在制作理念上应该存在某种关系。
#v(1fr)
#image("img/512-3.jpg")
#colbreak()
#box()[
// #set text(tracking: 0em)
#tablex(
columns: (auto,auto,9em,..(auto,)*6),
auto-lines: false,
// inset: .5em,
map-cells: cell => {
if cell.y > 1 {
let cfg = ();
if cell.x == 0 {
cell.align = end + horizon
cfg = sans_font_cfg
} else if cell.x == 3 or cell.x == 8 {
cell.align = center + horizon
}
cell.inset = .33em
cell.content = text(size: font_size_list.at(3), ..(cfg))[#cell.content]
} else {
cell.align = center + horizon
}
return cell
},
// 書体ナンバー
// メーカー
// p.9縦組のKeyナンバー
(),vlinex(end:1),(),vlinex(),
hlinex(),
rowspanx(2)[体系],
colspanx(2, rowspanx(2)[
字体编号\
制造商
]),
colspanx(6)[
#let page_511 = locate(loc => query(<明朝体分类Key>, loc).at(0).location().page())
p.#page_511 的key编号
],(),(),(),(),(),(),
(),(),(),[a],[b],[c],[d],[e],[f],
hlinex(),
// 築地活版5号(明27)
// 凸版印刷
// 岩田母型
// 印刷局
// 日立印刷所
// モトヤ
// 橋本母型
// 千代田活字
// 錦精社
// 共同印刷
// 研究社印刷
// 技報堂
// 晃文堂
// 写研
// モリサワ
// 大日本印刷
// 三省堂
// 日本マトリックス
// ダイヤモンド社
// 精興社
// 日本活字工業
// 河本精文堂
// 津田三省堂
// 図書印刷
// 細川活版所
// 岩橋栄進堂
// 光文堂
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
[A原型],[1],[築地活版5号(明27)],[37%],[1],[3],[3],[1],[6.7%],
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
[A1],[2],[凸版印刷],[43],[1],[3],[1],[1],[6.7],
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
vlinex(x:1, start: 7, end: 23),
vlinex(x:8, start: 7, end: 23),
rowspanx(4)[A2],[3],[岩田母型],rowspanx(4)[
40\
\~\
43
],[3],[3],[2],[1],
rowspanx(4)[
5.8\
\~\
5.9
],
(),[4],[印刷局],(),[3],[3],[3],[1],(),
(),[5],[日立印刷所],(),[3],[3],[2],[1],(),
(),[6],[モトヤ],(),[3],[2],[3],[1],(),
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
rowspanx(3)[A3],[7],[橋本母型],rowspanx(3)[
41\
\~\
44
],[1],[3],[3],[2],
rowspanx(3)[
6.0\
\~\
6.1
],
(),[8],[千代田活字],(),[1],[2],[2],[2],(),
(),[9],[錦精社],(),[1],[3],[2],[2],(),
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
rowspanx(4)[A4],[10],[共同印刷],rowspanx(4)[
42\
\~\
43
],[1],[1],[3],[1],
rowspanx(4)[
5.9
],
(),[11],[研究社印刷],(),[1],[1],[3],[1],(),
(),[12],[技報堂],(),[1],[1],[3],[1],(),
(),[13],[晃文堂],(),[1],[1],[3],[1],(),
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
rowspanx(2)[A5],[14],[写研],rowspanx(2)[
40\~\
42
],[1],[3],[3],[1]
,rowspanx(2)[
5.7
],
(),[15],[モリサワ],(),[1],[3],[1],[1],(),
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
hlinex(),
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
[B原型],[16],[大日本印刷],[49],[2],[2],[3],[1],[6.8],
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
vlinex(x:1, start: 27, end: 39),
vlinex(x:8, start: 27, end: 39),
rowspanx(4)[B1],[17],[三省堂],rowspanx(4)[
45\
\~\
48
],[1],[3],[2],[1],
rowspanx(4)[
6.6\
\~\
6.8
],
(),[18],[日本マトリックス],(),[1],[3],[2],[1],(),
(),[19],[ダイヤモンド社],(),[1],[3],[2],[1],(),
(),[20],[精興社],(),[1],[3],[2],[1],(),
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
rowspanx(3)[B2],[21],[日本活字工業],rowspanx(3)[
48\
\~\
52
],[3],[2],[3],[2],
rowspanx(3)[
5.9
],
(),[22],[河本精文堂],(),[3],[2],[3],[2],(),
(),[23],[津田三省堂],(),[3],[2],[3],[2],(),
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
rowspanx(3)[B3],[24],[図書印刷],rowspanx(3)[
45\
\~\
48
],[3],[3],[3],[2],
rowspanx(3)[
5.4
],
(),[25],[細川活版所],(),[3],[3],[3],[2],(),
(),[26],[岩橋栄進堂],(),[3],[3],[3],[2],(),
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
[B4],[27],[光文堂],[46],[3],[2],[2],[2],[4.8],
cellx(colspan: 3, inset:0.08em)[],(),(),cellx(colspan: 6, inset:0.08em)[],(),(),(),(),(),
hlinex(),
)
#image("img/512-4.jpg")
]
] |
https://github.com/vEnhance/1802 | https://raw.githubusercontent.com/vEnhance/1802/main/src/sol-foxtrot.typ | typst | MIT License | #import "@local/evan:1.0.0":*
= Solutions to Part Foxtrot
== Solution to @exer-opt-lm-sin
We want to minimize the function $ f (x , y) = x + y $ subject to the
constraint $ g (x , y) = sin (x) + sin (y) = 1 $ and $x,y >= 0$.
0. The region $cal(R)$ has boundary whenever $x = 0$ or $y = 0$.
It also has limit cases when $x -> +oo$ or $y -> +oo$.
1. We find the LM-critical points.
The gradients are $ nabla f = vec(1,1) $ and $ nabla g = vec(cos(x), cos(y)). $
From the first two equations, we have:
$ lambda = 1 / (cos (x)) quad upright("and") quad lambda = 1 / (cos (y)) . $
Equating these expressions for $lambda$, we get:
$ frac(1, cos (x)) = frac(1, cos (y)) ==> cos (x) = cos (y) . $
Thus, we get an LM-critical point whenever
$ cos(x) &= cos(y) \
sin(x) + sin(y) &= 1 $
Note that $sin(x)^2 = 1 - cos(x)^2 = 1 - cos(y)^2 = sin(y)^2$.
Since $sin(x)+sin(y) = 1 != 0$, we conclude $sin(x) = sin(y) = 1/2$.
Together with $cos(x) = cos(y)$,
that means $x$ and $y$ must differ by a multiple of $2 pi$.
Since we want $x+y$ to be as small as possible, we might as well take $x=y$.
The smallest $x$ for which $sin(x) = 1/2$ is $x = pi/6$.
So of all the LM-critical points, the lowest value occurs when
$ f (pi / 6 , pi / 6) = pi / 6 + pi / 6 = pi / 3 . $
2. In the limit cases if either $x -> +oo$ or $y -> +oo$ then $f -> +oo$
3. Suppose $x = 0$. Then $sin(y) = 1$.
So this part of the boundary consists of the points $(0,pi)$, $(0,3pi)$, $(0,5pi)$, ....
All of these have $x+y >= pi$, so they do worse than the point $(pi/6, pi/6)$ from before.
Similarly, if $y=0$, we get boundary points $(pi,0)$, $(3pi,0)$, $(5pi,0)$, ....
Again all of these have $x+y >= pi$, so they do worse than the point $(pi/6, pi/6)$ from before.
In conclusion the minimum possible value occurs at
$ f (pi / 6 , pi / 6) = pi / 3 . $
|
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/sections/ConsuntivoSprint/QuartoSprint.typ | typst | MIT License | #import "../../const.typ": Re_cost, Am_cost, An_cost, Ve_cost, Pr_cost, Pt_cost
#import "../../functions.typ": rendicontazioneOreAPosteriori, rendicontazioneCostiAPosteriori, glossary
== Quarto #glossary[sprint]
*Inizio*: Venerdì 15/12/2023
*Fine*: Giovedì 21/12/2023
#rendicontazioneOreAPosteriori(sprintNumber: "04")
#rendicontazioneCostiAPosteriori(sprintNumber: "04")
=== Analisi a posteriori
Il consuntivo si mantiene relativamente simile al preventivo (delineando anzi, come le ore effettive siano a ribasso rispetto a quelle preventivate per la prima volta) ma è da notare che le ore da Amministratore sono ancora una volta in quantità maggiore rispetto a quanto preventivato, mentre vale il contrario per le ore da Verificatore. La spiegazione sta nel fatto che il team aveva inizialmente pensato di poter preparare tutto il materiale necessario e sostenere la prima revisione #glossary[RTB] entro la fine di Dicembre e si era preparato, di conseguenza, a impiegare più risorse per la revisione di alcuni documenti. Tuttavia, sono risultate necessarie più ore da Amministratore di quanto pensato in partenza visto che i componenti che ricoprono tale ruolo sono impegnati nella stesura sia delle _Norme di Progetto_ che del _Piano di Qualifica_, ed entrambi non erano vicini ad essere ultimati. Per quanto riguarda il _Piano di Qualifica_, inoltre, non ci si aspettava di incorrere in difficoltà nel calcolo delle percentuali di lavoro preventivato e svolto, necessarie per la valutazione di PV (Planned Value) ed EV (Earned Value), per cui si è incorsi in un breve momento di stallo.
Il team ha portato a termine tutti gli obiettivi prefissati eccetto la stesura completa del cruscotto delle metriche all'interno del _Piano di Qualifica_, il quale è stato sviluppato includendo la valutazione delle metriche prescelte fino allo #glossary[sprint] 2, ma non oltre (nell'attesa di ricevere l'approvazione del metodo utilizzato per calcolare PV ed EV da parte del team). L'unico rischio emergente è dunque stato RP3 o Variazioni nei tempi e costi del progetto, con riferimento in particolare allo spostamento della data prevista per svolgere la prima revisione #glossary[RTB]. In questo senso, si è preso atto che la pianificazione a lungo termine realizzata inizialmente non risultava flessibile a sufficienza da poter accomodare eventuali imprevisti o variazioni e di fatto contraddice la prima misura preventiva che il team si era proposto di utilizzare. In secondo luogo, avendo cominciato la stesura del _Piano di Qualifica_ solo recentemente, il cruscotto delle metriche non è ancora avanzato e dettagliato al punto da facilitare la gestione delle risorse nel progetto. In conclusione, sicuramente si renderà necessario rivalutare la pianificazione utilizzata finora e investire più risorse nella stesura del _Piano di Qualifica_. |
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/docs/images/logo.typ | typst | MIT License |
#import "/src/quill.typ": *
#set page(width: auto, height: auto, margin: 1pt)
// #quantum-circuit(
// 1, gate("Quantum"), control(1),2, [\ ],
// 2, ctrl(), gate("Circui"), gate($T$)
// )
// #v(2cm)
// #quantum-circuit(
// // background: blue.lighten(90%),
// row-spacing: 8pt,
// lstick($|psi〉$), gategroup(2,3, fill:blue.lighten(80%), stroke: (thickness: .7pt, dash: "dashed"), radius: 2pt),gate("Quantum"), control(1),1, meter(target: 1), [\ ],
// setwire(2), 2, ctrl(), gate("Circuit"), ctrl(), 1
// )
// #v(2cm)
// This is the one
#rect(
stroke: none,
radius: 3pt,
inset: (x: 15pt, y: 4pt),
fill: white,
quantum-circuit(
row-spacing: 7pt,
column-spacing: 18pt,
wire: .6pt,
scale: 130%,
lstick($|psi〉$), gategroup(2,4, fill:blue.lighten(80%), stroke: (thickness: .7pt, dash: "dashed")),
gate([Quill], radius: 2pt), ctrl(1), 1, 1, meter(target: 1), [\ ],
setwire(2), 1, phantom(content: "X"), ctrl(0),
1, setwire(1, stroke: (thickness: .9pt, dash: "loosely-dotted")), 15pt, 1,
// phantom(content: "Circuit"),
setwire(2, stroke: (dash: "solid", thickness: .6pt)), ctrl(0), 1,
annotate((3.9, 4), (0.1, 1.4), ((x0, x1), (y0, y1)) => {
// place(line(start: (x0, y0), end: (x1, y1)))
let x1 = x0 + 21.5pt
place(path(((x0, y1)), ((x1, y0), (-20pt, 15pt)), stroke: .7pt))
let xp = x0 + .14*(x1 - x0)
let yp = y0 + .7*(y1 - y0)
// place(path(((x0, y1)), (xp, yp), ((x1, y0), (-20pt, 15pt))))
place(path((xp, yp), ((x1, y0), (-20pt, 15pt))))
place(path((xp, yp), ((x1, y0), (-17pt, 15pt))))
place(path((xp, yp), ((x1, y0), (-14pt, 19pt))))
})
)
)
// // This is the one
// #quantum-circuit(
// row-spacing: 7pt,
// column-spacing: 15pt,
// wire: .6pt,
// lstick($|psi〉$), gategroup(2,3, fill:blue.lighten(80%), stroke: (thickness: .7pt, dash: "dashed")),
// gate("Quantum", radius: 2pt), ctrl(1),1, meter(target: 1), [\ ],
// setwire(2), 2, ctrl(0), gate("Circuit", radius: 2pt), ctrl(0), 1
// )
// #v(2cm)
// #quantum-circuit(
// row-spacing: 8pt,
// lstick($|psi〉$), gategroup(2,3, fill:blue.lighten(80%)), gate([Quantum]), control(1),1, swap(1),1, [\ ],
// setwire(2), 2, ctrl(), gate("Circuit"), targX,1
// ) |
https://github.com/ymgyt/techbook | https://raw.githubusercontent.com/ymgyt/techbook/master/programmings/js/typescript/utility_types.md | markdown | # Utility Types
tsが提供してくれているbuiltin型。
https://www.typescriptlang.org/docs/handbook/utility-types.html
## `Partial<T>`
`T`のpropertiesをすべてoptionalにした型を返す。
## `Record<Keys, Type>`
* HashMap型をつくれる
```typescript
let x: Record<string,number>;
x = {f1: 1, f2: 2};
```
|
|
https://github.com/0x1B05/nju_os | https://raw.githubusercontent.com/0x1B05/nju_os/main/am_notes/template.typ | typst | #import "@preview/codelst:2.0.0": sourcecode, codelst
#import "@preview/showybox:2.0.1": showybox
#import "@preview/ctheorems:1.1.0": *
#import "@preview/mitex:0.2.2": *
#import "resource.typ": *
/*
本模板修改自 jsk-lecnotes
+ 添加中文环境
+ 修改封面布局
+ 添加必要字体
*/
#let template(
// 笔记标题
title: "Lecture Notes Title",
// 在页眉展示的短标题
short_title: none,
// 笔记描述(可选),例如:
// description: [A template for simple notes]
description: none,
// 笔记创建日期(可选),例如:
// datetime(year: 2020, month: 02, day: 02)
date: none,
// 作者信息(除 name 外,其他参数可选)
authors: (
// name: "",
// github: "",
// link: "",
// affiliations: "1,2",
),
// 所属机构列表,每一项包括一个 id 和 name。这些将显示在作者下方。
affiliations: (
// (id: "1", name: "Organization 1"),
// (id: "2", name: "Organization 2"),
),
// 参考书目文件路径
bibliography_file: none,
// 参考文献引用样式
bibstyle: "gb-7714-2015-numeric",
// 页面尺寸,同时会影响页边距。
paper_size: "a4",
// 文本和代码的字体
text_font: "Linux Libertine",
sc_font: "Noto Sans CJK SC",
code_font: "DejaVu Sans Mono",
// 主题颜色,必须是 HEX 颜色.
accent: "#DC143C",
// 封面背景图片和正文背景颜色
cover_image: none,
background_color: none,
// 笔记内容
body
) = {
let accent_color = rgb(accent)
// 使用 ctheorems 包
show: thmrules
// 中文粗体,斜体
show strong: set text(fill: accent_color, font: (text_font, sc_font))
show emph: text.with(font: (text_font, sc_font))
// set text(cjk-latin-spacing: auto)
// 设置文档元数据
set document(title: title, author: authors.map(author => author.name))
// 设置正文和代码的字体
set text(font: (text_font, sc_font), size: 12pt, lang: "zh", region: "cn")
show raw: set text(font: code_font, 10pt)
// 将链接设置蓝色并加下划线,并且对于作者列表禁用此设置。
show link: it => {
let author_names = ()
for author in authors {
author_names.push(author.name)
}
if it.body.has("text") and it.body.text in author_names {
it
} else {
underline(stroke: (dash: "densely-dotted"), text(fill: blue, it))
}
}
// 文本高亮
// set highlight(fill: accent_color.lighten(50%))
// 计数器
let chaptercounter = counter("chapter")
let footnotecounter = counter(footnote)
// 配置页面
set page(
paper: paper_size,
numbering: "1 / 1",
number-align: center,
// 页边距
margin: (x:1.6cm, y:2.3cm),
// 封面背景图片
background: locate(loc => {
if loc.page() == 1 and cover_image != none {
layout(size => {
image(cover_image, height: size.height)
})
} else if background_color != none{
layout(size => {
block(width:100%, height:100%, fill: rgb(background_color))
})
}
}),
header: locate(loc => {
if loc.page() == 1{return}
let footers = query(selector(<__footer__>).after(loc), loc)
let elems = query(
heading.where(level: 1).before(footers.first().location()), footers.first().location()
)
if elems == () {return}
let head_title = text()[
#if short_title != none { short_title } else { title }
]
if calc.even(loc.page()) == true {
emph(elems.last().body) + h(1fr) + emph(head_title)
}else{
emph(head_title) + h(1fr) + emph(elems.last().body)
}
v(-7pt)
align(center)[#line(length: 105%, stroke: (thickness: 1pt, dash: "solid"))]
}),
footer: locate(loc => {
if loc.page() == 1 {return}
[
#if calc.even(loc.page()) == true {
align(left)[#counter(page).display("1 / 1",both: true,)]
}else{
align(right)[#counter(page).display("1 / 1",both: true,)]
}
#footnotecounter.update(())
#label("__footer__")
]
})
)
// 配置列表
show list: it => [
#set list(tight: false, indent: 2em)
#set text(top-edge: "ascender")
#it
]
show enum: it => [
#set enum(tight: false, indent: 2em)
#set text(top-edge: "ascender")
#it
]
// 配置标题
set heading(numbering: "1.1.1.1.1.")
show heading: it => box(width: 100%)[
#if it.numbering != none { counter(heading).display() }
#it.body
#v(12pt, weak: true)
#if it.level == 1 and it.numbering != none{
chaptercounter.step()
}
]
// 配置一级标题
show heading.where(
level: 1
): it => box(width: 100%)[
#set align(left)
#set heading(numbering: "章节 1. ")
#set text(fill: accent_color)
#it
#v(-12pt)
#line(length:100%, stroke: gray)
]
// 配置公式的编号和间距
set math.equation(
numbering: (..nums) => locate(loc => {
numbering("(1.1)", chaptercounter.at(loc).first(), ..nums)
})
)
show math.equation: eq => {
set block(spacing: 0.65em)
eq
}
// 配置图像和图像编号
set figure(
numbering: (..nums) => locate(loc => {
numbering("1.1", chaptercounter.at(loc).first(), ..nums)
})
)
// 配置表格
set table(
fill: (_, row) => if row == 0 {accent_color.lighten(40%)} else {accent_color.lighten(80%)},
stroke: 1pt + white
)
// set figure(placement: auto)
show figure.where(
kind: table
): set figure.caption(position: bottom)
show figure.where(
kind: raw
): it => {
set block(width: 100%, breakable: true)
it
}
// 配置行内代码块
show raw.where(
block: false,
): it => box(fill: luma(240), inset: (x: 2pt), outset: (y: 3pt), radius: 1pt)[#it]
show: codelst(reversed: true)
//------------------------------------------------------------------
box(width: 100%, height: 40%)[
// 显示论文的标题和描述。
#align(right+bottom)[
#text(36pt, weight: "bold")[#title]
#parbreak()
#if description != none {
text(size: 16pt, style: "italic")[#description]
}
]
]
box(width: 100%, height: 50%)[
#align(right+top)[
#if authors.len() > 0 {
box(inset: (y: 10pt), {
authors.map(author => {
text(16pt, weight: "semibold")[
#if "homepage" in author {
[#link(author.homepage)[#author.name]]
} else { author.name }]
if "affiliations" in author {
super(author.affiliations)
}
if "github" in author {
link(author.github, box(height: 1.1em, baseline: 13.5%)[#image.decode(githubSvg)])
}
}).join(", ", last: {
if authors.len() > 2 {
", and"
} else {
" and"
}
})
})
}
#v(-2pt, weak: true)
#if affiliations.len() > 0 {
box(inset: (bottom: 10pt), {
affiliations.map(affiliation => {
text(12pt)[
#super(affiliation.id)#h(1pt)#affiliation.name
]
}).join(", ")
})
}
]
]
box(width: 100%)[
#if date != none {
text(size: 12pt, "最初写作于:")
text(
size: 12pt,
fill: accent_color,
weight: "semibold",
date.display("[month repr:long] [day padding:zero], [year repr:full]")
)
parbreak()
text(size: 12pt, "最后更新于:")
text(
size: 12pt,
fill: accent_color,
weight: "semibold",
datetime.today().display("[month repr:long] [day padding:zero], [year repr:full]")
)
} else {
text(size: 11pt)[最后更新于:#h(5pt)] + text(
size: 11pt,
fill: accent_color,
weight: "semibold",
datetime.today().display("[month repr:long] [day padding:zero], [year repr:full]")
)
}
]
pagebreak()
// 显示笔记的目录
outline(indent: auto)
v(24pt, weak: true)
// 将段落设置为两端对齐,并设置换行。
set par(justify: true, linebreaks: "optimized", first-line-indent:2em, leading: 0.8em)
pagebreak()
// 显示笔记的内容
body
pagebreak()
// 显示参考文献
if bibliography_file != none {
show bibliography: set text(10.5pt)
bibliography(bibliography_file, title: "参考文献", style: "gb-7714-2015-numeric")
}
}
// 函数===========================================================
// 代码块
#let code(body, caption: none) = {
figure(caption: caption)[#sourcecode[#body]]
}
// 配置块引用
#let blockquote(cite: none, body) = [
#set text(size: 10.5pt)
#pad(left: 0.5em)[
#block(
breakable: true,
width: 100%,
fill: gray.lighten(95%),
radius: (left: 4pt, right: 4pt),
stroke: (left: 4pt + eastern.darken(20%), rest: 1pt + silver),
inset: 1em
)[#body]
]
]
// 水平标尺
#let horizontalrule = [#v(0.5em) #line(start: (20%,0%), end: (80%,0%)) #v(0.5em)]
// 另外的水平标尺
#let sectionline = align(center)[#v(0.5em) * \* #sym.space.quad \* #sym.space.quad \* * #v(0.5em)]
// 尝试添加 LaTeX 中的 \boxed{} 命令
#let dboxed(con) = box(stroke: 0.5pt + black, outset: (x: 2pt), inset: (y: 8pt), baseline: 11pt, $display(#con)$)
#let iboxed(con) = box(stroke: 0.5pt + black, outset: (x: 2pt), inset: (y: 3pt), baseline: 2pt, $#con$)
// ==== 使用 showybox 和 ctheorems 包创建盒子 ====
//
// | 环境 | 强调色 |
// |---------|-----------------------|
// | 定义 | orange |
// | 示例 | blue |
// | 提示 | olive |
// | 注意 | red |
// | 引用 | eastern |
// | 定理 | yellow |
// | 命题 | navy |
#let boxnumbering = "1.1.1.1.1.1"
#let boxcounting = "heading"
#let notebox(name, number, body, _type, _icon, _color) = {
showybox(
title-style: (
weight: 1000,
color: _color.darken(20%),
sep-thickness: 0pt,
),
frame: (
border-color: _color.darken(20%),
title-color: _color.lighten(80%),
body-color: _color.lighten(80%),
thickness: (left: 4pt),
radius: 4pt
),
title: [#name #h(1fr) #box(height: 0.85em)[#image.decode(_icon)] #_type #number],
body
)
}
#let definition = thmenv(
"definition",
boxcounting, //base counter name
2, // number of base number levels to use
(name, number, body) => {
notebox(name, number, body, "定义", _def, orange)
}
).with(numbering: boxnumbering)
#let example = thmenv(
"example",
boxcounting,
2,
(name, number, body, ..args) => {
notebox(name, number, body, "示例", e_g_, blue)
}
).with(numbering: boxnumbering)
#let tip = thmenv(
"tip",
boxcounting,
2,
(name, number, body) => {
notebox(name, number, body, "提示", lightbulb, olive)
}
).with(numbering: boxnumbering)
#let attention = thmenv(
"attention",
boxcounting,
2,
(name, number, body) => {
notebox(name, number, body, "注意", _caution, red)
}
).with(numbering: boxnumbering)
#let quote = thmenv(
"quote",
boxcounting,
2,
(name, number, body) => {
notebox(name, number, body, "引用", _quote, eastern)
}
).with(numbering: boxnumbering)
#let theorem = thmenv(
"theorem",
boxcounting,
2,
(name, number, body) => {
notebox(name, number, body, "定理", _thm, yellow)
}
).with(numbering: boxnumbering)
#let proposition = thmenv(
"proposition",
boxcounting,
2,
(name, number, body) => {
notebox(name, number, body, "命题", _prop, navy)
}
).with(numbering: boxnumbering)
#import "@preview/tablex:0.0.6": tablex, hlinex
#import "@preview/tablem:0.1.0": tablem
#let three-line-table = tablem.with(
render: (columns: auto, ..args) => {
tablex(
columns: columns,
auto-lines: false,
align: center + horizon,
hlinex(y: 0),
hlinex(y: 1),
..args,
hlinex(),
)
}
)
|
|
https://github.com/DJmouton/Enseignement | https://raw.githubusercontent.com/DJmouton/Enseignement/main/SNT/Réseaux sociaux/Cours%20cyberviolence.typ | typst | #import "/Templates/layouts.typ": SNT, titre, sous_titre
#import "/Templates/utils.typ": cadre, pointillets
#import "@preview/cetz:0.2.2"
#show: doc => SNT(doc)
#sous_titre[SNT - Réseaux Sociaux - Partie 2]
#titre[Cyberviolence]
#cadre(titre: "L'essentiel")[
Sur le Web, la violence prend des formes variées :
- divulgation de photos publiées sans autorisation ou encore modifiées intentionnellement;
- diffusion d'images à caractère pornographique;
- usurpation d'identité ;
- envoie d'insultes et de menaces ;
- publication de calomnies, etc.
]
= Agir contre la cyberviolence
#cadre(titre: "L'essentiel")[
Les actes de harcèlement en ligne sont punis par des peines de prison et des amendes de plusieurs dizaines de milliers d'euros. Les sanctions sont aménagées pour les mineurs. Pour agir contre la cyberviolence et s'informer sur les dispositifs existants, il existe de nombreuses ressources en ligne sur le site https://nonauharcelement.education.gouv.fr, ainsi qu'un numéro de téléphone dédié: le *3020*.
]
#cadre(titre: "Définitions à connaître")[
- La *cyberviolence* est un acte agressif et intentionnel, organisé à l'encontre d'une victime par un ou plusieurs individus, par l'intermédiaire d'un média numérique tel un réseau social.
- Le *harcèlement* se définit comme une violence répétée qui peut être verbale, physique ou psychologique. Cette violence s'exerce aussi bien au sein de l'école que sur les réseaux sociaux.
] |
|
https://github.com/iniyanijoseph/Fair-Division | https://raw.githubusercontent.com/iniyanijoseph/Fair-Division/main/1_Introduction/1_Introduction.typ | typst | #import "@preview/touying:0.4.2": *
#import emoji: *
#import "@preview/ctheorems:1.1.2": *
#show: thmrules
#let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee"))
#let lemma = thmbox("lemma", "Lemma", fill: rgb("#eeffee"))
#let corollary = thmplain(
"corollary",
"Corollary",
base: "theorem",
titlefmt: strong
)
#let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em))
#let example = thmplain("example", "Example").with(numbering: none)
#let proof = thmproof("proof", "Proof")
#let s = themes.simple.register()
#let (init, slides, alert, touying-outline) = utils.methods(s)
#show: init
#let (slide, empty-slide) = utils.slides(s)
#show: slides.with(slide-level: 2)
= Introduction to Discrete Fair Division
=== Table of Contents
#touying-outline()
== Motivations
=== Motivations
- People want stuff
- But there is only a finite amount of things
#pause
- This is the fundamental question of economics
- How do we study the movement of resources within a society?
=== The Computational Problem
- It is a computationally difficult problem to distribute items among people
- How can we guarantee truthfulness in our algorithm? (People may lie about their value of a good)
=== Applications
Variations of this problem have been used for
#columns(2, gutter: 11pt)[
#set par(justify: true)
+ Food distribution
- Indy Hunger Network
- Foodbank Australia
+ Computing resources
- Memory
- CPU Time
+ Estate Divisions
- Spliddit
#image("Indy Hunger Network.png", width:73%)
]
== Premise
=== Premise
- How can we allocate a set of goods to a set of people fairly?
- This is surprisingly complicated
- People may like different goods differently
- What does fairness even mean?
=== Discrete Setting // Cite survey paper
- We define $N$ (of cardinality $n$) to be the set of agents and $M$ (of cardinality $m$) to be the set of goods.
- Each $i in N$ is equipped with a valuation function $v_i$, which assigns a positive valuation to each subset of $M$
$ v_i: 2^M -> RR_(>=0) $
- Intuitively, valuation $v_i (emptyset) = 0$
- An allocation is a partition of $M$
$ X = <X_1, X_2, ... X_n> $
- $v_i$ is additive $v_i (A union B) = v_i (A) + v_i (B)$
//- Several papers have also relaxed this to be monotonic $ v_i (A union {g}) >= v_i (A) $ or submodular
== EF and PROP
=== Notions of Fairness
- Proportionality
- Each agent believes they receive at least $1/n$ of the goods
$ v_i (X_i) >= 1/n times v_i (M)$
- Envy-Freeness (*EF*)
- Each agent believes they receive weakly more than the other agents
$ forall_(i,j in N) v_i (X_i) >= v_i (X_j) $
=== Notions of Fairness
#example[In a discrete setting, EF allocations may not always exist
#proof[
By counterexample, take 1 good and 2 agents.
We arbitrarily give agent 1 the good
$ v_2 (X_1) > 0 = v_2 (X_2) $
]
A similar argument can be applied to proportionality
]
===
#lemma[ $"EF" -> "PROP"$ for additive valuations
#proof[
Assume that there is an envy free allocation and non proportional allocation. Every player believes that they have a piece of equal or better value to that of everyone else. Because the $v_i (X_j)$ may have value < 1/n, and there are n player, this means that $v_i (M)$ can be $< v_i (M)$
]
]
=== Relaxing EF
- Envy Free up to X (EFX)
- Each agent believes they receive weakly more than the other agents without some good
$ forall_(i, j) forall_(g in X_j) v_i (X_i) >= v_i (X_j \\ {g}) <-> forall_(i, j) v_i (X_i) >= v_i (X_j \\ min(X_j)) $
- It is not clear if EFX allocations exist or can be computed in polynomial time in general // Cite this
- Several relaxations of EFX have been proposed
=== Known cases for EFX
- EFX can be computed efficiently for n=2
- Cut and Choose
- An algorithm exists to compute an EFX allocation in pseudo polynomial time for n=3 // Cite Chaudary and Akrami
== Relaxations
=== Relaxing EFX
- Realized valuations
- Shared valuation function $v$
- EFX exists and a polynomial time algorithm is known // Make these slides
- EF1
$ forall_(i, j) exists_(g in X_j) v_i (X_i) >= v_i (X_j \\ {g}) <-> forall_(i, j) v_i (X_i) >= v_i (X_j \\ max(X_j)) $
- $alpha$-EFX
- $ forall_(i, j) exists_(g in X_j) v_i (X_i) >= alpha times v_i (X_j \\ {g}) $
- If EFX allocations exist in general, then $alpha=1$
=== Break Time!
==== Let's Cut a Cake
#figure(
image("cakeImage.png", width:50%)
)
== Other Fairness
=== Maximin Fair Share
- Let $X_n (M)$ be the set of possible allocations of M goods to n agents
- $mu_i^ n (M)$ is one of the partitions which maximizes the least valuable bundle according to $i$
$ mu_i^n (M) = max_(B in X_n (M)) min_(S in B) v_i (S) $ //Cite
- Maximin Share Fair (MMS) allocations do not always exist // Cite
=== Relaxing MMS
- $alpha$-MMS $v_i (X_i)$
=== Pareto Optimality
- An allocation is Pareto Optimal (PO) iff an agent would protest to another allocation
- The allocation $A$ is PO if there is no allocation B such that $v_i (B_i) >= v_i (A_i)$ for all $i$ and one inequality is strict
- A is not _Pareto Dominated_ by another allocation
// Can this be computed efficiently?
// Apparently there are a polynomial number of PO allocations?
// Does EFkX or smth -> PO?
=== MNW
- Maximize the geometric mean of values for agents with positive value
$ (product_i^n v_i (X_i))^(1/n) $
- $"MNW" ->"EF1" and "PO"$
#proof[
]
- Can an EF1 and PO allocation be computed in polynomial time?
=== Questions
==== Questions
== Mechanisms
=== Round Robin
- Agents receive their most valued remaining good in a set order until no goods remain.
=== Envy-Cycle Elimination
- Let $G$ be the envy graph on $N$
- $i -->j$ in G iff $v_i (X_i) < v_i (X_j) $
- If a cycle is found, each agent can receive the bundle of the agent they envy in the cycle
- "Rotate" bundles around the cycle
== Results
=== Computing EF1
Round Robin and Envy-Cycle Elimination produce an EF1 Allocation
#proof[
]
=== Computing $1/2$ MMS
Round Robin and Envy-Cycle Elimination produce an EF1 Allocation
#proof[
]
== Conclusion
=== Conclusion
- Fair division is a wide field with various applications |
|
https://github.com/lucifer1004/leetcode.typ | https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/solutions/s0010.typ | typst | #import "../helpers.typ": *
#let regular-expression-matching-ref(s, p) = {
let s = s.clusters()
let p = p.clusters()
let m = s.len()
let n = p.len()
let dp = fill(fill(false, n + 1), m + 1)
dp.at(0).at(0) = true
for i in range(0, m + 1) {
for j in range(1, n + 1) {
if p.at(j - 1) != "*" {
if i > 0 and (p.at(j - 1) == "." or p.at(j - 1) == s.at(i - 1)) {
dp.at(i).at(j) = dp.at(i - 1).at(j - 1)
}
} else {
if j >= 2 {
dp.at(i).at(j) = dp.at(i).at(j) or dp.at(i).at(j - 2)
}
if i >= 1 and j >= 2 and (p.at(j - 2) == "." or p.at(j - 2) == s.at(i - 1)) {
dp.at(i).at(j) = dp.at(i).at(j) or dp.at(i - 1).at(j)
}
}
}
}
dp.at(m).at(n)
}
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/footnote-container_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test footnote in caption.
Read the docs #footnote[https://typst.app/docs]!
#figure(
image("/assets/files/graph.png", width: 70%),
caption: [
A graph #footnote[A _graph_ is a structure with nodes and edges.]
]
)
More #footnote[just for ...] footnotes #footnote[... testing. :)]
|
https://github.com/piepert/philodidaktik-hro-phf-ifp | https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/grundpositionen/historische_standpunkte.typ | typst | Other | #import "/src/template.typ": *
== Historische Standpunkte zur Philosophiedidaktik
// Es folgen einige historische Grundpositionen, die jeweils zwei Dinge derjenigen Vertreter charakterisieren sollen: zuerst den Philosphiebegriff und darauf folgend eine didaktische Grundhaltung. Die didaktische Grundhaltung kann ein thematischer und/oder methodischer Schwerpunkt sein.
// Von der Antike bis zur Moderne sind die folgenden Philosophie- und Philosophiedidaktikbegriffe vertreten:#en[Vgl. @Runtenberg2016_EPhiD[S. 18 ff]]
#let stances = (
"#1 Sokrates": [
#ix("", "Sokrates")Die Philosophie ist eine öffentliche Angelegenheit, kritisches Denken, Entwickeln von Problembewusstsein. Das Verfahren ist die _#ix("Hebammenkunst", "Mäeutik", "Hebammenkunst")_ bzw. _Mäeutik_: durch gezielte Verwirrung wird der Mensch zu selbständigem Denken angeregt, der Philosophielehrer ist die Hebamme, die den SuS hilft die Erkenntnis, die bereits in ihnen steckt, hervor zu bringen.#en[Vgl. @Runtenberg2016_EPhiD[S. 18 f]] Eine Methode der Mäeutik ist die _#ix("Elenktik")_.#en[Die Elenktik ist die Kunst der Überführung, in der Sokrates die Frage nach dem "Was ist $X$?" stellt und den Gesprächspartner überführt, sollte er Beispiele von $X$ nennen. Ziel des Sokrates ist das Ergründen des Wesens von $X$, also das, was die Beispiele gemein haben und sie überhaupt erst zu Beispielen von $X$ macht.#en-note("standp-sokrates1") Der genaue Inhalt der sokratischen Elenktik ist jedoch umstritten.#en-note("standp-sokrates2")]#en-content("standp-sokrates1")[Vgl. @Beaney2016_Analysis]#en-content("standp-sokrates2")[Vgl. @Strobach2017_Sokrates[S. 113 f]]
],
"#2 Platon": [
#ix("", "Platon")Die philosophische Erforschung der Wahrheit und die Prüfung des Selbst führen dazu, für die eigene Seele zu sorgen. Philosophieren findet an praktischen Fragen statt, als _Umgang mit den Ideen_. Die #ix("Dialektik") ist Hauptmethode des Philosophierens. Ziel der Philosophie ist gutes Leben.#en[Vgl. @Runtenberg2016_EPhiD[S. 19 f]]
],
"#3 Aristoteles": [
#ix("", "Aristoteles")Philosophie hat das gute, sittliche Leben und das Leben in der Wissenschaft zum Gegenstand. Ziel ist die Ausbildung von Klugheit in einer passenden Lernumgebund (entfernt vom Alltag), ein _#ix("Phronimos")_ (ein Weiser) zu werden, der das gute Leben organisieren kann und die rechte Mitte zwischen zwei Extremen findet.#en[Vgl. @Runtenberg2016_EPhiD[S. 20]]
],
"#4 Epikur": [
#ix("", "Epikur")Philosophie ist das Schulen der Vernunft und soll zu einer reflektierten Genussfähigkeit und einer _rationalen Auseinandersetzung mit irrationalen Ängsten_, Vorstellungen und Vorurteilen und damit zu einem insgesamt gelingendem Leben führen. Der Mensch ist selbstbestimmt und handelt verantwortungsbewusst.#en[Vgl. @Runtenberg2016_EPhiD[S. 20 f]]
],
"#5 Kant": [
#ix("", "Kant, Immanuel")Philosophie ist öffentlich und praktisch. Sie dient der Ausbildung der Urteilskraft, des Verstandes und der Vernunft als Reflexion. Im Mittelspunkt steht das Selbstdenken angeleitet durch die _induktive Methode_. Deduktive Methoden werden abgelehnt, da bei ihnen die Selbständigkeit im Lernprozess fehlt. Ziel ist die Bildung eines Autonomen, aufgeklärten, moralisch-urteilsfähigen Menschen. Der Mensch lernt nicht Philosophie, er lernt _zu philosophieren_.#en[Vgl. @Runtenberg2016_EPhiD[S. 21 ff]]
],
"#6 Hegel": [
#ix("", "Hegel, <NAME>.")Die Philosophie wird deduktiv gelernt, durch die Methode des _verstehenden Nachvollzugs_. Bereits bestehende Inhalte klassischer Philosophen müssen erlernt und nachvollzogen werden. Die Primärmethode des Philosophieunterrichts ist der Lehrervortrag, der die philosophischen Inhalte vermittelt. Es um das Erlernen formaler Denkfähigkeiten anhand klassischer Positionen zur Auseinandersetzung mit philosophischen Themen.#en[Vgl. @Runtenberg2016_EPhiD[S. 23 ff]]
],
"#7 Nietzsche": [
#ix("", "Nietzsche, <NAME>.")Philosophieren ist relativ an die Philosophie umgebenden Verhältnisse gebunden, die sie und ihre historische Entwicklung versucht kritisch zu betrachten. Philosophieren ist ein schmerzhafter Vereinsamungsprozess, sich von der gewohnten Lebenswelt abzutrennen, und soll zu einer Neugeburt des einsamen Denkers führen, bis nur die Liebe zum Leben, ein selbstdenkendes und kritisches Individuum mit einer neuen Perspektive auf die Welt zurückbleibt.#en[Vgl. @Runtenberg2016_EPhiD[S. 25 f]]
],
"#8 Foucault": [
#ix("", "<NAME>")Philosophie ist ein Ethos, eine Lebensgewohnheit, eine permanente Haltung. Das Selbstdenken steht auch hier im Vordergrund, Aufklärung ist eine Kritik der Weltanschauung, eine kritisch-historische Untersuchung. Die philosophische Bildung soll ein permanentes, freies und das Individuum im Einzelnen förderndes Angebot sein. Selbstauseinandersetzung steht im Mittelpunkt. Ziel ist die Arbeit an einer Bildung einer eigenen Identität durch Entledigung schlechter Gewohnheiten und falscher Ansichten.#en[Vgl. @Runtenberg2016_EPhiD[S. 26 ff]]
]
)
// #grid(columns: 1, column-gutter: 1em, row-gutter: 1em,
// ..(stances.keys().map(e => {
// block(breakable: false, {
// strong(e)+[\ ]
// stances.at(e)
// })
// })).flatten()
// )
#[
#show: columns.with(2)
#(stances.keys().slice(0, -1).map(e => {
block(breakable: false, {
strong(e)+[\ ]
stances.at(e)
})
})).flatten().join([])
]
#(stances.keys().slice(stances.keys().len()-1).map(e => {
block(breakable: false, {
strong(e)+[\ ]
stances.at(e)
})
})).flatten().join([]) |
https://github.com/ChHecker/unify | https://raw.githubusercontent.com/ChHecker/unify/main/lib.typ | typst | MIT License | #let _re-num = regex("^(-?\d+(\.|,)?\d*)?(((\+(\d+(\.|,)?\d*)-(\d+(\.|,)?\d*)))|((((\+-)|(-\+))(\d+(\.|,)?\d*))))?(e([-\+]?\d+))?$")
#let _unicode-exponents = (("\u2070", "0"), ("\u00B9", "1"), ("\u00B2", "2"), ("\u00B3", "3"), ("\u2074", "4"), ("\u2075", "5"), ("\u2076", "6"), ("\u2077", "7"), ("\u2078", "8"), ("\u2079", "9"), ("\u207A", "+"), ("\u207B", "-"))
#let _format-float(f, decsep: "auto", thousandsep: "#h(0.166667em)") = {
/// Formats a float with thousands separator.
/// - `f`: Float to format.
/// - `decsep`: Which decimal separator to use. This must be the same as the one used in `f`. Set it to `auto` to automatically choose it. Falls back to `.`.
/// - `thousandsep`: The separator between the thousands.
let string = ""
if decsep == "auto" {
if "," in f {
decsep = ","
} else {
decsep = "."
}
}
if thousandsep.trim() == "." {
thousandsep = ".#h(0mm)"
}
let split = str(f).split(decsep)
let int-part = split.at(0)
let dec-part = split.at(1, default: none)
let int-list = int-part.clusters()
string += str(int-list.remove(0))
for (i, n) in int-list.enumerate() {
let mod = (i - int-list.len()) / 3
if int(mod) == mod {
string += " " + thousandsep + " "
}
string += str(n)
}
if dec-part != none {
let dec-list = dec-part.clusters()
string += decsep
for (i, n) in dec-list.enumerate() {
let mod = i / 3
if int(mod) == mod and i != 0 {
string += " " + thousandsep + " "
}
string += str(n)
}
}
string
}
#let _format-num(
value, exponent: none, upper: none, lower: none,
multiplier: "dot", thousandsep: "#h(0.166667em)") = {
/// Format a number.
/// - `value`: Value of the number.
/// - `exponent`: Exponent in the exponential notation.
/// - `upper`: Upper uncertainty.
/// - `lower`: Lower uncertainty.
/// - `multiplier`: The symbol used to indicate multiplication
/// - `thousandsep`: The separator between the thousands of the float.
let formatted-value = ""
if value != none {
formatted-value += _format-float(value, thousandsep: thousandsep).replace(",", ",#h(0pt)")
}
if upper != none and lower != none {
if upper != lower {
formatted-value += "^(+" + _format-float(upper, thousandsep: thousandsep) + ")"
formatted-value += "_(-" + _format-float(lower, thousandsep: thousandsep) + ")"
} else {
formatted-value += " plus.minus " + _format-float(upper, thousandsep: thousandsep).replace(",", ",#h(0pt)")
}
} else if upper != none {
formatted-value += " plus.minus " + _format-float(upper, thousandsep: thousandsep).replace(",", ",#h(0pt)")
} else if lower != none {
formatted-value += " plus.minus " + _format-float(lower, thousandsep: thousandsep).replace(",", ",#h(0pt)")
}
if not (upper == none and lower == none) {
formatted-value = "lr((" + formatted-value
formatted-value += "))"
}
if exponent != none {
if value != none {
formatted-value += " " + multiplier + " "
}
formatted-value += "10^(" + str(exponent) + ")"
}
formatted-value
}
#let num(value, multiplier: "dot", thousandsep: "#h(0.166667em)") = {
/// Format a number.
/// - `value`: String with the number.
/// - `multiplier`: The symbol used to indicate multiplication
/// - `thousandsep`: The separator between the thousands of the float.
// str() converts minus "-" of a number to unicode "\u2212"
value = str(value).replace("−", "-").replace(" ", "")//.replace(",", ".")
let match-value = value.match(_re-num)
assert.ne(match-value, none, message: "invalid number: " + value)
let captures-value = match-value.captures
let upper = none
let lower = none
if captures-value.at(14) != none {
upper = captures-value.at(14)
lower = none
} else {
upper = captures-value.at(5)
lower = captures-value.at(7)
}
let formatted = _format-num(
captures-value.at(0),
exponent: captures-value.at(17),
upper: upper,
lower: lower,
multiplier: multiplier,
thousandsep: thousandsep
)
formatted = "$" + formatted + "$"
eval(formatted)
}
#let _prefix-csv(path, delimiter: ",") = {
/// Load a CSV file with pre- or postfixes.
/// - `path`: Path of the CSV file.
/// - `delimiter`: Passed to the `csv` function.
let array = csv(path, delimiter: delimiter)
let symbols = (:)
let symbols-short = (:)
for line in array {
symbols.insert(lower(line.at(0)), line.at(2))
symbols-short.insert(line.at(1), line.at(2))
}
(symbols, symbols-short)
}
#let _postfix-csv(path, delimiter: ",") = {
/// Load a CSV file with pre- or postfixes.
/// - `path`: Path of the CSV file.
/// - `delimiter`: Passed to the `csv` function.
let array = csv(path, delimiter: delimiter)
let dict = (:)
for line in array {
dict.insert(lower(line.at(0)), line.at(1))
}
dict
}
#let _unit-csv(path, delimiter: ",") = {
/// Load a CSV file with units.
/// - `path`: Path of the CSV file.
/// - `delimiter`: Passed to the `csv` function.
let array = csv(path, delimiter: delimiter)
let units = (:)
let units-short = (:)
let units-space = (:)
let units-short-space = (:)
for line in array {
units.insert(lower(line.at(0)), line.at(2))
units-short.insert(line.at(1), line.at(2))
if line.at(3) == "false" or line.at(3) == "0" {
units-space.insert(lower(line.at(0)), false)
units-short-space.insert(line.at(1), false)
} else {
units-space.insert(lower(line.at(0)), true)
units-short-space.insert(line.at(1), true)
}
}
(units, units-short, units-space, units-short-space)
}
#let _add-money-units(data) = {
let (units, units-short, units-space, units-short-space) = data
let array = csv("money.csv", delimiter: ",")
for line in array {
units.insert(lower(line.at(0)), line.at(2))
units-short.insert(line.at(1), line.at(2))
if line.at(3) == "false" or line.at(3) == "0" {
units-space.insert(lower(line.at(0)), false)
units-short-space.insert(line.at(1), false)
} else {
units-space.insert(lower(line.at(0)), true)
units-short-space.insert(line.at(1), true)
}
}
(units, units-short, units-space, units-short-space)
}
#let postfixes = _postfix-csv("postfixes.csv")
#let lang-db = state("lang-db",(
"en":(
"units":(_unit-csv("units-en.csv")),
"prefixes":(_prefix-csv("prefixes-en.csv")),
),
"ru":(
"units":(_unit-csv("units-ru.csv")),
"prefixes":(_prefix-csv("prefixes-ru.csv")),
),
)
)
// get units
#let __inits() = {
let lang = text.lang
let data = lang-db.get()
if lang in data {
_add-money-units(data.at(lang).units)
} else {
_add-money-units(data.en.units)
}
}
// get prefixes
#let __prefixes() = {
let lang = text.lang
let data = lang-db.get()
if lang in data {
data.at(lang).prefixes
} else {
data.en.prefixes
}
}
#let _unicode-exponent-list = for (unicode, ascii) in _unicode-exponents {(unicode,)}
#let _exponent-pattern = regex("[" + _unicode-exponent-list.join("|") + "]+")
#let _replace-unicode-exponents(unit-str) = {
let exponent-matches = unit-str.matches(_exponent-pattern)
let exponent = ""
for match in exponent-matches {
exponent = "^" + match.text
for (unicode, ascii) in _unicode-exponents {
exponent = exponent.replace(regex(unicode), ascii)
}
unit-str = unit-str.replace(match.text, exponent)
}
unit-str
}
#let chunk(string, cond) = (string: string, cond: cond)
#let _format-unit-short(
string, space: "#h(0.166667em)", per: "symbol",
units-short, units-short-space, prefixes-short
) = {
/// Format a unit using the shorthand notation.
/// - `string`: String containing the unit.
/// - `space`: Space between units.
/// - `per`: Whether to format the units after `/` with a fraction or exponent.
assert(per == "symbol" or per == "fraction" or per == "/")
let formatted = ""
string = _replace-unicode-exponents(string)
let split = string
.replace(regex(" */ *"), "/")
.replace(regex(" +"), " ")
.split(regex(" "))
let chunks = ()
for s in split {
let per-split = s.split("/")
chunks.push(chunk(per-split.at(0), false))
if per-split.len() > 1 {
for p in per-split.slice(1) {
chunks.push(chunk(p, true))
}
}
}
// needed for fraction formatting
let normal-list = ()
let per-list = ()
let prefixes = ()
for (string: string, cond: per-set) in chunks {
let u-space = true
let prefix = none
let unit = ""
let exponent = none
let qty-exp = string.split("^")
let quantity = qty-exp.at(0)
exponent = qty-exp.at(1, default: none)
if quantity in units-short {
// Match units without prefixes
unit = units-short.at(quantity)
u-space = units-short-space.at(quantity)
} else {
// Match prefix + unit
let pre = ""
for char in quantity.clusters() {
pre += char
// Divide `quantity` into `pre`+`u` and check validity
if pre in prefixes-short {
let u = quantity.trim(pre, at: start, repeat: false)
if u in units-short {
prefix = prefixes-short.at(pre)
unit = units-short.at(u)
u-space = units-short-space.at(u)
pre = none
break
}
}
}
if pre != none {
panic("invalid unit: " + quantity)
}
}
if per == "symbol" {
if u-space {
formatted += space
}
formatted += prefix + unit
if exponent != none {
if per-set {
formatted += "^(-" + exponent + ")"
} else {
formatted += "^(" + exponent + ")"
}
} else if per-set {
formatted += "^(-1)"
}
} else {
let final-unit = ""
// if u-space {
// final-unit += space
// }
final-unit += prefix + unit
if exponent != none {
final-unit += "^(" + exponent + ")"
}
if per-set {
per-list.push(chunk(final-unit, u-space))
} else {
normal-list.push(chunk(final-unit, u-space))
}
}
}
// return((normal-list, per-list))
if per != "symbol" {
if normal-list.at(0).at("cond") {
formatted += space
}
if per-list.len() > 0 {
formatted += " ("
}
for (i, chunk) in normal-list.enumerate() {
let (string: n, cond: space-set) = chunk
if i != 0 and space-set {
formatted += space
}
formatted += n
}
if per-list.len() == 0 {
return formatted
}
formatted += ")/("
for (i, chunk) in per-list.enumerate() {
let (string: p, cond: space-set) = chunk
if i != 0 and space-set {
formatted += space
}
formatted += p
}
formatted += ")"
}
formatted
}
#let _format-unit(string, space: "#h(0.166667em)", per: "symbol") = {
/// Format a unit using written-out words.
/// - `string`: String containing the unit.
/// - `space`: Space between units.
/// - `per`: Whether to format the units after `per` with a fraction or exponent.
assert(per == "symbol" or per == "fraction" or per == "/")
// load data
let (units, units-short, units-space, units-short-space) = __inits()
let (prefixes, prefixes-short) = __prefixes()
let formatted = ""
// needed for fraction formatting
let normal-list = ()
let per-list = ()
// whether per was used
let per-set = false
// whether waiting for a postfix
let post = false
// one unit
let unit = chunk("", true)
let split = lower(string).split(" ")
split.push("")
for u in split {
// expecting postfix
if post {
if per == "symbol" {
// add postfix
if u in postfixes {
if per-set {
unit.at("string") += "^(-"
} else {
unit.at("string") += "^("
}
unit.at("string") += postfixes.at(u)
unit.at("string") += ")"
if unit.at("cond") {
unit.at("string") = space + unit.at("string")
}
per-set = false
post = false
formatted += unit.at("string")
unit = chunk("", true)
continue
// add per
} else if per-set {
unit.at("string") += "^(-1)"
if unit.at("cond") {
unit.at("string") = space + unit.at("string")
}
per-set = false
post = false
formatted += unit.at("string")
unit = chunk("", true)
// finish unit
} else {
post = false
if unit.at("cond") {
unit.at("string") = space + unit.at("string")
}
formatted += unit.at("string")
unit = chunk("", true)
}
} else {
if u in postfixes {
unit.at("string") += "^("
unit.at("string") += postfixes.at(u)
unit.at("string") += ")"
if per-set {
per-list.push(unit)
} else {
normal-list.push(unit)
}
per-set = false
post = false
unit = chunk("", true)
continue
} else {
if per-set {
per-list.push(unit)
} else {
normal-list.push(unit)
}
per-set = false
post = false
unit = chunk("", true)
}
}
}
// detected per
if u == "per" {
per-set = true
// add prefix
} else if u in prefixes {
unit.at("string") += prefixes.at(u)
// add unit
} else if u in units {
unit.at("string") += units.at(u)
unit.at("cond") = units-space.at(u)
post = true
} else if u != "" {
return _format-unit-short(string, space: space, per: per, units-short, units-short-space, prefixes-short)
}
}
if per != "symbol" {
if normal-list.at(0).at("cond") {
formatted += space
}
if per-list.len() > 0 {
formatted += " ("
}
for (i, chunk) in normal-list.enumerate() {
let (string: n, cond: space-set) = chunk
if i != 0 and space-set {
formatted += space
}
formatted += n
}
if per-list.len() == 0 {
return formatted
}
formatted += ")/("
for (i, chunk) in per-list.enumerate() {
let (string: p, cond: space-set) = chunk
if i != 0 and space-set {
formatted += space
}
formatted += p
}
formatted += ")"
}
formatted
}
#let unit(unit, space: "#h(0.166667em)", per: "symbol") = {
/// Format a unit.
/// - `unit`: String containing the unit.
/// - `space`: Space between units.
/// - `per`: Whether to format the units after `per` or `/` with a fraction or exponent.
context {
let formatted-unit = ""
formatted-unit = _format-unit(unit, space: space, per: per)
let formatted = "$" + formatted-unit + "$"
eval(formatted)
}
}
#let qty(
value, unit, rawunit: false, space: "#h(0.166667em)",
multiplier: "dot", thousandsep: "#h(0.166667em)", per: "symbol") = {
/// Format a quantity (i.e. number with a unit).
/// - `value`: String containing the number.
/// - `unit`: String containing the unit.
/// - `multiplier`: The symbol used to indicate multiplication
/// - `rawunit`: Whether to transform the unit or keep the raw string.
/// - `space`: Space between units.
/// - `thousandsep`: The separator between the thousands of the float.
/// - `per`: Whether to format the units after `per` or `/` with a fraction or exponent.
value = str(value).replace("−", "-").replace(" ", "")
let match-value = value.match(_re-num)
assert.ne(match-value, none, message: "invalid number: " + value)
let captures-value = match-value.captures
let upper = none
let lower = none
if captures-value.at(14) != none {
upper = captures-value.at(14)
lower = none
} else {
upper = captures-value.at(5)
lower = captures-value.at(7)
}
let formatted-value = _format-num(
captures-value.at(0),
exponent: captures-value.at(17),
upper: upper,
lower: lower,
multiplier: multiplier,
thousandsep: thousandsep
)
context {
let formatted-unit = ""
if rawunit {
formatted-unit = space + unit
} else {
formatted-unit = _format-unit(unit, space: space, per: per)
}
let formatted = "$" + formatted-value + formatted-unit + "$"
eval(formatted)
}
}
#let _format-range(
lower, upper, exponent-lower: none, exponent-upper: none, multiplier: "dot",
delimiter: "-", space: "#h(0.16667em)", thousandsep: "#h(0.166667em)", force-parentheses: false
) = {
/// Format a range.
/// - `(lower, upper)`: Strings containing the numbers.
/// - `(exponent-lower, exponent-upper)`: Strings containing the exponentials in exponential notation.
/// - `multiplier`: The symbol used to indicate multiplication
/// - `delimiter`: Symbol between the numbers.
/// - `space`: Space between the numbers and the delimiter.
/// - `thousandsep`: The separator between the thousands of the float.
/// - `force-parentheses`: Whether to force parentheses around the range.
let formatted-value = ""
formatted-value += _format-num(lower, thousandsep: thousandsep).replace(",", ",#h(0pt)")
if exponent-lower != exponent-upper and exponent-lower != none {
if lower != none {
formatted-value += multiplier + " "
}
formatted-value += "10^(" + str(exponent-lower) + ")"
}
formatted-value += space + " " + delimiter + " " + space + _format-num(upper, thousandsep: thousandsep).replace(",", ",#h(0pt)")
if exponent-lower != exponent-upper and exponent-upper != none {
if upper != none {
formatted-value += multiplier + " "
}
formatted-value += "10^(" + str(exponent-upper) + ")"
}
if exponent-lower == exponent-upper and (exponent-lower != none and exponent-upper != none) {
formatted-value = "lr((" + formatted-value
formatted-value += ")) " + multiplier + " 10^(" + str(exponent-lower) + ")"
} else if force-parentheses {
formatted-value = "lr((" + formatted-value
formatted-value += "))"
}
formatted-value
}
#let numrange(
lower, upper, multiplier: "dot",
delimiter: "-", space: "#h(0.16667em)", thousandsep: "#h(0.166667em)") = {
/// Format a range.
/// - `(lower, upper)`: Strings containing the numbers.
/// - `multiplier`: The symbol used to indicate multiplication
/// - `delimiter`: Symbol between the numbers.
/// - `space`: Space between the numbers and the delimiter.
/// - `thousandsep`: The separator between the thousands of the float.
lower = str(lower).replace("−", "-").replace(" ", "")
let match-lower = lower.match(_re-num)
assert.ne(match-lower, none, message: "invalid lower number: " + lower)
let captures-lower = match-lower.captures
upper = str(upper).replace("−", "-").replace(" ", "")
let match-upper = upper.match(_re-num)
assert.ne(match-upper, none, message: "invalid upper number: " + upper)
let captures-upper = match-upper.captures
let formatted = _format-range(
captures-lower.at(0),
captures-upper.at(0),
exponent-lower: captures-lower.at(17),
exponent-upper: captures-upper.at(17),
multiplier: multiplier,
delimiter: delimiter,
thousandsep: thousandsep,
space: space,
)
formatted = "$" + formatted + "$"
eval(formatted)
}
#let qtyrange(
lower, upper, unit, rawunit: false, multiplier: "dot", delimiter: "-", space: "",
unitspace: "#h(0.16667em)", thousandsep: "#h(0.166667em)", per: "symbol"
) = {
/// Format a range with a unit.
/// - `(lower, upper)`: Strings containing the numbers.
/// - `unit`: String containing the unit.
/// - `rawunit`: Whether to transform the unit or keep the raw string.
/// - `multiplier`: The symbol used to indicate multiplication
/// - `delimiter`: Symbol between the numbers.
/// - `space`: Space between the numbers and the delimiter.
/// - `unitspace`: Space between units.
/// - `thousandsep`: The separator between the thousands of the float.
/// - `per`: Whether to format the units after `per` or `/` with a fraction or exponent.
lower = str(lower).replace("−", "-").replace(" ", "")
let match-lower = lower.match(_re-num)
assert.ne(match-lower, none, message: "invalid lower number: " + lower)
let captures-lower = match-lower.captures
upper = str(upper).replace("−", "-").replace(" ", "")
let match-upper = upper.match(_re-num)
assert.ne(match-upper, none, message: "invalid upper number: " + upper)
let captures-upper = match-upper.captures
let formatted-value = _format-range(
captures-lower.at(0),
captures-upper.at(0),
exponent-lower: captures-lower.at(17),
exponent-upper: captures-upper.at(17),
multiplier: multiplier,
delimiter: delimiter,
space: space,
thousandsep: thousandsep,
force-parentheses: true
)
context {
let formatted-unit = ""
if rawunit {
formatted-unit = space + unit
} else {
formatted-unit = _format-unit(unit, space: unitspace, per: per)
}
let formatted = "$" + formatted-value + formatted-unit + "$"
eval(formatted)
}
}
|
https://github.com/alberto-lazari/cns-report | https://raw.githubusercontent.com/alberto-lazari/cns-report/main/test.typ | typst | = Test results <test_results>
Since running tests on different applications require to write a distinct inspector for each application, our tests have been run on the "postepay" app. Then we showed that it is possible to automate the testing of applications which require a login by writing an inspector for the "discord" app.
#figure(
grid(
columns: 4,
gutter: 2mm,
image("images/Screenshot_1.png"),
image("images/Screenshot_2.png"),
image("images/Screenshot_3.png"),
image("images/Screenshot_4.png")
),
caption: "Test screenshots"
)
We run the complete test set of @QRFuzz on the "postepay" app without finding vulnerabilities and our tool was able to scan an average of 7 QRs every minute. |
|
https://github.com/0x1B05/nju_os | https://raw.githubusercontent.com/0x1B05/nju_os/main/lecture_notes/content/10_并发控制-同步2.typ | typst | #import "../template.typ": *
#pagebreak()
= 并发控制: 同步 (2)
== 信号量
=== 复习:生产者-消费者、互斥、条件变量
打印 “合法” 的括号序列 (())()
- 左括号对应 push
- 右括号对应 pop
```c
#define CAN_PRODUCE (count < n)
#define CAN_CONSUME (count > 0)
wait_until(CAN_PRODUCE) with (mutex) {
count++;
printf("(");
}
wait_until(CAN_CONSUME) with (mutex) {
count--;
printf(")");
}
```
=== 信号量:一种条件变量的特例
```c
void P(sem_t *sem) { // wait
wait_until(sem->count > 0) {
sem->count--;
}
}
void V(sem_t *sem) { // post (signal)
atomic {
sem->count++;
}
}
```
正是因为条件的特殊性,信号量不需要 broadcast
- P 失败时立即睡眠等待
- 执行 V 时,唤醒任意等待的线程
=== 理解信号量 (1)
初始时 `count = 1` 的特殊情况
互斥锁是信号量的特例
```c
#define YES 1
#define NO 0
void lock() {
wait_until(count == YES) {
count = NO;
}
}
void unlock() {
count = YES;
}
```
=== 理解信号量 (2)
P - prolaag (try + decrease/down/wait/acquire)
- 试着从袋子里取一个球
- 如果拿到了,离开
- 如果袋子空了,排队等待
V - verhoog (increase/up/post/signal/release)
- 往袋子里放一个球
- 如果有人在等球,他就可以拿走刚放进去的球了
- 放球-拿球的过程实现了同步
#tip("Tip")[
信号量是一种管理信号资源的同步对象。
]
=== 理解信号量 (3)
扩展的互斥锁:一个手环 → n 个手环
- 让更多同学可以进入更衣室
- 管理员(信号量)可以持有任意数量的手环 (count, 更衣室容量上限)
- 先进入更衣室的同学先进入游泳池
- 手环用完后需要等同学出来
- 信号量对应了 “资源数量”
=== 信号量:实现优雅的生产者-消费者
信号量设计的重点
- 考虑 “球”/“手环” (每一单位的 “_资源_”) 是什么
- 生产者/消费者 = 把球从一个袋子里放到另一个袋子里(一单位资源就是一堆括号。)
#image("./images/PV.png")
```c
// empty -> 还有多少空余的空间可以打左括号
// fill -> 有多少左括号已经有配对的右括号
sem_t fill, empty;
void Tproduce() {
P(&empty);
printf("("); // 注意共享数据结构访问需互斥
V(&fill);
}
void Tconsume() {
P(&fill);
printf(")");
V(&empty);
}
// 一个命令行参数代表嵌套深度。
int main(int argc, char *argv[]) {
assert(argc == 2);
SEM_INIT(&fill, 0);
SEM_INIT(&empty, atoi(argv[1]));
for (int i = 0; i < 8; i++) {
create(Tproduce);
create(Tconsume);
}
}
```
== 信号量:应用
信号量的两种典型应用
1. 实现一次临时的 happens-before
- 初始:s = 0
- A; V(s)
- P(s); B
- 假设 s 只被使用一次,保证 A happens-before B
#image("./images/A-happens-before-B.png")
>
这里比条件变量好用。如果使用条件变量,A先broadcast/signal那B来的时候也许已经丢了。还需要用额外的变量告诉B
A的任务已经完成。(信号量自带一个计数器,所以实现上会简单一些)
2. 实现计数型的同步
- 初始:done = 0
- Tworker: V(done)
- Tmain: P(done) × T
对应了两种线程 join 的方法 T1->T2->… v.s. 完成就行,不管顺序
第一种:
```
T1 T2 Tmain
..
.. P(T1 done)
.. P(T2 done)
V(T1 done)
V(T2 done)
```
第二种
```
T1 T2 Tmain
..
.. P(done)*|T|
V(done)
V(done)
```
#tip("Tip")[
用个循环。
]
两种方法各有优点,第一种可以控制顺序,例如先有第一个结果再有第二个结果。
第二种,只有执行完了就可以被唤醒一次。(可以知道相对每个线程执行完的时间)
```c
#include "thread-sync.h"
#include "thread.h"
#define T 4
#define N 10000000
sem_t done;
long sum = 0;
void atomic_inc(long *ptr) {
asm volatile("lock incq %0" : "+m"(*ptr) : : "memory");
}
void Tsum() {
for (int i = 0; i < N; i++) {
atomic_inc(&sum);
}
V(&done);
}
void Tprint() {
for (int i = 0; i < T; i++) {
P(&done);
}
printf("sum = %ld\n", sum);
}
int main() {
SEM_INIT(&done, 0);
for (int i = 0; i < T; i++) {
create(Tsum);
}
create(Tprint);
}
```
=== 例子:实现计算图
对于任何计算图
#image("images/2024-03-18-13-15-24.png")
- 为每个节点分配一个线程(每个边分配一个信号量)
- 对每条入边执行 P (wait) 操作
- 完成计算任务
- 对每条出边执行 V (post/signal) 操作
- 每条边恰好 P 一次、V 一次
- PLCS 直接就解决了啊?
```c
void Tworker_d() {
P(bd); P(ad); P(cd);
// 完成节点 d 上的计算任务
V(de);
}
```
乍一看很厉害
- 完美解决了并行问题
实际上……
- 创建那么多线程和那么多信号量 = Time Limit Exceeded
- 解决线程太多的问题
- 一个线程负责多个节点的计算(例如acd一个线程,bd一个线程。线程之间的同步就变少了,只要三个同步。省了线程和信号量。)
- 静态划分 → 覆盖问题
- 动态调度(计算图是动态生成的) → 又变回了生产者-消费者
- 解决信号量太多的问题
- 计算节点共享信号量
- 可能出现 “假唤醒” → 又变回了条件变量
==== 例子:毫无意义的练习题
有三种线程
- Ta 若干: 死循环打印 `<`
- Tb 若干: 死循环打印 `>`
- Tc 若干: 死循环打印 `_`
如何同步这些线程,保证打印出 `<><_` 和 `><>_` 的序列?
信号量的困难
- 上一条鱼打印后,`<` 和 `>` 都是可行的
- 我应该 P 哪个信号量?
- 可以 P 我自己的
- 由打印 `_` 的线程随机选一个
动态计算图:
```c
#include "thread-sync.h"
#include "thread.h"
#define LENGTH(arr) (sizeof(arr) / sizeof(arr[0]))
enum {
A = 1,
B,
C,
D,
E,
F,
};
struct rule {
int from, ch, to;
} rules[] = {
{A, '<', B}, {B, '>', C}, {C, '<', D}, {A, '>', E},
{E, '<', F}, {F, '>', D}, {D, '_', A},
};
int current = A;
sem_t cont[128];
void fish_before(char ch) {
P(&cont[(int)ch]);
// Update state transition
for (int i = 0; i < LENGTH(rules); i++) {
struct rule *rule = &rules[i];
if (rule->from == current && rule->ch == ch) {
current = rule->to;
}
}
}
void fish_after(char ch) {
int choices[16], n = 0;
// Find enabled transitions
for (int i = 0; i < LENGTH(rules); i++) {
struct rule *rule = &rules[i];
if (rule->from == current) {
choices[n++] = rule->ch;
}
}
// Activate a random one
int c = rand() % n;
V(&cont[choices[c]]);
}
const char roles[] = ".<<<<<>>>>___";
void fish_thread(int id) {
char role = roles[id];
while (1) {
fish_before(role);
putchar(role); // Not lock-protected
fish_after(role);
}
}
int main() {
setbuf(stdout, NULL);
SEM_INIT(&cont['<'], 1);
SEM_INIT(&cont['>'], 0);
SEM_INIT(&cont['_'], 0);
for (int i = 0; i < strlen(roles); i++) create(fish_thread);
}
```
=== 例子:使用信号量实现条件变量
当然是问 AI 了
- ChatGPT (GPT-3.5) 直接一本正经胡说八道
- 这个对 LLM 还是太困难了
- New Bing 给出了一种 “思路”
- 第一个 wait 的线程会在持有 mutex 的情况下 P(cond)
- 从此再也没有人能获得互斥锁……
- ~~像极了我改期末试卷的体验~~
=== 使用信号量实现条件变量:本质困难
操作系统用自旋锁保证 wait 的原子性
```c
wait(cv, mutex) {
release(mutex);
sleep();
}
```
#link("http://birrell.org/andrew/papers/ImplementingCVs.pdf")[ 信号量实现的矛盾 ]
- 不能带着锁睡眠 (NewBing 犯的错误)
- 也不能先释放锁
- `P(mutex); nwait++; V(mutex);`
- 此时 signal/broadcast 发生,唤醒了后 wait 的线程
- `P(sleep);`
- (我们稍后介绍解决这种矛盾的方法)
=== 信号量的使用:小结
信号量是对 “袋子和球/手环” 的抽象
- 实现一次 happens-before,或是计数型的同步
- 能够写出优雅的代码: `P(empty); printf("("); V(fill)`
- 但并不是所有的同步条件都容易用这个抽象来表达
== 哲 ♂ 学家吃饭问题
=== 哲学家吃饭问题 (<NAME>, 1960)
经典同步问题:哲学家 (线程) 有时思考,有时吃饭(五个哲学家,5把叉子)
- 吃饭需要同时得到左手和右手的叉子
- 当叉子被其他人占有时,必须等待,如何完成同步?
=== 成功与失败的尝试
成功的尝试 (万能的方法)
```c
#define CAN_EAT (avail[lhs] && avail[rhs])
mutex_lock(&mutex);
while (!CAN_EAT)
cond_wait(&cv, &mutex);
avail[lhs] = avail[rhs] = false;
mutex_unlock(&mutex);
mutex_lock(&mutex);
avail[lhs] = avail[rhs] = true;
cond_broadcast(&cv);
mutex_unlock(&mutex);
```
失败的尝试
- 把信号量当互斥锁:先拿一把叉子,再拿另一把叉子
```c
Tphilosopher{
P(lhs);
P(rhs);
eat();
V(lhs);
V(rhs);
}
```
Trick: 死锁会在 5 个哲学家 “同时吃饭” 时发生
==== 成功的尝试:信号量
- 破坏这个条件即可
- 保证任何时候至多只有 4 个人可以吃饭
- 直观理解:大家先从桌上退出
- 袋子里有 4 张卡
- 拿到卡的可以上桌吃饭 (拿叉子)
- 吃完以后把卡归还到袋子
- 任意 4 个人想吃饭,总有一个可以拿起左右手的叉子
- 教科书上有另一种解决方法 (lock ordering;之后会讲)
但这真的对吗?
- `philosopher-check.py`
- 在必要的时候使用 model checker
=== 反思:分布与集中
“Leader/follower” - 有一个集中的 “总控”,而非
“各自协调”(有一个服务员来进行叉子的调度,更加公平,之前的实现有可能出现一个哲学家反复吃的情况。)
- 在可靠的消息机制上实现任务分派
- Leader 串行处理所有请求 (例如:条件变量服务)
```c
void Tphilosopher(int id) {
send(Twaiter, id, EAT);
receive(Twatier); // 等待 waiter 把两把叉子递给哲学家
eat();
send(Twaiter, id, DONE); // 归还叉子
}
void Twaiter() {
while (1) {
(id, status) = receive(Any);
switch (status) { ... }
}
}
```
你可能会觉得,管叉子的人是性能瓶颈
- 一大桌人吃饭,每个人都叫服务员的感觉
- Premature optimization is the root of all evil (<NAME>)
抛开 workload 谈优化就是耍流氓
#image("images/2024-03-18-13-21-00.png")
- 吃饭的时间通常远远大于请求服务员的时间
- 如果一个 manager 搞不定,可以分多个 (fast/slow path)
- 把系统设计好,集中管理可以不是瓶颈:[ The Google File System (SOSP'03)
](https://pdos.csail.mit.edu/6.824/papers/gfs.pdf) 开启大数据时代
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/meta/footnote-invariant.typ | typst | Apache License 2.0 | // Ensure that a footnote and the first line of its entry
// always end up on the same page.
---
#set page(height: 120pt)
#lorem(13)
There #footnote(lorem(20))
|
https://github.com/jw2476/cslog-new | https://raw.githubusercontent.com/jw2476/cslog-new/master/main.typ | typst | #set text(font: "JetBrains Mono", size: 10pt)
#outline(indent: 2em)
= Analysis
= Problem and Stakeholders
== Outline
My project is an application that helps with scheduling and productivity. You input tasks you need to do, as well as the time they take and the time they must be done by, and the app will make a schedule for you to follow. The schedule is adaptive, tasks can be added or changed at any time and the schedule will adapt. When adding tasks you can set them to repeat on certain days or every interval. To help with following the schedule, the app will send you notifications when you need to change tasks. If a task is taking longer to complete than you entered, you can defer the task for later or extend the task and the schedule will adapt to fit. You can also schedule very long tasks and they will be broken up into chunks and put into the schedule. The app is a website you have to log into the access the schedule, meaning the schedule can be accessed from anywhere on any device.
== Justification of a Computational Solution
Schedules have been made by hand for centuries, and a lot of tools and algorithms have been developed to aid in this such as Gantt charts and scheduling diagrams. The issue with making schedules by hand is that it takes a long time, a complex schedule can take up to an hour to create and they are very hard to optimise. This high time cost means that most people don't schedule their time, especially for personal tasks. It also makes schedules very rigid because if anything changes then the schedule has to be remade from scratch, this means that schedules that are made by hand are very bad at responding to change which is bound to happen at some point.
Essentially, scheduling is a number crunching task, you try every permutation of the list of tasks in order to find one that fufills all deadlines and criteria. For a low to medium amount of tasks, this approach is extremely fast on computers compared to making a schedule by hand, microseconds compared to hours. This means that computed schedules can be very quickly regenerated in response to changes in a user's plans.
As well as this a correct scheduling algorithm would make no mistakes, whereas schedules made by hand often have mistakes which are very hard to fix because of how much time they take to remake.
== Stakeholders
Due to the nature of the project, it could appeal to anyone who wants some help with staying on top of lots of different tasks, but my main target audience is students as they both have a lot of different tasks to keep track of, and also the most likely to adopt a digital schedule as the majority of them reguarly use computers throughout the day. To make the app useful for students, I need to make sure common tasks like school, revision, and homework are easy to add so they can set up their schedule quickly. A lot of these are repeating tasks so the app will need to handle those well. Also, the main device of most students is smartphones, so I'll need to make the website responsive and works well on mobile platforms, as well as making sure notifications work on iOS and Android. Adding tasks needs to be easy and fast otherwise people won't use the app. Finallly, the website needs to look aesthetic otherwise people won't use it.
== Research
In order to inform the design of my app, I researched existing solutions and conducted a survey and evalutated these to find features my stakeholders will find useful.
== Existing Solutions
==== Microsoft To Do
#table(columns: (auto, auto),
[#image("microsoft.png", height: 25%)],
[
- Easy to add tasks, just press the plus button and type in the task title, but trying to do anything else is very difficult, the repeat feature is hard to use and limited
- "My Day" view is useful as a form of basic schedule
- Tasks don't have a duration or an end time, and there's not a proper schedule so you have to manually schedule reminders
- Integrated well with Microsoft ecosystem, you can attach documents and link to emails
- No way to add large tasks that are split up
]
)
==== Google ToDo
#table(columns: (auto, auto),
[#image("google.png", height: 25%)],
[
- Easy to add basic tasks, similar to Microsoft To Do, but no way of repeating tasks automatically and difficult to add details
- No form of schedule, just a list of tasks
- Tasks don't have a duration or an end time so reminders can't be automated
- No way to add large tasks
]
)
==== Todoist
#table(columns: (auto, auto),
[#image("todoist.png", height: 25%)],
[
- Best looking UI out of the 3, lots of colour
- Very complicated, there are lots of different types of tasks and it wasn't explained
- Easy to add tasks, just need a title, but many basic features like reminders and repeating are locked behind a paid version
- No form of schedule, just a list of tasks
- Tasks don't have a duration or an end time so reminders can't be automated
- No way to add large tasks
]
)
== Summary of Existing Solutions
#table(columns: (auto, auto, auto, auto), [*App*], [*Feature*], [*Will I be adding it?*], [*Justification*],
[Microsoft To Do and Google ToDo], [Easy to add tasks], [Yes], [The easier tasks are to add, the higher the chance that users will add them],
[Microsoft To Do], [My Day view], [Yes], [Makes it easy to work out what needs to be done compared to a list of tasks],
[Microsoft To Do], [Integration with other software], [No], [This feature is not feasible for the project (see limitations)],
[Todoist], [Colourful UI], [Yes], [The good UI design made it very easy to understand the quite complicated task UI],
)
The main thing I noticed while researching existing solutions is that there aren't any major apps that provide a scheduling feature, they all stop at a list of tasks with optional reminders. Google ToDo can integrate with Google Calendar, but its not automated and manually scheduling tasks is long and complicated to do by hand. If my app had this feature it would set it apart from the competition. Also the ability to repeat tasks was missing from nearly all of the apps I tried, so this is definately something I need to implement.
== Survey
I created a survey and sent it out to some student peers, I got 8 repsonses in total with the following answers:
#image("q1.png", height: 30%)
#image("q2.png", height: 30%)
#image("q3.png", height: 30%)
#image("q4.png", height: 30%)
#image("q5.png", height: 30%)
#image("q6.png", height: 30%)
#image("q7.png", height: 30%)
My first takeaway from this survey is that only 1 person is currently using a todo/scheduling app, I spoke to some of the participants after they took the interview, and all of them explained how they'd like to use one, but felt that all the existing solutions were missing features or were poor fits for their lifestyle. This is really promising as it shows that there is a demand that hopefully this project will fill. Some of the participants also agreed to try out my app once it's completed and give feedback.
The participants slightly preferred a schedule over a list of tasks, although this was very split so I will need to implement both for my website. When I spoke to some of the participants after, most of them said that schedules took too long to make by hand, or that they were too inflexible, this would be fixed by automatically generating a schedule like I'm planning to do.
Most participants said that they'd be happy inputting a title, deadline and priority for each task, so these are inputs I can design the scheduling algorithm around. Just under half of the participants said they wouldn't want to enter a duration, when I spoke to them after the survey I found the main reason was because they find it hard to guess how long something will, this is a very important input for a scheduling algorithm, so I'll need to think of a way to address this.
All participants said they found reminder notifications useful, this will be one of my highest priority features. All candidates said that they would use the app on smartphones, so they should be my main platform, this was closely followed by PCs and laptops, so I will need to support those platforms too. I will not test for tablet support, but it might work out of the box depending on UI design. When asked for the most important platform for them, the majority of participants responded with smartphones, so this further highlights the importance of supporting smartphones.
Most participants said that a good looking UI was important for them, so I will need to make sure my UI is aesthetic.
== Summary of Survey
- There is a large demand for a feature-complete todo/scheduling app among students
- Most people would like to use automatic scheduling
- Smartphones are the most important platform, followed by PCs/laptops
- Reminder notifications are one of the most important features
- UI needs to look good
== Features of the Proposed Solution
#table(columns: (auto, auto, auto, auto), [*Source*], [*Feature*], [*Priority*], [*Explanation*],
[Own Idea], [Automatic Scheduling], [High], [This means that users don't need to keep deadlines and their todo list in their head to pick what tasks they need to do. Nearly all of the survey participants said they wanted this feature so I have made it high priority],
[Research], [Todo List View], [High], [This allows users to easily view all of their tasks so they can be modified or deleted, nearly all similar apps had this feature so I've given it a high priority],
[Stakeholder], [Repeated Tasks], [High], [Since my main stakeholder is students, who have lots of repeated tasks such as school and revision sessions, the app will need to handle repeated tasks well, so I've given it a high priority],
[Research], [Reminder Notifications], [High], [Nearly all of the people who filled out the survey said reminder notifications were important to them, so I've given them a high priority],
[Research], [Delaying tasks/ Take a break button], [Medium], [Many survey participants who I spoke to afterwards explained they would like a way of delaying tasks or taking a break for a length of time, this should be easy to add to the automatic scheduling system but not essential, so I've given it a medium priority],
[Research], [API], [Low], [While speaking to survey participants, a few brought up making an API to get things like the current/upcoming task so they can use it in othe projects, I would to make this but it is not essential so I've given it a low priority],
[Own Idea], [Schedule View], [Low], [Being able to view the entire schedule at once might be a nice feature, but its quite hard to make and since the schedule can completely change I'm not sure if it would be useful, so I've given it a low priority]
)
== Limitations
The first limitation is that the user must be connected to the internet in order to access their task list/ schedule, I may be able to get some sort of local caching working, but if another device makes a change the the schedule it will not be updated until the first device reconnects to the internet.
Another limitation is that you cannot attach documents to tasks like you can in other solutions, this is because it adds a lot of complexity and its not a feature I or any of my peers I spoke to would use. You will also not be able to share your schedule with others.
In addition, I am only planning on supporting smartphones, PCs and laptops, tablet support will not be tested as I don't have a tablet to test with. I also don't plan on adding any integrations with other services such as email apps or GitHub as this adds a lot of complexity to the project, however I may look at doing this if I take this project further.
Finally, there will be no way to get a data dump of your task list to backup or store locally, and there will be no way of accessing the history of your schedule as this would be very expensive to store on the server.
== Hardware and Software Requirements
=== PC/Laptop Minimum Requirements:
#table(columns: (auto, auto),
[*Item*], [*Justification*],
[Monitor], [Users will need to be able to see the visual output of the website in order to use it],
[Keyboard], [The user will need to be able to type information about the tasks into the web app, this could be done with a mouse and on-screen keyboard],
[Mouse], [A mouse will be needed to interact with the web app, to select tasks and press buttons],
[Windows 10/11 or macOS 10.15 or a 64-bit Linux OS], [The user will need a supported operating system to run an internet browser to access the website. These are the supported operating systems for Chrome],
[SSE3 capable processor/ Intel Pentium 4 and up], [The user will need a supported CPU to run an internet browser. This is the requirement for Chrome],
[4GB of RAM or more], [The user will need enough memory to run a browser smoothly, this is taken from the Chrome requirements],
[~1GB of harddrive space], [The user will need to have a web browser installed which usually takes up ~1GB]
)
=== Mobile Minimum Requirements:
#table(columns: (auto, auto),
[*Item*], [*Justification*],
[Touchscreen], [Users will need to be able to see the website and interact with it through a touchscreen],
[Android 8.0+ or iOS 10.0+], [Minimum supported OSes for Chrome/Safari respectively],
[2GB of RAM or more], [This is listed as Chrome and Safari's minimum memory requirements, this is lower than on PCs likely because mobile browsers are more memory optimised],
[~1GB of hardrive space], [The user will need to have a web browser installed which usually takes up ~1GB]
)
== Success Criteria
=== Inputs
#table(columns: (auto, auto, auto),
[*Criteria*], [*Explanation*], [*Measure*],
[The user should be able to add tasks with a title, deadline, duration, repeat scheduling and priority easily on both desktop and mobile platforms], [Users need to be able to add tasks as they think of them, else they might forget and it won't be added to their schedule. If adding tasks is complicated or takes too long then people just won't add them], [During evaluation, I will ask those who tested the app how easy they felt it was to add tasks],
[The user should be able to edit tasks and delete them], [Tasks can change as users realise they might take longer than estimate, or the deadline might move, or someone else might do the task for them, the app needs to facilitate this by letting users edit and delete tasks], [During evaluation, I will check if I implemented this feature, as well as asking testers whether they were aware of the feature],
[The user should be able to mark tasks as complete easily], [Tasks need to be easily marked as complete else users might forget which would mean the schedule will desync], [During evaluation, I will ask testers how easy they felt it was to mark a task as complete],
[The user should be able to take a break for any length of time, which will clear their schedule], [If users are taking a break, the app needs to not schedule any tasks for that time else the schedule will desync], [During evaluation, I will check I added this feature, as well as if testers found it worked and was useful]
)
=== Outputs
#table(columns: (auto, auto, auto),
[*Criteria*], [*Explanation*], [*Measure*],
[The user should be able to see a list of tasks and their information easily], [The users will need to manage their tasks, this could include editting them, deleting them and more. This information needs to be nicely presented to the user], [During evaluation, I will ask for feedback on how tasks were presented to testers],
[The user should be able to quickly see their current task and upcoming tasks on their schedule], [Users could want to check what task they need to do, or prepare for upcoming ones], [During evaluation, I will ask testers on how the current and upcoming tasks were presented],
[The user should be sent reminder notifications when they need to start a new task], [As I found in my survey, users want to be reminded of their task when they need to start it, so they don't have to constantly check the app], [During evaluation, I will ask for feedback on how reliable and useful the reminder notification were],
[The website should be aesthetic and intuitive to use], [As I found in the survey, UIs that are both aesthetic and easy to use are quite important for most people], [I will ask testers about whether the UI was easy to use and whether it looked good on their devices]
)
=== Processing
#table(columns: (auto, auto, auto),
[*Criteria*], [*Explanation*], [*Measure*],
[When a user makes any change to their task list, it should be stored on the server], [Users might want to use the app on multiple devices, meaning tasks have to be synced across them. For this a user's task list must be stored in a database with APIs for getting and modifying the task list], [I will ask testers if they found task syncing and persistence to be reliable, or if they lost any task information between devices],
[A schedule should be generated for the users task list], [As I found by talking to people that took the survey, many people want a personal schedule to follow, but don't want to have to schedule it themselves because it takes too long and isn't flexible. By generating a schedule on-the-fly it becomes nearly instant and flexible as another schedule can be generated at any time], [I will ask testers how they found the generated schedule],
[When a user makes any change to their task list or decides to take a break, the schedule should be regenerated], [The schedule need to be synchronised with a user's task list, otherwise its not useful, so it must be regenerated on any change], [I will ask testers how reliable they felt the schedule regeneration was],
[Generated schedules should meet all deadlines and prioritise tasks correctly], [If a schedule doesn't fit the user's task list, then its not very useful], [I will check generated schedules against a user's task list when implementing the algorithm]
)
#pagebreak()
= Design
== Decomposition
=== Full Diagram
#image("decomp.png")
=== Frontend
#image("frontend.png")
This shows the different pages and operations I will need to implement on the frontend, I chose to break down the project into pages and the flow on each page as they are a natural way of breaking up web apps. I also split the project into frontend (client-side) and backend (server-side), this is because the code will not be able to be shared between them easily, so its important to work out where each feature belongs. I've tried to make each page single purpose, for example the login page is only responsible for logging the user in, the overview page is only for providing an overview, this separation of concerns will make the site easier to implement than if lots of features were on one page. I've outlined the flow through each site to try and work out which algorithms will need to be on which page, and if there are any that need to be shared.
=== Backend
#image("backend.png")
This shows the different API routes I will need to implement on the backend, these will be used by the frontend. I've left out the scheduling algorithm as I cover it properly below in the algorithms section. I decomposed the needed APIs by operation so each route only had one thing to worry about, this would make it easy to reuse the APIs across the project in a modular way. Again I've outlined the program flow for each API route to start getting an idea about the algorithms I'll be implemented, and I've kept each route as simple as possible.
#pagebreak()
== Interface Mock-Ups
=== Overview Page
#image("overview.png")
This page will be the first page the user sees after logging in to their account. It shows the current task if there is one, some upcoming tasks and some buttons used to complete/snooze the task, or go on a break. If a button is pressed, it will trigger an API call to edit the current task. It also has the navbar in the top left to navigate between this, the task list and the schedule view. All pages share this
=== Task List Page
#image("tasks.png")
This page is a grid-like view of a users tasks, it will be sorted by scheduled start time, but the sorting can be changed, by clicking on a task it will pop up the task editting UI.
=== Schedule Page
#image("schedule.png")
This page shows the users schedule for the day, I chose to only make it the current day as the dynamic schedule will probably move tasks around quite a lot, and I don't want users to see a schedule that will likely change. By clicking on a task it opens up the task editting UI
=== Signup/Login Page
#image("login.png")
This page is what users will use to sign up for and log in to their account, from here the user will be redirected to the overview page. When the submit button is pressed the login/signup API route will be called.
=== Edit Task Popup
#image("edit.png")
This will pop up from the bottom of the screen whenever the user click on a task in any of the 3 main pages. To simplify input validation, I've chosed to use on dropdowns, native date and time pickers as much as possible. I'm not sure if the title editting by clicking on it will be obvious so I might change that design if its an issue
== Usability Features
#table(columns: (auto, auto),
[*Feature*], [*Justification*],
[Large user interface], [As I found in my survey, the main target platform will be mobile devices. To make UIs easy to use on devices with smaller screens things like buttons need to be much larger than on desktop so the user can easily click on them. The same is true for text and inputs.],
[Simple user interface], [The UI needs to be simple and intuitive to use so the user can easily learn how to use the website. Simple UIs also are easier to use for younger children or older people, although these aren't a huge part of my target audience.],
[Colour coded buttons], [All buttons will be a bright colour to make it clear that they are buttons rather then information, and that the user can interact with this. This is helpful because it separates interactables from the rest of the UI, making it easier to use.],
[Input validation], [When the user is inputting data, it needs to be clear how to input the data correctly, and not let them enter invalid data. This can be done with validation and good error messages if invalid data is entered.],
[Icons], [Icons can demonstrate meaning easily without needing lots of work, for instance a calendar next to a date could show a deadline, or a clock next to a time would likely mean duration. Using icons means the UI will be easier and more intuitive to use],
[Large text], [The larger the text, the easier it is to read, especially on mobile platforms and for people with impaired eyesight. By including this feature the UI will be usable by more people],
[Error messages], [Error messages can be used to communicate issues with inputs, such as trying to complete a task when there isn't a current task. This means the user can understand what went wrong and try to fix it, rather than the website silently failing, confusing the user],
[Automatic Navigation], [Automatic redirects and forwarding should be used to help the user navigate around the site, for example if the user goes to the an sign up page and they are logged in, the user should be sent to the overview page]
)
== Algorithms
=== Signup
On the frontend this algorithm needs to run some basic validation and then call the signup backend API with the inputted username and password. The server will then check the username if the username is free, if it is then it creates a new account, generates a login token and returns it to the frontend which will then save it, before going to the overview page.
```rs
function signup_frontend(username, password) {
if username.is_empty() or password.is_empty() {
return;
}
token = signup_backend(username, password);
// Error handling
save_login_token(token);
goto("overview")
}
function signup_backend(username, password) {
existing_users = get_users();
if existing_users.contains(username) {
return ERR_USERNAME_TAKEN;
}
user = add_user(username, password);
token = generate_login_token(user);
return token;
}
```
#table(columns: (auto, auto, auto, auto),
[*Variable*], [*Type*], [*Stores*], [*Justification*],
[username], [string], [The user's username], [Used as the username for the new account],
[password], [string], [The user's password], [Used as the password for the new account],
[existing_users], [Array<User>], [All existing users], [Needed to check the new username doesn't conflict with any existing accounts],
[token], [string], [An encrypted authentication token], [Will be used to authenticate the user in other routes]
)
=== Login
On the frontend this algorithm needs to run some basic validation and then call the lgoin backend API with the inputted username and password. The server will then check the username and password are correct, if it is then it generates a login token and returns it to the frontend which will then save it, before going to the overview page.
```rs
function login_frontend(username, password) {
if username.is_empty() or password.is_empty() {
return;
}
token = login_backend(username, password);
// Error handling
save_login_token(token);
goto("overview")
}
function login_backend(username, password) {
user = get_user(username); // Get user with username from database, null if doesn't exist
if user == null {
return ERR_USER_DOES_NOT_EXIST;
}
if password != user.<PASSWORD> {
return ERR_PASSWORD_INCORRECT;
}
token = generate_login_token(user);
return token;
}
```
#table(columns: (auto, auto, auto, auto),
[*Variable*], [*Type*], [*Stores*], [*Justification*],
[username], [string], [The user's username], [Used as the username for the new account],
[password], [string], [The user's password], [Used as the password for the new account],
[user], [User], [The user's account], [Needed to check the inputted password with the user's set password],
[token], [string], [An encrypted authentication token], [Will be used to authenticate the user in other routes]
)
=== Get Tasks API
This algorithm is used by the frontend to fetch the list of tasks to display in the todo list view.
```rs
function get_tasks(token) {
user = get_user_from_token(token);
tasks = get_tasks().filter(task => task.owner == user);
return tasks;
}
```
#table(columns: (auto, auto, auto, auto),
[*Variable*], [*Type*], [*Stores*], [*Justification*],
[token], [string], [An encrypted authentication token], [Needed to authenticate the user],
[user], [User], [The authenticated user], [Needed to fetch all tasks belonging to the user],
[tasks], [Array<Task>], [The user's tasks], [Used as the function's output],
)
=== Get Schedule API
This algorithm is used by the frontend to fetch the schedule to display the current and upcoming tasks in the overview page.
```rs
function get_schedule(token) {
user = get_user_from_token(token);
schedule = get_schedules().filter(schedule => schedule.owner == user)[0]; // A user will only have one schedule
return schedule;
}
```
#table(columns: (auto, auto, auto, auto),
[*Variable*], [*Type*], [*Stores*], [*Justification*],
[token], [string], [An encrypted authentication token], [Needed to authenticate the user],
[user], [User], [The authenticated user], [Needed to fetch the user's schedule],
[schedule], [Schedule], [The user's schedule], [Used as the function's output],
)
=== Edit Task API
This algorithm edits a task stored in the database, the schedule must be regenerated to keep it up to date
```rs
function edit_task(token, oldTask, newTask) {
user = get_user_from_token(token);
if user != oldTask.owner { return ERR_UNAUTHORISED; }
edit_task_query(oldTask, newTask);
generate_schedule(user);
}
```
#table(columns: (auto, auto, auto, auto),
[*Variable*], [*Type*], [*Stores*], [*Justification*],
[token], [string], [An encrypted authentication token], [Needed to authenticate the user],
[oldTask], [Task], [The existing task], [Needed to work out which task to edit],
[newTask], [Task], [The editted task], [Needed to store the data used for the edit query],
[user], [User], [The authenticated user], [Needed to check the task belongs to the user],
)
=== Delete Task API
This algorithm deleted a task stored in the database, the schedule must be regenerated to keep it up to date
```rs
function delete_task(token, task) {
user = get_user_from_token(token);
if user != task.owner { return ERR_UNAUTHORISED; }
delete_task_query(task);
generate_schedule(user);
}
```
#table(columns: (auto, auto, auto, auto),
[*Variable*], [*Type*], [*Stores*], [*Justification*],
[token], [string], [An encrypted authentication token], [Needed to authenticate the user],
[task], [Task], [The task to delete], [Needed to work out which task to delete],
[user], [User], [The authenticated user], [Needed to check the task belongs to the user],
)
=== Generate Schedule
This algorithm takes a list of tasks and returns a schedule with every task somewhere on it, this algorithm will be developed properly as I iterate on the implemented version, so for now I've picked a very simple algorithm which will be optimised in the future. All it currently does is sort the tasks by the deadline and then packs them into the schedule.
```rs
struct ScheduledTask {
start: Time,
end: Time,
task: Task
}
type Schedule = Array<ScheduledTask>
function generate_schedule(tasks: Array<Task>, day_start: Time, day_end: Time) -> Schedule {
sorted = tasks.sort(a, b => a.deadline - b.deadline);
start = now();
schedule = [];
for task in sorted {
if day_end < (start + task.duration) { // If the task would finish after the day's ended, move it to the beginning of the next day
start = day_start;
}
schedule.push(ScheduledTask { start, end: start + task.duration, task }); // Add the task to the schedule
start += task.duration; // Advance the start time by the task's duration
}
return schedule;
}
```
This algorithm has a lot of flaws, like it doesn't pack tasks a the end of a day and doesn't nessesarily meet all deadlines, but it will work the majority of the time, and I can improve it once the rest of the product is built.
#table(columns: (auto, auto, auto, auto),
[*Variable*], [*Type*], [*Stores*], [*Justification*],
[tasks], [Array<Task>], [The list of tasks to schedule], [Needed to work out which tasks need to be scheduled],
[day_start], [Time], [The time the user's day starts], [Used as the time start is reset to when moving on to the next day],
[day_end], [Time], [The time the user's day ends], [Needed to check against when the task would end, if this time is earlier, the algorithm moves onto the next day],
[sorted], [Array<Task>], [The list of tasks sorted by deadline], [Stores the tasks in a more useful order than tasks, since the deadline acts as a kind of priority],
[start], [Datetime], [The time the next task would be schedule for], [Keeps track of when the next scheduled task will be scheduled for],
[schedule], [Array<ScheduledTask>], [The list of scheduled tasks], [Used to store scheduled tasks so they can be returned from the function],
)
=== Data Types
```rust
struct User {
username: String,
password: String,
}
struct Task {
title: String,
duration: Duration,
deadline: Time,
owner: User
}
struct ScheduledTask {
start: Time,
end: Time,
task: Task
}
struct Schedule {
tasks: Array<ScheduledTask>,
owner: User
}
```
=== Validation
Most validation has been included in algorithms planning, but I will need to ensure User references in the Schedule and Task struct are valid when I use them to ensure the program is robust.
=== Forming a Complete Solution
Each of these algorithms are responsible for one API route/ page which corresponds to an API route/page on the decompostion diagram above, since every page and route is covered, it will form a complete solution according to the decompostion diagram.
== Testing
I will take an iterative approach to testing where after each feature is implemented I will run the associated tests to check its working, if it doesn't work then I'll fix it before moving on to the next iteration.
=== Login
#table(columns: (auto, auto, auto, auto),
[*No.*], [*Description*], [*Data*], [*Expected*],
[L1], [Log in with a correct username and password], [Valid], [Login succeeds and returns a auth token],
[L2], [Log in with a username that does not exist], [Invalid], [Error is raised and user is asked to sign up],
[L3], [Log in with a correct username and invalid password], [Invalid], [Error is raised and user is asked to recheck their password],
[L4], [Log in with either an empty username or password], [Invalid], [Error is raised and user is asked to fill username and password boxes],
[L5], [Goes to log in page while already logged in], [Boundary], [User is redirected to overview page]
)
=== Signup
#table(columns: (auto, auto, auto, auto),
[*No.*], [*Description*], [*Data*], [*Expected*],
[S1], [Sign up with an unused username and password], [Valid], [Sign up succeeds and returns a auth token],
[S2], [Sign up with a used username], [Invalid], [Error is raised and user is asked to choose a different username],
[S3], [Sign up with either an empty username or password], [Invalid], [Error is raised and user is asked to fill username and password boxes],
[S4], [Goes to sign up page while already logged in], [Valid], [User is redirected to overview page]
)
=== Overview
#table(columns: (auto, auto, auto, auto),
[*No.*], [*Description*], [*Data*], [*Expected*],
[O1], [Go to page while there is a current task], [Valid], [Page shows current task, remaining time, and other information],
[O2], [Go to page while there is not a current task], [Valid], [Page shows there is no task and shows the next upcoming task],
[O3], [Complete button pressed while there is a current task], [Valid], [Completes the task, regenerates schedule and updates page],
[O4], [Complete button pressed while there is no current task], [Invalid], [Errors saying there is no ongoing task],
[O5], [Snooze button pressed while there is a current task], [Valid], [Snoozes the task, regenerates the schedule and updates page],
[O6], [Snooze button pressed while there is no current task], [Invalid], [Errors saying there is no ongoing task],
[07], [Break button pressed], [Valid], [Pop up prompting for break duration],
[O8], [Duration entered into break popup], [Valid], [Clears all task for the entered duration, regenerates schedule and updates the page],
[O9], [Task list button pressed], [Valid], [Goes to task list page],
[O10], [Schedule list button pressed], [Valid], [Goes to schedule view page],
[O11], [Overview button pressed], [Valid], [Nothing happens],
[O12], [Any task pressed], [Valid], [Task edit UI appears]
)
=== Task List
#table(columns: (auto, auto, auto, auto),
[*No.*], [*Description*], [*Data*], [*Expected*],
[T1], [Go to page], [Valid], [See a list of all tasks],
[T2], [Click on any task], [Valid], [Opens task edit UI],
[T3], [Overview button pressed], [Valid], [Goes to overview page],
[T4], [Task list button pressed], [Valid], [Does nothing],
[T5], [Schedule button pressed], [Valid], [Goes the schedule view page]
)
=== Task Edit
#table(columns: (auto, auto, auto, auto),
[*No.*], [*Description*], [*Data*], [*Expected*],
[E1], [Delete button pressed], [Valid], [Task deleted and schedule regenerated],
[E2], [Title editted to a non-empty value], [Valid], [Task title changed],
[E3], [Title editted to an empty value], [Invalid], [Error message appears saying tasks must have a title],
[E4], [Deadline editted], [Valid], [Task deadline changed, schedule regenerated],
[E5], [Duration editted to a non-zero value], [Valid], [Task duration changed, schedule regenerated],
[E6], [Duration editted to a zero], [Invalid], [Error appears saying tasks must have a duration],
[E7], [Priority changed], [Valid], [Task priority changed, schedule regenerated]
)
=== Schedule Generation
#table(columns: (auto, auto, auto, auto),
[*No.*], [*Description*], [*Data*], [*Expected*],
[G1], [Schedule generated with valid list of tasks], [Valid], [All tasks are scheduled to be completed before their deadline],
[G2], [Schedule generated with valid list of tasks], [Valid], [All tasks are scheduled to take their duration],
[G3], [Schedule generated with impossible list of tasks], [Invalid], [Error raised about impossible task list],
[G4], [Schedule generated with valid list of tasks], [Valid], [Tasks with higher priorities are often schedules before tasks with lower priorities],
)
=== Schedule View
Will come up with these once I've decided more about the schedule view
= Implementation
== Tech Stack
When making web apps there is a massive choice in frameworks and libraries to help with making reactive websites in JavaScript, such as React, Vue, Svelte, SolidJS, and even new WebAssembly libaries like Leptos and Yew which are both written in Rust. I need my app to load anywhere, including places with slow internet so I need my bundle sizes to be as small as possible. This means frameworks like React, Vue, Leptos and Yew won't be a good fit as they come with large library bloat. Whereas Svelte and SolidJS both compile away when building the website meaning the bundle will be kept small, and only contain the code I use. I've used Svelte in the past and I want to learn something new so I've chosen to use SolidJS for my frontend library.
For the backend, I've also chosed SolidJS as I'm planning to use a fullstack framework based on SolidJS called SolidStart, this allows me to write the website frontend and the backend API in one codebase.
== Authentication
I could have started with a page like the overview, as it will be the most used, however since so many features depend on authentication, I've chosen to start with it instead. Firstly, I designed a login and sign up page based on the UI mockups I created earlier:
#image("loginpage.png")
#image("signup.png")
The base HTML code for this is as follows, I've used some prebuilt components from a library called solid-ui and then modified them to my preference:
```html
<Card class="mx-auto my-16 max-w-[320px]">
<CardHeader>
<CardTitle>Sign Up</CardTitle>
</CardHeader>
<CardContent>
<Label for="username">Username</Label>
<Input onInput={(e) => set("username", e.target.value)} type="username" id="username" placeholder="Username" autocomplete="username" />
<br />
<Label for="password">Password</Label>
<Input onInput={(e) => set("password", e.target.value)} type="password" id="password" placeholder="<PASSWORD>" autocomplete="new-<PASSWORD>" />
<br />
<Label for="confirm">Confirm Password</Label>
<Input onInput={(e) => set("confirm", e.target.value)} type="password" id="confirm" placeholder="Confirm Password" autocomplete="new-password" />
</CardContent>
<CardFooter>
<Button onClick={() => signup()} class="w-full" type="submit">Sign Up</Button>
</CardFooter>
</Card>
```
The form inputs are all placed into a card element then gives the border around the outside, I've also registered the event functions that update the fields in the JavaScript, as well as the button on click event handler.
Next I had to call the server API for signup when the button was pressed, which I used the following JS:
```javascript
const [fields, setFields] = createStore({ username: "", password: "", confirm: "" });
const signup = async () => {
// Send POST request to signup with username and password
const res = await fetch("/api/signup", {
method: "POST",
body: JSON.stringify({ username: fields.username, password: fields.password })
});
if (res.status === 409) { // Username conflict
setTaken(true);
return;
}
if (!res.ok) return; // Return if other failure
showToast({ title: `Welcome ${fields.username}!`, description: "Going to overview..." }); // Pop up
const token = await res.text();
localStorage.setItem("token", token); // Save token for later
}
// Clear errors
const set = (field: "username" | "password" | "confirm", value: string) => {
setFields(field, value);
};
```
This doesn't do any data validation at the moment, but I just want to get something working. The input data is stored in a SolidJS store, which will update any code that uses it when something changes. Next I moved onto the server-side to build up the api route:
For the database, I've decided to use MongoDB as its simple and I can host it online for free, to interface with it I've chosen to use a library called mongoose which allows me to create schemas and easily manage a connection. Before I started on the API route I needed to connect to the database:
```ts
import mongoose, { Schema } from "mongoose"
import dotenv from "dotenv"
//get variables from .env
dotenv.config()
//connect to local mongoose server
mongoose.connect(process.env.MONGO_URI)
mongoose.connection
.on("open", () => console.log("Connected to Mongoose"))
.on("error", (error) => console.log(error))
const userSchema = new Schema({
username: String,
password: String
})
export const User = mongoose.model("User", userSchema)
```
This loads a URI to connect to from my .env file, this means I don't have to hardcode the database URI which will help keep my database secret and allow me to quickly change it later. Once connected it logs a message to the console and creates a User schema which for now just has a username and a password.
Now I have a database to work with, I started to work on the API route:
```ts
const SALT_ROUNDS = 10;
export async function POST({ request }: APIEvent) {
const { username, password } = await request.json();
if (username == null || password == null) {
return new Response("Missing field", { status: 400 });
}
// TODO: Check username is free
const existing = await User.findOne({ username });
if (existing != null) {
console.log(existing);
return new Response("Username taken", { status: 409 });
}
const hashed = await bcrypt.hash(password, SALT_ROUNDS);
const user = new User();
user.username = username;
user.password = <PASSWORD>;
await user.save();
const token = jwt.sign({ username }, process.env.JWT_SECRET);
return new Response(token);
}
```
This code gets the username and password out of the incoming request from the frontend, it also checks these both are present before continuing, else it responds with an error code. Then the route queries the database to check there aren't any users with the same username, if there are the route returns a 409 Conflict code and an error will be displayed on the website. Next the password is hashed using bcrypt to ensure no passwords will be leaked in the case of a data breach, this is more secure than standard encryption because hashing is a one way function its very hard to get the password back from the hashed form, even if you have the key used to hash it. This is not true for standard encryption algorithms, as if you have the key most encrypted data can be easily decrypted to get back the original passwords.
Next the user record is created and filled out using the username and the hashed password, and then saved to the database. Finally the username is encoded into a JSON Web Token, which is a nice why of encrypting some data into a token, with an encrypted secret that can be used to confirm the token was issued by the server. The JWT will be used to authenticate the user in other API routes.
=== Signup Testing
Now that the signup UI has been made and the API route was written, I decided to do a small test to check that the user account is created in the database and the JWT issued is valid.
#table(columns: (auto, auto, auto, auto, auto),
[*Test Id*], [*Test Title*], [*Expected*], [*Outcome*], [*Fix*],
[S1], [Sign up with an unused username and password], [Sign up succeeds and returns a auth token], [Record is created in database and token is issued], [],
[S2], [Sign up with a used username], [Error is raised and user is asked to choose a different username], [API route fails but no error is visibly raised], [Display error in UI],
[S3], [Sign up with either an empty username or password], [Error is raised and user is asked to fill username and password boxes], [API route fails but no error is visibly raised], [Display error in UI],
[S4], [Goes to sign up page while already logged in], [User is redirected to overview page], [N/A], []
)
The API route was working well but the UI was not raising any errors about empty fields or the username being taken, so I decided to add some red labels next to the fields to explain the issue.
```html
<Label for="username">Username</Label>
<Input onInput={(e) => set("username", e.target.value)} type="username" id="username" placeholder="Username" autocomplete="username" />
{empty.username ? <p class="text-red-500">Cannot be empty</p> : <></>}
{taken() ? <p class="text-red-500">Username taken</p> : <></>}
<br />
<Label for="password">Password</Label>
<Input onInput={(e) => set("password", e.target.value)} type="password" id="password" placeholder="<PASSWORD>" autocomplete="new-password" />
{empty.password ? <p class="text-red-500">Cannot be empty</p> : <></>}
<br />
<Label for="confirm">Confirm Password</Label>
<Input onInput={(e) => set("confirm", e.target.value)} type="password" id="confirm" placeholder="Confirm Password" autocomplete="new-password" />
{empty.confirm ? <p class="text-red-500">Cannot be empty</p> : <></>}
{mismatch() ? <p class="text-red-500">Passwords do not match</p> : <></>}
```
This UI toggles error labels if different values are set when processing the submit request. Next I needed to write the JS code to toggle the values depending on the issue with the users input:
```js
const [empty, setEmpty] = createStore({ username: false, password: false, confirm: false });
const [mismatch, setMismatch] = createSignal(false);
const [taken, setTaken] = createSignal(false);
...
let error = false;
// Username empty
if (fields.username == "") {
setEmpty("username", true);
error = true;
}
// Password empty
if (fields.password == "") {
setEmpty("password", true);
error = true;
}
// Confirm password empty
if (fields.confirm == "") {
setEmpty("confirm", true);
error = true;
}
// Mismatch
if (fields.password != fields.confirm) {
setMismatch(true);
error = true;
}
if (error) return;
// Send POST request to signup with username and password
const res = await fetch("/api/signup", {
method: "POST",
body: JSON.stringify({ username: fields.username, password: <PASSWORD>.<PASSWORD> })
});
if (res.status === 409) { // Username conflict
setTaken(true);
return;
}
...
```
This code raises errors if any of the fields are empty, or if the passwords don't match, or if the username is taken and shows a red label in the UI.
#image("signuperror.png")
=== Signup Error Testing
#table(columns: (auto, auto, auto, auto, auto),
[*Test Id*], [*Test Title*], [*Expected*], [*Outcome*], [*Fix*],
[S1], [Sign up with an unused username and password], [Sign up succeeds and returns a auth token], [Record is created in database and token is issued], [],
[S2], [Sign up with a used username], [Error is raised and user is asked to choose a different username], [API route fails and error appears in UI], [],
[S3], [Sign up with either an empty username or password], [Error is raised and user is asked to fill username and password boxes], [API route fails and error appears in UI], [],
[S4], [Goes to sign up page while already logged in], [User is redirected to overview page], [N/A], []
)
With the sign in page success criteria fully met, except for S4 which depends on the overview page, I decided to move onto the login page
=== Login
Firstly I took the signup UI and duplicated it as I thought it would be easier to modify it into a login view:
```html
<Card class="mx-auto my-16 max-w-[320px]">
<CardHeader>
<CardTitle>Login</CardTitle>
</CardHeader>
<CardContent>
<Label for="username">Username</Label>
<Input onInput={(e) => set("username", e.target.value)} type="username" id="username" placeholder="Username" autocomplete="username" />
{empty.username ? <p class="text-red-500">Cannot be empty</p> : <></>}
{incorrect() ? <p class="text-red-500">Incorrect username or password</p> : <></>}
<br />
<Label for="password">Password</Label>
<Input onInput={(e) => set("password", e.target.value)} type="password" id="password" placeholder="<PASSWORD>" autocomplete="new-password" />
{empty.password ? <p class="text-red-500">Cannot be empty</p> : <></>}
{incorrect() ? <p class="text-red-500">Incorrect username or password</p> : <></>}
</CardContent>
<CardFooter>
<Button onClick={() => login()} class="w-full" type="submit">Login</Button>
</CardFooter>
</Card>
```
This is very similar to the signup UI with the confirm password input removed and the error messages changed slightly, next I moved onto the verification login and sending the request to the server:
```js
const [empty, setEmpty] = createStore({ username: false, password: false });
const [fields, setFields] = createStore({ username: "", password: "" });
const [incorrect, setIncorrect] = createSignal(false);
const login = async () => {
let error = false;
if (fields.username == "") {
setEmpty("username", true);
error = true;
}
if (fields.password == "") {
setEmpty("password", true);
error = true;
}
if (error) return;
const res = await fetch("/api/login", {
method: "POST",
body: JSON.stringify({ username: fields.username, password: fields.password })
});
if (res.status === 401) {
setIncorrect(true);
return;
}
if (!res.ok) return;
showToast({ title: `Welcome ${fields.username}!`, description: "Going to overview..." });
const token = await res.text();
localStorage.setItem("token", token);
}
const set = (field: "username" | "password", value: string) => {
setFields(field, value);
setEmpty(field, false);
};
```
With the frontend page finished, I moved onto the API route. It needs to get the user record from the database using the username from the request, and then compare the hashed password with the password from the request. If the username and the password is correct, then a JWT is generated similar to the signup API and returned to the frontend:
```js
export async function POST({ request }: APIEvent) {
const {username, password} = await request.json();
const user = await User.findOne({username});
if (!await bcrypt.compare(password, user.password)) {
return new Response("Incorrect username or password", {status: 401})
}
const token = jwt.sign({username}, process.env.JWT_SECRET);
return new Response(token)
}
```
With login route finished I decided to test it:
=== Login Testing
#table(columns: (auto, auto, auto, auto, auto),
[*Test Id*], [*Test Title*], [*Expected*], [*Outcome*], [*Fix*],
[L1], [Log in with a correct username and password], [Login succeeds and returns a auth token], [As expected], [],
[L2], [Log in with a username that does not exist], [Error is raised and user is asked to sign up], [As expected], [],
[L3], [Log in with a correct username and invalid password], [Error is raised and user is asked to recheck their password], [As expected], [],
[L4], [Log in with either an empty username or password], [Error is raised and user is asked to fill username and password boxes], [As expected], [],
[L5], [Goes to log in page while already logged in], [User is redirected to overview page], [N/A], []
)
All tests passed except for the one that requires the overview page, which is what I decided to work on next.
== Move to SvelteKit
While developing the overview page, I kept running into strange issues where API routes would return HTML of other pages instead of running the API route, for instance `/api/signup` would sometimes return the HTML of the page for sign up. After researching a bit I found that this was a bug within solid-start, the framework I was using, and that it was in early access and very unstable, I tried to find a way to work around this most of them meant iterating would take too long as I'd have to run a release build every time or I'd have to move out the server-side into a different program, which defeated the purpose of a full-stack framework. With this is mind I decided to switch to SvelteKit, another full-stack framework, but this time using Svelte instead of SolidJS. I already had some experience with SvelteKit so it was quite quick to rebuild authentication in it:
I decided to use a library called superforms which made the verifcation of forms and handling all the accessibility and error messages for me, which made the code a lot shorter and simpler:
login/+page.ts
```svlt
<script lang="ts">
// Imports omitted
export let data: SuperValidated<Infer<Schema>>;
const form = superForm(data, {
validators: zodClient(schema)
});
const { form: formData, enhance, message } = form;
message.subscribe((token) => {
toast('Logged in');
});
</script>
<Card class="mx-[40vw] my-16 p-16">
<form method="POST" use:enhance>
<Form.Field {form} name="username">
<Form.Control let:attrs>
<Form.Label>Username</Form.Label>
<Input {...attrs} bind:value={$formData.username} />
</Form.Control>
<Form.FieldErrors />
</Form.Field>
<Form.Field {form} name="password">
<Form.Control let:attrs>
<Form.Label>Password</Form.Label>
<Input {...attrs} bind:value={$formData.password} type="<PASSWORD>" />
</Form.Control>
<Form.FieldErrors />
</Form.Field>
<br />
<Form.Button>Log In</Form.Button>
</form>
</Card>
<Toaster />
```
Sign up was nearly exactly the same but with some different labels, so I won't show the code. When the form is submitted it calls a server action, which can be handled in the routes `+page.server.ts` file.
Here's the handling code for login:
login/+page.server.ts
```ts
// Import omitted
export const actions: Actions = {
default: async (event) => {
const form = await superValidate(event, zod(schema));
if (!form.valid) {
return fail(400, {
form,
});
}
let user = await db.query.users.findFirst({ where: eq(users.username, form.data.username) });
if (user == null) {
return setError(form, "username", "User not found");
}
if (!await compare(form.data.password, user.password)) {
return setError(form, "password", "Incorrect password");
}
let token = jwt.sign(form.data.username, JWT_SECRET);
return message(form, token);
},
};
```
This is nearly identical to the previous version, the data is validated and the passwords are compared, if they match then a JWT is returned to the client. The only big change here is that I decided to swap my database manager from mongoose which uses MongoDB, to drizzle-orm which uses SQL, mainly because the query syntax is very similar to SQL and I wanted to get some practice in for my exam, but also because its a lot faster and lighter than mongoose. It also has the added benefit of being fully type safe which means I can catch database errors early.
The handling for signup is also very similar:
+page.server.ts
```ts
// Imports omitted
const SALT_ROUNDS = 10;
export const actions: Actions = {
default: async (event) => {
const form = await superValidate(event, zod(schema));
if (!form.valid) {
return fail(400, {
form,
});
}
let hashed = await hash(form.data.password, SALT_ROUNDS);
if (await db.query.users.findFirst({
where: eq(users.username, form.data.username)
})) {
return setError(form, "username", "Username taken");
}
await db
.insert(users)
.values({ username: form.data.username, password: <PASSWORD> });
console.log("Created user");
let token = jwt.sign(form.data.username, JWT_SECRET);
return message(form, token);
},
};
```
Now that I've moved to a more stable framework, I could finally move onto the tasks view:
=== Signup Error Testing
#table(columns: (auto, auto, auto, auto, auto),
[*Test Id*], [*Test Title*], [*Expected*], [*Outcome*], [*Fix*],
[S1], [Sign up with an unused username and password], [Sign up succeeds and returns a auth token], [Record is created in database and token is issued], [],
[S2], [Sign up with a used username], [Error is raised and user is asked to choose a different username], [API route fails and error appears in UI], [],
[S3], [Sign up with either an empty username or password], [Error is raised and user is asked to fill username and password boxes], [API route fails and error appears in UI], [],
[S4], [Goes to sign up page while already logged in], [User is redirected to overview page], [N/A], []
)
=== Login Testing
#table(columns: (auto, auto, auto, auto, auto),
[*Test Id*], [*Test Title*], [*Expected*], [*Outcome*], [*Fix*],
[L1], [Log in with a correct username and password], [Login succeeds and returns a auth token], [As expected], [],
[L2], [Log in with a username that does not exist], [Error is raised and user is asked to sign up], [As expected], [],
[L3], [Log in with a correct username and invalid password], [Error is raised and user is asked to recheck their password], [As expected], [],
[L4], [Log in with either an empty username or password], [Error is raised and user is asked to fill username and password boxes], [As expected], [],
[L5], [Goes to log in page while already logged in], [User is redirected to overview page], [N/A], []
)
== Tasks
This time I decided to start with the API routes instead of the frontend, as I knew I was going to need all CRUD (Create Read Update Delete) methods on tasks. I started with the GET route:
api/tasks/+server.ts
```ts
export async function GET({ cookies }) {
const token = cookies.get("token");
if (token == null) {
return error(401);
}
let tasks = getTasks(token);
if (typeof tasks == "number") {
return error(tasks);
}
return new Response(JSON.stringify(tasks));
}
```
I decided to split out the majority of the logic into a separate getTasks function as I knew that was going to be used in different places such as scheduling and the GET route:
```ts
export async function getTasks(token: string): Promise<Array<Task> | number> {
let username = await jwt.verify(token, JWT_SECRET);
if (typeof username != "string") { return 400; }
let user = await db.query.users.findFirst({
with: {
tasks: true
},
where: eq(users.username, username)
});
if (user == null) {
return 404;
}
return user.tasks;
}
```
This function verifies the JWT to get the username, which is then uses to run a query for all tasks belonging to the user, if the username is invalid the function returns a 404, if the JWT is invalid the function returns a 400 client error, if everything is successful the function returns the list of tasks belonging to the user.
Next I decided to implement the POST route which will be used to create the tasks, it takes a task structure from the requests body, as well as the token located in the users cookies, to create the task in the database:
```ts
export async function POST({ request, cookies }) {
let { deadline, duration, title } = await request.json();
let deadlineDate = new Date(deadline);
const token = cookies.get("token");
if (token == null) {
return error(401);
}
let username = await jwt.verify(token, JWT_SECRET);
if (typeof username != "string") { return error(400, "Bad token"); }
const user = await db.query.users.findFirst({ where: eq(users.username, username) });
if (user == null) {
return error(404);
}
const task = await db.insert(tasks).values({ deadline: deadlineDate, duration, title, user_id: user.id }).returning({ id: tasks.id });
return new Response(JSON.stringify({ id: task[0].id }));
}
```
If the token is not set then a 401 unauthorised code is returned, if the username is invalid then a 404 not found is returned, else the primary key of the task is returned, this is so the user can manipulate the task later using that primary key.
Next I made the PATCH route, which updates a task:
```ts
export async function PATCH({ request, cookies }) {
const { id, deadline, duration, title } = await request.json();
let deadlineDate = new Date(deadline);
const token = cookies.get("token");
if (token == null) {
return error(401);
}
let username = await jwt.verify(token, JWT_SECRET);
if (typeof username != "string") { return error(400, "Bad token"); }
const user = await db.query.users.findFirst({ where: eq(users.username, username) });
if (user == null) {
return error(404);
}
const task = await db.query.tasks.findFirst({ where: eq(tasks.id, id) });
if (task == null) {
return error(404);
}
if (task.user_id != user.id) {
return error(401);
}
await db.update(tasks).set({ deadline: deadlineDate, duration, title }).where(eq(tasks.id, id));
return new Response();
}
```
This route takes a the primary key of the task the user wants to edit, as well as the new data to update the task to. The task is found from the database to verify that it belongs to the authenticating user, if it does then the task is updated and the route returns successfully.
Finally was the DELETE route, which deletes a task using its primary key:
```ts
export async function DELETE({ request, cookies }) {
const { id } = await request.json();
const token = cookies.get("token");
if (token == null) {
return error(401);
}
let username = await jwt.verify(token, JWT_SECRET);
if (typeof username != "string") { return error(400, "Bad token"); }
const user = await db.query.users.findFirst({ where: eq(users.username, username) });
if (user == null) {
return error(404);
}
const task = await db.query.tasks.findFirst({ where: eq(tasks.id, id) });
if (task == null) {
return error(404);
}
if (task.user_id != user.id) {
return error(401);
}
await db.delete(tasks).where(eq(tasks.id, id));
return new Response();
}
```
As with the PATCH route, the task is fetched before the operating to verify the task belongs to the authenticated user, if it does then the task is deleted.
With the task manipulation API routes written I decided to move onto the website UI. As I was still using the svelte-shadcn component library, I had a look at the easiest way to display a grid of information, and I came across the table component, I thought it looked really nice and did everything I wanted to do so I made the decision to center my UI around it. I started by mocking up a basic table with to display information how I wanted:
```ts
<script lang="ts">
export let data;
let tasks = writable(data.tasks);
let staging: Task = { deadline: new Date(Date.now()), duration: 0, title: '', id: 0 };
function duration(duration: number): string {
function pad(data: string): string {
if (data.length == 1) {
return data + '0';
} else {
return data;
}
}
let hours = Math.floor(duration / 3600);
let minutes = Math.floor((duration % 3600) / 60);
return `${hours}:${pad(minutes.toString())}`;
}
function deadline(deadline: Date): string {
console.log(deadline);
if (deadline.toDateString() == new Date(Date.now()).toDateString()) {
return `${deadline.getHours()}:${deadline.getMinutes()}`;
} else {
return `${deadline.getDate()}-${deadline.getMonth()}-${deadline.getFullYear()}`;
}
}
</script>
<Card.Root class="m-16 px-16 pb-16 pt-4">
<Card.Header>
<Card.Title class="cols-span-9 text-center text-5xl">Tasks</Card.Title>
</Card.Header>
<Card.Root>
<Table.Root>
<Table.Header>
<Table.Row>
<Table.Head>Title</Table.Head>
<Table.Head>Duration</Table.Head>
<Table.Head>Deadline</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each $tasks as task}
<Table.Row>
<Table.Cell>{task.title}</Table.Cell>
<Table.Cell>{duration(task.duration)}</Table.Cell>
<Table.Cell>{deadline(task.deadline)}</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
</Table.Root>
</Card.Root>
</Card.Root>
```
The array of tasks is stored in one of svelte's writable stores, they allow me to control the reactivity of the tasks array so I can force the UI to update when I come to updating the information. I can do this by calling the `update` function on the store, which rerenders all the UI using the store after changing the value.
Next I needed to add some buttons in order to interact with the task table, I started with an edit and delete button which I placed in a column to the right.
```svlt
<Card.Root class="m-16 px-16 pb-16 pt-4">
<Card.Header>
<Card.Title class="cols-span-9 text-center text-5xl">Tasks</Card.Title>
</Card.Header>
<Card.Root>
<Table.Root>
<Table.Header>
<Table.Row>
<Table.Head>Title</Table.Head>
<Table.Head>Duration</Table.Head>
<Table.Head>Deadline</Table.Head>
<Table.Head class="px-8 text-right">Actions</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each $tasks as task}
<Table.Row>
<Table.Cell>{task.title}</Table.Cell>
<Table.Cell>{duration(task.duration)}</Table.Cell>
<Table.Cell>{deadline(task.deadline)}</Table.Cell>
<Table.Cell class="text-right">
<Button variant="outline" size="icon">
<Pencil class="h-4 w-4" />
</Button>
<Button variant="destructive" size="icon">
<Trash class="h-4 w-4" />
</Button>
</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
</Table.Root>
</Card.Root>
</Card.Root>
```
With the buttons in place, I now needed to make them do something, I decided the delete button would be the easiest to implement first as it didn't need a form.
```ts
<script lang="ts">
...
async function deleteTask(task: Task) {
await fetch('/api/tasks', { method: 'DELETE', body: JSON.stringify({ id: task.id }) });
tasks.update((tasks) => {
tasks.splice(data.tasks.indexOf(task), 1);
return tasks;
});
}
</script>
...
<Button variant="destructive" size="icon" on:click={() => deleteTask(task)}>
<Trash class="h-4 w-4" />
</Button>
...
```
Next was the task editting/creation UI, I decided to put it all in a dialog box that pops up when you press the edit/create buttons. Because this was going to be a standalone component, I decided to break it up into its own file:
```ts
<script lang="ts">
export let task: Task;
let title: string;
let hours: number, minutes: number;
let deadlineDate: DateValue, deadlineHours: number, deadlineMinutes: number;
let open: bool = false;
function start() {
title = task.title;
hours = task.duration / 3600;
minutes = (task.duration % 3600) / 60;
deadlineDate = fromDate(task.deadline, 'Europe/London');
deadlineHours = task.deadline.getHours();
deadlineMinutes = task.deadline.getMinutes();
}
async function submit() {
let duration = hours * 3600 + minutes * 60;
let deadline = deadlineDate.toDate('Europe/London');
deadline.setHours(deadlineHours);
deadline.setMinutes(deadlineMinutes);
task = { title, duration, deadline, id: task.id };
await fetch('/api/tasks', { method: 'PATCH', body: JSON.stringify(task) });
open = false;
}
</script>
<Dialog.Root bind:open>
<Dialog.Trigger class={buttonVariants({ variant: 'outline' })} on:click={start}>
<slot />
</Dialog.Trigger>
<Dialog.Content>
<Dialog.Header>
<Dialog.Title class="text-center">Edit task</Dialog.Title>
</Dialog.Header>
<div class="grid gap-4 py-4">
<div class="grid grid-cols-5 items-center gap-4">
<Label for="title" class="text-right">Title</Label>
<Input id="title" bind:value={title} class="col-span-4" />
</div>
<div class="grid grid-cols-5 items-center gap-4">
<Label for="duration" class="text-right">Duration</Label>
<Input id="hours" bind:value={hours} class="col-span-2" />
<Input id="minutes" bind:value={minutes} class="col-span-2" />
</div>
<div class="grid grid-cols-5 items-center gap-4">
<Label for="duration" class="text-right">Deadline</Label>
<DatePicker bind:value={deadlineDate} class="col-span-4" />
</div>
<div class="grid grid-cols-5 items-center gap-4">
<p />
<Input id="hours" bind:value={deadlineHours} class="col-span-2" />
<Input id="minutes" bind:value={deadlineMinutes} class="col-span-2" />
</div>
</div>
<Dialog.Footer>
<Button type="submit" on:click={submit}>Save</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>
```
This Svelte code creates a dialog popup and a trigger button, the popup is a full form including a date picker for the deadline, and several inputs for title, duration minutes and hours, and deadline minutes and hours. I used HTML grids in order to align and structure the form to keep it easy to use and aesthetic.
Another thing to note is that instead of directly modifying the task passed into the component, I instead read out the task's values and copy them to other variables, which are modified instead, this is so the original task isn't modified until the request is send, after which the values are copied back into the task. Originally, I tried to modify the original and keep a backup to restore to if the request failed, but I switched to this method as it was simpler.
I did a quick test at this point to check deletion and editting were working correctly, to do this I filled the database with mock data and used the UI to edit them.
=== Task Editing and Deletion Testing
#table(columns: (auto, auto, auto, auto),
[*Test Id*], [*Test Title*], [*Expected*], [*Outcome*],
[E1], [Delete button pressed], [Task deleted and schedule regenerated], [Task deleted and UI updated],
[E2], [Title editted to a non-empty value], [Task title changed], [Failed due to server error],
[E3], [Title editted to an empty value], [Error message appears saying tasks must have a title], [Failed due to server error],
[E4], [Deadline editted], [Task deadline changed, schedule regenerated], [Failed due to server error],
[E5], [Duration editted to a non-zero value], [Task duration changed, schedule regenerated], [Failed due to server error],
[E6], [Duration editted to a zero], [Error appears saying tasks must have a duration], [Failed due to server error],
[E7], [Priority changed], [Task priority changed, schedule regenerated], [N/A as there is no priority yet],
)
All of the tests other than deletion failed due to a server error: "value.toUTCString is not a function" being raised from within my PostgreSQL driver. This meant I had an issue with handling the deadline Date object on the edit API route, taking a look at the request body, the deadline was being represented as a UTC string rather than an actual Date object, which is what the server was expecting. To fix this I needed to either make the server parse the UTC string, or use a different format which the server could easily parse. Parsing a UTC timedate string is very slow and not in the JS standard library, so I decided to search for a exchange format, I found the `Date.getTime()` function which returns the number of seconds since the 1970 epoch, similar to the UNIX timestamp used in UNIX derivates. This meant that it was just a simple number I could send in the request body, and it could easily be turned back into a Date object, in fact its constructor takes one of these values. So with a bit of modification I should be able to fix the issue:
api/tasks/+server.ts
```ts
export async function PATCH({ request, cookies }) {
const { id, deadline, duration, title } = await request.json();
let deadlineDate = new Date(deadline);
...
await db.update(tasks).set({ deadline: deadlineDate, duration, title }).where(eq(tasks.id, id));
return new Response();
}
```
tasks/Edit.svelte
```ts
async function submit() {
let duration = hours * 3600 + minutes * 60;
let deadline = deadlineDate.toDate('Europe/London');
deadline.setHours(deadlineHours);
deadline.setMinutes(deadlineMinutes);
task = { title, duration, deadline, id: task.id };
const body = {
deadline: task.deadline.getTime(), // Changed
duration: task.duration,
title: task.title,
id: task.id
};
await fetch('/api/tasks', { method: 'PATCH', body: JSON.stringify(body) }); // Changed
open = false;
}
```
With this done I reran the test suite:
#table(columns: (auto, auto, auto, auto),
[*Test Id*], [*Test Title*], [*Expected*], [*Outcome*],
[E1], [Delete button pressed], [Task deleted and schedule regenerated], [Task deleted and UI updated],
[E2], [Title editted to a non-empty value], [Task title changed], [Task title changed],
[E3], [Title editted to an empty value], [Error message appears saying tasks must have a title], [Changed to empty title],
[E4], [Deadline editted], [Task deadline changed, schedule regenerated], [Task deadline changed],
[E5], [Duration editted to a non-zero value], [Task duration changed, schedule regenerated], [Task duration changed],
[E6], [Duration editted to a zero], [Error appears saying tasks must have a duration], [Client error],
[E7], [Priority changed], [Task priority changed, schedule regenerated], [N/A as there is no priority yet],
)
This shows the core functionality is working, and all I had left was some validation, to do this I used zod again, but without superforms this time:
```ts
let schema = z.object({
hours: z.number().min(0),
minutes: z.number().min(0).max(60),
deadlineHours: z.number().min(0),
deadlineMinutes: z.number().min(0).max(60),
deadlineDate: z.date(),
title: z.string().min(1)
});
const result = schema.safeParse({ hours, minutes, deadlineHours, deadlineMinutes, deadlineDate: deadlineDate.toDate('Europe/London'), title });
if (!result.success) {
console.log(result.error.issues)
issues = result.error.issues.map(issue => `${issue.path[0]}: ${issue.message}`);
return
}
```
The errors are not the best since I'm not using superforms, at somepoint I'll probably go back and fix this but for now it works well. As part of this I also made a NumericInput component, which is like an input but it only lets you input digits:
NumericInput.svelte
```ts
<script lang="ts">
import { Input } from '$lib/components/ui/input';
let className: string | null | undefined = undefined;
export let value: number;
let text: string
export { className as class };
function check() {
let c = text[text.length - 1];
if (c < '0' || c > '9') {
text = text.substring(0, text.length - 2);
} else {
value = parseInt(text);
}
}
</script>
<Input class={className} bind:value={text} on:input={check} />
```
I replaced the standard Input component with these, meaning the hours and minutes fields were already guarenteed to be numeric. With validation done I decided to rerun the test suite:
#table(columns: (auto, auto, auto, auto),
[*Test Id*], [*Test Title*], [*Expected*], [*Outcome*],
[E1], [Delete button pressed], [Task deleted and schedule regenerated], [Task deleted and UI updated],
[E2], [Title editted to a non-empty value], [Task title changed], [Task title changed],
[E3], [Title editted to an empty value], [Error message appears saying tasks must have a title], [Error message appears saying tasks must have a title],
[E4], [Deadline editted], [Task deadline changed, schedule regenerated], [Task deadline changed],
[E5], [Duration editted to a non-zero value], [Task duration changed, schedule regenerated], [Task duration changed],
[E6], [Duration editted to a zero], [Error appears saying tasks must have a duration], [Error appears saying tasks must have a duration],
[E7], [Priority changed], [Task priority changed, schedule regenerated], [N/A as there is no priority yet],
)
With all test passing I was happy with the editting UI, so I decided to work on generalising it to work with both the creation form and the editting form, firstly I made the form title an input, as well as taking an effect callback which takes the task from the form and does something with it:
```
<script lang="ts">
...
export let dialogTitle: string;
export let callback: (task: Task) => void;
async function submit() {
let schema = z.object({
hours: z.number().min(0),
minutes: z.number().min(0).max(60),
deadlineHours: z.number().min(0),
deadlineMinutes: z.number().min(0).max(60),
deadlineDate: z.date(),
title: z.string().min(1)
});
const result = schema.safeParse({ hours, minutes, deadlineHours, deadlineMinutes, deadlineDate: deadlineDate.toDate('Europe/London'), title });
if (!result.success) {
console.log(result.error.issues)
issues = result.error.issues.map(issue => `${issue.path[0]}: ${issue.message}`);
return
}
let duration = hours * 3600 + minutes * 60;
let deadline = deadlineDate.toDate('Europe/London');
deadline.setHours(deadlineHours);
deadline.setMinutes(deadlineMinutes);
task = { title, duration, deadline, id: task.id };
callback(task);
open = false;
}
...
</script>
...
<Dialog.Header>
<Dialog.Title class="text-center">{dialogTitle}</Dialog.Title>
</Dialog.Header>
...
```
With that I added the create button at the top of the page, created a patchTask and createTask function, and wired up the new generic UI:
```ts
<script lang="ts">
export let data;
let tasks = writable(data.tasks);
let staging: Task = { deadline: new Date(Date.now()), duration: 0, title: '', id: 0 };
function duration(duration: number): string {
function pad(data: string): string {
if (data.length == 1) {
return data + '0';
} else {
return data;
}
}
let hours = Math.floor(duration / 3600);
let minutes = Math.floor((duration % 3600) / 60);
return `${hours}:${pad(minutes.toString())}`;
}
function deadline(deadline: Date): string {
console.log(deadline);
if (deadline.toDateString() == new Date(Date.now()).toDateString()) {
return `${deadline.getHours()}:${deadline.getMinutes()}`;
} else {
return `${deadline.getDate()}-${deadline.getMonth()}-${deadline.getFullYear()}`;
}
}
async function deleteTask(task: Task) {
await fetch('/api/tasks', { method: 'DELETE', body: JSON.stringify({ id: task.id }) });
tasks.update((tasks) => {
tasks.splice(data.tasks.indexOf(task), 1);
return tasks;
});
}
async function patchTask(task: Task) {
const body = {
deadline: task.deadline.getTime(),
duration: task.duration,
title: task.title,
id: task.id
};
await fetch('/api/tasks', { method: 'PATCH', body: JSON.stringify(body) });
}
async function createTask(task: Task) {
const body = { deadline: task.deadline.getTime(), duration: task.duration, title: task.title };
let res = await fetch('/api/tasks', { method: 'POST', body: JSON.stringify(body) });
task.id = (await res.json()).id;
tasks.update((tasks) => {
tasks.push(task);
return tasks;
});
}
</script>
<Card.Root class="m-16 px-16 pb-16 pt-4">
<Card.Header>
<Card.Title class="cols-span-9 text-center text-5xl">Tasks</Card.Title>
<br />
<Edit callback={createTask} bind:task={staging} dialogTitle="Create task">
<Plus class="h-4 w-4" />
</Edit>
</Card.Header>
<Card.Root>
<Table.Root>
<Table.Header>
<Table.Row>
<Table.Head class="text-center">Title</Table.Head>
<Table.Head class="text-center">Duration</Table.Head>
<Table.Head class="text-center">Deadline</Table.Head>
<Table.Head class="px-8 text-right">Actions</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each $tasks as task}
<Table.Row>
<Table.Cell class="text-center">{task.title}</Table.Cell>
<Table.Cell class="text-center">{duration(task.duration)}</Table.Cell>
<Table.Cell class="text-center">{deadline(task.deadline)}</Table.Cell>
<Table.Cell class="text-right">
<Edit callback={patchTask} dialogTitle="Edit task" bind:task>
<Pencil class="h-4 w-4" />
</Edit>
<Button variant="destructive" size="icon" on:click={() => deleteTask(task)}>
<Trash class="h-4 w-4" />
</Button>
</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
</Table.Root>
</Card.Root>
</Card.Root>
```
With this done I reran the test suite for the whole page:
#table(columns: (auto, auto, auto, auto),
[*No.*], [*Description*], [*Expected*], [*Outcome*],
[T1], [Go to page], [Valid], [See a list of all tasks], [See a list of all tasks],
[T2], [Click on any task], [Valid], [Opens task edit UI], [Opens task edit UI],
[T3], [Overview button pressed], [Valid], [Goes to overview page], [N/A],
[T4], [Task list button pressed], [Valid], [Does nothing], [N/A],
[T5], [Schedule button pressed], [Valid], [Goes the schedule view page], [N/A],
)
#table(columns: (auto, auto, auto, auto),
[*Test Id*], [*Test Title*], [*Expected*], [*Outcome*],
[E1], [Delete button pressed], [Task deleted and schedule regenerated], [Task deleted and UI updated],
[E2], [Title editted to a non-empty value], [Task title changed], [Task title changed],
[E3], [Title editted to an empty value], [Error message appears saying tasks must have a title], [Error message appears saying tasks must have a title],
[E4], [Deadline editted], [Task deadline changed, schedule regenerated], [Task deadline changed],
[E5], [Duration editted to a non-zero value], [Task duration changed, schedule regenerated], [Task duration changed],
[E6], [Duration editted to a zero], [Error appears saying tasks must have a duration], [Error appears saying tasks must have a duration],
[E7], [Priority changed], [Task priority changed, schedule regenerated], [N/A as there is no priority yet],
)
All passed as expected, so next I moved onto the schedule generation and overview page:
== Schedule Generation
To start I decided to implement the basic schedule generation algorithm from the algorithms planning section. It sorts the tasks based on deadlines and then schedules them between the user's start and end time in that order.
```ts
export type ScheduledTask = {
task: Task,
start: Date,
}
function end(time: string, day: Date): Date {
let day_copy = new Date(day.getTime()); // Create copy to avoid modifying argument
let hours = parseInt(time.substring(0, 2));
let minutes = parseInt(time.substring(3, 5));
day_copy.setHours(hours);
day_copy.setMinutes(minutes);
day_copy.setSeconds(0);
return day_copy;
}
function nextDay(time: string, day: Date): Date {
let day_copy = new Date(day.getTime()); // Create copy to avoid modifying argument
let hours = parseInt(time.substring(0, 2));
let minutes = parseInt(time.substring(3, 5));
day_copy.setHours(hours);
day_copy.setMinutes(minutes);
day_copy.setSeconds(0);
day_copy.setMilliseconds(0);
return new Date(day_copy.getTime() + 24 * 3600);
}
export function generateSchedule(user: User, tasks: Array<Task>): Array<ScheduledTask> {
const sorted: Array<Task> = tasks.sort((a, b) => a.deadline.getTime() - b.deadline.getTime());
let start: Date = new Date(Date.now());
let schedule: Array<ScheduledTask> = [];
sorted.forEach(task => {
const next_day = nextDay(user.start, start);
const day_end = end(user.end, start);
if (day_end.getTime() < (start.getTime() + task.duration)) { // If the task would finish after the day's ended, move it to the beginning of the next day
start = next_day;
}
schedule.push({ start, task }); // Add the task to the schedule
start = new Date(start.getTime() + task.duration); // Advance the start time by the task's duration
});
return schedule;
}
```
I decided to put the start and end times in the user database record, this means that eventually I could implement a user configuration page where the user can choose when their scheduled day starts and ends. However this mean I had to modify my databse schema for the user table:
```ts
export const users = pgTable('users', {
id: serial('id').primaryKey(),
username: text('username').notNull(),
password: text('<PASSWORD>').notNull(),
start: time('start').notNull(),
end: time('end').notNull()
});
```
I chose the `time` field type as it only needs to store the time of day, not the date or a specific time stamp, this also meant the exact time of day could be represented in a much cheaper way. I decided to make the defaults for these values 9am till 5pm, inline with the standard working hours in the UK. Since I had modified table columns I had to regenerate migrations and apply them to the database, after that was done I filled the database with some mock data and decided to generate a test schedule.
I created 3 tasks, a 15 minutes task due first, then a 40 minute task, then a 1 hour long task. It was 4pm at the time so I only had an hour left for the scheduler to place tasks, the expected output was that the both the 15 and 40 minute tasks would be scheduled for today, and the 1 hour one would be scheduled for the beginning of tomorrow. After a quick test I could see this wasn't working as expected, all 3 tasks were scheduled for today with odd durations and start times. After digging through the `generateSchedule` function, I found that the `Date.getTime` function actually returns the number of milliseconds since the UNIX epoch, rather than seconds like UNIX timestamps, this meant I was adding duration in milliseconds, despite the fact the value represented seconds, this meant each task took 0.1% of the time it should, and to fix it I'd need to multiply duration by 1000 to convert it to milliseconds:
Bugs: Turns out JS Date.getTime() returns milliseconds instead of seconds like the UNIX timestamp
```ts
export function generateSchedule(user: User, tasks: Array<Task>): Array<ScheduledTask> {
const sorted: Array<Task> = tasks.sort((a, b) => a.deadline.getTime() - b.deadline.getTime());
let start: Date = new Date(Date.now());
let schedule: Array<ScheduledTask> = [];
sorted.forEach(task => {
const next_day = nextDay(user.start, start);
const day_end = end(user.end, start);
if (day_end.getTime() < (start.getTime() + task.duration * 1000)) { // If the task would finish after the day's ended, move it to the beginning of the next day
start = next_day;
}
schedule.push({ start, task }); // Add the task to the schedule
start = new Date(start.getTime() + task.duration * 1000); // Advance the start time by the task's duration
});
return schedule;
}
```
With this fixed I reran the function and this time it the correct schedule, so I moved onto the overview page. Referring back to the design I made earlier, I decided the easiest way to make this UI would be to use a mixture of CSS flex and grid, two things I wasn't very familiar with at the time, so I did a bit of research on how to use them with #link("https://tailwindcss.com/docs/flex")[TailwindCSS]. With that I made the overview page, which started with the server side function fetching the schedule.
```ts
export async function load({ cookies }) {
const token = cookies.get("token");
if (token == null) {
return error(401);
}
const user = await getUser(token);
if (typeof user == "number") {
return error(user);
}
const tasks = await getTasks(user);
if (typeof tasks == "number") {
return error(tasks);
}
const schedule = await generateSchedule(user, tasks);
return { schedule };
}
```
This function will be run on the server when the page is accessed, it gets the username out of the token and authenticates the user, the user id is then used to get the list of tasks, which is then used to generate the schedule. Finally the schedule is returned to be used by the Svelte component:
```ts
<script lang="ts">
export let data; // Return value of server-side function will be stored here
let schedule: Array<ScheduledTask> = data.schedule;
$: schedule = data.schedule;
let current: ScheduledTask | undefined;
let next: Array<ScheduledTask> = [];
// Constantly check whether current or next tasks need changing
onMount(() => {
setInterval(setCurrent, 1000);
setInterval(setNext, 1000);
});
function setCurrent() {
current = schedule.find((task, a, b) => {
let now = Date.now();
let start = task.start.getTime();
let end = task.start.getTime() + task.task.duration * 1000;
return start <= now && now <= end;
});
}
function setNext() {
next = schedule
.sort((a, b) => a.start.getTime() - b.start.getTime())
.filter((task) => task.start.getTime() > Date.now());
}
function timeUntil(task: ScheduledTask): string {
let between = task.start.getTime() - Date.now();
return formatDuration(between / 1000);
}
</script>
<div class="p-8 md:p-16 lg:mx-[15vw] lg:grid lg:grid-cols-3 lg:gap-4">
<div class="flex flex-col items-stretch gap-4 lg:col-span-2">
{#if current}
<Task description="Current" task={current} />
{:else}
<Card.Root class="p-16">
<Card.Header>
<Card.Title class="text-center text-5xl">Nothing to do!</Card.Title>
</Card.Header>
</Card.Root>
{/if}
<div class="grid gap-4 max-lg:grid-rows-2 lg:grid-cols-2">
<Button.Root class="p-8 text-xl lg:p-16 lg:text-3xl">Complete</Button.Root>
<Button.Root class="p-8 text-xl lg:p-16 lg:text-3xl">Snooze</Button.Root>
</div>
{#if next[0]}
<Task description={`Next in ${timeUntil(next[0])}`} task={next[0]} />
{:else}
<Card.Root class="p-16">
<Card.Header>
<Card.Title class="text-center text-5xl">Nothing upcoming</Card.Title>
</Card.Header>
</Card.Root>
{/if}
<Button.Root class="p-16 text-3xl">Take a break</Button.Root>
</div>
<div class="hidden grid-rows-4 gap-4 lg:grid">
{#each next.slice(1, 4) as task}
<Task description={`Next in ${timeUntil(task)}`} task={task} />
{/each}
</div>
</div>
```
This component creates the UI from the design section successfully, and it also scales correctly for mobile usage:
#image("overviewpage.png")
#image("overviewpagemobile.png")
One thing I encountered while making the page is that displaying task information was something needed in many places, so I decided to abstract it into a separate component:
```ts
<script lang="ts">
export let task: ScheduledTask;
export let description: string;
function duration(): string {
return formatDuration(task.task.duration);
}
function deadline(): string {
const value = task.task.deadline;
return `${value.getDate()}/${value.getMonth()}/${value.getFullYear()}`
}
</script>
<Card.Root>
<Card.Header>
<Card.Title class="text-center text-5xl">{task.task.title}</Card.Title>
<Card.Description class="text-center">{description}</Card.Description>
</Card.Header>
<Card.Footer class="lg:px-16">
<div class="flex grow justify-between">
<div class="flex grow justify-start gap-2">
<Clock />
{duration()}
</div>
<div class="flex grow justify-end gap-2">
<Calendar />
{deadline()}
</div>
</div>
</Card.Footer>
</Card.Root>
```
The Task component takes a task and description as input, and displays the task's title, duration and deadline. The usage is shown in the overview page.
With the UI done, the next step was to add some functionality to the buttons, snooze and take a break both required features I haven't added to the scheduling algorithm yet, so I started with the complete button.
The complete button when pressed needs to check if there is a current task, if there is it should be deleted from the database and the schedule should be regenerated:
```ts
async function complete() {
if (current == undefined) return;
await fetch("/api/tasks", { method: "DELETE", body: JSON.stringify({ id: current.task.id }) });
await invalidateAll();
}
```
This uses the tasks API I made earlier to delete the task from its ID, and the `invalidateAll` function refetched the data calculated during the server-side `load` function, which since that is how the page fetched the schedule, it will update it. At this point I decided to do a run of the overview page's tests:
=== Overview Testing
#table(columns: (auto, auto, auto, auto),
[*No.*], [*Description*], [*Expected*], [*Outcome*],
[O1], [Go to page while there is a current task], [Page shows current task, remaining time, and other information], [Page shows information correctly],
[O2], [Go to page while there is not a current task], [Page shows there is no task and shows the next upcoming task], [Page shows information correctly],
[O3], [Complete button pressed while there is a current task], [Completes the task, regenerates schedule and updates page], [Task is deleted and schedule is updated],
[O4], [Complete button pressed while there is no current task], [Errors saying there is no ongoing task], [No effect],
[O5], [Snooze button pressed while there is a current task], [Snoozes the task, regenerates the schedule and updates page], [No effect],
[O6], [Snooze button pressed while there is no current task], [Errors saying there is no ongoing task], [No effect],
[07], [Break button pressed], [Pop up prompting for break duration], [No effect],
[O8], [Duration entered into break popup], [Clears all task for the entered duration, regenerates schedule and updates the page], [No effect],
[O9], [Task list button pressed], [Goes to task list page], [N/A],
[O10], [Schedule list button pressed], [Goes to schedule view page], [N/A],
[O11], [Overview button pressed], [Nothing happens], [N/A],
[O12], [Any task pressed], [Task edit UI appears], [Removing],
)
O1 through O3 were successful, however O4 failed as I have not yet implemented an error message, O5-O11 fail expectedly as the buttons either have no functionality, or don't exist. When speaking to stakeholders, we decided the ability to click on any task to edit it was not helpful, and would make the website hard to use on mobile platforms, so I have decided to remove O12 from the tests.
With testing completed, everything implemented so far was working correctly, however I still had to implement the snooze and take a break feature. However while testing, despite everything working correctly, there was some odd behaviour. Since the schedule was generated at page load, it would change every time a user would reload the page, or access it on another device. This meant that a users schedule would be inconsistent across devices, which isn't especially easy to follow. To address this I decided to make schedules persistent and only regenerate them when the user's task list is modified. To start I had to modify the task schema:
```ts
export const tasks = pgTable('tasks', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
duration: integer('duration').notNull(),
scheduled: timestamp('scheduled'), // New
deadline: timestamp('deadline', { withTimezone: true }).notNull(),
user_id: integer('user_id').references(() => users.id)
});
```
I added an optional column, the scheduled time. This column would be used to store the scheduled time when the schedule was generated, meaning the `generateSchedule` function had to be modified:
```ts
export async function generateSchedule(user: User, tasks: Array<Task>) {
const sorted: Array<Task> = tasks.sort((a, b) => a.deadline.getTime() - b.deadline.getTime());
let start: Date = new Date(Date.now());
sorted.forEach(task => {
const next_day = nextDay(user.start, start);
const day_end = end(user.end, start);
if (day_end.getTime() < (start.getTime() + task.duration * 1000)) { // If the task would finish after the day's ended, move it to the beginning of the next day
start = next_day;
}
task.scheduled = start; // New, schedule in this task
(async () => await db.update(schema.tasks).set({ scheduled: start }).where(eq(schema.tasks.id, task.id)))(); // New, update database to include scheduled time
start = new Date(start.getTime() + task.duration * 1000); // Advance the start time by the task's duration
});
}
```
Now the schedule was persistent I had to update the overview page load function to fetch the schedule from the database instead of generating it at load time, this meant returning the task list, since tasks now contained the time they were scheduled for:
```ts
export async function load({ cookies }) {
const token = cookies.get("token");
if (token == null) {
return error(401);
}
const user = await getUser(token);
if (typeof user == "number") {
return error(user);
}
const tasks = await getTasks(user);
if (typeof tasks == "number") {
return error(tasks);
}
return { tasks };
}
```
Finally I needed to move the schedule regeneration to whenever the task list was modified, which currently was only in the `/api/tasks` API:
```ts
export async function POST({ request, cookies }) {
...
const taskList = await getTasks(user);
if (typeof taskList === "number") {
return error(taskList);
}
await generateSchedule(user, taskList);
...
}
export async function DELETE({ request, cookies }) {
...
const taskList = await getTasks(user);
if (typeof taskList === "number") {
return error(taskList);
}
await generateSchedule(user, taskList);
...
}
export async function PATCH({ request, cookies }) {
...
const taskList = await getTasks(user);
if (typeof taskList === "number") {
return error(taskList);
}
await generateSchedule(user, taskList);
...
}
```
With this done, I decided to retest the overview page just to double check I didn't break anything:
#table(columns: (auto, auto, auto, auto),
[*No.*], [*Description*], [*Expected*], [*Outcome*],
[O1], [Go to page while there is a current task], [Page shows current task, remaining time, and other information], [Page shows information correctly],
[O2], [Go to page while there is not a current task], [Page shows there is no task and shows the next upcoming task], [Page shows information correctly],
[O3], [Complete button pressed while there is a current task], [Completes the task, regenerates schedule and updates page], [Task is deleted and schedule is updated],
[O4], [Complete button pressed while there is no current task], [Errors saying there is no ongoing task], [No effect],
[O5], [Snooze button pressed while there is a current task], [Snoozes the task, regenerates the schedule and updates page], [No effect],
[O6], [Snooze button pressed while there is no current task], [Errors saying there is no ongoing task], [No effect],
[07], [Break button pressed], [Pop up prompting for break duration], [No effect],
[O8], [Duration entered into break popup], [Clears all task for the entered duration, regenerates schedule and updates the page], [No effect],
[O9], [Task list button pressed], [Goes to task list page], [N/A],
[O10], [Schedule list button pressed], [Goes to schedule view page], [N/A],
[O11], [Overview button pressed], [Nothing happens], [N/A],
[O12], [Any task pressed], [Task edit UI appears], [Removing],
)
Everything seemed to be working as before, except with persistent schedules so I could finally move onto the take a break feature.
=== Take a Break
Currently since I didn't have a way of forcing tasks to start after a certain time, I decided to just create a task with a high deadline priority when making a break. The task will have the duration specified and a deadline such that it will be scheduled for the first task:
```ts
<script lang="ts">
let breakHours: number = 0;
let breakMinutes: number = 0;
async function takeBreak() {
let duration = breakHours * 3600 + breakMinutes * 60;
let deadline = new Date(Date.now() + duration * 1000);
let title = "Break";
await fetch("/api/tasks", { method: "POST", body: JSON.stringify({ duration, deadline, title }) });
await invalidateAll();
}
</script>
...
<NumericInput bind:value={breakHours} />
<NumericInput bind:value={breakMinutes} />
<Button.Root class="text-xl" on:click={takeBreak}>Take a break</Button.Root>
...
```
I decided to put the break hours and minutes inputs directly on the page rather than behind a popup, mainly to make it easier and more obvious how to enter the information, but also to simplify the UI. With the take a break feature working, there was only one other feature that didn't need start times, which was repeated tasks.
=== Repeat Tasks
To start with I had to add another column to the `tasks` table, the repeat column, which would specify the interval between repeats in days:
```ts
export const tasks = pgTable('tasks', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
duration: integer('duration').notNull(),
scheduled: timestamp('scheduled'),
repeat: integer('repeat'),
deadline: timestamp('deadline', { withTimezone: true }).notNull(),
user_id: integer('user_id').references(() => users.id)
});
```
The column is nullable, as a null value would mean the task is unrepeated. A value of 0 days is also treated as a one-time task. With the field in the database, I next moved onto changing the task edit UI to allow the user to enter a repeat interval:
```ts
<div class="grid grid-cols-5 items-center gap-4">
<Label for="duration" class="text-right">Repeat</Label>
<NumericInput bind:value={repeat} class="col-span-2" />
<Label for="duration" class="col-span-2 text-left">Days</Label>
</div>
```
This added another row to the form grid, I decided to display the units of the interval to make it clear to the user that the unit used is days.
#image("taskeditrepeatfield.png")
Now tasks were able to be set to repeat, I needed to reschedule repeat tasks when they are completed, rather than deleting them like I am currently. Since this meant I could no longer just use `DELETE /api/tasks` I decided to make a new API route `/api/complete` which would handle the completion of a task:
api/complete/+server.ts
```ts
export async function POST({ request, cookies }) {
const { id } = await request.json();
const token = cookies.get("token");
if (token == null) {
return error(401);
}
let username = await jwt.verify(token, JWT_SECRET);
if (typeof username != "string") { return error(400, "Bad token"); }
const user = await db.query.users.findFirst({ where: eq(users.username, username) });
if (user == null) {
return error(404);
}
const task = await db.query.tasks.findFirst({ where: eq(tasks.id, id) });
if (task == null) {
return error(404);
}
if (task.user_id != user.id) {
return error(401);
}
if (task.repeat) {
await db.update(tasks).set({ deadline: new Date(task.deadline.getTime() + task.repeat * (24 * 3600 * 1000)) }).where(eq(tasks.id, task.id));
} else {
await db.delete(tasks).where(eq(tasks.id, task.id));
}
const taskList = await getTasks(user);
if (typeof taskList === "number") {
return error(taskList);
}
await generateSchedule(user, taskList);
return new Response()
}
```
With this I changed the complete button to use the new API route instead of the DELETE method:
```ts
async function complete() {
if (current == undefined) return;
await fetch('/api/complete', { method: 'POST', body: JSON.stringify({ id: current.id }) });
await sleep(500);
await invalidateAll();
}
```
I also added a sleep to the function, as I found the schedule wasn't being regenerated before it was being refetched so the change wasn't observed. While a 500ms delay does make the refresh take longer it was a lot more reliable.
=== Start After
I finally had to bite the bullet and implement the start after feature. I needed a way of specifying that tasks couldn't be started until after a certain time, for example I wouldn't be able to do my maths lesson until it was time for it. To start I modified the `tasks` table again to add the start after field:
```ts
export const tasks = pgTable('tasks', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
duration: integer('duration').notNull(),
scheduled: timestamp('scheduled'),
repeat: integer('repeat'),
startAfter: timestamp('start_after').notNull(), // New
deadline: timestamp('deadline', { withTimezone: true }).notNull(),
user_id: integer('user_id').references(() => users.id)
});
```
Like the repeat feature, I needed to update the task edit UI to add the new field:
```ts
<script lang="ts">
let startDate: DateValue, startHours: number, startMinutes: number;
...
</script>
<div class="grid grid-cols-5 items-center gap-4">
<Label for="duration" class="text-right">Start After</Label>
<DatePicker bind:value={startDate} class="col-span-4" />
</div>
<div class="grid grid-cols-5 items-center gap-4">
<p />
<NumericInput bind:value={startHours} class="col-span-2" />
<NumericInput bind:value={startMinutes} class="col-span-2" />
</div>
```
I chose an identical design to the deadline input in order to be consistent with my timestamp inputs. After tweaking some parts to make sure it was being send to and recieved by the server, I was able to create tasks with an earliest start time, next I needed to update the schedule generation algorithm to take these times into account, for now I went with the simplest approach of just setting the current time to the start after time if the current time was too early:
```ts
export async function generateSchedule(user: User, tasks: Array<Task>) {
const sorted: Array<Task> = tasks.sort((a, b) => a.deadline.getTime() - b.deadline.getTime());
let start: Date = new Date(Date.now());
sorted.forEach(task => {
const next_day = nextDay(user.start, start);
const day_end = end(user.end, start);
if (day_end.getTime() < (start.getTime() + task.duration * 1000)) { // If the task would finish after the day's ended, move it to the beginning of the next day
start = next_day;
}
// New
if (start.getTime() < task.startAfter.getTime()) {
start = task.startAfter;
}
task.scheduled = start; // Schedule in this task
(async () => await db.update(schema.tasks).set({ scheduled: start }).where(eq(schema.tasks.id, task.id)))();
start = new Date(start.getTime() + task.duration * 1000); // Advance the start time by the task's duration
});
}
```
While this meant there were a lot more holes in the timetable, it did work correctly and allowed me to schedule tasks such as lessons which had to be in a fixed time. Finally I needed to update the complete API to update the start after time for repeated tasks, for instance if I have a maths lesson at 10am every week on Mondays, after its finished I want the start after time to become the start of next week's lesson:
```ts
...
if (task.repeat) {
await db.update(tasks).set({
startAfter: new Date(task.startAfter.getTime() + task.repeat * (24 * 3600 * 1000)),
deadline: new Date(task.deadline.getTime() + task.repeat * (24 * 3600 * 1000))
}).where(eq(tasks.id, task.id));
} else {
await db.delete(tasks).where(eq(tasks.id, task.id));
}
...
```
With this feature implement, not only was I able to schedule fixed tasks, I was finally able to implement the snooze feature!
=== Snoozing
I decided to implement snoozing by changing the current task's start after time to one hour after the current time, meaning it would be rescheduled for an hours time at the earliest. This meant snoozing was as simple as:
```ts
<script lang="ts">
async function snooze() {
if (!current) { return; }
current.startAfter = new Date(current.startAfter.getTime() + (3600 * 1000));
const body = {
startAfter: current.startAfter.getTime(),
deadline: current.deadline.getTime(),
duration: current.duration,
title: current.title,
id: current.id,
repeat: current.repeat
};
await fetch('/api/tasks', { method: 'PATCH', body: JSON.stringify(body) });
await sleep(500);
await invalidateAll();
}
</script>
...
<Button.Root class="p-8 text-xl lg:p-16 lg:text-3xl" on:click={snooze}>Snooze</Button.Root>
...
```
With all of the buttons working in theory, I decided to do another full test of the overview page:
#table(columns: (auto, auto, auto, auto),
[*No.*], [*Description*], [*Expected*], [*Outcome*],
[O1], [Go to page while there is a current task], [Page shows current task, remaining time, and other information], [Page shows information correctly],
[O2], [Go to page while there is not a current task], [Page shows there is no task and shows the next upcoming task], [Page shows information correctly],
[O3], [Complete button pressed while there is a current task], [Completes the task, regenerates schedule and updates page], [Task is deleted and schedule is updated],
[O4], [Complete button pressed while there is no current task], [Errors saying there is no ongoing task], [No effect],
[O5], [Snooze button pressed while there is a current task], [Snoozes the task, regenerates the schedule and updates page], [Snoozes the task and schedule is updates],
[O6], [Snooze button pressed while there is no current task], [Errors saying there is no ongoing task], [No effect],
[07], [Break button pressed], [Pop up prompting for break duration], [Inputs work correctly],
[O8], [Duration entered into break popup], [Clears all task for the entered duration, regenerates schedule and updates the page], [Clears all tasks and updates schedule],
[O9], [Task list button pressed], [Goes to task list page], [N/A],
[O10], [Schedule list button pressed], [Goes to schedule view page], [N/A],
[O11], [Overview button pressed], [Nothing happens], [N/A],
)
All features were working except for error messages, the app was nearly finished! To do a proper test and get some feedback I deployed the app and asked my stakeholders to sign up for an account and test it out. I left them for a few hours to wait for feedback and these were the results:
#table(columns: (auto, auto),
[*Feedback*], [*Decisions*],
[Difficult to navigate], [Create navigation bar with buttons that go to all important pages],
[Signup/Login pages don't go anywhere if successful], [Create redirects on success that sends the user to the overview page],
[Have to go to tasks page to add task], [Introduce add task button onto new navbar]
)
=== Navigation
The majority of the feedback I recieved was that navigating around the pages was too difficult. To fix this I've decided to add a navigation bar at the top of all pages with buttons to all of the major pages on the site:
```html
<div class="flex justify-between border-b p-4">
<div class="flex items-start gap-4">
<Button href="/">Overview</Button>
<Button href="/tasks">Tasks</Button>
</div>
{#if authed}
<Button on:click={logout}>Log Out</Button>
{:else}
<div class="flex items-end gap-4">
<Button href="/login">Log In</Button>
<Button href="/signup">Sign Up</Button>
</div>
{/if}
</div>
```
#image("navbarwithoutbutton.png")
I decided to give the navbar two model, authenticated and unauthenticated, which will change the right hand buttons from Logout to Login+Signup respectively. The navbar's variant will be set on each page, the pages that require the user to be authenticated will show the navbar in the authenticated variant.
As well as the navbar I decided to implement different automatic redirects to try and guide the user to the correct page:
If logged in:
#table(columns: (auto, auto), [*From*], [*To*], [Signup], [Overview], [Login], [Overview])
If logged out:
#table(columns: (auto, auto), [*From*], [*To*], [Overview], [Login], [Tasks], [Login])
The login and signup forms also redirect to the overview page if they were successful.
This meant it was much harder to get lost on a page because the user wasn't authenticated.
Finally I also added a new API route, `/api/logout` that allowed the user to log out:
```ts
export async function GET({ cookies }) {
cookies.delete("token", { path: "/" });
return new Response();
}
```
All the route does is delete the user's `token` cookie, meaning the client will look like it hasn't logged in, meaning it will be redirected to the login page.
With those changes made I updated the deployment and asked the stakeholders for feedback, they said the website was much easier to use than before. 2 of the 3 pieces of feedback I was given had been addressed, so I moved onto adding the new add task button onto the navbar.
=== Extra Add Task Button
The other piece of feedback I recieved from stakeholders was the lack of a create task button on any page other than the tasks list view. One of my success criteria is that tasks should be easy and intuitive to add, so making sure they could be added from anywhere was very important. I decided to copy the new task button from the task list page to the navigation bar, there wasn't any new code here since I was just refactoring and copying code from the task list page:
```ts
<script lang="ts">
let staging: Task = {
deadline: new Date(Date.now()),
duration: 0,
title: '',
id: 0,
scheduled: null,
repeat: 0,
startAfter: new Date(Date.now())
};
async function createTask(task: Task) {
const body = {
startAfter: task.startAfter.getTime(),
deadline: task.deadline.getTime(),
duration: task.duration,
title: task.title,
repeat: task.repeat
};
await fetch('/api/tasks', { method: 'POST', body: JSON.stringify(body) });
await invalidateAll(); // Reload page to make task list changes take effect
}
...
</script>
<div class="flex justify-between gap-4 border-b p-4">
<div class="flex items-start gap-4">
<Button href="/">Overview</Button>
<Button href="/tasks">Tasks</Button>
</div>
{#if authed}
<Edit callback={createTask} bind:task={staging} class="grow" dialogTitle="Create task">
<Plus class="h-4" />
</Edit>
<Button on:click={logout}>Log Out</Button>
{:else}
<div class="flex items-end gap-4">
<Button href="/login">Log In</Button>
<Button href="/signup">Sign Up</Button>
</div>
{/if}
</div>
```
Since the user had to be logged in to add a task, I decided to only show the button when the nav bar was in authenticated mode. I reused the `Edit` component from the task list page and added a new `class` property which allowed me to specify the styling. With that the new add task button was made and I had responded to all of my stakeholders' feedback, meaning I was ready to implement the last feature: reminder notifications.
=== Reminder Notifications
I wanted to send a series of notifications to the user for events such as tasks starting/finishing, or timed warning such as 10 minutes before a task ending. To send notifications on a web app I had to use the #link("https://developer.mozilla.org/en-US/docs/Web/API/notification#examples")[Notifications API] which handled requesting permisson to send notifications, as well as sending the notifications to the operating system. It also provided a convinient `Notification` class which I could fill out with things like images and badges to make my notification look nicer, however I decided to not use those features.
To implement notifications, the first thing I had to do was request permission when on the overview page, which is the page the user must be on for notifications to work.
```ts
<script lang="ts">
onMount(async () => {
if (Notification.permission !== "granted") {
await Notification.requestPermission();
}
...
});
...
</script>
```
This code checks if permission has already been granted, if not it prompts the browser to request permission which in Google Chrome causes this popup:
#image("popup.png", height: 30%)
With permission granted I could now send notifications to the browser, looking at the Mozilla API docs, it looked like all I needed to do was to construct a `Notification` object, for example:
```ts
new Notification("Hello, World!");
```
Would cause a notification with the body `Hello, World!` to appear on the user's computer. Running a quick test I could see it was working:
#image("testnotification.png", height: 30%)
The first notification I wanted to make was the new task started notification, for which I needed to check if the current task had changed, and if it had to send a notification:
```ts
function setCurrent() {
const old = current;
current = schedule.find((task, a, b) => {
if (task.scheduled === null) {
return false;
}
let now = Date.now();
let start = task.scheduled.getTime();
let end = task.scheduled.getTime() + task.duration * 1000;
return start <= now && now <= end;
});
if (browser && old !== current && current != null) {
new Notification(`Task Started: ${current.title}`);
}
}
```
With the task started notification working, I moved on to the task starts/ends in 10 minutes notification:
```ts
function checkNotifications() {
let now = Date.now();
schedule.forEach((task) => {
if (!task.scheduled) return;
let start = task.scheduled.getTime();
let tenBeforeStart = start - 10 * 60 * 1000;
let end = task.scheduled.getTime() + task.duration * 1000;
let tenTillEnd = end - 10 * 60 * 1000; // Subtract 10 mins in ms
if (lastRan <= tenBeforeStart && tenBeforeStart <= now) {
// ten minutes until end was in time window
new Notification(`Starting in 10: ${task.title}`);
}
if (lastRan <= tenTillEnd && tenTillEnd <= now) {
// ten minutes until end was in time window
new Notification(`10 minutes remaining: ${task.title}`);
}
});
lastRan = now;
}
```
This algorithm works by checking if the times (e.g. 10 minutes before end) have past in the window between when we last ran the function and now. If it does a notification is sent to the user.
After entering some mock task data to check the notifications were working, I saw everything was working fine:
#image("startingsoon.png", height: 30%)
#image("endingsoon.png", height: 30%)
With all the reminder notifications added, I decided to deploy to the public test server.
At this point I only had two features left to implement, the schedule view and task priority. After having a discussion with my stakeholders about whether the features were a good idea, nearly all felt that the schedule view would be misleading since the schedule can change greatly. We felt the user being able to see the schedule so far in advance would result in confusion if the task is rescheduled for a different time, so I've decided not to implement the schedule view. We also felt adding a priority option to tasks was one column to many, the task addition form was already taking a while to fill out, and priority wasn't really that userful to schedule generation as I'd initially thought, so I've decided to drop that feature also. This meant that I'd unknowingly finished the product, so I decided to do a full test of the product:
= Evaluation
== Final Testing
=== Video
Here's a #link("https://youtu.be/OB6mlZVhnI0")[video] of me demoing the product, the timestamps below refer to moments in this video where each test is showcased to pass/fail.
=== Login
#table(columns: (auto, auto, auto, auto, auto),
[*No.*], [*Description*], [*Expected*], [*Outcome*], [*Timestamp*],
[L1], [Log in with a correct username and password], [Login succeeds and returns a auth token], [Login success and auth token is saved to browser cookies, user is redirected to overview page], [0:31],
[L2], [Log in with a username that does not exist], [Error is raised and user is asked to sign up], [Error is raised and user is asked to sign up], [0:09],
[L3], [Log in with a correct username and invalid password], [Error is raised and user is asked to recheck their password], [Error is raised and user is asked to recheck their password],[0:09],
[L4], [Log in with either an empty username or password], [Error is raised and user is asked to fill username and password boxes], [Error is raised and user is asked to fill username and password boxes],[0:06],
[L5], [Goes to log in page while already logged in], [User is redirected to overview page], [User is redirected to overview page],[0:31],
)
=== Signup
#table(columns: (auto, auto, auto, auto, auto),
[*No.*], [*Description*], [*Expected*], [*Outcome*], [*Timestamp*],
[S1], [Sign up with an unused username and password], [Sign up succeeds and returns a auth token], [Sign up succeeds and returns a auth token, user is redirected to overview page],[0:17],
[S2], [Sign up with a used username], [Error is raised and user is asked to choose a different username], [Error is raised and user is asked to choose a different username],[0:27],
[S3], [Sign up with either an empty username or password], [Error is raised and user is asked to fill username and password boxes], [Error is raised and user is asked to fill username and password boxes],[0:15],
[S4], [Goes to sign up page while already logged in], [User is redirected to overview page], [User is redirected to overview page],[0:17],
)
=== Overview
#table(columns: (auto, auto, auto, auto, auto),
[*No.*], [*Description*], [*Expected*], [*Outcome*], [*Timestamp*],
[O1], [Go to page while there is a current task], [Page shows current task, remaining time, and other information], [As expected],[1:16],
[O2], [Go to page while there is not a current task], [Page shows there is no task and shows the next upcoming task], [As expected],[0:39],
[O3], [Complete button pressed while there is a current task], [Completes the task, regenerates schedule and updates page], [As expected],[1:24],
[O4], [Complete button pressed while there is no current task], [Errors saying there is no ongoing task], [As expected],[0:39],
[O5], [Snooze button pressed while there is a current task], [Snoozes the task, regenerates the schedule and updates page], [As expected],[1:33],
[O6], [Snooze button pressed while there is no current task], [Errors saying there is no ongoing task], [As expected],[0:39],
[07], [Break button pressed], [Pop up prompting for break duration], [No popup anymore but break task is added to schedule],[1:40],
[O8], [Duration entered into break popup], [Clears all task for the entered duration, regenerates schedule and updates the page], [As expected],[1:38],
[O9], [Task list button pressed], [Goes to task list page], [As expected],[0:40],
[O10], [Schedule list button pressed], [Goes to schedule view page], [Schedule view page does not exist],[-],
[O11], [Overview button pressed], [Nothing happens], [As expected],[1:13],
)
=== Task List
#table(columns: (auto, auto, auto, auto, auto),
[*No.*], [*Description*], [*Expected*], [*Outcome*], [*Timestamp*],
[T1], [Go to page], [See a list of all tasks], [As expected],[0:43, 1:44],
[T2], [Click on any task], [Opens task edit UI], [As expected],[0:43],
[T3], [Overview button pressed], [Goes to overview page], [As expected],[1:12],
[T4], [Task list button pressed], [Does nothing], [As expected],[0:41],
[T5], [Schedule button pressed], [Goes the schedule view page], [Schedule view page does not exist],[-],
)
=== Task Edit
#table(columns: (auto, auto, auto, auto, auto),
[*No.*], [*Description*], [*Expected*], [*Outcome*], [*Timestamp*],
[E1], [Delete button pressed], [Task deleted and schedule regenerated], [As expected],[1:45],
[E2], [Title editted to a non-empty value], [Task title changed], [As expected],[0:53],
[E3], [Title editted to an empty value], [Error message appears saying tasks must have a title], [As expected],[2:15],
[E4], [Deadline editted], [Task deadline changed, schedule regenerated], [As expected],[0:53],
[E5], [Duration editted to a non-zero value], [Task duration changed, schedule regenerated], [As expected],[0:53],
[E6], [Duration editted to a zero], [Error appears saying tasks must have a duration], [Accepted the input and failed],[2:24],
[E7], [Priority changed], [Task priority changed, schedule regenerated], [Priority is no longer a feature],[-],
)
=== Schedule Generation
#table(columns: (auto, auto, auto, auto, auto),
[*No.*], [*Description*], [*Expected*], [*Outcome*], [*Timestamp*],
[G1], [Schedule generated with valid list of tasks], [All tasks are scheduled to be completed before their deadline], [As expected],[1:16],
[G2], [Schedule generated with valid list of tasks], [All tasks are scheduled to take their duration], [As expected],[1:16],
[G3], [Schedule generated with impossible list of tasks], [Error raised about impossible task list], [As close to valid task list as possible is generated, we found this was more useful than just erroring],[1:16],
[G4], [Schedule generated with valid list of tasks], [Tasks with higher priorities are often schedules before tasks with lower priorities], [Priority is no longer a feature],[-],
)
And will that done, all tests have either passed or failed as expected meaning the product is complete! As well as this a few stakeholders and I used the website for a few days and ran in to no issues, the scheduling algorithm was a bit strange at times but thats something I can look at improving if I wanted to take this project further.
== Success Criteria Evaluation
=== Inputs
#table(columns: (auto, auto, auto, auto),
[*Criteria*], [*Explanation*], [*Justification*], [*Outcome*],
[The user should be able to add tasks with a title, deadline, duration, repeat scheduling and priority easily on both desktop and mobile platforms], [Users need to be able to add tasks as they think of them, else they might forget and it won't be added to their schedule. If adding tasks is complicated or takes too long then people just won't add them], [E2-E6 shows the form used to edit and create tasks validates the input correctly, this makes it easy to use. In addition, everyone who tested the website said the UI was "very intuitive" which shows the feature is easy to use and works correctly.], [Fully Met],
[The user should be able to edit tasks and delete them], [Tasks can change as users realise they might take longer than estimate, or the deadline might move, or someone else might do the task for them, the app needs to facilitate this by letting users edit and delete tasks], [E1 shows deletion working, E2-E6 shows editting tasks working. All users encountered the edit and delete task buttons by themselves, they also were able to use the form without me having to explain it, this shows the feature is intuitive to use.], [Fully Met],
[The user should be able to mark tasks as complete easily], [Tasks need to be easily marked as complete else users might forget which would mean the schedule will desync], [O3 and O4 shows that the complete task feature was working correctly, all testers found the complete button and understood its usage by themselves, this shows the feature is easy to use and intuitive], [Fully Met],
[The user should be able to take a break for any length of time, which will clear their schedule], [If users are taking a break, the app needs to not schedule any tasks for that time else the schedule will desync], [O7 and O8 show the break feature working correctly, not all users understood how breaks work, or how to enter a time, so this feature may need improvement], [Partially Met],
)
=== Outputs
#table(columns: (auto, auto, auto, auto),
[*Criteria*], [*Explanation*], [*Justification*], [*Outcome*],
[The user should be able to see a list of tasks and their information easily], [The users will need to manage their tasks, this could include editting them, deleting them and more. This information needs to be nicely presented to the user], [O1 and O2 show the overview page working corretly, this shows the user their current and upcoming tasks. T1 shows the task list page working correctly, this shows the user all their tasks and allows for editting and deletion. Both features were easily identified by testers, showing it is easy to use, many testers also said the multiple views make their task lists easier to understand and process], [Fully Met],
[The user should be able to quickly see their current task and upcoming tasks on their schedule], [Users could want to check what task they need to do, or prepare for upcoming ones], [O1 and O2 show the current and upcoming tasks were displayed correctly on the overview page, all testers found this feature intuitive to use. The overview page is also the root URL of the site, and the first page the user will go to when they go to the website, this means it is quick to check.], [Fully Met],
[The user should be sent reminder notifications when they need to start a new task], [As I found in my survey, users want to be reminded of their task when they need to start it, so they don't have to constantly check the app], [While reminder notifications worked for those testing on PC, any mobile users said reminder notifications didn't work for them. I will need to test this feature further to fix it for mobile users, however those who had them said they were very useful], [Partially Met],
[The website should be aesthetic and intuitive to use], [As I found in the survey, UIs that are both aesthetic and easy to use are quite important for most people], [Nearly all usability features were met, in addition most testers said the UI was one of the strongest parts of the website, it was intuitive to use, and mostly worked on both mobile and desktop.], [Fully Met]
)
=== Processing
#table(columns: (auto, auto, auto, auto),
[*Criteria*], [*Explanation*], [*Justification*], [*Outcome*],
[When a user makes any change to their task list, it should be stored on the server], [Users might want to use the app on multiple devices, meaning tasks have to be synced across them. For this a user's task list must be stored in a database with APIs for getting and modifying the task list], [O1, O2 and T1 all show the task list being fetched correctly, E1-E6 as well as O3-O8 show modifications to the task list were synced to the server correctly and persisted. No testers complained about syncing issues even when using multiple devices or bad internet, which suggests the feature is reliable], [Fully Met],
[A schedule should be generated for the users task list], [As I found by talking to people that took the survey, many people want a personal schedule to follow, but don't want to have to schedule it themselves because it takes too long and isn't flexible. By generating a schedule on-the-fly it becomes nearly instant and flexible as another schedule can be generated at any time], [While G1-G4 show schedule generation working correctly, and the E1-E6 shows the schedule is regenerated at the correct time, many testers complained how the generated schedule wasn't great, there were lots of issues like task order being strange and the day start/end times resulting in testers being confused why tasks were being scheduled for the following day instead of immediately. This shows I have a lot more work to do with schedule generation], [Partially Met],
[When a user makes any change to their task list or decides to take a break, the schedule should be regenerated], [E1-E6 and O3-O8 show the schedule is regenerated at the correct times, there were also no complaints from testers about the schedule not being regenerated], [Fully Met],
[Generated schedules should meet all deadlines and prioritise tasks correctly], [If a schedule doesn't fit the user's task list, then its not very useful], [G1-G4 shows schedule generation worked for the large amount of schedules I tested it with, in addition no testers complained about incorrect schedules, showing this feature is reliably implemented], [Fully Met]
)
=== Conclusion
#table(columns: (auto, auto),
[*Issue*], [*Potential Fixes*],
[Many testers felt quality of schedules were poor and they were generated in an unintuitive way], [Improve scheduling algorithm, many add some more fields, and also make the day start/end time more obvious to the user],
[Reminder notifications didn't work on mobile], [With more time and testing, this should be fixable, I imagine its just a bug in the code],
[Taking a break was unintuitive], [A better UI would probably help, maybe my original idea with a popup window would've worked better. In addition modifying the start time might be a more reliable method of inserting a break into the schedule compared to the current method of creating a break task]
)
== Usability Features
#table(columns: (auto, auto, auto),
[*Feature*], [*Justification*], [*Outcome*],
[Large user interface], [All pages had large easy to see buttons and text, especially the overview page which was designed mainly for mobile devices. Many testers gave feedback on how the UI was easy to use on mobile devices], [Fully met],
[Simple user interface], [All pages had a simple, elegant UI with the information presented clearly without visual distrractions. Many testers gave feedback on how the UI was very intuitive to use], [Fully met],
[Colour coded buttons], [All buttons were a bright colour, I chose blue as my default colour but chose to use colours like red for destructive operations meaning the user can infer the meaning. Many testers gave feedback on how the UI was intuitive to use and it was obvious where buttons where and what they did], [Fully Met],
[Input validation], [Input validation was implmented on all forms, and no testers ran into a way of entering invalid data], [Fully Met],
[Icons], [Icons were used throughout the website to communicate meaning, for example a pencil icon was used for the edit button and a bin icon was used for the delete button. Many testers gave feedback on how intuitive the UI was, which shows the icons communicated meaning successfully], [Fully Met],
[Large text], [Large text was used throughout website to communicate visual heirarchy as well as making important information easy to read. No testers felt that any information was hard to read on either mobile or desktop, however none of the testers had impaired eyesight so I may need to do more testing], [Partially Met],
[Error messages], [Error messages were used on every form and effectively communicate any issues with invalid inputs. No testers were able to input invalid data into any forms], [Fully Met],
[Automatic Navigation], [The final website included many redirects and gotos which helped to automate navigation around the site. No testers complained about getting lost in the pages and said the site was easy to navigte], [Fully Met]
)
== Maintenance and Limitations
The existing code should be easy to add to or modify as it is well-named, modular, and commented. Since the server and client both use JS, an interpreted language, it would be easy to run on all sorts of machines and new hardware if the server needed to be updated. While modifying the code to add new features would be quite easy, if it involves updating the database schemas the maintainer will need to run a database migration to preserve user data. One of the big things that needs to be improved is the scheduling algorithm, since this is all located in one function it will be easy to improve in future, however care needs to be taken to regenerate everyones timetable whenever there is a scheduling modification to avoid race conditions.
== Future Developments
#table(columns: (auto, auto),
[*Limitation/Issue*], [*Possible Solutions*],
[Generated schedules aren't great], [More work could be done on the scheduling algorithm to increase the quality of the schedules, either by introducing new inputs or heuristics such as priority. This would be fairly easy to do since scheduling is all contained in a single module, however if any changes need to be made to the database the schemas must be updates and migrations ran],
[Reminder notifications don't work on mobile], [This is likely a software bug so should be fixable easily, however this represents a larger issue that the app cannot send notifications unless it is open. Ideally the app would be used as a PWA(Progressive Web App) which would allow the user's schedule to be cached locally and reminder notifications can be queued meaning they will work without the app being open. This is a massive change to the entire site and would likely need a large rework],
[Minor UI improvements], [With a few UI and styling tweaks some of the pages could be made easier to use, especially on mobile devices. This would likely be easy to implement since each page is stored in a standalone component]
)
|
|
https://github.com/RandomcodeDev/FalseKing-Design | https://raw.githubusercontent.com/RandomcodeDev/FalseKing-Design/main/game/visuals.typ | typst | = Visuals
Due to limited resources and artistic talent on my part, the game will use low-poly models and simple textures. There will be a particle system, and the elemental powers will be given extra attention. |
|
https://github.com/mem-courses/calculus | https://raw.githubusercontent.com/mem-courses/calculus/main/recourses-2/mid-term-2023-sim-lxj.typ | typst | #import "../template.typ": *
#show: project.with(
course: "Calculus II",
course_fullname: "Calculus (A) II",
course_code: "821T0160",
title: "Mid Term 2023: 卢兴江模拟题",
authors: ((
name: "memset0",
email: "https://mem.ac/",
id: [_<EMAIL>_],
),),
semester: "Spring-Summer 2024",
date: "April 10, 2024",
)
#v(-2em)
#let int = math.integral
#let divider = [#v(1fr)$ "" $]
*Problem 1.* (12 points) 分析下列级数是绝对收敛?条件收敛?还是发散?
(1) $display(sum_(n=1)^(oo) (-1)^(n-1) int_0^(1/n) sqrt(x)/(1+x^2) dif x)$
#v(0.5em)
(2) $display(sum_(n=1)^(oo) (-1)^n (3^n)/(n(3^n+2^n)))$
#divider
*Problem 2.* (12 points)
(1) 求过 $x$ 轴且与 $x+y+z=1$ 垂直的平面方程。
(2) 求过点 $(1,-1,2)$ 且与 $display(x/1 = (y-1)/1 = (z-3)/(-3))$ 垂直相交的直线方程。
#divider
#pagebreak(weak: true)
*Problem 3.* (12 points)
(1) 已知 $z=z(x,y)$ 满足 $display((diff z)/(diff y) = x^2 + 2y)$,$z(x,x^2)=1$,求 $z(x,y)$ 的表达式。
(2) 设 $z=f(2x-y, x^2 y) + g(x^2 + y^2)$,其中 $f$ 具有二阶连续偏导数,$g$ 具有二阶连续导数,求 $display((diff^2 z)/(diff x diff y))$。
#divider
*Problem 4.* (12 points)
(1) 已知函数 $f(x) = x+1$。若 $f(x) = display((a_0)/2 + sum_(n=1)^(oo) a_n cos n x),space x in [0,pi]$,求 $display(sum_(n=1)^(oo) a_(2n-1))$ 的和。
(2) 将函数 $display(f(x) = x/(x^2-5x+6))$ 展开成 $x-1$ 的幂级数并指出收敛域。
#divider
#pagebreak(weak: true)
*Problem 5.* (12 points)
(1) 求直线 $display(cases(x-y+2x-1=0,2x+y+z-2=0))$ 绕 $x$ 轴旋转一周所得的旋转曲面方程。
#v(0.5em)
(2) 求曲线 $display(cases(z=x^2 + 2y^2, 2x-4y+z=1))$ 在平面 $2x+y+5z=0$ 上的投影曲线方程。
#divider
*Problem 6.* (10 points) 设 $u=display(x/y)$,$v=x$,$w = x z - y$,试将方程 $display(y (diff^2 z)/(diff y^2) + 2 (diff z)/(diff y) = 2 /x)$ 变换成函数 $w=w(u,v)$ 关于变量 $u,v$ 的方程。
#divider
#pagebreak(weak: true)
*Problem 7.* (10 points) 设球面 $S$ 与平面 $x-2y+2z=3$ 与 $2x+2y-2z=8$ 皆相切,且球心在直线 $display(cases(2x-y=0,3x-z=0))$ 上,求此球面的方程。
#divider
*Problem 8.* (10 points) 求级数 $display(sum_(n=1)^(oo) ((x^2+x+1)^n)/(n(n+1)))$ 的收敛域与和函数。
#divider
*Problem 9.* (10 points) 设正数列 ${a_n}$ 单调增加且有界,证明级数 $display(sum_(n=1)^(oo) (1-a_n/a_(n+1)))$ 收敛。
#divider
|
|
https://github.com/explicit-refinement/ert-lean-together | https://raw.githubusercontent.com/explicit-refinement/ert-lean-together/main/slides.typ | typst | BSD Zero Clause License | #import "@preview/polylux:0.3.1": *
#import "@preview/curryst:0.1.0": *
#import themes.simple: *
#show: simple-theme
#let ert = $λ_sans("ert")$;
#let stlc = $λ_sans("stlc")$;
#let app = $med$;
#let llet = $sans("let")$;
#let case = $sans("case")$;
#title-slide[
= Explicit Refinement Types
#v(2em)
<NAME> #h(1em)
<NAME>
University of Cambridge
January 12
Lean Together 2024 -- Online
]
#let newmark = text(red, "(new!)")
#slide[
= The Plan
#line-by-line(start: 2)[
- Speedrun STLC w/ de-Bruijn indices tutorial
- See #link("https://leanprover.github.io/lean4/doc/examples/deBruijn.lean.html")[Dependent de Bruijn indices in the Lean Manual]
- Sketch syntactic weakening and substitution #newmark
- Sketch semantic weakening and substitution #newmark
- Sketch refinement types #newmark
- *Hopefully*: sketch _semantic regularity_ #newmark
]
#uncover("7-")[
*Follow along at:* #link("https://github.com/explicit-refinement/ert-lean-together")
]
]
#focus-slide[
= What is a type theory?
]
#focus-slide[
= Simply-typed Lambda Calculus
]
#let stlc-var(ctx, var, ty) = rule(name: "var", $ctx ⊢ var: ty$, $var: ty ∈ ctx$)
#let stlc-app(c, l, r) = rule(name: "app", c, l, r)
#let stlc-lam(c, p) = rule(name: $λ$, c, p)
#let stlc-pair(c, l, r) = rule(name: $×$, c, l, r)
#let stlc-let2(c, p) = rule(name: "let2", c, p)
#let stlc-unit(ctx) = rule(name: $()$, $Γ ⊢ (): bold(1)$, $$)
#let stlc-inl(c, p) = rule(name: $ι_0$, c, p)
#let stlc-inr(c, p) = rule(name: $ι_1$, c, p)
#let stlc-cases(c, e, l, r) = rule(name: $sans(c)$, c, e, l, r)
#let stlc-zero(ctx) = rule(name: $0$, $Γ ⊢ 0: ℕ$, $$)
#let stlc-succ(c, p) = rule(name: $sans(s)$, c, p)
#let stlc-natrec(c, z, s) = rule(name: $sans(i)$, c, z, s)
#let stlc-abort(ctx, A) = rule(name: $⊥$, $Γ ⊢ attach(⊥, br: A): #A$, $$)
#let stlc-const(ctx, n) = rule(name: $n$, $ctx ⊢ #n: ℕ$, $$)
#slide[
#align(center + horizon, stack(dir: ttb, spacing: 2em,
stack(dir: ltr, spacing: 2em,
only("1-", proof-tree(stlc-var($Γ$, $x$, $A$))),
only("3-", proof-tree(stlc-app($Γ ⊢ s med t: B$, $Γ ⊢ s: A -> B$, $Γ ⊢ t: A$))),
),
stack(dir: ltr, spacing: 2em,
only("4-", proof-tree(stlc-lam($Γ ⊢ λ x: A. t: A -> B$, $Γ, x: A ⊢ t: B$))),
),
stack(dir: ltr, spacing: 2em,
only("5-", proof-tree(stlc-unit($Γ$))),
only("6-", proof-tree(stlc-const($Γ$, $n$))),
only("7-", proof-tree(stlc-abort($Γ$, $A$))),
),
only("2-", $Γ = x: A, y: B, z: C, ...", etc."$)
))
]
#focus-slide[
= Properties of Type Theories
]
#slide[
= Weakening
#align(center + horizon)[
$f: A -> B, #only("2", text(red, $y: C, $)) x: A ⊢ f med x: B$
]
]
#slide[
#align(center + horizon)[
*Lemma* (Weakening):
#uncover("2-")[*If* $Γ ⊇ Δ$]
#uncover("3-")[and $Δ ⊢ a: A$,]
#uncover("4-")[*then* $Γ ⊢ a: A$]
]
]
#slide[
= Substitution
#align(center + horizon)[
$
f: A -> B, x: A ⊢ f med x: B
$
$
#only("1", $y: B,$)
#only("2", text(red, $f: A -> B, x: A,$))
g: B -> C ⊢ g
#only("1", $y$)
#only("2", text(red, $(f med x)$)): C
$
]
]
#let stlc-subst-nil(ctx) = rule(name: "subst-nil", $dot: ctx -> dot$, $$)
#let stlc-subst-cons(c, σ, t) = rule(name: "subst-cons", c, σ, t)
#slide[
= Substitution
#align(horizon)[
#stack(dir: ttb, spacing: 2em,
[
Given $σ: sans("Var") -> sans("Stlc")$,
#uncover("2-", [we say $σ: Γ -> Δ$ if])
#uncover("3-")[$∀x, x: A ∈ Δ ==> Γ ⊢ σ(x): A$]
],
[
#uncover("4-")[*Lemma* (Substitution):]
#uncover("5-")[*If* $σ: Γ -> Δ$, ]
#uncover("6-")[$Δ ⊢ a: A$]
#uncover("7-")[*then* $Γ ⊢ [σ]a: A$]
],
[
#uncover("8-")[Here $[σ]$ denotes *capture-avoiding* substitution.]
]
)
]
]
#focus-slide[
= How would we represent this in Lean?
]
#slide[
= Types
#align(center + horizon, grid(
columns: 3,
gutter: 3em,
align(left, $A, B ::= bold(1) | ℕ | A -> B$),
uncover("2-", $ ⇝ $),
uncover("2-", align(left, ```lean
inductive Ty: Type
| unit
| nat
| fn (A B: Ty)
```)),
))
]
#slide[
= Untyped Syntax
#align(center + horizon, grid(
columns: 3,
gutter: 2em,
align(left, $s, t ::= x | s med t | λ x: A. t | () | n | attach(⊥, br: A)$),
uncover("2-", $ ⇝ $),
align(left,[
#only("-4", uncover("2-", ```lean
inductive Stlc: Type
| var -- ???
| app (s t: Stlc)
| lam (A: Ty) (t: Stlc)
| nil
| cnst (n: Nat)
| abort (A: Ty)
```))
#only("5-", ```lean
inductive Stlc: Type
| var (n: Nat)
| app (s t: Stlc)
| lam (A: Ty) (t: Stlc)
| nil
| cnst (n: Nat)
| abort (A: Ty)
```)
]),
// only("7-", align(left, $Γ, Δ ::= dot | Γ, x: A$)),
// only("8-", $ ⇝ $),
// only("8-", align(left, ```lean
// def Ctx := List Ty
// ```)),
))
#only("3-")[- Want $λ x: A. x = λ y: A. y$ ($α$-conversion)]
#only("4-")[- Need to impelement capture-avoiding substitution]
#only("5-")[*Solution: de Bruijn indices*]
]
#let mkred(x) = text(red, x)
#let mkblue(x) = text(blue, x)
#let mkgreen(x) = text(olive.darken(20%), x)
#slide[
= de-Bruijn Indices
#align(center + horizon, grid(columns: 3, gutter: 2em,
$mkred(λ x). mkblue(λ y). bold(mkgreen(λ z)). bold(mkgreen(z))$,
uncover("2-", $==>$),
uncover("2-", $mkred(λ) mkblue(λ) bold(mkgreen(λ)) bold(mkgreen(0))$),
uncover("3-", $mkred(λ x). bold(mkblue(λ y)). mkgreen(λ z). mkblue(y)$),
uncover("4-", $==>$),
uncover("4-", $mkred(λ) bold(mkblue(λ)) mkgreen(λ) bold(mkblue(1))$),
uncover("5-", $bold(mkred(λ x)). mkblue(λ y). mkgreen(λ z). bold(mkred(x))$),
uncover("6-", $==>$),
uncover("6-", $bold(mkred(λ)) mkblue(λ) mkgreen(λ) bold(mkred(2))$),
uncover("7-", $-: A, bold(#[$w: B,$]) -: C ⊢ mkred(λ x). mkblue(λ y). mkgreen(λ z). bold(w)$),
uncover("8-", $==>$),
uncover("8-", $A, bold(B), C ⊢ mkred(λ) mkblue(λ) mkgreen(λ) bold(4)$)
))
]
#slide[
= Typing Contexts
#align(center + horizon, grid(
columns: 3,
gutter: 2em,
align(left, $s, t ::= x | s med t | λ x: A. t | () | n | attach(⊥, br: A)$),
$ ⇝ $,
align(left,[
```lean
inductive Stlc: Type
| var (n: Nat)
| app (s t: Stlc)
| lam (A: Ty) (t: Stlc)
| nil
| cnst (n: Nat)
| abort (A: Ty)
```
]),
only("2-", align(left, $Γ, Δ ::= dot | Γ, x: A$)),
only("3-", $ ⇝ $),
only("3-", align(left, ```lean
def Ctx := List Ty
```)),
))
]
#slide[
= Typing Judgements
#align(horizon)[
```lean
inductive Stlc.HasTy : Ctx -> Stlc -> Ty -> Type
```
]
]
#slide[
= Variables
#align(horizon, stack(dir: ttb, spacing: 2em,
```lean
inductive Stlc.HasTy : Ctx -> Stlc -> Ty -> Type
| var : Var Γ n A -> HasTy Γ (var n) A
```,
align(center, proof-tree(stlc-var($Γ$, $x$, $A$))),
only("2-")[
```lean
inductive Var : Ctx -> Nat -> Ty -> Type
| head : Var (A :: Γ) 0 A
| tail : Var Γ n A -> Var (B :: Γ) (n + 1) A
```
]
))
]
#slide[
= Applications
#align(horizon, stack(dir: ttb, spacing: 2em,
```lean
inductive Stlc.HasTy : Ctx -> Stlc -> Ty -> Type
| var : Var Γ n A -> HasTy Γ (var n) A
| app : HasTy Γ s (fn A B)
-> HasTy Γ t A
-> HasTy Γ (app s t) B
```,
align(center, proof-tree(
stlc-app($Γ ⊢ s med t: B$, $Γ ⊢ s: A -> B$, $Γ ⊢ t: A$))),
))
]
#slide[
= $λ$-Abstraction
#align(horizon, stack(dir: ttb, spacing: 2em,
```lean
inductive Stlc.HasTy : Ctx -> Stlc -> Ty -> Type
| var : Var Γ n A -> HasTy Γ (var n) A
| app : HasTy Γ s (fn A B)
-> HasTy Γ t A
-> HasTy Γ (app s t) B
| lam : HasTy (A :: Γ) t B -> HasTy Γ (lam A t) (fn A B)
```,
align(center, proof-tree(
stlc-lam($Γ ⊢ λ x: A. t: A -> B$, $Γ, x: A ⊢ t: B$))),
))
]
#slide[
= Constants and Effects
#align(horizon)[
```lean
inductive Stlc.HasTy : Ctx -> Stlc -> Ty -> Type
| var : Var Γ n A -> HasTy Γ (var n) A
| app : HasTy Γ s (fn A B)
-> HasTy Γ t A
-> HasTy Γ (app s t) B
| lam : HasTy (A :: Γ) t B -> HasTy Γ (lam A t) (fn A B)
| nil: HasTy Γ nil unit
| cnst : HasTy Γ (cnst n) nat
| abort: HasTy Γ (abort A) A
```
]
]
#focus-slide[
= Formalizing properties of the STLC
]
#slide[
= Weakening
#align(left + horizon)[
```lean
inductive Wk: (Nat -> Nat) -> Ctx -> Ctx -> Type
```
#uncover("3-")[
```lean
| nil: Wk ρ [] []
```
]
#uncover("4-")[
```lean
| lift: Wk ρ Γ Δ -> Wk (liftWk ρ) (A::Γ) (A::Δ)
```
]
#uncover("5-")[
```lean
| step: Wk ρ Γ Δ -> Wk (stepWk ρ) (A::Γ) Δ
```
]
#only("4")[
```lean
def liftWk (ρ: Nat -> Nat): Nat -> Nat
| 0 => 0
| n + 1 => (ρ n) + 1
```
]
#only("5")[
```lean
def stepWk (ρ: Nat -> Nat) (n: Nat): Nat := (ρ n) + 1
```
]
#uncover("2-")[
```lean
def Var.wk: Wk ρ Γ Δ -> Var Δ n A -> Var Γ (ρ n) A
```
]
]
]
#slide[
= Weakening Variables
```lean
inductive Wk: (Nat -> Nat) -> Ctx -> Ctx -> Type
| nil: Wk ρ [] []
| lift: Wk ρ Γ Δ -> Wk (liftWk ρ) (A::Γ) (A::Δ)
| step: Wk ρ Γ Δ -> Wk (stepWk ρ) (A::Γ) Δ
def Var.wk: Wk ρ Γ Δ -> Var Δ n A -> Var Γ (ρ n) A
| lift R, head => head
| lift R, tail v
| step R, v => tail (v.wk R)
```
]
#slide[
= Weakening Syntax
#align(left + horizon)[
```lean
def Stlc.wk (ρ: Nat -> Nat) : Stlc -> Stlc
| var n => var (ρ n)
| app s t => app (wk ρ s) (wk ρ t)
| lam t => lam (wk (liftWk ρ) t)
| t => t
```
#uncover("2-")[
```lean
theorem Stlc.wk_id: wk id s = s
```
]
#uncover("3-")[
```lean
theorem Stlc.wk_comp: (wk ρ (wk σ t)) = wk (ρ ∘ σ) t
```
]
#uncover("4-")[
etc...
]
]
]
#slide[
= Weakening Derivations
#align(horizon)[
```lean
theorem HasTy.wk (R: Wk ρ Γ Δ): HasTy Δ s A
-> HasTy Γ (wk ρ s) A
| var v => v.wk R
| app s t => app (wk R s) (wk R t)
| lam A t => lam A (wk R.lift t)
| unit => unit
| cnst => cnst
| abort => abort
```
]
]
/*
#slide[
= Weakening: aside
#align(horizon)[
```lean
inductive Wk
| id
| lift (ρ: Wk)
| step (ρ: Wk)
def Wk.var: Wk -> Nat -> Nat
| id, n => n
| lift ρ, 0 => 0
| lift ρ, n + 1 => (ρ.var n) + 1
| step ρ, n => (ρ.var n) + 1
```
]
]
*/
#slide[
= Syntax Substitution
#align(horizon)[
#align(center)[
#only("1")[
$σ: sans("Var") -> sans("Stlc")$
]
#only("2-")[
```lean
σ: Nat -> Stlc
```
]
]
#uncover("3-")[
```lean
def Stlc.subst (σ: Nat -> Stlc) : Stlc -> Stlc
| var n => σ n
| app s t => app (subst σ s) (subst σ t)
| lam A t => lam A (subst (liftSubst σ) t)
| t => t
```
]
#uncover("4-")[
```lean
def liftSubst (σ: Nat -> Stlc) : Nat -> Stlc
| 0 => var 0
| n + 1 => (σ n).wk (stepWk id)
```
]
]
]
#slide[
= Substitution
#align(horizon)[
#only("1", align(center)[
$σ: Γ -> Δ <==> ∀x, x: A ∈ Δ ==> Γ ⊢ σ(x): A$
])
#only("2-")[
```lean
def Subst (σ: Nat -> Stlc) (Γ Δ: Ctx): Type :=
∀{n A}, Var Δ n A -> HasTy Γ (σ n) A
```
]
#uncover("3-")[
```lean
def HasTy.subst (S: Subst σ Γ Δ): HasTy Δ s A
-> HasTy Γ (s.subst σ) A
```
]
#uncover("4-")[
```lean
| var v => S v
```
]
#uncover("5-")[
```lean
| app s t => app (subst S s) (subst S t)
```
]
#uncover("5-")[
```lean
| lam t => lam (subst S.lift t)
```
#only("6-7")[
```lean
lam : HasTy (A :: Γ) t B -> HasTy Γ (lam A t) (fn A B)
```
]
#only("7")[
```lean
Subst σ Γ Δ -> Subst (liftSubst σ) (A :: Γ) (A :: Δ)
```
]
]
]
]
#slide[
= Substitution Lifting
#align(horizon)[
```lean
def Subst.lift (S: Subst σ Γ Δ): Subst (liftSubst σ) (A::Γ) (A::Δ)
| _, _, head => var head
| _, _, tail v => (S v).wk (Wk.step Wk.id)
```
#uncover("2-")[
```lean
def Wk.id: {Γ: Ctx} -> Wk id Γ Γ
| [] => nil
| _::_ => liftWk_id ▸ lift Wk.id
```
]
#uncover("3-")[
```lean
theorem liftWk_id: liftWk id = id
:= by funext v; cases v <;> rfl
```
]
]
]
#slide[
= Substitution (cont.)
#align(horizon)[
```lean
def HasTy.subst (S: Subst σ Γ Δ): HasTy Δ s A
-> HasTy Γ (s.subst σ) A
| var v => S v
| app s t => app (subst S s) (subst S t)
| lam t => lam (subst S.lift t)
| unit => unit
| cnst => cnst
| abort => abort
```
]
]
#focus-slide[
= What is a (denotational) semantics?
]
#let optm = $sans("Option")$
#slide[
= Type semantics
#align(horizon,
stack(dir: ttb, spacing: 3em,
[
#only("1-8", stack(dir: ltr, spacing: 3em,
uncover("2-", $[| bold(1) |] = bold(1)$),
uncover("3-", $[| ℕ |] = ℕ$),
uncover("4-", $[| A -> B |] = [| A |] -> #uncover("5-", optm) [| B |]$)
))
#only("9-")[
```lean
def Ty.den: Ty -> Type
| nil => Unit
| nat => Nat
| fn A B => A.den -> Option (B.den)
```
]
]
,
[
#only("1-9", stack(dir: ltr, spacing: 3em,
uncover("6-", $[| dot |] = bold(1)$),
uncover("7-",
$[| Γ, x: A |] = #uncover("8-", optm) [|A|] × [| Γ |]$)
))
#only("10-")[
```lean
inductive Ctx.den: Ctx -> Type
| nil: Ctx.den []
| cons: Option (Ty.den A)
-> Ctx.den Γ
-> Ctx.den (A::Γ)
```
]
]
))
]
#slide[
= Term semantics
#align(horizon)[
```lean
def HasTy.den: HasTy Γ s A -> Ctx.den Γ -> Option A.den
```
]
]
#slide[
= Variable semantics
#align(horizon)[
```lean
def HasTy.den: HasTy Γ s A -> Ctx.den Γ -> Option A.den
| var v, G => v.den G
```
#uncover("-2")[
```lean
def Var.den: Var Γ n A -> Ctx.den Γ -> Option A.den
| head, Ctx.den.cons a _ => a
| tail v, Ctx.den.cons _ G => v.den G
```
]
]
]
#slide[
= Application semantics
#align(horizon)[
```lean
def HasTy.den: HasTy Γ s A -> Ctx.den Γ -> Option A.den
| var v, G => v.den G
| app s t, G => do
let s <- s.den G
let t <- t.den G
s t
```
]
]
#slide[
= Lambda semantics
#align(horizon)[
```lean
def HasTy.den: HasTy Γ s A -> Ctx.den Γ -> Option A.den
| var v, G => v.den G
| app s t, G => do
let s <- s.den G
let t <- t.den G
s t
| lam t, G => pure (λx => t.den (Ctx.den.cons x G))
```
]
]
#slide[
= Constant semantics
#align(horizon)[
```lean
def HasTy.den: HasTy Γ s A -> Ctx.den Γ -> Option A.den
| var v, G => v.den G
| app s t, G => do
let s <- s.den G
let t <- t.den G
s t
| lam t, G => pure (λx => t.den (Ctx.den.cons x G))
| nil, G => pure ()
| @cnst _ n, _ => pure n
| abort, _ => none
```
]
]
#slide[
= Semantic Weakening
#align(horizon)[
```lean
def Wk.den: Wk ρ Γ Δ -> Ctx.den Γ -> Ctx.den Δ
| nil, x => x
| lift ρ, Ctx.den.cons a G => Ctx.den.cons a (ρ.den G)
| step ρ, Ctx.den.cons a G => ρ.den G
```
#uncover("2-")[
```lean
theorem Var.wk_den: (v: Var Δ n A) -> (R: Wk ρ Γ Δ)
-> ∀{G: Γ.den}, v.den (R.den G) = (v.wk R).den G
| head, lift R, Ctx.den.cons _ _ => rfl
| tail v, lift R, Ctx.den.cons _ _
| v, step R, Ctx.den.cons _ _
=> by simp [Wk.den, den, v.wk_den R]
```
]
]
]
#slide[
= Semantic Weakening
#align(horizon)[
```lean
theorem HasTy.wk_den (R: Wk ρ Γ Δ) (h: HasTy Δ a A)
: ∀{G: Γ.den}, h.den (R.den G) = (h.wk R).den G := by
induction h generalizing ρ Γ with
| var v => exact Var.wk_den v R
| lam t I => intros; simp [den, <-I]; rfl
| _ => simp [den, *]
```
]
]
#slide[
= Semantic Substitution
#align(horizon)[
```lean
def Subst.den: {Γ Δ: _} -> Subst σ Γ Δ -> Γ.den -> Δ.den
| _, [], _, _ => Ctx.den.nil
| _, _::_, S, G => Ctx.den.cons
((S head).den G)
(den (Subst.uncons S) G)
```
#uncover("2-")[
```lean
def Var.subst_den: (S: Subst σ Γ Δ) -> (v: Var Δ n A)
-> ∀{G: Γ.den}, v.den (S.den G) = (S v).den G
| S, head, G => rfl
| S, tail v, G => by simp [den, Var.subst_den]; rfl
```
]
]
]
#slide[
= Semantic Substitution
//TODO: fix sorry?
#align(horizon)[
```lean
def HasTy.subst_den (S: Subst σ Γ Δ) (h: HasTy Δ s A):
∀{G: Γ.den}, h.den (S.den G) = (h.subst S).den G := by
induction h generalizing Γ σ with
| var v => exact Var.subst_den S v
| lam t I => sorry
| _ => simp [den, *]
```
]
]
#let donemark = text(green, "✓")
#focus-slide[
= Recap
]
#slide[
= The Plan
#line-by-line[
- Speedrun STLC w/ de-Bruijn indices tutorial #donemark
- Sketch syntactic weakening and substitution #donemark
- Sketch semantic weakening and substitution #donemark
- Sketch refinement types
- *Hopefully*: sketch _semantic regularity_
]
]
#focus-slide[
= What is a refinement type?
]
#slide[
= Refinement Types
#align(horizon)[
$
#only("3-", $(a: $) ℕ#only("3-", $)$)
-> #only("2-", ${b :$)ℕ #only("2-", $| b ≤ 10 #only("3-", $∧ b ≤ a$) }$)
$
$
#only("4-", $∀a: ℕ. { b : ℕ | a + b ≥ a }$)
#only("5-", $≃ {b: ℕ | ∀a, a + b ≥ a}$)
#only("6-", $≃ {b: ℕ | b ≠ 0}$)
$
]
]
#slide[
= Ghosts and proofs
#align(horizon)[
$
∀a, b: ℕ. a + b = b + a
$
#only("2-",
$
∀a: ℕ, { ℓ: [ℕ] | sans("len") med ℓ = a } -> { n: ℕ | n = a }
$
)
]
]
#slide[
= Refined Terms
$
∀a: ℕ, { ℓ: [ℕ] | sans("len") med ℓ = a } -> { n: ℕ | n = a }
$
#align(left + horizon)[
#only("2-")[
$#only("3-", $|$)hat(λ) a: ℕ. λ (ℓ, p): { ℓ: [ℕ] | sans("len") med ℓ = a }.
(sans("len") med ℓ, p)#only("3-", $|$)$
]
#only("3-")[
$= λ-: bold(1). |λ (ℓ, p): { ℓ: [ℕ] | sans("len") med ℓ = a }.
(sans("len") med ℓ, p)|$
]
#only("4-")[
$= λ-: bold(1). λ ℓ: [ℕ]. |(sans("len") med ℓ, p)|$
]
#only("5-")[
$= λ-: bold(1). λ ℓ: [ℕ]. sans("len") med ℓ$
]
#only("5-")[
$= λ-: bold(1). sans("len")$
(by $η$)
]
]
]
#let ert-ok-nil() = rule(name: "nil-ok", $dot med sans("ok")$, $$)
#let ert-ok-cons(c, pg, pa) = rule(name: "nil-cons", c, pg, pa)
#slide[
= "Dependent" Types
#align(center + horizon, stack(dir: ttb, spacing: 3em,
$
Γ ⊢ A med sans("ty")
$,
only("2-")[
#stack(dir: ltr, spacing: 3em,
proof-tree(ert-ok-nil()),
proof-tree(ert-ok-cons($Γ, x: A med sans("ok")$, $Γ med sans("ok")$, $Γ ⊢ A med sans("ty")$))
)
],
only("3-")[
*Lemma* (Regularity): $Γ ⊢ a: A ==> Γ ⊢ A med sans("ty")$
]
))
]
#slide[
= Semantics of Refinement Types
#align(horizon)[
#only("1")[
$
[|A|]: 𝒫([| |A| |])
$
]
#only("2")[
$
[|Γ ⊢ A med sans("ty")|]: [| |Γ| |] -> 𝒫([| |A| |])
$
]
]
]
#slide[
= Semantics of Refined Contexts
#align(horizon)[
$
[|Γ ⊢ A med sans("ty")|]: [| |Γ| |] -> 𝒫([| |A| |])
$
$
[|Γ med sans("ok")|]: 𝒫([| |Γ| |])
$
#uncover("2-")[
$
[|dot med sans("ok")|] &= bold(1) \
[|Γ, x: A med sans("ok")|] &= [|Γ med sans("ok")|] × [|Γ ⊢ A med sans("ty")|]
$
]
]
]
#slide[
= Semantic Regularity
#align(horizon)[
*Theorem* (Semantic Regularity):
$
Γ ⊢ a: A ==> ∀ G ∈ [|Γ med sans("ok")|],
[| |Γ| ⊢ |a|: |A| |] med G ∈ [|Γ ⊢ A med sans("ty")|]
$
]
]
#focus-slide[
= So how do we represent this in Lean?
]
#slide[
= Refined Terms
```lean
inductive Term: Type
-- Terms
| var (n: Nat)
| app (s t: Term)
| lam (A: Term) (t: Term)
| nil
| cnst (n: Nat)
```
]
#slide[
= Ghost Binders
```lean
inductive Term: Type
-- Terms
| var (n: Nat)
| app (s t: Term)
-- `true` for comp
-- `false` for ghosts
| lam (k: Bool) (A: Term) (t: Term)
| nil
| cnst (n: Nat)
```
]
#slide[
= "Proofs"
```lean
inductive Term: Type
-- Terms
| var (n: Nat)
| app (s t: Term)
| lam (k: Bool) (A: Term) (t: Term)
| nil
| cnst (n: Nat)
-- Proofs
| refl (a: Term)
```
]
#slide[
= "Dependent Types"
```lean
inductive Term: Type
-- Types (New!)
| pi (k: Bool) (A: Term) (B: Term)
| unit
| nat
| eq (A: Term) (s t: Term)
-- Terms
| var (n: Nat)
| lam (k: Bool) (A: Term) (t: Term)
-- ...
```
]
#slide[
= Type Erasure
#align(horizon)[
```lean
def Term.ty: Term -> Ty
| pi true A B => A.ty.fn B.ty
| pi false _ B => Ty.unit.fn B.ty
| nat => Ty.nat
| _ => Ty.unit
```
]
]
#slide[
= Term Erasure
#align(horizon)[
```lean
def Term.stlc: Term -> Stlc
| var n => Stlc.var n
| app s t => s.stlc.app t.stlc
| lam true A t => t.stlc.lam A.ty
| lam false _ t => t.stlc.lam Ty.unit
| nil => Stlc.nil
| cnst n => Stlc.cnst n
| _ => Stlc.nil
```
]
]
#slide[
= Syntactic Weakening
#align(horizon)[
```lean
def Term.wk (ρ: Nat -> Nat) : Term -> Term
-- new: types weaken just like terms
| pi k A B => pi k (wk ρ A) (wk ρ B)
| eq A s t => eq (wk ρ A) (wk ρ s) (wk ρ t)
--
| var n => var (ρ n)
| app s t => app (wk ρ s) (wk ρ t)
| lam k A t => lam k A (wk (liftWk ρ) t)
| t => t
```
]
]
#slide[
= Syntactic Substitution
#align(horizon)[
```lean
def Term.subst (σ: Nat -> Term) : Term -> Term
-- new: types substitute just like terms
| pi k A B => pi k (subst σ A) (subst σ B)
| eq A s t => eq (subst σ A) (subst σ s) (subst σ t)
--
| var n => σ n
| app s t => app (subst σ s) (subst σ t)
| lam k A t => lam k A (subst (liftDSubst σ) t)
| t => t
```
]
]
#slide[
= Dependent Contexts
#align(horizon)[
```lean
def DCtx := List (Bool × Term)
```
#uncover("2-")[
```lean
def DCtx.stlc: DCtx -> Ctx
| [] => []
| ⟨true, A⟩::Γ => A.ty :: stlc Γ -- computational
| ⟨false, _⟩::Γ => Ty.unit :: stlc Γ -- ghost
```
]
#uncover("3-")[
```lean
def DCtx.gstlc: DCtx -> Ctx
| [] => []
| ⟨_, A⟩::Γ => A.ty :: gstlc Γ
```
]
]
]
#slide[
= Downgrade
#align(horizon)[
```lean
def DCtx.downgrade: {Γ: DCtx} -> Γ.gstlc.den -> Γ.stlc.den
| [], Ctx.den.nil
=> Ctx.den.nil
| ⟨true, _⟩::_, Ctx.den.cons a G
=> Ctx.den.cons a (downgrade G)
| ⟨false, _⟩::_, Ctx.den.cons _ G
=> Ctx.den.cons none (downgrade G)
```
]
]
#slide[
= Typing Judgements
```lean
inductive DHasTy: DCtx -> Term -> ??? -> Type
-- ...
```
#line-by-line[
- `Ty` doesn't work since `Term` can have a dependent type
- `Term` works for terms, but we want to distinguish valid types...
- We also want to distinguish "ghost" terms versus "computational" ones
- *Solution*: introduce new `Annot` type
]
#uncover("4-")[
```lean
inductive Annot: Type
| ty
| tm (k: Bool) (A: Term)
```
]
]
#slide[
= Valid Types
```lean
inductive DHasTy: DCtx -> Term -> Annot -> Type
```
#only("2-4")[
```lean
| pi: DHasTy Γ A ty -> DHasTy (⟨k, A⟩::Γ) B ty
-> DHasTy Γ (pi k A B) ty
```
]
#only("3-4")[
```lean
| eq: DHasTy Γ A ty
-> DHasTy Γ s (tm k A)
-> DHasTy Γ t (tm k A)
-> DHasTy Γ (eq A s t) ty
```
]
#only("4")[
```lean
| unit: DHasTy Γ unit ty
| nat: DHasTy Γ nat ty
```
]
#only("5-")[
```lean
-- ...
inductive VCtx: DCtx -> Type
| nil: VCtx []
| cons: DHasTy Γ A ty -> VCtx Γ -> VCtx (⟨k, A⟩::Γ)
```
]
]
#slide[
= Variables
#align(horizon)[
```lean
inductive DHasTy: DCtx -> Term -> Annot -> Type
-- ...
| var: DVar Γ n a -> DHasTy Γ (var n) a
```
#only("2-4")[
```lean
inductive DVar: DCtx -> Nat -> Annot -> Type
```
]
#only("3-4")[
```lean
| head: k ≥ k'
-> DVar (⟨k, A⟩::Γ) 0 (tm k' (A.wk (stepWk id)))
```
]
#only("4-4")[
```lean
| tail: DVar Γ n (tm k A)
-> DVar (X::Γ) (n + 1) (tm k (A.wk (stepWk id)))
```
]
#only("5-")[
```lean
def DVar.ghost: DVar Γ n (tm k A) -> DVar Γ n (tm false A)
| head H => head (by simp)
| tail v => tail (ghost v)
```
]
]
]
#slide[
= Terms
```lean
inductive DHasTy: DCtx -> Term -> Annot -> Type
-- ...
```
#only("1")[
```lean
| lam:
DHasTy (⟨k, A⟩::Γ) t (tm k' B)
-> DHasTy Γ (lam k A t) (tm k' (pi k A B))
```
]
#only("2-3")[
```lean
| app:
DHasTy Γ s (tm k (pi k' A B))
-> DHasTy Γ t (tm k A)
-> k' ≥ k
-> DHasTy Γ (app s t) (tm k (B.subst t.subst0))
```
]
#only("3")[
```lean
def Term.subst0 (s: Term): Nat -> Term
| 0 => s
| n + 1 => var n
```
]
#only("4-")[
```lean
| nil: DHasTy Γ nil (tm k unit)
| cnst: DHasTy Γ nat (tm k nat)
```
]
]
#slide[
= Proofs
```lean
inductive DHasTy: DCtx -> Term -> Annot -> Type
-- ...
| refl: DHasTy Γ a (tm k A)
-> DHasTy Γ (refl a) (tm k' (eq A a a))
```
#only("2-")[
```lean
def DHasTy.ghost: DHasTy Γ s (tm k A)
-> DHasTy Γ s (tm false A)
```
]
]
#slide[
= Erasure
#align(horizon)[
```lean
def DHasTy.gstlc: DHasTy Γ s (tm k A)
-> HasTy Γ.gstlc s.stlc A.ty
```
#only("2-")[
```lean
def DHasTy.stlc: DHasTy Γ s (tm true A)
-> HasTy Γ.stlc s.stlc A.ty
```
]
#only("3-")[
```lean
theorem DHasTy.ty_wk: DHasTy Γ s ty
-> (s.wk ρ).ty = s.ty
theorem DHasTy.ty_subst: DHasTy Γ s ty
-> (s.subst σ).ty = s.ty
```
]
]
]
#slide[
= Weakening
#align(horizon)[
```lean
inductive DWk: (Nat -> Nat) -> DCtx -> DCtx -> Type
| nil: DWk ρ [] []
| step: DWk ρ Γ Δ -> DWk (stepWk ρ) (X::Γ) Δ
```
#only("2-")[
```lean
| lift: DWk ρ Γ Δ -> k ≥ k'
-> DWk (liftWk ρ) (⟨k, A⟩::Γ) (⟨k', A.wk ρ⟩::Δ)
```
]
#only("3-")[
```lean
def DVar.wk: DWk ρ Γ Δ -> DVar Δ n a -> DVar Γ (ρ n) a
```
]
#only("4-")[
```lean
def DHasTy.wk (R: DWk ρ Γ Δ):
DHasTy Δ s a -> DHasTy Γ (s.wk ρ) a
```
]
]
]
#slide[
= Substitution
#align(horizon)[
```lean
def DSubst (σ: Nat -> Term) (Γ Δ: DCtx): Type :=
∀{n a}, DVar Δ n a -> DHasTy Γ (σ n) a
```
#only("2-")[
```lean
def DHasTy.subst (S: DSubst σ Γ Δ):
DHasTy Δ s a -> DHasTy Γ (s.subst σ) a
```
]
]
]
#slide[
= Regularity
#align(horizon)[
```lean
def DHasTy.reg: DHasTy Γ s (tm k A) -> DHasTy Γ A ty
```
]
]
#focus-slide[
= Semantics of refinement types
]
#slide[
= Semantic Regularity
#align(horizon)[
```lean
def DHasTy.den_ty: DHasTy Γ s ty
-> Γ.gstlc.den -> s.ty.den -> Prop
```
#only("2-")[
```lean
def VCtx.den: VCtx Γ -> Γ.gstlc.den -> Prop
```
]
#only("3-")[
```lean
theorem DHasTy.den_reg: (HΓ: VCtx Γ)
-> (H: DHasTy Γ s (tm k A))
-> HΓ.den G
-> ∃a, some a = H.gstlc.den G ∧ H.reg.den_ty G a
```
]
]
]
#slide[
= Irrelevance
#align(horizon)[
```lean
theorem DHasTy.irrel: (H: DHasTy Γ s (tm true A))
-> H.gstlc.den G = H.stlc.den (DCtx.downgrade G)
```
]
]
#focus-slide[
= Questions?
---
#link("mailto:<EMAIL>")[`<EMAIL>`]
]
#slide[
= Aside: Coherence
#uncover("2-")[
- *Option 1:* _Adding Nothing to HOL_
```lean
theorem HasTy.ty_coh: HasTy Γ s A -> HasTy Γ s B -> A = B
theorem HasTy.coh (H H': HasTy Γ s A) : H = H'
```
- Pros: very easy to define things by induction on well-typed terms
- Cons: doesn't erase quite the same as `Prop`...
]
#uncover("3-")[
- *Option 2:* _Explicit Refinement Types_
```lean
inductive Stlc.HasTy : Ctx -> Stlc -> Ty -> Prop
inductive Stlc.Var : Ctx -> Nat -> Ty -> Prop
```
- Pros: coherence comes for free, can use tactics
- Cons: annoying to define things by induction on well-typed terms
]
]
#slide[
= Aside: why the spurious $bold(1)$ parameter?
#align(horizon)[
$
|hat(λ) (n, p): { n: ℕ | ⊥ } . sans("abort") med p|
= λ-: bold(1). ⊥
$
]
] |
https://github.com/EstebanMunoz/typst-template-evaluacion | https://raw.githubusercontent.com/EstebanMunoz/typst-template-evaluacion/main/conf.typ | typst | MIT No Attribution | #import "@preview/codly:1.0.0": *
#import "@preview/subpar:0.1.1"
// Template
#let conf(
title: none,
subject: none,
students: (),
teachers: (),
auxiliaries: (),
assistants: (),
lab-assistants: (),
due-date: none,
university: none,
faculty: none,
department: none,
logo: none,
course-code: none,
course-name: none,
doc
) = {
// Seteo general del documento
set document(title: title, author: auxiliaries)
set page(
"us-letter",
margin: (top: 4.46cm, bottom: 2.7cm, right: 2.54cm, left: 2.54cm),
header: [
#set align(left)
#set text(11pt)
#stack(
dir: ttb,
spacing: 4pt,
[#stack(
dir: ltr,
spacing: 1fr,
[#stack(
dir: ttb,
spacing: 6pt,
[#university],
[#department],
[#course-code #course-name]
)],
logo
)],
[#line(length: 100%, stroke: 0.4pt)]
)
],
footer: [#stack(
dir: ttb,
spacing: 4.5pt,
line(length: 100%, stroke: 0.4pt),
[#h(1fr) #context counter(page).display(here().page-numbering())]
)],
numbering: "1"
)
set par(leading: 0.55em, justify: true)
set heading(numbering: "1.")
set text(size: 11pt, font: "New Computer Modern", lang: "es")
set raw(syntaxes: "template/assets/syntaxes/Arduino.sublime-syntax")
show raw: set text(size: 11pt, font: "New Computer Modern Mono")
show bibliography: set par(justify: false)
set bibliography(style: "institute-of-electrical-and-electronics-engineers")
// Resize de títulos y subtítulos
let font-sizes = (17.28pt, 14.4pt, 12pt)
show heading: it => block(above: 1.4em, below: 1em)[
#let new-size = font-sizes.at(it.level - 1, default: 11pt)
#set text(size: new-size)
#if it.numbering == none {
it.body
} else [
#context counter(it.func()).display() #h(10pt) #it.body
]
]
// Título
let place-people(people, single-people-str, multiple-people-str) = {
let num-people = people.len()
if num-people == 0 {()}
let identifier = if num-people == 1 {
single-people-str
} else {
multiple-people-str
}
return [*#identifier* #people.join(", ")]
}
align(center)[
#text(size: 20pt)[#title] \
#if subject != none { text(size: 14pt)[#subject] } else { none }
#place-people(teachers, "Profesor:", "Profesores:")
#place-people(auxiliaries, "Auxiliar:", "Auxiliares:") \
#place-people(assistants, "Ayudante:", "Ayudantes:")
*Fecha de entrega:* #due-date
]
// Modifica enum para enumerar preguntas
// set enum(numbering: n => return [*P#n.*], tight: false)
// Modifica apariencia de tablas
show table.cell.where(y: 0): strong
set table(
stroke: (_, y) => (
left: 0pt,
right: 0pt,
top: if y == 1 { 1pt } else { 0pt },
bottom: 1pt
),
inset: (x, y) => if y == 0 { 8pt } else { 5pt }
)
// Usa el paquete Codly para modificar la apariencia de códigos
show figure.where(kind: raw): set figure(supplement: "Código")
let icon(codepoint) = {
box(
height: 0.8em,
baseline: 0.05em,
image(codepoint)
)
h(0.1em)
}
show: codly-init.with()
codly(languages: (
python: (
name: "Python",
icon: icon("template/assets/logos/python.svg"),
color: rgb("#FFC331")
),
rust: (
name: "Rust",
icon: icon("template/assets/logos/rust.svg"),
color: rgb("#CE412B")
),
arduino: (
name: "Arduino",
icon: icon("template/assets/logos/arduino.svg"),
color: rgb("#00878F")
)
))
// Figuras pueden ser contenidas en múltiples páginas
show figure: set block(breakable: true)
// Comienzo del documento
doc
}
// Crea función para subfigures
#let subfigures = subpar.grid.with(
gap: 1em,
numbering-sub-ref: "1.a",
)
// Misc: configuraciones extra
#let months = ("January": "Enero", "February": "Febrero", "March": "Marzo", "April": "Abril", "May": "Mayo", "June": "Junio", "July": "Julio", "August": "Agosto", "September": "Septiembre", "October": "Octubre", "November": "Noviembre", "December": "Diciembre")
#let month = datetime.today().display("[month repr:long]")
#let today = datetime.today().display("[day] de [month repr:long] de [year]").replace(month, months.at(month)) |
https://github.com/francescoo22/LCD-exercises | https://raw.githubusercontent.com/francescoo22/LCD-exercises/main/src/lemmas.typ | typst | #import "common.typ": *
#import "rules.typ": *
== Lemmas
0. $forall P in CCS_seq . P ended => e(P) ->^(tau*) P_"temp" ntrans P' and P' ended$
1. $fi forall P in CCS_seq . fi P atrans P' then e(P) wnu awtrans P'' wnu and P' cr (P'' wnu) \ then forall P in CCS_seq . fi P atrans P' "and" Q approx e(P) then Q wnu awtrans P'' wnu and P' cr (P'' wnu) "and dual"$
3. $forall P in CCS_seq . P ended => P approx 0$
4. $forall P in CCS_seq . e(P) approx e(P) wnup$
=== Lemma 0
$ forall P in CCS_seq . P ended => e(P) ->^(tau*) P_"temp" ntrans P' and P' ended $
By induction on the height of the derivation tree of $P ended$
*Base case End-Zero*
If $ r1 $
then $e(0) = nu . 0 ntrans 0$
*Inductive case End-Par*
If $ r2 $ then by induction $e(P) ->^(tau*) P_"temp" ntrans P' and P' ended$ and also $e(Q) ->^(tau*) Q_"temp" ntrans Q' and Q' ended$
So
$
e(P|Q) = (e(P)[nu'/nu] | e(Q)[nu'/nu] | overline(nu') . overline(nu') . nu . 0)wnup \
->^(tau*) (P_"temp" [nu'/nu] | Q_"temp" [nu'/nu] | overline(nu') . overline(nu') . nu . 0) wnup \
ttrans (P'[nu'/nu] | Q_"temp" [nu'/nu] | overline(nu') . nu . 0) wnup \
ttrans (P'[nu'/nu] | Q'[nu'/nu] | nu . 0) wnup \
ntrans (P'[nu'/nu] | Q'[nu'/nu] | 0) wnup ended
$
*Inductive case End-Seq*
If $ r6 $ then by induction $e(P) ->^(tau*) P_"temp" ntrans P' and P' ended$ and also $e(Q) ->^(tau*) Q_"temp" ntrans Q' and Q' ended$
So
$
e(P; Q) = (e(P)[nu'/nu] | overline(nu') . e(Q)) wnup \
->^(tau*) (P_"temp" [nu'/nu] | overline(nu') . e(Q)) wnup \
ttrans (P' [nu'/nu] | e(Q)) wnup \
->^(tau*) (P' [nu'/nu] | Q_"temp") wnup \
ntrans (P' [nu'/nu] | Q') wnup ended
$
=== Lemma 1.1
$
fi forall P,Q in CCS_seq . fi P atrans P' then e(P) wnu awtrans P'' wnu and P' cr (P'' wnu) \
then forall P,Q in CCS_seq, P cr Q wnu . fi P atrans P' then Q wnu awtrans Q' wnu and P' cr (Q' wnu)
$
*Proof:*
$e(P) wnu awtrans P'' wnu =>^"only rule" e(P) awtrans P'' =>^(Q approx e(P)) Q awtrans Q' and P'' approx Q' =>^"transitivity" Q' approx e(P') => P' cr Q' wnu$
=== Lemma 1.2
$
fi forall P,Q in CCS_seq . fi e(P) wnu atrans P'' wnu then P awtrans P' and P' cr (P'' wnu) \
then forall P,Q in CCS_seq, P cr Q wnu . fi Q wnu atrans Q' wnu then P awtrans P' and P' cr (Q' wnu)
$
*Proof:*
$Q wnu atrans Q' wnu =>^"only rule" Q atrans Q' =>^(Q approx e(P)) e(P) awtrans P'' and Q' approx P'' \
=>^"hide" e(P) wnu awtrans P'' wnu =>^"hypothesis" P awtrans P' and P' cr P'' wnu =>^"relation" P'' approx e(P') =>^"transitivity" Q' approx e(P')$ |
|
https://github.com/k4zuy/Typst-Template-HTW | https://raw.githubusercontent.com/k4zuy/Typst-Template-HTW/main/style/style.typ | typst | #import "../common/acronyms.typ": usedAcronyms, acronyms
//#import "../common/acronyms.typ": *
#import "@preview/hydra:0.2.0": hydra
#let style(
title: "",
titleGerman: "",
degree: "",
program: "",
supervisor: "",
advisors: (),
author: "",
studentNumber: "",
startDate: none,
submissionDate: none,
body,
) = {
set document(title: title, author: author)
set page(
paper: "a4",
margin: (
top: 3cm,
bottom: 3cm,
left: 4cm,
right: 2cm
),
numbering: "I",
number-align: right,
header:{
set align(right)
set text(style: "italic") //should be size 10pt but looks shitty
hydra(fallback-next: true, top-margin: 3cm)
v(-8pt)
line(length: 100%, stroke: 0.5pt + black)
}
)
//let body-font = "New Computer Modern"
//let sans-font = "New Computer Modern Sans"
let body-font = "Times New Roman"
let sans-font = "Times New Roman"
set text(
font: body-font,
size: 12pt,
lang: "de"
)
show math.equation: set text(weight: 400)
// --- Headings ---
show heading: set block(below: 1.4em, above: 1.75em)
show heading: set text(font: body-font)
set heading(numbering: "1.1")
// spacing within heading blocks
show heading.where(numbering: "1.1", level: 1): it => block({
box(width: 25pt, counter(heading).display())
it.body
})
show heading.where(numbering: "1.1", level: 2): it => block({
box(width: 30pt, counter(heading).display())
it.body
})
show heading.where(numbering: "1.1", level: 3): it => block({
box(width: 30pt, counter(heading).display())
it.body
})
show heading.where(level: 1): set text(size:16pt, weight: "semibold")
show heading.where(level: 2): set text(size:14pt,weight:"semibold")
show heading.where(level: 3): set text(size:12pt,weight:"semibold")
show heading.where(level: 4): set text(size:12pt,weight: "regular",style: "italic")
show heading.where(level: 1, numbering: "1.1"): it => {
pagebreak() //pagebreak(weak: true)
it
}
// Reference first-level headings as "Abschnitt"
show ref: it => {
let el = it.element
if el != none and el.func() == heading and el.level == 1 {
[Abschnitt ]
numbering(
el.numbering,
..counter(heading).at(el.location())
)
} else {
it
}
}
// --- Footer ---
set footnote.entry(indent: 0em, clearance: 1em)
// --- Paragraphs ---
set par(leading: 1em)
// --- Citations ---
set cite(style: "../literature/my_ieee.csl")//"ieee")
//"institute-of-electrical-and-electronics-engineers")
// --- Figures ---
show figure.where(kind: image): pic => {
//set text(size: 0.85em)
pic
//rect(pic)
}
// --- Table of Contents ---
show outline.entry.where(level: 1): it => {
//if outline.entry != image and it.kind != table{
show: strong
v(1pt, weak: false)
let params = it.fields()
//if-condition to prevent recursion
if it.fill != none {
let params = it.fields()
params.fill = none
outline.entry(..params.values())
} else {
it
}
//}
}
//heading(numbering: none)[Inhaltsverzeichnis]
outline(
title: "Inhaltsverzeichnis",
fill: repeat([.]+h(0.5em)),
indent: auto
)
//v(2.4fr)
//List of acronyms
pagebreak()
heading(numbering: none)[Abkürzungsverzeichnis]
locate(loc => usedAcronyms.final(loc)
.pairs()
.filter(x => x.last())
.map(pair => pair.first())
.sorted()
.map(key => grid(
columns: (auto, auto, auto),
gutter: 0em,
strong(key),repeat([.]),acronyms.at(key)
)).join())
// List of figures.
pagebreak();
// show outline.entry: it => {
// if it.at("label", default: none) == <modified-entry> {
// it // prevent infinite recursion
// } else {
// let caption = it.body
// let elem-label = it.element.at("label", default: none)
// if elem-label != none {
// let caption-label = label(repr(elem-label).slice(1, -1) + "-caption")
// caption = locate(loc => {
// let q = query(selector(metadata).and(selector(caption-label)), loc)
// if q.len() > 0 {
// let short-caption = q.first().value
// let figure-number = numbering("1", ..it.element.counter.at(it.element.caption.location))
// [#it.element.supplement #figure-number: #short-caption]
// } else {
// it.body
// }
// })
// }
// [#outline.entry(
// it.level,
// it.element,
// caption,
// it.fill,
// it.page,
// ) <modified-entry>
// ]
// }
// }
heading(numbering: none)[Abbildungsverzeichnis]
outline(
title: none,
//fill: repeat([.]),
target: figure.where(kind: image)
)
//command for acronym package
//print-index()
//command for second variant
//print_acronym_listing("")
// List of tables.
pagebreak()
heading(numbering: none)[Tabellenverzeichnis]
outline(
title: none,
target: figure.where(kind: table)
)
//pagebreak()
// Main body.
set par(justify: true, leading: 1em, linebreaks: "optimized" /*first-line-indent: 2em*/)
// show par: p => {
// set par(leading: 1.15em,justify: true)
// text(p)
// v(1em)
// }
set page(numbering: "1")
counter(page).update(1)
body
// Appendix.
pagebreak()
heading(numbering: none)[Anhang A: Supplementary Material]
include("../common/appendix.typ")
pagebreak()
heading(numbering: none)[Literaturverzeichnis]
bibliography("../literature/literature.bib", title: none)//, style: "../literature/my_ieee.csl")
//Selbstständigkeitserklärung
set page(numbering: none)
heading(numbering: none)[Selbstständigkeitserklärung]
[Ich versichere, dass ich die Masterarbeit selbständig verfasst und keine anderen als die angegebenen Quellen und Hilfsmittel benutzt habe.]
v(3cm)
table(
stroke: none,
inset: 0pt,
row-gutter: 10pt,
columns: (1fr,1fr,1fr),
align: (x,y) => (left,center,right).at(x),
rows: 2,
line(length: 100%),
[],
line(length: 100%),
[Datum, Ort],
[],
[#author]
)
}
#let apos(text) = {
[\"] + text + [\"]
}
#let mark_yellow(text) = {
box(
fill: yellow
)[#text]
}
#let mark_green(text) = {
box(
fill: green
)[#text]
}
#let mark_red(text) = {
box(
fill: red
)[#text]
}
#let placeholder(text) = {
box(
rect(
fill: yellow,
width: 100%
)[#text]
)
}
|
|
https://github.com/noahjutz/AD | https://raw.githubusercontent.com/noahjutz/AD/main/uebungen/2/psi_convergence.typ | typst | #import "@preview/cetz:0.2.2"
#cetz.canvas(length: 100%, {
import cetz.draw: *
import cetz.plot
plot.plot(
axis-style: "school-book",
x-tick-step: none,
x-ticks: (1,),
y-tick-step: none,
y-ticks: (-1, 1,),
y-min: -1,
y-max: 1,
x-min: -1,
x-label: $n$,
y-label: $psi^n$,
size: (.8, .3),
{
let n = 10
let phi = 1.6180339887
let psi = -0.6180339887
plot.add(
domain: (0, n),
x => calc.pow(1/phi, x),
style: (stroke: (paint: gray, dash: "dashed")),
)
plot.add(
domain: (0, n),
x => -calc.pow(1/phi, x),
style: (stroke: (paint: gray, dash: "dashed")),
)
let values = range(n).map(x => (x, calc.pow(psi, x)))
plot.add(
values,
style: (stroke: none),
mark: "o",
mark-size: 6pt,
mark-style: (stroke: none, fill: black)
)
})
}) |
|
https://github.com/floriandejonckheere/utu-thesis | https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/chapters/09-conclusion.typ | typst | #import "@preview/acrostiche:0.3.1": *
= Conclusion <conclusion>
This thesis discussed the problem of (semi-)automated modularization of monolith applications, with a focus on the automated identification of microservice candidates.
In the first part of the thesis, we investigated the modular monolith architecture, and discussed the advantages and drawbacks of the software architecture.
Then, we presented a comprehensive overview of the state of the art on (semi-)automated technologies for modularization of monolith applications.
We identified and described the most frequently used approaches in the literature, and compared them against each other.
In the third part, we presented our solution for the automated identification of microservice candidates in monolith codebases, based on the findings of our systematic literature review.
We comprehensively described the architecture of our tool, and discussed the technical implementation details.
Finally, we evaluated the effectiveness of our solution using a case study on a real-world monolith application.
We concluded that our solution is able to meet the requirements we set for it, and that it generates a decomposition of suitable quality.
The tool is flexible in use, and can be easily extended to support other programming languages, and clustering algorithms.
#pagebreak()
== Future considerations
The research field of (semi-)automated modularization of monolith applications is still developing, and there are many opportunities for improvements.
In recent years, there has been a pickup in the number of publications on this topic, and we expect to see more research papers published in the near future.
There are several areas where we see potential for improvement in our proposed solution.
As many experts have already pointed out, the information extracted from the codebase can be improved by using additional techniques.
For example, the structural coupling can be improved by dynamically collecting information during the runtime of the application, as static analysis is very limited in highly dynamic languages such as Ruby and Python.
Furthermore, enhancing the extracted information with additional object-oriented relationships (e.g. inheritance and composition) can improve the accuracy of the microservice candidate identification algorithm.
Alternatively, supplementary heuristics, such as semantic coupling, can be utilized as well.
A case can be made for considering alternative microservice candidate identification algorithms as well, such as clustering algorithms that work top-down instead of the bottom-up approach we opted for in our solution.
Finally, the MOSAIK tool can be improved technically.
For instance, rewriting critical parts of the identification algorithm in another, more performant language could yield large gains in runtime performance.
Moreover, the tool can be extended to support more programming languages, as the current implementation only supports Ruby.
|
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2006/WS-02.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (1 - 32)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[1], [ZHANG Yining], [CHN], [2983],
[2], [GUO Yue], [CHN], [2698],
[3], [GUO Yan], [CHN], [2641],
[4], [NIU Jianfeng], [CHN], [2554],
[5], [LI Xiaoxia], [CHN], [2527],
[6], [CAO Zhen], [CHN], [2496],
[7], [WANG Nan], [CHN], [2486],
[8], [TIE Yana], [HKG], [2468],
[9], [FUKUHARA Ai], [JPN], [2448],
[10], [LI Jiawei], [SGP], [2436],
[11], [BOROS Tamara], [CRO], [2417],
[12], [KIM Kyungah], [KOR], [2391],
[13], [GAO Jun], [USA], [2375],
[14], [MOON Hyunjung], [KOR], [2366],
[15], [FAN Ying], [CHN], [2361],
[16], [CHANG Chenchen], [CHN], [2361],
[17], [TOTH Krisztina], [HUN], [2358],
[18], [LIN Ling], [HKG], [2346],
[19], [#text(gray, "KIM Hyang Mi")], [PRK], [2346],
[20], [WANG Yuegu], [SGP], [2314],
[21], [LEE Eunhee], [KOR], [2281],
[22], [#text(gray, "BAI Yang")], [CHN], [2279],
[23], [<NAME>], [ROU], [2263],
[24], [PAVLOVICH Viktoria], [BLR], [2249],
[25], [LIU Shiwen], [CHN], [2245],
[26], [JEON Hyekyung], [KOR], [2242],
[27], [<NAME>], [RUS], [2234],
[28], [<NAME>], [GER], [2233],
[29], [FUJII Hiroko], [JPN], [2216],
[30], [SUN Beibei], [SGP], [2208],
[31], [KIM Bokrae], [KOR], [2194],
[32], [LI Jiao], [NED], [2191],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (33 - 64)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[33], [SONG Ah Sim], [HKG], [2190],
[34], [LEE Eunsil], [KOR], [2186],
[35], [LI Nan], [CHN], [2186],
[36], [SCHALL Elke], [GER], [2184],
[37], [LAU Sui Fei], [HKG], [2181],
[38], [LIU Jia], [AUT], [2177],
[39], [SHEN Yanfei], [ESP], [2147],
[40], [STEFANOVA Nikoleta], [ITA], [2143],
[41], [ZHANG Rui], [HKG], [2142],
[42], [TAN Wenling], [ITA], [2141],
[43], [PENG Luyang], [CHN], [2139],
[44], [FUJINUMA Ai], [JPN], [2133],
[45], [HIRANO Sayaka], [JPN], [2126],
[46], [ZAMFIR Adriana], [ROU], [2125],
[47], [UMEMURA Aya], [JPN], [2122],
[48], [POTA Georgina], [HUN], [2090],
[49], [ZHANG Xueling], [SGP], [2090],
[50], [KIM Mi Yong], [PRK], [2084],
[51], [KWAK Bangbang], [KOR], [2081],
[52], [WU Xue], [DOM], [2079],
[53], [LAY Jian Fang], [AUS], [2076],
[54], [JIANG Huajun], [HKG], [2072],
[55], [HIURA Reiko], [JPN], [2065],
[56], [DING Ning], [CHN], [2063],
[57], [SCHOPP Jie], [GER], [2058],
[58], [STRBIKOVA Renata], [CZE], [2053],
[59], [LANG Kristin], [GER], [2052],
[60], [ODOROVA Eva], [SVK], [2050],
[61], [PAVLOVICH Veronika], [BLR], [2047],
[62], [RAMIREZ Sara], [ESP], [2039],
[63], [PARK Miyoung], [KOR], [2038],
[64], [TASEI Mikie], [JPN], [2027],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (65 - 96)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[65], [KOTIKHINA Irina], [RUS], [2023],
[66], [<NAME>], [GER], [2017],
[67], [<NAME>], [NZL], [2015],
[68], [<NAME>], [CHN], [2015],
[69], [<NAME>], [JPN], [2009],
[70], [KONISHI An], [JPN], [2006],
[71], [<NAME>], [KOR], [2003],
[72], [<NAME>], [KOR], [2001],
[73], [<NAME>], [HUN], [2000],
[74], [#text(gray, "<NAME>")], [HUN], [1998],
[75], [<NAME>], [THA], [1997],
[76], [PASKAUSKIENE Ruta], [LTU], [1994],
[77], [ONO Shiho], [JPN], [1992],
[78], [XU Jie], [POL], [1980],
[79], [<NAME>], [GER], [1978],
[80], [BOLLMEIER Nadine], [GER], [1977],
[81], [BADESCU Otilia], [ROU], [1969],
[82], [<NAME>], [ISR], [1966],
[83], [VACENOVSKA Iveta], [CZE], [1964],
[84], [<NAME>], [SGP], [1960],
[85], [HUANG Yi-Hua], [TPE], [1955],
[86], [<NAME>], [GER], [1952],
[87], [<NAME>], [CRO], [1951],
[88], [#text(gray, "<NAME>")], [HUN], [1947],
[89], [<NAME>], [HUN], [1944],
[90], [LU Yun-Feng], [TPE], [1943],
[91], [<NAME>], [RUS], [1943],
[92], [KIM Soongsil], [KOR], [1940],
[93], [<NAME>], [GER], [1937],
[94], [<NAME>], [GER], [1937],
[95], [<NAME>], [AUT], [1934],
[96], [<NAME>], [SRB], [1929],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (97 - 128)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[97], [LI Bin], [HUN], [1925],
[98], [PAN Chun-Chu], [TPE], [1923],
[99], [MUANGSUK Anisara], [THA], [1922],
[100], [<NAME>], [SWE], [1922],
[101], [ISHIGAKI Yuka], [JPN], [1917],
[102], [DOBESOVA Jana], [CZE], [1916],
[103], [KISHIDA Satoko], [JPN], [1908],
[104], [WATANABE Yuko], [JPN], [1907],
[105], [KO Un Gyong], [PRK], [1907],
[106], [<NAME>], [ROU], [1907],
[107], [<NAME>], [ROU], [1905],
[108], [KIM Junghyun], [KOR], [1903],
[109], [NEGRISOLI Laura], [ITA], [1901],
[110], [<NAME>], [ESP], [1901],
[111], [GRUNDISCH Carole], [FRA], [1900],
[112], [XU Yan], [SGP], [1898],
[113], [FUKUOKA Haruna], [JPN], [1894],
[114], [LOVAS Petra], [HUN], [1889],
[115], [NEMES Olga], [ROU], [1889],
[116], [KO Somi], [KOR], [1888],
[117], [MIROU Maria], [GRE], [1887],
[118], [FADEEVA Oxana], [RUS], [1886],
[119], [KIM Hyehyun], [KOR], [1884],
[120], [TERUI Moemi], [JPN], [1883],
[121], [WU Jiaduo], [GER], [1881],
[122], [ERDELJI Anamaria], [SRB], [1879],
[123], [ETSUZAKI Ayumi], [JPN], [1877],
[124], [<NAME>], [FRA], [1877],
[125], [<NAME>], [CRO], [1876],
[126], [<NAME>], [AUS], [1876],
[127], [<NAME>], [LUX], [1871],
[128], [<NAME>], [KOR], [1866],
)
) |
|
https://github.com/lyzynec/hys-or-kys | https://raw.githubusercontent.com/lyzynec/hys-or-kys/main/03/main.typ | typst | #import "../lib.typ": *
#knowledge[
#question(name: [Characterize the (max,+) algebra as a set: what are its
elements?])[]
#question(name: [Define the two key operations of (max,+) algebra. Do it both for scalars and for matrices.])[]
#question(name: [Write down a general (max,+) linear (also MPL)
discrete--event system.])[]
]
#skills[
#question(name: [Formulate a simple queueing problem as an optimal control
problem for an MPL system.])[]
#question(name: [Solve a simple optimal control problem for an MPL
system.])[]
] |
|
https://github.com/EricWay1024/Scientific-Computation-Notes | https://raw.githubusercontent.com/EricWay1024/Scientific-Computation-Notes/master/README.md | markdown | # Notes for MATH3036 _Scientific Computation and Numerical Analysis_
This document serves as an unofficial companion for the module MATH3036, _Scientific Computation and Numerical Analysis_, at the University of Nottingham. The material presented here is based on the available lecture slides from the academic year 2022-23. It is important to note that there might be slight variations in notation and the order of topics covered. As the course evolves, the content itself may also undergo changes at the instructor's discretion in subsequent academic years. Please be aware that this current version is provided with the caveat that it may contain typos, errors or inaccuracies. Your valuable contributions to enhance this resource are greatly appreciated. Feel free to get in touch by [email](mailto:<EMAIL>) or by submitting an issue or pull request on this repo.
## Download the latest PDF
Please go to [release](https://github.com/EricWay1024/Scientific-Computation-Notes/releases) and find the PDF file under assets of the lastest version.
## Contribute to the repo
Clone the repo with `git`:
```
git clone https://github.com/EricWay1024/Scientific-Computation-Notes.git
```
To compile the `typst` source code to PDF, please install `typst` as described [here](https://github.com/typst/typst). Then run
```bash
typst watch main.typ main.pdf
```
## Based on
- [`typst`](https://typst.app/docs/)
- [`typst-algorithms`](https://github.com/platformer/typst-algorithms)
- [`typst-theorems`](https://github.com/sahasatvik/typst-theorems) |
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/par.typ | typst | Apache License 2.0 | // Test configuring paragraph properties.
---
// Test ragged-left.
#set align(right)
To the right! Where the sunlight peeks behind the mountain.
---
// Test changing leading and spacing.
#set block(spacing: 1em)
#set par(leading: 2pt)
But, soft! what light through yonder window breaks?
It is the east, and Juliet is the sun.
---
// Test that paragraph spacing loses against block spacing.
// TODO
#set block(spacing: 100pt)
#show table: set block(above: 5pt, below: 5pt)
Hello
#table(columns: 4, fill: (x, y) => if calc.odd(x + y) { silver })[A][B][C][D]
---
// While we're at it, test the larger block spacing wins.
#set block(spacing: 0pt)
#show raw: set block(spacing: 15pt)
#show list: set block(spacing: 2.5pt)
```rust
fn main() {}
```
- List
Paragraph
|
https://github.com/Mouwrice/thesis-typst | https://raw.githubusercontent.com/Mouwrice/thesis-typst/main/measurements/measurement_methods.typ | typst | #import "../lib.typ": *
== Methods
To be able to get indications of the accuracy of MediaPipe Pose, a baseline, or base "truth", needed to be established. Using the aforementioned Qualisys MoCap setup at ASIL we can track marker locations at sub-millimetre accuracy, which are then taken as ground truth.
=== Measurement Setup <measurement-setup>
The setup is configured to be in line with the expected environment the drum application will be used in. Being, a single person sat on a chair facing a webcam, performing drumming motions. The person performing the movements has infrared reflective trackers positioned on the body as close as possible to where the MediaPipe Pose landmarks are located. This setup is shown in @front-still.
#figure(image("../images/front_still.png"), caption: [A frame from the camera recording showing the measurement setup.]) <front-still>
The Qualisys Motion Capture setup first requires a calibration step, after which markers can be tracked with a precision of up to 0.3 mm. In later measurements, the accuracy has dropped to 0.8 mm, which can be attributed to calibrating a larger volume of space. For our use case, this level of accuracy is still sufficient. As we will see, the MediaPipe accuracy will not get close to an accuracy of 0.8 mm, so the Qualisys accuracy is more than sufficient.
After applying the reflective markers, motion capture can easily be performed using the Qualisys Track Manager (QTM) program #footnote()[#link("https://www.qualisys.com/software/qualisys-track-manager/")[https://www.qualisys.com/software/qualisys-track-manager/ #link-icon]]. After having labeled each marker and trajectory, these can be exported to a TSV (tab separated values) file @tsv.
One such a file looks like the snippet below, @tsv-snippet. First, some context is provided on the measurement. After the listing of the marker names and their trajectory types, follows the actual trajectory. Every line in the file then describes the 3D position of every marker per frame. Every three floating point numbers are the x, y and z coordinates of a given marker, in the same order as they are listed.
#figure(caption: [A snippet of what a TSV output from a Qualisys tracked measurement looks like.])[
```tsv
NO_OF_FRAMES 6916
NO_OF_CAMERAS 13
NO_OF_MARKERS 10
FREQUENCY 120
NO_OF_ANALOG 0
ANALOG_FREQUENCY 0
DESCRIPTION --
TIME_STAMP 2024-04-15, 10:39:38.777 406646.66137317
DATA_INCLUDED 3D
MARKER_NAMES Wrist_L Hip_L Foot_Index_L
TRAJECTORY_TYPES Measured Measured Measured
-473.521 191.980 613.382 -677.077 164.814 615.497 -138.493 187.190 53.579
-473.564 192.348 613.040 -677.061 164.822 615.494 -138.494 187.229 53.555
-473.646 192.696 612.779 -677.045 164.794 615.445 -138.465 187.193 53.464
-473.683 192.890 612.513 -676.988 164.782 615.436 -138.448 187.252 53.482
```
] <tsv-snippet>
The video recordings are captured with a regular webcam with a maximum resolution of 1080p and a frame rate of 30 frames per second. The camera placement needs to be in line with the forward facing axis of the Qualisys captures to reduce any deviations introduced by being off-axis.
Afterward, the videos get processed frame by frame with MediaPipe, using the _VIDEO_ running mode #footnote()[#link("https://developers.google.com/mediapipe/solutions/vision/pose_landmarker/python#video")[https://developers.google.com/mediapipe/solutions/vision/pose_landmarker/python#video #link-icon]]. The video mode is an offline processing mode, meaning that no frames will be dropped to satisfy a live stream constraint. This mode allows us to measure models that we otherwise would not be able to run at a constant 30 frames per second.
The result of every processed frame is then written to a CSV file. Every line in the file contains all the known information of one marker at the given frame. Resulting in the following format, displayed in @csv-snippet: _frame number_, _time_ (in milliseconds), _index_ (of the marker), _x_, _y_, _z_, _visibility_, _presence_, _landmark_type_ (either 0 to indicate a `Landmark`, or a 1 to indicate a `WorldLandmark`).
#figure(caption: [A snippet of the CSV output taken from MediaPipe processed frames. Lines are truncated.])[
```csv
frame,time,index,x,y,z,visibility,presence,landmark_type
2,53,0,0.4807698130607605,0.22160261869430542,-0.360921174287796,0.9999996423721313,0.9999953508377075,0
2,53,1,0.4906315207481384,0.20818790793418884,-0.33244213461875916,0.9999991655349731,0.9999819993972778,0
2,53,2,0.4961097836494446,0.2083108127117157,-0.33247220516204834,0.999998927116394,0.9999785423278809,0
2,53,3,0.49966344237327576,0.20876441895961761,-0.33247825503349304,0.9999988079071045,0.9999737739562988,0
2,53,4,0.4742940366268158,0.2077968716621399,-0.3331023156642914,0.999998927116394,0.9999858140945435,0
2,53,5,0.4689987897872925,0.2078893780708313,-0.3331734538078308,0.999998927116394,0.9999849796295166,0
2,53,6,0.4639938175678253,0.20820003747940063,-0.3331492245197296,0.9999990463256836,0.9999834299087524,0
2,53,7,0.5079091787338257,0.21490448713302612,-0.17037953436374664,0.9999978542327881,0.9999762773513794,0
2,53,8,0.46058356761932373,0.21451136469841003,-0.17510229349136353,0.9999986886978149,0.9999876022338867,0
2,53,9,0.49152788519859314,0.23765860497951508,-0.30100592970848083,0.9999997615814209,0.9999942779541016,0
```
] <csv-snippet>
=== Deviation from one time series to another <comparing-time-series>
Before describing how the outputs from the previous section are used to come up with accuracy measurements, a brief overview of how deviation from one time series to another is derived, is needed. We want to compare the trajectories from the Qualisys capture with that of the MediaPipe captures. These trajectories consist of discrete-time points. As the frame rate of both systems differ, the discrete-time points are unaligned.
@unaligned-time-series provides a visual representation of the problem. We have two time series to compare. Series $f$ in red and series $g$ in blue. Due to these points having a different frequency and unaligned time stamps, it is not possible to compare these just by iterating over both series at the same time. Where an iteration corresponds to jumping to the next point in time in both series.
#figure(caption: [Example of unaligned time series, the horizontal axis being time, the vertical axis would be some value])[
#image(width: 100%, "../images/time_series_unaligned.png")
] <unaligned-time-series>
One option would be to "walk" over the series based on the time difference between points.
The walk starts by selecting the first point of each series, $A$ and $K$ in this example.
Then there are three options:
+ Only jump to the next point in the first series
+ Only jump to the next point in the second series
+ Jump to the next point in both series
The option that minimizes the time difference between the selected points is chosen. This method ensures that every point in both series is taken into account. The pairs of points that would be selected by this technique is displayed in @time-series-unaligned-compare-all by the dotted lines. The measured difference between both signals is then the sum of the length of all dotted lines (the difference between point pairs) divided by the amount of dotted lines (pairs).
#figure(caption: [Point pairs selected by walking over both series indicated by the dotted lines.])[
#image(width: 100%, "../images/time_series_unaligned_compare_all.png")
] <time-series-unaligned-compare-all>
However, it is clear to see that this method will result in a higher deviation when comparing a high frequency signal against a lower frequency signal. Which is the case in our measurements. A high frequency Qualisys measurement (100Hz or more) is compared against a lower frequency MediaPipe measurement (30Hz). Because we know these differences in frequency, we are not interested in a difference method that takes these into account. The goal of the measurements is to find the average deviation of a point generated by MediaPipe with that of the corresponding point generated by the Qualisys capture. The following new method achieves that goal.
Instead of comparing every point in both series, a dominant series is selected. This simple method iterates over the dominant series and for each point in the dominant series finds the corresponding point in the other series. The corresponding point being the point with the timestamp closest to that of the dominant point. Adapting the behavior of the "walk" to accommodate this idea of having a dominant time series, would result in the following procedure:\
For each point in the dominant time series, walk over the points of the other series until the difference in time stamps with the dominant point no longer decreases. Then we have found a new pair. Results of this procedure are displayed in @time-series-unaligned-compare-dominant.
#figure(caption: [Point pairs selected by iterating over the dominant series ($g$, blue) and walking over the other ($f$, red), indicated by the dotted lines.])[
#image(width: 100%, "../images/time_series_unaligned_compare_base.png")
] <time-series-unaligned-compare-dominant>
With this method, we have that the irrelevant points are no longer included in the measurements. Yet this does not mean that the points that are now taken into account are perfectly aligned with one another. However, due to the high frequency of the Qualisys captures, we note that the time difference will be relatively small, and thus the difference induced by this nonalignment will be quite small. For a Qualisys capture with a frame rate of 120Hz, there is a frame every $(1000 "ms") / (120 "Hz") = 8.33... $ milliseconds. In the worst case, the MediaPipe point lies exactly between two Qualisys frames, resulting in a maximum time difference of only 4.166... milliseconds.
=== Metrics <metrics>
Two simple metrics can now be computed having found a way to get point pairs.
A first one is the average offset of one signal to another. By simply taking the average difference of each point pair. A second and very similar metric is the average deviation. It denotes how much a signal deviates from another one. Instead of taking the regular difference of a point pair, the absolute difference is taken. This is an important distinction. The average offset is simply a metric that tells us how far a signal is from another. The average deviation, however, can be interpreted as the accuracy with which a signal approximates another signal. So when the Qualisys signal is seen as the base truth and the MediaPipe signal is seen as an approximation of that base truth, we have an accuracy measure for the MediaPipe signal!
Another important metric is the signal stability. For instance, if the MediaPipe signal is very stable, but has a high average deviation, it is still a good approximation of the Qualisys signal. This is because the MediaPipe signal is consistently off by the same amount. This is an essential metric for interactive applications. If the signal is not stable, the application will not be able to provide a consistent experience to the user. The stability of a signal can be measured by the standard deviation of the deviation. A low standard deviation means that the signal is stable, a high standard deviation means that the signal is not stable. Another way to measure the stability of a signal is by taking the differences in deviation between consecutive points. A stable signal should have a low difference in deviation between consecutive points. It is important to note that the stability of a signal is not the same as the accuracy of a signal. A signal can be very stable but not accurate, and vice versa.
After this slight detour, follow the methods used to align the MediaPipe results to the Qualisys captures.
=== Aligning MediaPipe to Qualisys
Using the setup described in @measurement-setup we have two time series that can be compared using the method from the previous section. However, before that is possible there is still one major issue that needs to be solved. The points from the MediaPipe result originate from a totally different axis and origin point. The Qualisys captures have their origin point calibrated on the floor, with the x-axis being the forward facing axis, the y-axis the horizontal axis and the z-axis the vertical axis.
The MediaPipe Landmarks, on the other hand, do not actually correspond with a point in space but rather with a point in the video frame and an associated depth. For the `Landmark` markers the origin point in this MediaPipe case is the left corner of the video frame. The x-axis is the horizontal axis along the frame, the y-axis is the vertical axis along the frame, and the z-axis is the depth from the camera.
MediaPipe also has a different kind of Landmarks (`Landmark`), namely the World Landmarks (`WorldLandmark`). These try to map the regular Landmarks, which are a point in the video frame, to a point in space. With the center of the hips taken as origin. The axis remain the same but are scaled so that the `WorldLandmarks` are in line with the actual size of movement in the space.
This section gives a complete overview on how the MediaPipe signal has been aligned to match the Qualisys signal and provide a proper measurement on accuracy.
The entire section uses a measurement of the vertical position of the left wrist marker, taken from MediaPipe using regular `Landmarks` and the `FULL` model. A high level overview of all the alignment steps are shown in @alignment-chart.
#figure(
caption: [The entire alignment process of the MediaPipe signal to the Qualisys signal.],
placement: none)[
#image(width: 100%, "../images/alignment_chart.svg")
] <alignment-chart>
==== Axis Rearrangement
The output from the recordings are time series that can be plotted. The output from the measurements is read and without any processing plotted to a line plot in @left_wrist_axis_z_positions_base. On the horizontal axis is time in seconds. On the vertical axis is the value of the point in time in millimeter. @left_wrist_axis_z_positions_base shows a clear mismatch in axis. Plotted is the z-axis from both capture systems. But as mentioned, in MediaPipe the z-axis is the depth and not the vertical axis.
#figure(caption: [Plot of the MediaPipe (Blue) and Qualisys (Red) left wrist z-axis without processing.])[
#image(width: 100%, "../images/left_wrist_axis_z_positions_base.svg")
] <left_wrist_axis_z_positions_base>
The problem of mismatched axes is a very simple one to solve. Before plotting the MediaPipe signal we switch the axis so they match with the actual direction of axis in the Qualisys recording. The MediaPipe axes are thus mapped as follows:
- $ x -> y $
- $ y -> z $
- $ z -> x $
As can be seen in @left_wrist_axis_z_positions_apply_axis_transformations, we now have plotted the proper vertical axis. One might have noted the pretty nonsensical values of the MediaPipe signal. For one, they are negative. Whereas moving up corresponds to an increase in value with the Qualisys captures, the inverse is true for the MediaPipe results. This requires us to re-invert the vertical values during analysis, resulting in negative values.
Normally `Landmark` values would be in the range [0, 1], 0 being one side of the video frame, 1 the other side. But these values are inverted by multiplying by -1 resulting in a new range of [0, -1]. Because this inverting method should also work for `WorldLandmarks` which have no predefined range of values it is not possible to invert the values using the following method: $x => 1- x$.
Secondly, all MediaPipe values have been multiplied by 1000. As the Qualisys output is in millimeter we already prepare the MediaPipe signal by interpreting the incoming signal as meter and converting it to millimeter. The MediaPipe `Landmark` signal has no real unit of course but interpreting it as meters allows for a simpler interpretation when it comes to scaling, explained later in this section.
#figure(caption: [Plot of MediaPipe (Blue) and Qualisys (Red) left wrist z-axis after re-arranging the MediaPipe axes.])[
#image(width: 100%, "../images/left_wrist_axis_z_positions_apply_axis_transformations.svg")
] <left_wrist_axis_z_positions_apply_axis_transformations>
==== Removing Average Offset and Time Offset
Now that the basics are out of the way, we can start aligning the signal. A first step is removing the average offset from the MediaPipe signal to the Qualisys signal. The method of walking over the dominant series (MediaPipe in this case) and gathering pairs of points from both series as discussed in the previous section, @comparing-time-series, is used for this. For every pair of points, we can simply take the difference between those points. The average of these differences is then the offset of the MediaPipe signal. The result of removing this offset from the MediaPipe signal is displayed in @left_wrist_axis_z_positions_remove_offset.
#figure(caption: [Plot of the MediaPipe (Blue) and Qualisys (Red) left wrist z-axis with the average offset removed.])[
#image(width: 100%, "../images/left_wrist_axis_z_positions_remove_offset.svg")
] <left_wrist_axis_z_positions_remove_offset>
With the two signals close together, another problem becomes apparent. They are offset in time. This makes sense, as both measurements cannot easily be started at exactly the same time. We need to introduce a starting offset. This starting offset should minimize the deviation between both signals. This is achieved by iteratively increasing a starting offset and capturing the offset that resulted in the least deviation. In @left_wrist_axis_z_positions_frame_offset, it is shown that this method finds the most perfect offset. Both signals are perfectly aligned in time. After this offset operation, the average vertical offset is computed again and subtracted from the signal.
#figure(caption: [Plot of the MediaPipe (Blue) and Qualisys (Red) left wrist z-axis with the time offset removed.])[
#image(width: 100%, "../images/left_wrist_axis_z_positions_frame_offset.svg")
] <left_wrist_axis_z_positions_frame_offset>
==== Scaling
The final and most intricate part of the alignment is getting the scaling right. As we can see in the previous plots, the scale of the signal is not at all correct. Here, a scaling factor needs to be found that minimizes the deviation. There is one caveat, we cannot simply scale the signal by multiplying it with a given factor. This would scale the signal away from the origin point. One can see that, in fact, we should "stretch" the signal vertically to make it align. In other words, the signal needs to be scaled around the center point of the signal that it is being aligned to.
The center point of the signal is easily calculated as the average of the signal's values.
The stretching of the signal then goes as follows: For every original point of the signal, take the difference between that point and the center point of the other signal. Scale the difference by the scaling factor. The new stretched point is now the center point plus the scaled difference.
The previous method of finding the optimal time offset is a simple one. Since it is a discrete problem, the optimal value can easily be found by testing all possible values.
The optimal scale, however, is not a discrete value. To find the optimal scaling factor, we need an optimization algorithm.
The optimization problem at hand can be solved using Golden-section search @golden-section-search.
#footnote[During the measurement we found that the depth axis, the X axis, is so inaccurate that it is not possible to use the described method to align the signals. The golden section search would converge to a scaling factor of 0, which minimizes the deviation. This is not a useful result. This is why the depth axis always has a fixed scale of 0.5 applied to it. It is a value that was found to produce the best alignment in the measurements.]
It is a technique for finding an extremum (minimum or maximum) of a function inside a specified interval @golden-section-search-wiki. In our case, the function is the deviation function that takes as input the scale factor and outputs the deviation after applying the scale. The algorithm converges to one extremum by narrowing down an interval of possible values. Without going into too much detail on the algorithm and its implementation, the algorithm is initialized to search within a range of [0, 10] as possible scale factors and stops when the improvements in deviation fall below 0.01 mm.
Applying the Golden-section search method on our running example returns a scale factor of around 2 and results in a nice alignment between both signals (@left_wrist_axis_z_positions_stretch). The factor of 2 also makes sense. In the `Landmark` mode, the range of values lie between 0 and 1, reaching these outer values at the edges of the frame. As mentioned, the `Landmark` signal is interpreted to be in meter. As a consequence, the scaling factor is not only a scaling factor, it has become a measurement of the dimensions of what is visible in the frame. This means that the visible height in the video frame is 2 meters, at the location of the test subject, of course.
#figure(caption: [Plot of the MediaPipe (Blue) and Qualisys (Red) left wrist z-axis with the MediaPipe signal scaled to match.])[
#image(width: 100%, "../images/left_wrist_axis_z_positions_stretch.svg")
] <left_wrist_axis_z_positions_stretch>
|
|
https://github.com/Myriad-Dreamin/shiroa | https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/packages/shiroa/templates.typ | typst | Apache License 2.0 | #import "template-link.typ": *
#import "template-theme.typ": * |
https://github.com/SnowManKeepsOnForgeting/NoteofModernControlTheory | https://raw.githubusercontent.com/SnowManKeepsOnForgeting/NoteofModernControlTheory/main/Homework/Homework_2.typ | typst | #import "@preview/physica:0.9.3": *
#import "@preview/i-figured:0.2.4"
+ Given differential equations of system,try to write down their state space representation.
(1) $accent(y,dot.triple) + accent(y,dot.double) + 4 accent(y,dot) + 5 y = 3 u$
(2) $2 accent(y,dot.triple) + 3 accent(y,dot) = accent(u,dot.double) - u$
Solution:(1)let us choose $x_1=y,x_2=accent(y,dot),x_3=accent(y,dot.double)$ as state variables.We have state equations:
$
cases(
accent(x_1,dot) = x_2\
accent(x_2,dot) = x_3\
accent(x_3,dot) = -5 x_1 - 3 x_2 - 2 x_3 + 7 u
)
$
And output equation:
$
y = x_1
$
(2)Let $2 accent(y,tilde)^((3)) + 3 accent(y,tilde)^((1)) = u$
We have:
$
y = accent(y,tilde)^((2)) - accent(y,tilde)^((1))
$
Let us choose $x_1 = accent(y,tilde),x_2 = accent(y,tilde)^((1)),x_3 = accent(y,tilde)^((2))$
We have state equations:
$
cases(
accent(x,dot)_1 = x_2\
accent(x,dot)_2 = x_3\
accent(x,dot)_3 = -3/2 x_2 + 1/2 u
)
$
And output equation:
$
y = x_3 - x_2
$
+ Given transfer function of system.try to establish its state space representation.
(1)$g(s) = (s^3+s+1)/(s^3+6 s^2 + 11s + 6)$
Solution:
$
g(s) = (s^3+s+1)/(s^3+6 s^2 + 11s + 6) = 1 + (-6s^2 -10s -5)/(s^3+6 s^2 + 11s + 6)
$
Let $h(s) = (-6s^2 -10s -5)/(s^3+6 s^2 + 11s + 6)$
Introduce intermediate variable $Z(s)$
$
h(s) = Y(s)/Z(s) Z(s)/U(s) = (-6s^2 -10s -5)/1 1/(s^3+6 s^2 + 11s + 6)
$
Thus we have:
$
cases(
y = -6z^((2)) - 10 z^((1)) - 5 z \
z^((3)) + 6 z^((2)) + 11 z^((1)) + 6z= u
)
$
Let us choose $x_1 = z,x_2 = z^((1)),x_3 = z^((2))$
We have state equations:
$
cases(
accent(x,dot)_1 = x_2\
accent(x,dot)_2 = x_3\
accent(x,dot)_3 = -6 x_3 -11 x_2 - 6x_1 + u
)
$
And output equation:
$
y = -6 x_3 - 10 x_2 - 5 x_1 + u
$
+ Try to transform the state matrix into diagonal canonical form.
(1)$vec(delim: "[",accent(x,dot)_1,accent(x,dot)_2) = mat(delim: "[",0,1;-5,-6) vec(delim: "[",x_1,x_2) + vec(delim: "[",0,1)u$
Solution:
Let $bold(A) = mat(delim: "[",0,1;-5,-6)$ and $bold(B) = vec(delim: "[",0,1)$
Let us find the eigenvalues vectors of $bold(A)$
$
|lambda bold(I) - bold(A)| = mat(delim: "|",lambda,-1;5,lambda+6) = lambda^2 + 6 lambda + 5 = 0\
lambda_1 = -1,lambda_2 = -5
$
Let
$
(-bold(I) - bold(A)) bold(v_1) = mat(delim: "[",-1,-1;5,5)bold(v_1) = 0\
(-5bold(I)-bold(A)) bold(v_2) = mat(delim: "[",-5,-1;5,1)bold(v_2) = 0
$
Take the basic solution$bold(v_1) = vec(delim: "[",1,-1),bold(v_2) = vec(delim: "[",1,-5)$
Thus we have transformation matrix
$
bold(P) = mat(delim: "[",1,1;-1,-5) "and" bold(P)^(-1) = mat(delim: "[",5/4,1/4;-1/4,-1/4)
$
So we have:
$
accent(bold(A),macron) = bold(P)^(-1) bold(A) bold(P) = mat(delim: "[",-1,0;0,-5)\
accent(bold(B),macron) = bold(P)^(-1) bold(B) = vec(delim: "[",1/4,-1/4)
$
Thus the diagonal canonical form is:
$
accent(accent(bold(x),macron),dot) = mat(delim: "[",-1,0;0,-5)accent(bold(x),macron) + vec(delim: "[",1/4,-1/4)u
$
+ Try to transform the state matrix into Jordan canonical form.
(1)$vec(delim: "[",accent(x,dot)_1,accent(x,dot)_2,accent(x,dot)_3) = mat(delim: "[",4,1,-2;1,0,2;1,-1,3) vec(delim: "[",x_1,x_2,x_3) + mat(delim: "[",3,1;2,7;5,3) vec(delim: "[",u_1,u_2)$
Solution:Let $bold(A) = mat(delim: "[",4,1,-2;1,0,2;1,-1,3)$ and $bold(B) = mat(delim: "[",3,1;2,7;5,3)$
Let us find the eigenvalues vectors of $bold(A)$
$
|lambda bold(I) - bold(A)| = mat(delim: "|",lambda-4,-1,2;-1,lambda,-2;-1,1,lambda-3) = lambda^3 - 7 lambda^2 + 15 lambda - 9 = 0\
lambda_1 = 1,lambda_2 = 3,lambda_3 = 3
$
Let
$
|bold(I) - bold(A)| bold(v)= mat(delim: "[",-3,-1,2;
-1,1,-2;-1,1,-2) bold(v) = 0\
bold(v_1) = vec(delim: "[",0,2,1)\
|3 bold(I) - bold(A)| bold(v_1) = mat(delim: "[",-1,-1,2;-1,3,-2;-1,1,0) bold(v) = 0\
bold(v_2) = vec(delim: "[",1,1,1)\
$
Let
$
|3 bold(I) - bold(A)| bold(v_3) = mat(delim: "[",-1,-1,2;-1,3,-2;-1,1,0) bold(v_3) = -bold(v_2) = vec(delim: "[",-1,-1,-1)\
bold(v_3) = vec(delim: "[",1,0,0)
$
Thus we have transformation matrix:
$
bold(P) = mat(delim: "[",0,1,1;2,1,0;1,1,0) "and" bold(P)^(-1) = mat(delim: "[",0,1,-1;0,-1,2;1,1,-2)
$
So we have:
$
accent(bold(A),macron) = bold(P)^(-1) bold(A) bold(P) = mat(delim: "[",1,0,0;0,3,1;0,0,3)\
accent(bold(B),macron) = bold(P)^(-1) bold(B) = mat(delim: "[",-3,4;8,-1;15,14)
$
Thus the Jordan canonical form is:
$
accent(accent(bold(x),macron),dot) = mat(delim: "[",1,0,0;0,3,1;0,0,3)accent(bold(x),macron) + mat(delim: "[",-3,4;8,-1;15,14)vec(delim: "[",u_1,u_2)
$
+ Let the forward path transfer function matrix and the feedback path transfer function matrix of the system be matrix below. Find the closed-loop transfer function matrix.
$
bold(G) = mat(delim: "[",1/(s+1),-1/s;2,1/(s+2)), bold(H) = mat(delim: "[",1,0;0,1)
$
Solution:
$
bold(G)_(bold(H))(s) = (bold(I) + bold(G)(s)bold(H)(s))^(-1)bold(G)(s) = mat(delim: "[",(s+2)/(s+1) , -1/s;2,(s+3)/(s+2))^(-1) mat(delim: "[",1/(s+1),-1/s;2,1/(s+2))\
=mat(delim: "[",(s(s+1)(s+3))/((s+2)(s^2+5s+2)),(s+1)/(s^2+5s+2);(-2s(s+1))/(s^2+5s+2),(s(s+2))/(s^2+5s+2)) mat(delim: "[",1/(s+1),-1/s;2,1/(s+2))\
=mat(delim: "[",(3s^2+9s+4)/(s^2+5s+2),(-s-1)/(s^2+5s+2);(2s(s+1))/(s^2+5s+2),(3s+2)/(s^2+5s+2))\
$ |
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/raw2.typ | typst | Apache License 2.0 |
````typ
#(let a
````
== A
- a
- b
```typ
#(let a
```
|
https://github.com/ekmanib/curriculum-vitae | https://raw.githubusercontent.com/ekmanib/curriculum-vitae/main/main.typ | typst | #set page(
fill: rgb("#EFE5DC")
)
#set text(
font: "Libre Franklin",
size: 12pt
)
#include("./docs/header.typ")
#line(length: 100%, stroke: 0.5pt + rgb("a60707"))
#v(10pt)
#grid(
columns: (3fr, 1fr),
rows: (auto, auto),
gutter: 10pt,
row-gutter: 20pt,
include("./docs/education.typ"),
grid.cell(
rowspan: 2,
include("./docs/skills.typ")
),
include("./docs/experience.typ"),
)
|
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/template/theme.typ | typst | Other | #import "@preview/book:0.2.5": target
#let theme-target = if target.contains("-") {
target.split("-").at(1)
} else if "theme" in sys.inputs {
sys.inputs.theme
} else {
"light"
}
#let themes = (
light: (
kind: "light",
bg: white,
main: color.black,
link: color.rgb("#2a7ae2"),
note: color.rgb("#828282"),
raw-stroke: color.rgb("#e8e8e8"),
table-stroke: color.rgb("#ccc"),
),
rust: (
"kind": "light",
bg: color.hsl(60deg, 9%, 87%),
main: color.rgb("#262625"),
link: color.rgb("#2b79a2"),
note: color.rgb("#727272"),
raw-stroke: color.rgb("#d8d8d8"),
table-stroke: color.rgb("#bbb"),
),
coal: (
kind: "dark",
bg: color.hsl(200deg, 7%, 8%),
main: color.rgb("#98a3ad"),
link: color.rgb("#2b79a2"),
note: color.rgb("#787888"),
raw-stroke: color.rgb("#282838"),
table-stroke: color.rgb("#445"),
),
navy: (
kind: "dark",
bg: color.hsl(226deg, 23%, 11%),
main: color.rgb("bcbdd0"),
link: color.rgb("2b79a2"),
note: color.rgb("#788088"),
raw-stroke: color.rgb("#283038"),
table-stroke: color.rgb("#404850"),
),
ayu: (
kind: "dark",
bg: color.hsl(210deg, 25%, 8%),
main: color.rgb("#c5c5c5"),
link: color.rgb("#0096cf"),
note: color.rgb("#787878"),
raw-stroke: color.rgb("#282828"),
table-stroke: color.rgb("#444"),
)
)
#let theme = if theme-target in themes {
themes.at(theme-target)
} else {
panic("Unknown theme " + theme-target)
}
#let choose = (a, b) => if theme.kind == "light" { a } else { b }
#let code-highlighting = choose(none, "/syntax/tokyo-night.tmTheme")
|
https://github.com/max-niederman/CS250 | https://raw.githubusercontent.com/max-niederman/CS250/main/hw/5.typ | typst | #import "../lib.typ": *
#show: homework.with(title: "CS 250 Homework #5")
#set math.vec(delim: "[")
#set math.mat(delim: "[")
= Sets
== 1
We'll first convert the sets to a normal form for comparison:
+ ${5}$
+ ${-24, -12, -8, -6, -4, -3, -2, -1, 1, 2, 3, 4, 6, 8, 12, 24}$
+ ${1, 2, 3, 4}$
+ ${5, 8, 13}$
+ ${1, 2, 3, 4}$
+ $emptyset$
+ ${1, 2, 3, 4, 6, 8, 12, 24}$
+ ${1, 2, 3, 4}$
Two of these are duplicates,
so there are six distinct sets.
== 2
#[
#set enum(numbering: "a.")
+ $|S| = 2$
+ $|S| = 2$
+ $|S| = 1$
+ $|S| = 3$
+ $|S| = 3$
]
== 3
#[
#set enum(numbering: "a.")
+ False.
+ True.
+ False.
+ True.
+ True.
+ True.
]
== 4
#[
#set enum(numbering: "a.")
+ True.
+ True.
+ False; $emptyset in C$ but $emptyset in.not A$.
+ True.
+ True.
+ False; $A$ contains $a$, ${a}$, and ${{a}}$, but not ${a, {a}}$.
+ True.
+ False; $a in B$ but $a in.not C$.
+ True.
]
== 5
$
S = {& a, b } \
cal(P)(S) = {& emptyset, {a}, {b}, {a, b} } \
cal(P)(cal(P)(S)) = {
&emptyset, \
&{emptyset}, \
&{{a}}, \
&{emptyset, {a}}, \
&{{b}}, \
&{emptyset, {b}}, \
&{{a}, {b}}, \
&{emptyset, {a}, {b}}, \
&{{a, b}}, \
&{emptyset, {a, b}}, \
&{{a}, {a, b}}, \
&{emptyset, {a}, {a, b}}, \
&{{b}, {a, b}}, \
&{emptyset, {b}, {a, b}}, \
&{{a}, {b}, {a, b}}, \
&{emptyset, {a}, {b}, {a, b}}
}
$
= Binary and Unary Operation
== 1
#[
#set enum(numbering: "a.")
+ $ x &= 1 \ y &= 5 $
+ $ x &= 8 \ y &= 7 $
+ $
mat(
2, -1;
1, 1;
) vec(x, y) &= vec(-2, 5) \
mat(
3, 0;
1, 1;
) vec(x, y) &= vec(-2, 5) \
mat(
1, 0;
0, 1;
) vec(x, y) &= vec(-2/3, 13/3) \
x &= -2/3 \ y &= 13/3
$
]
== 2
#[
#set enum(numbering: "a.")
+ This is a binary operation on $NN$.
+ This is a binary operation on $NN$.
+ This is a binary operation on $ZZ$.
+ This is not a closed unary operation on $RR$, because $ln 0 in.not RR$.
]
== 3
#[
#set enum(numbering: "a.")
+ This is a unary operation on $ZZ$.
+ This is not a binary operation on ${1, 2, 3}$, because $3 circle.tiny 3 = 5 in.not {1, 2, 3}$.
+ This is a binary operation on $QQ$ assuming that the denominator refers to the denominator of the simplest fraction, or on $ZZ^2$ where the first element is the numerator and the second the denominator.
+ This is a binary operation on any set of ten people *with different names*.
]
== 4
#[
#set enum(numbering: "a.")
+ This is not a binary operation on $RR$ because it is undefined for $x = 0$.
+ This is a closed binary operation on ${p, q, r} ast.basic$.
+ This is a unary operation on $RR$.
+ This is a closed binary operation on $NN$.
]
== 5
#[
#set enum(numbering: "a.")
+ This is a binary operation on $NN$.
+ This is not a closed binary operation on the set of Fibonacci numbers;
$1$ and $3$ are Fibonacci numbers, but $1 circle.tiny 3 = 4$ is not.
+ This is a unary operation on ${p, q, r} ast.basic$.
+ This is not a closed binary operation on $RR - QQ$;
$sqrt(2)$ and $1 - sqrt(2)$ are in $RR - QQ$, but $sqrt(2) circle.tiny (1 - sqrt(2)) = 1 in.not RR - QQ$.
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.