repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/nathanielknight/tsot | https://raw.githubusercontent.com/nathanielknight/tsot/main/src/common_moves.typ | typst | #let introduce = [
- Introduce your character. Give them a name and two or three traits from the Character Elements sheet. Describe what they look like and how the audience should feel about them. How is this information communicated?
]
#let setting = [
- Mark a Trait on the Settings or Mission Elements Sheet. How is this detail communicated to the audience? _You can make this move again if there are fewer than four players._
]
|
|
https://github.com/seapat/markup-resume-lib | https://raw.githubusercontent.com/seapat/markup-resume-lib/main/cover_letter.typ | typst | Apache License 2.0 | // This function gets your whole document as its `body`
// and formats it as a simple letter.
#let letter(
// render_settings,
// The letter's sender, which is display at the top of the page.
sender: none,
// The letter's recipient, which is displayed close to the top.
recipient: none,
// The date, displayed to the right.
date: none,
// The subject line.
subject: none,
// The name with which the letter closes.
name: none,
ending: none, // default value set in caller (see below)
// The letter's content.
body: none,
signature_pic: none,
) = {
// Configure page
set page(margin: (top: 2cm), numbering: none)
// Display sender at top of page. If there's no sender
// add some hidden text to keep the same spacing.
text(9pt, if sender == none {
hide("a")
} else {
sender
})
v(1.8cm)
// Display recipient.
recipient
v(0.25cm)
// Display date. If there's no date add some hidden
// text to keep the same spacing.
align(right, if date != none {
date
} else {
hide("a")
})
v(0.5cm) // 2cm
// Add the subject line, if any.
if subject != none {
pad(right: 10%, strong(subject + 2 * linebreak()))
}
// Add body and name.
body
v(0.5cm)
ending
if signature_pic != none { image(signature_pic, width: auto, height: 3em) }
name
}
#let make_letter(cv_data, render_settings) = {
let today = datetime.today()
let day = today.day()
let written_number = {
if day == 1 { "st" } else if day == 2 { "nd" } else if day == 3 { "rd" } else { "th" }
}
letter(
sender: [
#let order = if "address_order" in render_settings.keys() {render_settings.address_order} else {("street", ",", "city", ",", "postalCode", ",","country")}
#cv_data.personal.name,
#for value in order {
if value in cv_data.personal.location.keys() {
str(cv_data.personal.location.at(value))
} else {
value
}
}
],
recipient: {
if "name" in cv_data.recipient.keys() { cv_data.recipient.name + linebreak() }
if "affiliation" in cv_data.recipient.keys() {
cv_data.recipient.affiliation + linebreak()
}
if "location" in cv_data.recipient.keys() {
let location = cv_data.recipient.location
if "street" in location { location.street + linebreak() }
if "postalCode" in location { str(location.postalCode) + " " }
if "city" in location { location.city + linebreak() }
if "regionCode" in location { str(location.regionCode) + " " }
if "country" in location { location.country }
}
},
date: cv_data.personal.location.city + ", " + if "date_string" in render_settings {
render_settings.date_string
} else {
today.display("[month repr:long] [day padding:none]" + written_number + ", [year]")
},
subject: cv_data.letter.subject,
name: cv_data.personal.name,
body: cv_data.letter.text,
ending: if "letter_ending" in render_settings { render_settings.letter_ending } else { "Sincerely," },
signature_pic: if "signature" in cv_data.personal.keys() { cv_data.personal.signature } else { none },
)
} |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.0/src/path-util.typ | typst | Apache License 2.0 | #import "@preview/oxifmt:0.2.0": strfmt
// This file contains utility functions for path calculation
#import "util.typ"
#import "vector.typ"
#import "bezier.typ"
#let default-samples = 25
/// Get first position vector of a path segment
///
/// - s (segment): Path segment
/// -> vector
#let segment-start(s) = {
return s.at(1)
}
/// Get last position vector of a path segment
///
/// - s (segment): Path segment
/// -> vector
#let segment-end(s) = {
if s.at(0) == "line" {
return s.last()
}
return s.at(2)
}
/// Calculate bounding points for a list of path segments
///
/// - segments (array): List of path segments
/// -> array: List of vectors
#let bounds(segments) = {
let bounds = ()
for s in segments {
let (kind, ..pts) = s
if kind == "line" {
bounds += pts
} else if kind == "cubic" {
bounds.push(pts.at(0))
bounds.push(pts.at(1))
bounds += bezier.cubic-extrema(..pts)
}
}
return bounds
}
/// Calculate length of a single path segment
///
/// - s (array): Path segment
/// -> float: Length of the segment in canvas units
#let _segment-length(s, samples: default-samples) = {
let (kind, ..pts) = s
if kind == "line" {
let len = 0
for i in range(1, pts.len()) {
len += vector.len(vector.sub(pts.at(i - 1), pts.at(i)))
}
return len
} else if kind == "cubic" {
return bezier.cubic-arclen(..pts, samples: samples)
} else {
panic("Invalid segment: " + kind, s)
}
}
/// Get the length of a path
///
/// - segments (array): List of path segments
/// -> float: Total length of the path
#let length(segments) = {
return segments.map(_segment-length).sum()
}
/// Finds the two points that are between t on a line segment.
#let _points-between-distance(pts, distance) = {
let travelled = 0
let length = 0
for i in range(1, pts.len()) {
length = vector.dist(pts.at(i - 1), pts.at(i))
if travelled <= distance and distance <= travelled + length {
return (
start: i - 1,
end: i,
distance: distance - travelled,
length: length
)
}
travelled += length
}
return (
start: pts.len() - 2,
end: pts.len() - 1,
distance: length,
length: length
)
}
/// Finds the point at a given distance from the start of a line segment. Distances greater than the length of the segment return the end of the line segment. Distances less than zero return the start of the segment.
///
/// - segment (array): The line segment
/// - distance (float): The distance along the line segment to find the point
/// -> vector: The point on the line segment
#let _point-on-line-segment(segment, distance) = {
let pts = segment.slice(1)
let (start, end, distance, length) = _points-between-distance(pts, distance)
return vector.lerp(pts.at(start), pts.at(end), distance / length)
}
/// Finds the point at a given distance from the start of a path segment. Distances greater than the length of the segment return the end of the path segment. Distances less than zero return the start of the segment.
///
/// - segment (segment): Path segment
/// - distance (float): The distance along the path segment to find the point
/// - extrapolate (bool): If true, use linear extrapolation for distances outsides the path
///
/// -> vector: The point on the path segment
#let _point-on-segment(segment, distance, samples: default-samples, extrapolate: false) = {
let (kind, ..pts) = segment
if kind == "line" {
return _point-on-line-segment(segment, distance)
} else if kind == "cubic" {
return bezier.cubic-point(
..pts,
bezier.cubic-t-for-distance(
..pts,
distance,
samples: samples
)
)
}
}
#let segment-at-t(segments, t, rev: false, samples: default-samples, clamp: false) = {
let lengths = segments.map(_segment-length.with(samples: samples))
let total = lengths.sum()
if type(t) == ratio {
t = total * t / 100%
}
if not clamp {
assert(t >= 0 and t <= total,
message: strfmt("t is expected to be between 0 and the length of the path ({}), got: {}", total, t))
}
if rev {
segments = segments.rev()
lengths = lengths.rev()
}
let travelled = 0
for (i, segment-length) in segments.zip(lengths).enumerate() {
let (segment, length) = segment-length
if travelled <= t and t <= travelled + length {
return (
index: if rev { segments.len() - i } else { i },
segment: segment,
// Distance travelled
travelled: travelled,
// Distance left
distance: t - travelled,
// The length of the segment
length: length
)
}
travelled += length
}
return (index: if rev { 0 } else { segments.len() - 1 },
segment: segments.last(),
travelled: total,
distance: t,
length: lengths.last())
}
#let _extrapolated-point-on-segment(segment, distance, rev: false, samples: 100) = {
let (kind, ..pts) = segment
let (pt, dir) = if kind == "line" {
let (a, b) = if rev {
(pts.at(0), pts.at(1))
} else {
(pts.at(-2), pts.at(-1))
}
(if rev {a} else {b}, vector.sub(b, a))
} else {
let dir = bezier.cubic-derivative(..pts, if rev { 0 } else { 1 })
if vector.len(dir) == 0 {
dir = vector.sub(pts.at(1), pts.at(0))
}
(if rev {pts.at(0)} else {pts.at(1)}, dir)
}
if vector.len(dir) != 0 {
return vector.add(pt, vector.scale(vector.norm(dir), distance * if rev { -1 } else { 1 }))
}
return none
}
/// Get position on path
///
/// - segments (array): List of path segments
/// - t (int,float,ratio): Absolute position on the path if given an
/// float or integer, or relative position if given a ratio from 0% to 100%
/// - extrapolate (bool): If true, use linear extrapolation if distance is outsides the paths range
/// -> none,vector: Position on path. If the path is empty (segments == ()), none is returned
#let point-on-path(segments, t, samples: default-samples, extrapolate: false) = {
assert(
type(t) in (int, float, ratio),
message: "Distance t must be of type int, float or ratio"
)
let rev = if type(t) == ratio and t < 0% or type(t) in ("int", "float") and t < 0 {
true
} else {
false
}
if rev {
t *= -1
}
// Extrapolate at path boundaries if enabled
if extrapolate {
let total = length(segments)
let absolute-t = if type(t) == ratio { t / 100% * total } else { t }
if absolute-t > total {
return _extrapolated-point-on-segment(segments.first(), absolute-t - total, rev: rev, samples: samples)
}
}
let segment = segment-at-t(segments, t, samples: samples, rev: rev)
return if segment != none {
let (distance, segment, length, ..) = segment
_point-on-segment(segment, if rev { length - distance } else { distance }, samples: samples, extrapolate: extrapolate)
}
}
/// Get position and direction on path
///
/// - segments (array): List of path segments
/// - t (float): Position (from 0 to 1)
/// - clamp (bool): Clamp position between 0 and 1
/// -> tuple: Tuple of the point at t and the scaled direction
#let direction(segments, t, samples: default-samples, clamp: false) = {
let (segment, distance, length, ..) = segment-at-t(segments, t, samples: samples, clamp: clamp)
let (kind, ..pts) = segment
return (
_point-on-segment(segment, distance, samples: samples),
if kind == "line" {
let (start, end, distance, length) = _points-between-distance(pts, distance)
vector.norm(vector.sub(segment.at(end+1), segment.at(start+1)))
} else {
let t = bezier.cubic-t-for-distance(..pts, distance, samples: samples)
let dir = bezier.cubic-derivative(..pts, t)
if vector.len(dir) == 0 {
vector.norm(vector.sub(pts.at(1), pts.at(0)))
} else {
dir
}
}
)
}
/// Create a line segment with points
///
/// - points (array): List of points
/// -> array Segment
#let line-segment(points) = {
("line",) + points
}
/// Create a cubic bezier segment
///
/// - a (vector): Start
/// - b (vector): End
/// - ctrl-a (vector): Control point a
/// - ctrl-b (vector): Control point b
/// -> array Segment
#let cubic-segment(a, b, ctrl-a, ctrl-b) = {
("cubic", a, b, ctrl-a, ctrl-b)
}
/// Shortens a segment by a given distance.
#let shorten-segment(segment, distance, snap-to: none, mode: "CURVED", samples: default-samples) = {
let rev = distance < 0
if distance >= _segment-length(segment) {
return line-segment(if rev {
(segment-start(segment), segment-start(segment))
} else {
(segment-end(segment), segment-end(segment))
})
}
let (kind, ..s) = segment
if kind == "line" {
if rev {
distance *= -1
s = s.rev()
}
let (start, end, distance, length) = _points-between-distance(s, distance)
if length != 0 {
s = (vector.lerp(s.at(start), s.at(end), distance / length),) + s.slice(end)
}
if rev {
s = s.rev()
}
} else {
s = if mode == "LINEAR" {
bezier.cubic-shorten-linear(..s, distance)
} else {
bezier.cubic-shorten(..s, distance, samples: samples)
}
// Shortening beziers suffers from rounding or precision errors
// so we "snap" the curve start/end to the snap-points, if provided.
if snap-to != none {
if rev { s.at(1) = snap-to } else { s.at(0) = snap-to }
}
}
return (kind,) + s
}
/// Shortens a path's segments by the given distances. The start of the path is shortened first by moving the point along the line towards the end. The end of the path is then shortened in the same way. When a distance is 0 no other calculations are made.
///
/// - segments (segments): The segments of the path to shorten.
/// - start-distance (int, float): The distance to shorten from the start of the path.
/// - end-distance (int, float): The distance to shorten from the end of the path
/// - pos (none, tuple): Tuple of points to "snap" the path ends to
/// -> segments Segments of the path that have been shortened
#let shorten-path(segments, start-distance, end-distance, snap-to: none, mode: "CURVED", samples: default-samples) = {
let total = length(segments)
let (snap-start, snap-end) = if snap-to == none {
(none, none)
} else {
snap-to
}
if start-distance > 0 {
let (segment, distance, index, ..) = segment-at-t(
segments,
start-distance,
clamp: true,
)
segments = segments.slice(index + 1)
segments.insert(0,
shorten-segment(
segment,
distance,
mode: mode,
samples: samples,
snap-to: snap-start
)
)
}
if end-distance > 0 {
let (segment, distance, index, ..) = segment-at-t(
segments,
end-distance,
rev: true,
clamp: true,
)
segments = segments.slice(0, index - 1)
segments.push(
shorten-segment(
segment,
-distance,
mode: mode,
samples: samples,
snap-to: snap-end
)
)
}
return segments
}
|
https://github.com/kaarmu/splash | https://raw.githubusercontent.com/kaarmu/splash/main/src/palettes/seaborn.typ | typst | MIT License | #let bright = (
blue: rgb("#023EFF"),
orange: rgb("#FF7C00"),
green: rgb("#1AC938"),
red: rgb("#E8000B"),
purple: rgb("#8B2BE2"),
brown: rgb("#9F4800"),
magenta: rgb("#F14CC1"),
gray: rgb("#A3A3A3"),
yellow: rgb("#FFC400"),
cyan: rgb("#00D7FF"),
)
#let bright6 = (
blue: rgb("#023EFF"),
green: rgb("#1AC938"),
red: rgb("#E8000B"),
purple: rgb("#8B2BE2"),
yellow: rgb("#FFC400"),
cyan: rgb("#00D7FF"),
)
#let colorblind = (
blue: rgb("#0173B2"),
orange: rgb("#DE8F05"),
green: rgb("#029E73"),
red: rgb("#D55E00"),
purple: rgb("#CC78BC"),
brown: rgb("#CA9161"),
magenta: rgb("#FBAFE4"),
gray: rgb("#949494"),
yellow: rgb("#ECE133"),
cyan: rgb("#56B4E9"),
)
#let colorblind6 = (
blue: rgb("#0173B2"),
green: rgb("#029E73"),
red: rgb("#D55E00"),
purple: rgb("#CC78BC"),
yellow: rgb("#ECE133"),
cyan: rgb("#56B4E9"),
)
#let dark = (
blue: rgb("#001C7F"),
orange: rgb("#B1400D"),
green: rgb("#12711C"),
red: rgb("#8C0800"),
purple: rgb("#591E71"),
brown: rgb("#592F0D"),
magenta: rgb("#A23582"),
gray: rgb("#3C3C3C"),
yellow: rgb("#B8850A"),
cyan: rgb("#006374"),
)
#let dark6 = (
blue: rgb("#001C7F"),
green: rgb("#12711C"),
red: rgb("#8C0800"),
purple: rgb("#591E71"),
yellow: rgb("#B8850A"),
cyan: rgb("#006374"),
)
#let deep = (
blue: rgb("#4C72B0"),
orange: rgb("#DD8452"),
green: rgb("#55A868"),
red: rgb("#C44E52"),
purple: rgb("#8172B3"),
brown: rgb("#937860"),
magenta: rgb("#DA8BC3"),
gray: rgb("#8C8C8C"),
yellow: rgb("#CCB974"),
cyan: rgb("#64B5CD"),
)
#let deep6 = (
blue: rgb("#4C72B0"),
green: rgb("#55A868"),
red: rgb("#C44E52"),
purple: rgb("#8172B3"),
yellow: rgb("#CCB974"),
cyan: rgb("#64B5CD"),
)
#let muted = (
blue: rgb("#4878D0"),
orange: rgb("#EE854A"),
green: rgb("#6ACC64"),
red: rgb("#D65F5F"),
purple: rgb("#956CB4"),
brown: rgb("#8C613C"),
magenta: rgb("#DC7EC0"),
gray: rgb("#797979"),
yellow: rgb("#D5BB67"),
cyan: rgb("#82C6E2"),
)
#let muted6 = (
blue: rgb("#4878D0"),
green: rgb("#6ACC64"),
red: rgb("#D65F5F"),
purple: rgb("#956CB4"),
yellow: rgb("#D5BB67"),
cyan: rgb("#82C6E2"),
)
#let pastel = (
blue: rgb("#A1C9F4"),
orange: rgb("#FFB482"),
green: rgb("#8DE5A1"),
red: rgb("#FF9F9B"),
purple: rgb("#D0BBFF"),
brown: rgb("#DEBB9B"),
magenta: rgb("#FAB0E4"),
gray: rgb("#CFCFCF"),
yellow: rgb("#FFFEA3"),
cyan: rgb("#B9F2F0"),
)
#let pastel6 = (
blue: rgb("#A1C9F4"),
green: rgb("#8DE5A1"),
red: rgb("#FF9F9B"),
purple: rgb("#D0BBFF"),
yellow: rgb("#FFFEA3"),
cyan: rgb("#B9F2F0"),
)
|
https://github.com/zadigus/math | https://raw.githubusercontent.com/zadigus/math/main/number-theory/README.md | markdown | # Compile
typst compile main.typ main.pdf
|
|
https://github.com/wzy1935/Typst-Blocks | https://raw.githubusercontent.com/wzy1935/Typst-Blocks/master/README.md | markdown | # Typst Blocks
My personal Typst template blocks. Load it like this:
```
#import "blocks.typ": *
```
See use cases in `examples`.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/cancel-05.typ | typst | Other | // Rotated
$x + cancel(y, rotation: #90deg) - cancel(z, rotation: #135deg)$
$ e + cancel((j + e)/(f + e)) - cancel((j + e)/(f + e), rotation: #30deg) $
|
https://github.com/Trebor-Huang/HomotopyHistory | https://raw.githubusercontent.com/Trebor-Huang/HomotopyHistory/main/category.typ | typst | #import "common.typ": *
= 范畴论
范畴是数学中广泛存在的抽象结构. 一个*范畴*由一些对象 ${X, Y, dots}$ 与这些对象之间的态射 $f : X -> Y$ 组成. 每个对象有恒同态射 $id : X -> X$, 态射之间有复合操作, 满足结合律. 例如, 以群作为对象, 群同态作为态射, 就构成一个范畴. 如此抽象的定义仍然有实用价值, 令人吃惊. 例如, 可以抽象地定义*同构*的概念, 即两个映射 $f : X -> Y$, $g : Y -> X$, 使得互相复合都得到恒同态射.
尽管范畴论来自同调代数的研究, 但是它的抽象性决定了它能应用于非常多的领域, 例如代数、几何、逻辑, 甚至物理、计算机、哲学中都有应用范畴论的研究. 它作为强大的组织抽象概念的工具, 力量不容小觑.
== 范畴论的提出
// https://plato.stanford.edu/entries/category-theory/#BrieHistSket
1945 年, Eilenberg 与 <NAME> 在一篇文章《自然同构概论》@NatEquiv 中一举提出了范畴、函子与自然变换的概念.
给定两个范畴 $cal(C), cal(D)$, 一个*函子* $F : cal(C) -> cal(D)$ 给 $cal(C)$ 的每个对象 $X$ 赋予 $cal(D)$ 的一个对象 $F(X)$, 每个态射 $f : X -> Y$ 也对应赋予一个态射 $F(f) : F(X) -> F(Y)$, 使得保持复合关系. 一般来说, 给定一个数学结构, 构造一个新的数学结构的过程, 都可以看作合适的范畴之间的函子. 函子也可以看成是广义的对象, 或者自然的一族对象.
*自然变换*则是定义在两个函子 $F, G : cal(C) arrows cal(D)$ 之间的, 可以看作广义对象之间的广义态射. 自然变换 $alpha$ 是一族态射 $alpha_X : F(X) -> G(X)$, 使得对于 $cal(C)$ 中的每个态射 $f : X -> Y$, $alpha_Y compose F(f) = G(f) compose alpha_X$, 即这四个态射构成的正方形交换.
这些概念实际上都只是为论文标题中的*自然同构*作铺垫. 如果有两个自然变换 $alpha, beta$ 使得每一组 $alpha_X, beta_X$ 都构成同构, 就称它们为自然同构. Eilenberg 与 <NAME> 在论文中举出了线性空间的对偶的例子. 有限维的向量空间 $V$ 总是与它的对偶 $V^*$ 同构, 因为维数相同. 但是这样的同构并不典范. 与之相反, 向量空间 $V^(**)$ 与 $V$ 之间的同构是 “自然” 的, 可以直接写出 $v |-> (phi |-> phi(v))$. 这是因为双重对偶操作 $(-)^(**)$ 是 (有限维) 向量空间范畴到自身的函子, 而这个函子到恒同函子 $"Id"(V) = V$ 有自然同构.
这样, 范畴论的框架就能为表达代数、拓扑等等学科中出现的 “自然” 性, 提出了一种方便的语言. 例如代数拓扑中出现的长正合列都有自然性, 这就可以用范畴论的语言表述.
在论文中, 还提出了正向极限与逆向极限的抽象定义. 回忆之前出现的逆向极限是逆着态射方向的极限, 而正向极限则是沿着态射方向的极限, $X_1 -> X_2 -> dots.c$ 表示一列逐渐扩大的代数结构的并集. 例如 $ZZ \/ p ZZ -> ZZ \/ p^2 ZZ -> dots.c$, 其中每个态射都是乘以 $p$, 则极限是 $ZZ \/ p^oo ZZ$, 也可以看作复单位元中形如 $exp((2 pi i k)/p^n)$ 的元素构成的群.
这些极限与拓扑中的极限有非常相似的定义. 考虑拓扑空间 $NN subset.eq NN_oo$, 其中后者定义为 $NN union {oo}$, 并且开集要么是 $NN$ 中的任意子集, 要么包含某个 $[n, oo]$. 点列 ${a_n}$ 可以看作连续函数 $a_n : NN -> X$. 如果这个函数可以延拓到 $NN_oo -> X$, 那么 $a_oo$ 就是这个点列的极限. (如果拓扑空间不满足 Hausdorff 性质, 那么极限不唯一, 但是每个极限都对应一个这样的延拓.)
对应地, $cal(C)$ 中的一列对象 $X_1 -> X_2 -> dots.c$ 相当于范畴 $cal(N)$ 到 $cal(C)$ 的函子, 其中 $cal(N)$ 的对象是正整数, $m$ 到 $n$ 有一个态射当且仅当 $m <= n$. 我们可以添加一个对象 $oo$ 得到范畴 $cal(N)_oo$, 并且试图将 $cal(N) -> cal(C)$ 延拓到 $cal(N)_oo -> cal(C)$. 这样的延拓有很多, 但是有一个延拓 $T$ 满足对于别的延拓 $S$ 都有自然变换 $T -> S$, 使得自然变换在 $cal(N)$ 上的分量都是恒同态射.
逆向极限则是将范畴的所有态射全部反向得到的. 对于每个范畴论概念, 都可以将态射全部反向得到另一个概念. 这种现象称作*对偶*. 对偶可以揭示数学结构中的许多对称性, 并且也需要在范畴论的语言中才能发挥全部的威力.
1952 年, 日本数学家米田信夫证明了著名的米田引理. 它蕴含非常深刻的思想, 影响了后续范畴论的发展. 它的大致内容是, 如果需要刻画范畴中的某个对象 $X$, 只需要描述到这个对象的所有态射 $hom(-, X)$. 例如在拓扑空间中, $hom(1, X)$ 是 $X$ 的点集. 而如果 $I = [0,1]$ 是区间拓扑空间, 则 $hom(I, X)$ 是 $X$ 中所有道路的集合. 这可以看作是 $X$ 的 “广义点” 构成的集合. 描述了所有形状的广义点, 就完全描述了 $X$ 本身.
1956 年左右, Kan 提出了伴随函子、极限与余极限、Kan 扩张等的定义, 这些形成了当今范畴论的基础概念. 在 Eilenberg 与 Mac Lane 的文章中, 正向极限与逆向极限都只能对特殊的图表进行. 对于正向极限来说, 每两个对象 $X, Y$ 都需要有第三个对象 $Z$ 使得图表中包含 $X -> Z$ 与 $Y -> Z$, 并且每两个对象之间至多有一个态射. 之前我们讨论的图表形如 $bullet -> bullet -> dots.c$, 满足要求. 这种图表称作*有向集*. Kan @AdjointFunctors 讨论了任意形状的图表的极限.
如果图表中只有两个对象, 没有额外的态射, 那么得到的极限就是 (二元) *乘积*. 具体来说, 两个对象 $A, B$ 的乘积是对象 $C$ 配备两个投影映射 $pi_1 : C -> A$, $pi_2 : C -> B$, 使得对于任何其他三元组 $(C', pi'_1, pi'_2)$, 都有唯一的 $C -> C'$ 使得图表交换:\
#box(width: 100%)[
#set align(center)
#fletcher.diagram($
& C' edge("dl", ->) edge("dr", ->) & \
A #edge(label: $pi_1$, label-side: left, "<-") & C #edge(label: $pi_2$, label-side: left, "->") edge("u", "-->") & B
$)]
在集合范畴中, 这个定义得到的就是 Descartes 积. 在代数结构的范畴中也会类似得到直积, 在拓扑空间中得到乘积拓扑. 显然, 这个定义可以推广到任意数量的对象. 这可以体现出使用范畴论定义的好处之一. 无限个拓扑空间的乘积, 容易想到的定义是箱拓扑, 它的性质不好. 正确的乘积拓扑的定义初看可能略微反直觉. 如果使用范畴论语言定义, 那么这个有些复杂的定义就是自然的推广结果.
如果考虑零个对象的乘积, 就得到*终对象*, 记作 $1$. 这是因为终对象是乘积的单位元, $1 times X tilde.equiv X$. 展开定义就得到, 终对象是满足 $hom(X, 1)$ 恰好都有一个元素的对象. 这定义了单点集、单点拓扑空间、单元素代数结构, 等等.
对偶地, 可以考虑对象的*余积*. 这定义了集合与拓扑空间的不交并、群的融合积、交换环的张量积, 等等. 零元余积是*始对象* $0$, 定义了空集、空拓扑空间.
还有一对重要的极限/余极限的概念. 给定平行的两个态射 $f, g : X arrows.rr Y$, 它们构成的图表的极限称作*等化子*. 在集合范畴里, 就是方程 $f(x) = g(x)$ 的解集. 对偶的有*余等化子*, 对应 $f(x) ∼ g(x)$ 生成的等价关系的商.
伴随函子也是数学中广泛存在的现象. 如果 $hom(F(X), Y)$ 与 $hom(X, G(Y))$ 自然同构, 就说 $F tack.l G$ 构成一对伴随函子. 例如, 拓扑空间上有三个函子, $Gamma : sans("Top") -> sans("Set")$ 取出拓扑空间的点集, $Delta : sans("Set") -> sans("Top")$ 为集合赋予离散拓扑, $nabla : sans("Set") -> sans("Top")$ 赋予余离散拓扑. 从离散拓扑空间出发的任何函数都连续, 因此有自然同构 $hom(Delta X, Y) tilde.equiv hom(X, Gamma Y)$. 对偶地, 也有 $Gamma tack.l nabla$. 在代数中, 自由代数对象往往是反方向的典范函子的左伴随. $(A times.circle -)$ 与 $hom(A, -)$ 也构成伴随.
== Abel 范畴
范畴在一段时间内都只是一种同调代数中临时方便性质的语言. 这种现状维持了十几年. 范畴论真正成为独立的学科, 是在 Grothendieck 发表于 1957 年的论文 _Sur quelques points d'algèbre homologique_ @Tohoku, 由于其发表的刊物名称, 一般简称作 “Tôhoku 论文”.
Eilenberg 与 Cartan 编写《同调代数》时, 只处理了环上的模构成的同调代数理论. 虽然层上同调的理论与之极为相似, 但是不能纳入这个框架中. 为此, 他们试图提出一些能够刻画同调代数的需求的公理. 最终得到广泛运用的公理体系是 Grothendieck 提出的 Abel 范畴.
如果某个范畴任何两个对象之间的态射集上都有交换群结构, 并且态射复合是双线性映射 $hom(Y, Z) times.circle hom(X, Y) -> hom(X, Z)$, 就称它是*预加性范畴*. 预加性范畴中, 始对象与终对象是重合的, 称作*零对象*, 记作 $0$; 二元积与二元余积是重合的, 称作*双积*, 记作 $plus.circle$. 如果这些都存在, 就称这个范畴是*加性范畴*.
尽管预加性范畴是范畴上的额外结构 (即一个范畴可以通过不同的交换群结构构成预加性范畴), 但一个范畴如果可以构成加性范畴, 那么其构成方式是唯一的. 这可以从另一个等价的定义中看出来. 如果一个范畴有所有的有限积与余积, 并且它们重合, 那么态射集就有典范的交换幺半群结构. 其中零元由 $X -> 0 -> Y$ 复合给出, 而加法 $f + g$ 定义为
$ X -->^Delta X plus.circle X -->^⟨f, g⟩ Y plus.circle Y -->^nabla Y. $
如果这些幺半群有逆元 —— 逆元总是唯一的 —— 就构成加性范畴.
进一步, 等化子的理论也被态射的交换群结构简化了. $f$ 与 $g$ 的等化子等价于 $f-g$ 与 $0$ 的等化子. 因此我们只需要考虑后者. 在模范畴中, 这就是态射的零点构成的子模, 称作*核*. 对偶地, 态射与 $0$ 的余等化子称作*余核*. $ker("coker"(f))$ 可以看作态射*像*的定义. 对偶的有余像 $"coker"(ker(f))$. 在模范畴中, 这两者是有典范同构的. 如果核与余核存在, 并且像与余像典范同构, 那么就称这个加性范畴构成 *Abel 范畴*.
Abel 范畴的定义使得同调代数可以在更高的抽象层次上进行. 例如导出函子可以在任何有足够投射或内射对象的 Abel 范畴中定义. 层上同调可以表述为层上的函子 $Gamma(X) = hom(1, X)$ 的导出. 代数几何也由此能够运用同调代数的一般工具. Grothendieck 还引入了万有 $delta$-函子等概念, 基本完成了当代同调代数的框架.
== 意象
Abel 范畴的成功启发了数学家, 可以在其他领域中寻找能够囊括领域基础概念的范畴公理化体系.
在 1960 年代, Lawvere 将范畴论与数学基础联系起来. 集合构成的范畴 $sans("Set")$, 传统上是先用集合论的公理刻画, 再定义出函数的概念, 进而构成范畴. 但是这个范畴也可以用范畴语言唯一确定. Lawvere @ETCS 给出了一系列性质, 唯一刻画了集合范畴. 这相当于一套范畴论风格的集合论公理, 现在称作 “集合范畴的初等理论”, 缩写为 ETCS.
例如, 函数集合 $B^A$ 可以用范畴语言表述为*函数对象* (也称作*指数对象*). 如果 $(A times -)$ 函子有右伴随, 就将这个伴随记作 $(-)^A$. 在集合范畴中, 这就是函数集的概念. 在拓扑空间范畴中, 如果函数对象存在, 就是连续函数在紧开拓扑下构成的空间. ETCS 中的一条公理就是所有函数对象都存在.
给定一个态射 $i : Y -> X$, 如果对于所有 $f, g : Z -> Y$ 使得 $i compose f = i compose g$, 都有 $f = g$, 就称 $i$ 是*单态射*. 这可以靠把 $f, g$ 看作 $Y$ 的广义元素来理解. 对于某个对象 $X$, 其*子对象*就是有序对 $(Y, i)$, 其中 $i$ 是 $Y -> X$ 的单射. 对于集合来说, 子集 $Y subset.eq X$ 可以等效描述为示性函数 $X -> {0, 1}$. 这在范畴论中对应*子对象分类子*的概念. 假如有 $t : 1 -> Omega$, 满足任何子对象 $Y -> X$ 都是一个拉回\
#box(width: 100%)[
#set align(center)
#fletcher.diagram($
Y edge("d", ->) edge("r", ->) & 1 edge("d", ->, "t") \
X edge("r", ->) & Omega
$)]
那么就称 $(Omega, t)$ 是子对象分类子. 这里 $t$ 的作用是指出哪个元素表达 “包含在子对象中”. 注意一般来说不一定有 $Omega = 1 + 1$. $Omega$ 的函数对象 $Omega^X$ 可以刻画幂集的概念.
Lawvere 还将数理逻辑中的许多概念用范畴表述. 例如, $forall, exists$ 量词可以用伴随函子的方式定义. Lawvere 认为, 范畴论中的伴随函子可以在数学基础中发挥巨大作用. 同时, Lambek 将推理系统的性质放在了范畴的框架下研究. 这开启了范畴逻辑学的学科.
这些研究催生了意象 (topos) 的概念. Grothendieck 起初将意象用于代数几何的研究. 拓扑空间上的层不能完全满足代数几何的需求. Grothendieck 将拓扑空间中的开覆盖的概念推广, 得到了 *Grothendieck 拓扑*. 考虑一个范畴 $cal(C)$ (在拓扑空间的情况, 就是其开集与包含关系构成的范畴). 对某个对象 $X$, 我们规定某些陪域是 $X$ 的态射构成的集合是 $X$ 的*覆盖*. 例如在拓扑空间的情况, 我们规定 ${Y_i -> X}$ 构成覆盖当且仅当 $union.big_i Y_i = X$. 这些覆盖需要满足四条性质:
- 如果 $f : Y -> X$ 是同构, 那么 ${f}$ 构成一组覆盖.
- 如果 ${f_i : Y_i -> X}$ 是一组覆盖, 并且 ${g_(i j) : Z_(i j) -> Y_i}$ 各自覆盖了 $Y_i$, 那么复合映射 ${f_i compose g_(i j)}$ 也覆盖了 $X$.
- 如果 ${f_i : Y_i -> X}$ 是一组覆盖, 并且 $Y -> X$ 是某个态射, 那么拉回 ${Y_i times_X Y -> Y}$ 得到的也是覆盖. 这在拓扑空间中说的是 $X$ 的开覆盖逐个与 $Y subset.eq X$ 取交集得到的是 $Y$ 的开覆盖.
配备了 Grothendieck 拓扑的范畴称作*景* (site). 在景上可以类似拓扑空间一样定义层. Grothendieck 意象就是形如某个景上的层构成的范畴.
Grothendieck 范畴也可以抽象地用公理定义, 这称作 Giraud 公理. 1970 年, Lawvere 提出了*初等意象*的概念. 所有 Grothendieck 意象都是初等意象, 并且 ETCS 公理也可以看作是在初等意象的基础上添加了额外限制. 初等意象表现得非常像集合, 因此可以利用一种类似集合的语言讨论, 例如写出公式
$ {(f(x), y) | x in X, y in Y, g(x) = h(y)} $
就可以翻译为初等意象中的构造, 等等. 在 1970 年代, 意象在各个领域都得到了应用, 展现出截然不同的面貌, 正如盲人摸象一般. 意象论的重要参考书籍 _Sketches of an Elephant_ @elephant 也因此得名.
== 抽象同伦论
仿照同调代数的理论, Quillen 试图给出一套刻画同伦论的范畴公理. 这被称作 “同伦代数”, 可以看作是同调代数的非交换版本 —— 因为有 Hurewicz 定理等等. 由此, 他在 1967 年提出了 Quillen 同伦模型范畴的概念. 今天在同伦论的研究中一般简称作*模型范畴*. 在模型范畴或其变体中, 就可以进行各种同伦相关的操作.
首先, 仿照拓扑空间, Quillen 要求模型范畴中包含所有极限与余极限.
在代数拓扑的研究中, 核心概念是弱同伦等价, 即某个映射 $f : X -> Y$ 使得诱导的群同态 $pi_n (X) -> pi_n (Y)$ 都是群同构. 这大致说的是两个空间之间没有同伦论感兴趣的区别. 但是, 弱同伦等价不一定有逆. 模型范畴中, 需要指定一族态射称作弱等价, 包含所有的同构, 并且满足一条定律: 如果 $f, g, f compose g$ 三者中弱等价有二, 则三者都是弱等价. 因为弱等价不需要有逆, 即没有对称性, 这是一种有向的传递性条件.
其次, 代数拓扑中还有*纤维化*的概念, 是纤维丛的同伦推广. 纤维丛的每个纤维都同胚, 并且随着底空间连续变化. 而纤维化的纤维只同伦等价, 不一定同胚. 其中最常用的是 Hurewicz 纤维化. 如果连续映射 $E -> B$ 满足对于每个交换方\
#box(width: 100%)[
#set align(center)
#fletcher.diagram($
X times {0} edge("d", arrow.hook, i) edge("r", ->) & E edge("d", ->, p) \
X times [0,1] edge("r", ->) edge("ur", "-->") & B
$)]
都能填入虚线的箭头, 就称其为 *Hurewicz 纤维化*. 它的拓扑含义是任何一个在底空间 $B$ 运动的 $X$ 状空间, 规定了初始时刻在 $E$ 的抬升后, 总是可以连续选择其余时刻的抬升.
这种抬升现象在同伦论中非常常见. 我们将其记作 $i fork p$, 即 $i, p$ 组成的任何交换方都可以如图填入对角线. 将形如 $X times {0} -> X times [0,1]$ 的映射集合记作 $C$, 那么 Hurewicz 纤维化就是那些满足 $C fork p$ 的映射. 对偶地, 也可以定义*余纤维化*的概念. 给定一族映射 $F$, 将满足 $i fork F$ 的映射称作余纤维化. 余纤维化描述了性质良好的空间含入. 模型范畴需要规定一族纤维化与一族余纤维化, 满足适合的抬升关系.
由简洁与高度对称的公理, 就足够完成同伦论中的许多操作. 例如可以定义*柱对象* $"Cyl"(X)$, 类似拓扑的柱体 $X times [0,1]$. 则 $"Cyl"(X) -> Y$ 可以表示映射的同伦. 对偶的有*路径对象* $"Path"(Y)$, 类似拓扑的道路空间 $[0,1] -> Y$. 则 $X -> "Path"(Y)$ 也可以表达映射的同伦.
代数中, 链复形构成一个模型范畴, 因此也可以运用同伦的方法. 这将同伦与同调之间长期存在的类比关系严格地放到了一个框架下. 例如链复形之间有链同伦、映射柱、映射锥等等构造, 都可以用模型范畴的语言统一表达.
|
|
https://github.com/PgBiel/glypst | https://raw.githubusercontent.com/PgBiel/glypst/main/README.md | markdown | MIT License | # glypst
Typst bindings for Gleam
[](https://hex.pm/packages/glypst)
[](https://hexdocs.pm/glypst/)
```sh
gleam add glypst
```
```gleam
import glypst
pub fn main() {
// TODO: An example of the project in use
}
```
Further documentation can be found at <https://hexdocs.pm/glypst>.
## Development
```sh
nix develop # Install dependencies, incl. Gleam, Erlang and Typst, using the flake (optional)
gleam run # Run the project
gleam test # Run the tests (requires `typst` in the PATH)
gleam shell # Run an Erlang shell
```
|
https://github.com/kokkonisd/typst-phd-template | https://raw.githubusercontent.com/kokkonisd/typst-phd-template/main/examples/report.typ | typst | The Unlicense | // Replace 0.2.3 with the version of the template you've installed.
#import "@local/phd-template:0.2.3" as template
#show: doc => template.report-setup(
doc,
title: "Annual thesis report",
subtitle: "Very interesting and long title of the thesis",
subtitle-size: 20pt,
date: datetime(day: 23, month: 04, year: 2025),
authors: (
(
(
group: "Myself",
members: (
(
name: "<NAME>",
organization: "My Lab",
email: "<EMAIL>",
),
)
),
),
),
signature: "Signature of someone important idk",
bibliography: bibliography("dummy.bib"),
)
= Introduction
#lorem(100)
#lorem(100)
#lorem(100)
= Background
As some people smarter than me have found @Turing2009,
#lorem(100)
#lorem(100)
#lorem(100)
= Contributions
== Theorectical
#lorem(100)
== Technical
#lorem(100)
= Conclusion
#lorem(100)
|
https://github.com/TJ-CSCCG/tongji-slides-typst | https://raw.githubusercontent.com/TJ-CSCCG/tongji-slides-typst/main/main.typ | typst | MIT License | #import "@preview/polylux:0.3.1": *
#import "./theme/university.typ": *
#show: university-theme.with(
short-author: "Short author", short-title: "Short title", short-date: "Short date",
)
#set text(size: 15pt)
//#let cell = rect.with(width: 100%, height: 46%, stroke: none)
#title-slide(
authors: ("李狗蛋", "蛋狗李"), title: "Tongji slides typst", subtitle: "Template", date: "Date", institution-name: "Tongji University",
) // 这里修改title-slide
#matrix-slide[
== EXAMPLE
#align(
top + left, [== DMI效应产生原因
#v(1em)
- DMI是由于反演对称性破缺和`Spin-Orbit Couple`(SOC)引起的反对称交换作用
- 在具有非对称晶体结构的材料中,由于原子排列的不均匀性,电子在原子间运动时会经历不均匀的电场。这个不均匀的电场改变了自旋-轨道耦合的性质,导致电子的自旋倾向于以特定的方式与其轨道运动相耦合。这种耦合产生了一个优先的方向,使得磁矩倾向于非对易地排列。
#figure(image("pic/DMI_1.png", height: 40%), caption: [
Dzyaloshinskii–Moriya interaction
])
],
)
][
#v(1em)
#align(
top + left, [
- DMI效应最早发现于$alpha-"Fe"_2"O"_3$反铁磁材料中,实验上发现了弱铁磁性。
- Dzyaloshinskii给出了唯象的解释$H_("DM")=D dot [S_i times S_j]$,即DMI相互作用使相邻磁矩趋于垂直。
- Moriya结合超交换理论提出这种效应可以看作是磁绝缘体中SOC以及对称性破缺所引起的附加项。
- 在相互交换作用和DMI的共同作用下,磁矩会趋于形成一定夹角,因此会形成`SKyrmions`结构。
#figure(image("pic/SKyrmion.png", height: 39%), caption: [`SKyrmions`结构])
],
)
]
#slide[
#align(center + horizon, [+ 这是不需要分列的slide])
]
#matrix-slide[
#align(center, [#text(20pt, `1`)])
][
#align(center, [#text(20pt, `2`)])
]
#matrix-slide(columns: 2, rows: 2)[
#align(center, [#text(20pt, `1`)])
][
#align(center, [#text(20pt, `2`)])
][
#align(center, [#text(20pt, `3`)])
][
#align(center, [#text(20pt, `4`)])
]
#focus-slide(
background-img: image("./theme/img/E9B78952-B8E5-49B8-9326-A0AD28C9A337_1_105_c.jpeg"),
)[
//#text(fill: )[*在这里显示字*]
]
|
https://github.com/swablab/documents | https://raw.githubusercontent.com/swablab/documents/main/spendenbescheinigung.typ | typst | Creative Commons Zero v1.0 Universal | #import "templates/tmpl_page.typ": tmpl_page
#import "templates/common.typ": colors
#import "templates/form.typ": form_field
#let config = yaml("spendenbescheinigung.yml")
#show: doc => tmpl_page(
title: "Spendenbescheinigung",
doc,
)
// DIN 5008 Sichtfenster: 45mm
#place(
top+left,
dy: 25mm,
)[
#text(size: 0.75em)[#underline[swablab e.V. - Katharinenstr. 1 - 72250 Freudenstadt]] \
#v(0.5em)
#config.address
]
// DIN 5008 Informationsblock: 50mm
#place(
top+right,
dy: 30mm,
)[
#v(1em)
Datum: #config.date
]
// DIN 5008 Faltmarke 1: 105mm
#place(
top+left,
dy: 85mm,
dx: -1cm,
line(
length: -1em,
stroke: 0.5pt + colors.subtext
)
)
// DIN 5008 Faltmarke 2: 210mm
#place(
top+left,
dy: 190mm,
dx: -1cm,
line(
length: -1em,
stroke: 0.5pt + colors.subtext
)
)
#place(
top+left,
dy: 67mm,
)[
#if config.collection != none {
[Sammelbestätigung über Geldzuwendungen/Mitgliedsbeiträge]
} else {
[Bestätigung über Geldzuwendungen/Mitgliedsbeitrag]
}
im Sinne des § 10b des Einkommensteuergesetzes an eine der in § 5 Abs. 1 Nr. 9 des Körperschaftsteuergesetzes bezeichneten Körperschaften, Personenvereinigungen oder Vermögensmassen.
]
// DIN 5008 nach Faltmarke 1
#place(
top+left,
dy: 85mm,
)[
#table(
columns: (auto, 1fr, auto),
fill: (_, row) => if row == 0 { colors.highlight } else { white },
stroke: 0.1pt + colors.subtext,
[*Gesamtbetrag der Zuwendung*],
[*- in Buchstaben -*],
[*Tag der Zuwendung*],
[#config.amount EUR],
[#config.amount_text EUR],
[#config.date_of_donation]
)
#text(size: 10pt)[
#if config.collection != none {[
Ob es sich um den Verzicht auf Erstattung von Aufwendungen handelt, ist der Anlage zur Sammelbestätigung zu entnehmen.
]} else {
if config.release_expenditures {
[Es handelt sich um den Verzicht auf Erstattung von Aufwendungen: #h(5em) ☑ Ja #h(5em) ☐ Nein]
} else {
[Es handelt sich um den Verzicht auf Erstattung von Aufwendungen: #h(5em) ☐ Ja #h(5em) ☑ Nein]
}
}
☑ Wir sind wegen Förderung _von Organisationen der Bildung, Wissenschaft und Forschung_ nach dem Freistellungsbescheid bzw. nach der Anlage zum Körperschaftsteuerbescheid des Finanzamtes _Finanzamt Freudenstadt_ StNr. _42099/46775_, vom _21.12.2020_ für den letzten Veranlagungszeitraum _2023_ nach § 5 Abs. 1 Nr. 9 des Körperschaftsteuergesetzes von der Körperschaftsteuer und nach § 3 Nr. 6 des Gewerbesteuergesetzes von der Gewerbesteuer befreit.
☑ Die Einhaltung der satzungsmäßigen Voraussetzungen nach den §§ 51, 59, 60 und 61 AO wurde vom Finanzamt _Finanzamt Freudenstadt_, StNr. _42099/46775_ mit Bescheid vom _21.12.2020_ nach § 60a AO gesondert festgestellt.
Wir fördern nach unserer Satzung _von Organisationen der Bildung, Wissenschaft und Forschung_.
#box(stroke: black, inset: 0.5em)[
Es wird bestätigt, dass die Zuwendung nur zur Förderung _von Organisationen der Bildung, Wissenschaft und Forschung_ verwendet wird.
*Nur für steuerbegünstigte Einrichtungen, bei denen die Mitgliedsbeiträge steuerlich nicht abziehbar sind:* \
☑ Es wird bestätigt, dass es sich nicht um einen Mitgliedsbeitrag handelt, dessen Abzug nach § 10b Abs. 1 des Einkommensteuergesetzes ausgeschlossen ist.
]
]
]
// Footer
#place(bottom+left)[
#form_field(width: 50%)[Freudenstadt, den #config.date]
#text(size: 0.7em, fill: colors.subtext)[
*Hinweis:* Wer vorsätzlich oder grob fahrlässig eine unrichtige Zuwendungsbestätigung erstellt oder veranlasst, dass Zuwendungen nicht zu den in der Zuwendungsbestätigung angegebenen steuerbegünstigten Zwecken verwendet werden, haftet für die entgangene Steuer (§ 10b Abs. 4 EStG, § 9 Abs. 3 KStG, § 9 Nr. 5 GewStG).
Diese Bestätigung wird nicht als Nachweis für die steuerliche Berücksichtigung der Zuwendung anerkannt, wenn das Datum des Freistellungsbescheides länger als 5 Jahre bzw. *das Datum der Feststellung der Einhaltung der satzungsmäßigen Voraussetzungen nach § 60a Abs. 1 AO länger als 3 Jahre seit Ausstellung des Bescheides zurückliegt (§ 63 Abs. 5 AO).*
#table(
stroke: none,
align: top+left,
columns: (1fr,1fr,auto,1fr,1fr),
[*Telefon*],[*E-Mail / Web*],[*Bankverbindung*],[*Vereinsregister*],[*Vorstand*],
[
+49 15679232971
],
[
<EMAIL> \
https://swablab.de
],
[
VR-Bank Dornstetten-Horb \
DE12 6426 2408 0125 6340 05
],
[
VR 724909 \
Amtsgericht Stuttgart
],
[
<NAME> \
<NAME>
],
)
]
]
#if config.collection != none {[
#pagebreak()
#heading[*Anlage zur Sammelbestätigung*]
#v(1em)
Es wird bestätigt, dass über die in der Gesamtsumme enthaltenen Zuwendungen keine weiteren Bestätigungen, weder formelle Zuwendungsbestätigungen noch Beitragsquittungen oder Ähnliches ausgestellt wurden und werden.
#table(
columns: (auto, 1fr, auto, auto),
fill: (_, row) => if row == 0 { colors.highlight } else { white },
stroke: 0.1pt + colors.subtext,
[*Datum der Zuwendung*],
[*Art der Zuwendung*],
[*Verzicht auf die\ Erstattung von\ Aufwendungen*],
[*Betrag*],
..config.collection.map(e => (
e.date,
e.type,
if e.release_expenditures {"Ja"} else {"Nein"},
[#e.amount EUR],
)).flatten().map(e => [#e]),
)
]} |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-15.typ | typst | Other | // Test the `min` and `max` functions.
#test(calc.min(2, -4), -4)
#test(calc.min(3.5, 1e2, -0.1, 3), -0.1)
#test(calc.max(-3, 11), 11)
#test(calc.min("hi"), "hi")
|
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/VerbaliInterni/VerbaleInterno_240315/content.typ | typst | MIT License | #import "meta.typ": inizio_incontro, fine_incontro, luogo_incontro
#import "functions.typ": glossary, team
#let participants = csv("participants.csv")
= Partecipanti
/ Inizio incontro: #inizio_incontro
/ Fine incontro: #fine_incontro
/ Luogo incontro: #luogo_incontro
#table(
columns: (3fr, 1fr),
[*Nome*], [*Durata presenza*],
..participants.flatten()
)
= Sintesi Elaborazione Incontro
/*************************************/
/* INSERIRE SOTTO IL CONTENUTO */
/*************************************/
Nell'incontro si è discussa l'organizzazione del lavoro futuro, di seguito se ne riportano i momenti salienti.
== Nuovi ruoli
Vengono stabiliti i seguenti i nuovi incarichi relativi allo sprint corrente:
- <NAME>: Amministratore, Progettista, Programmatore, Verificatore;
- <NAME>: Responsabile, Programmatore;
- <NAME>: Programmatore, Verificatore;
- <NAME>: Programmatore, Verificatore, Progettista;
- <NAME>: Verificatore, Amministratore;
- <NAME>: Verificatore.
== Test di integrazione
Durante la riunione odierna, si è sollevata la questione dell'organizzazione dei test di integrazione e dell'effettiva utilità di questa attività all'interno del progetto. Tuttavia, non si è giunti ad una conclusione definitiva in merito e la discussione è stata rimandata per consentire un'ulteriore valutazione una volta raccolte più informazioni. In particolare, è stato evidenziato il bisogno di approfondire il ruolo dei test di integrazione nel contesto specifico del nostro progetto, valutando attentamente i potenziali benefici e svantaggi di questa pratica, specialmente considerando le molte risorse che richiederebbe.
== Modifiche all'_Analisi dei Requisiti_
È stata discussa una modifica all'_Analisi dei Requisiti_, riguardante la terminologia utilizzata per riferirsi alla dashboard contenente la tabella relativa ai dati grezzi inviati da tutti i simulatori. Si è deciso di modificare il termine "Sensori" in "Dati grezzi". Questa modifica non riguarda solo il nome della dashboard, ma anche il suo contenuto: nel software non è stato implementato il passaggio di informazioni relative al sensore come lo stato della batteria, la data di ultima manutenzione ed altro, nonostante queste fossero state inizialmente incluse nell'_Analisi dei Requisiti_; inoltre, dato che la Proponente ha espresso il desiderio che i dati grezzi possano essere visibili e filtrabili all'interno di una tabella dedicata, il team ha deciso di scartare l'idea obsoleta di una dashboard dedicata allo stato dei sensori, optando per una dashboard dedicata, appunto, ai dati grezzi veri e propri.
Si occuperanno di questa modifica i futuri Analisti.
== Norme di Progetto: _Manuale Utente_
Si è deciso di aggiungere alle _Norme di Progetto_ la sezione riguardante il _Manuale Utente_. Questa sezione ha il duplice scopo di fungere da guida e di fornire una struttura organizzativa per lo sviluppo del documento. <NAME> si occupa sia di normarne la struttura e i contenuti all'interno delle _Norme di Progetto_, che di procedere con la stesura iniziale del documento vero e proprio, riflettendo le funzionalità attualmente implementate all'interno della dashboard di visualizzazione Grafana.
== Dashboard Grafana
Durante questo sprint, verranno implementate due dashboard: una relativa ai dati grezzi e l'altra al superamento delle soglie. La dashboard dei dati grezzi verrà utilizzata come sistema di filtraggio per i dati generati dai simulatori, consentendo di filtrare sia per i nomi dei sensori che per la loro tipologia. Se ne occupa <NAME>. La dashboard relativa al superamento delle soglie mostrerà i dati che superano determinati valori, in formato tabellare. Se ne occupa <NAME>.
== Metriche del _Piano di Qualifica_
<NAME> si occupa del calcolo delle metriche relative al prodotto, e della creazione di una github action per l'automatizzazione del calcolo delle metriche sull'efficienza.
== Mypy
È stata discussa l'introduzione di MyPy nell'attività di codifica (in sostiuzione di Pydantic) ma è stata presa la decisione di non procedere con tale implementazione. Si è ritenuto che l'introduzione di MyPy potesse aggiungere complessità senza fornire vantaggi significativi nel contesto attuale del progetto.
== Incontro con Cardin
Si è deciso di pianificare un incontro con il Professor Cardin la prossima settimana, per risolvere alcuni dubbi sul documento _Specifiche Tecniche_.
|
https://github.com/kaarmu/splash | https://raw.githubusercontent.com/kaarmu/splash/main/src/palettes/tol.typ | typst | MIT License | /* <NAME>'s (2021) color scheme.
*
* All colors and descriptions are credited <NAME>, see source below.
*
* Source: https://personal.sron.nl/~pault/data/colourschemes.pdf
* Accessed: 2023-04-12
*/
#let tol-bright = (
blue : rgb("#4477aa"),
cyan : rgb("#66ccee"),
green : rgb("#228833"),
yellow : rgb("#ccbb44"),
red : rgb("#ee6677"),
purple : rgb("#aa3377"),
grey : rgb("#bbbbbb"),
)
#let tol-high-contrast = (
white : rgb("#ffffff"),
yellow : rgb("#ddaa33"),
red : rgb("#bb5566"),
blue : rgb("#004488"),
black : rgb("#000000"),
)
#let tol-vibrant = (
blue : rgb("#0077bb"),
cyan : rgb("#33bbee"),
teal : rgb("#009988"),
orange : rgb("#ee7733"),
red : rgb("#cc3311"),
magenta : rgb("#ee3377"),
grey : rgb("#bbbbbb"),
)
#let tol-muted = (
indigo : rgb("#332288"),
cyan : rgb("#88ccee"),
teal : rgb("#44aa99"),
green : rgb("#117733"),
olive : rgb("#999933"),
sand : rgb("#ddcc77"),
rose : rgb("#cc6677"),
wine : rgb("#882255"),
purple : rgb("#aa4499"),
pale-grey : rgb("#dddddd"),
)
#let tol-medium-contrast = (
white : rgb("#ffffff"),
light-yellow : rgb("#eecc66"),
light-red : rgb("#ee99aa"),
light-blue : rgb("#6699cc"),
dark-yellow : rgb("#997700"),
dark-red : rgb("#994455"),
dark-blue : rgb("#004488"),
black : rgb("#000000"),
)
#let tol-light = (
light-blue : rgb("#77aadd"),
light-cyan : rgb("#99ddff"),
mint : rgb("#44bb99"),
pear : rgb("#bbcc33"),
olive : rgb("#aaaa00"),
light-yellow : rgb("#eedd88"),
orange : rgb("#ee8866"),
pink : rgb("#ffaabb"),
pale-grey : rgb("#dddddd"),
)
|
https://github.com/buxx/cv | https://raw.githubusercontent.com/buxx/cv/master/metadata.typ | typst | #let firstName = "Bastien"
#let lastName = "Sevajol"
#let personalInfo = (
github: "buxx",
phone: "+33 6 76 54 83 82",
email: "<EMAIL>",
extraInfo: ("bux.fr & linuxfr.org/users/bux-2")
)
#let headerQuoteInternational = (
"": [Développeur spécialisé dans l'open source depuis 15 ans],
)
#let cvFooterInternational = (
"": "Curriculum vitae",
)
#let letterFooterInternational = (
"": "Cover Letter",
)
#let nonLatinOverwriteInfo = (
"customFont": "Heiti SC",
"firstName": "",
"lastName": "",
)
#let awesomeColor = "skyblue" // Optional: skyblue, red, nephritis, concrete, darknight
#let profilePhoto = "../src/avatar.png" // Leave blank if profil photo is not needed
#let varLanguage = "" // INFO: value must matches folder suffix; i.e "zh" -> "./modules_zh"
#let varEntrySocietyFirst = false // Decide if you want to put your company in bold or your position in bold
#let varDisplayLogo = false // Decide if you want to display organisation logo or not
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion/completion_title.typ | typst | Apache License 2.0 | // path: references.bib
@article{Russell:1908,
Author = {<NAME>},
Journal = {American Journal of Mathematics},
Pages = {222--262},
Title = {Mathematical logic based on the theory of types},
Volume = 30,
Year = 1908}
-----
// contains:Russell:1908,Mathematical logic based on the theory of types
// compile:true
#set heading(numbering: "1.")
== Test <R>
@R/* range -2..0 */
#bibliography("references.bib")
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/ttt-exam/0.1.0/template/exam.typ | typst | Apache License 2.0 | #import "@preview/ttt-exam:0.1.0": *
#set text(size: 12pt, font: ("Rubik"), weight: 300, lang: "de")
#let logo = box(height: 5cm,image("logo.jpg") )
#show: exam.with(..toml("meta.toml").exam, logo: logo );
= Part 1: Free text questions
#assignment[
Answer the following questions.
#question(points: 1)[
Solve the following equation for $x$:
$ 3x+5=17 $]
#answer(field: caro(6))[
$ 3x+5=17 $
$ 3x=17-53x=17-5 $
$ 3x=123x=12 $
$ x=123x=312 $
$ x=4x=4 $
]
]
= Part 2: Multiple and single choice
#multiple-choice(
prompt: "Which numbers are even",
distractors: (
"1", "3", "5"
),
answer: (
"2", "4",
),
dir: ltr,
hint: [_Two options are correct_]
)
#multiple-choice(
prompt: "Which number is a prime number",
distractors: (
"1", "6", "15", "9",
),
answer: (
"7",
),
dir: ltr,
)
// show point-table or point-sum-box
// uncomment if you need it.
// = Points
// #point-table
// #h(1fr)
// #align(end, point-sum-box)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-2EBF0.typ | typst | Apache License 2.0 | #let data = (
"0": ("<CJK Ideograph Extension I, First>", "Lo", 0),
"26d": ("<CJK Ideograph Extension I, Last>", "Lo", 0),
)
|
https://github.com/piepert/philodidaktik-hro-phf-ifp | https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/unterrichtsplanung/medien.typ | typst | Other | #import "/src/template.typ": *
== #ix("Medien", "Medien", "Medium")
#def("Medien", [
Medien sind Träger und Vermittler von Informationen.
])
Medien sind vielfältig und können im Unterricht verschiedene Aufgaben erfüllen. Unter anderem könnte man sie wie folgt einteilen:
#[
#set par(justify: false)
#table(columns: 5,
inset: 0pt,
column-gutter: 1.125em,
row-gutter: 1em,
stroke: none, ..(
[schriftliche Medien],
[graphische Medien],
[visuelle Medien],
[akustische Medien],
[Gegenstände]
).map(e => strong(e)),
[Textauszüge], [Tagelbilder], [Bilder], [Musik], [Statuen],
[Schulbücher], [Schemata], [Karikaturen], [Tonaufnahme], [Denkmäler],
[Populärliteratur], [Diagramme], [Kurzvideos], [Hörspiele], [Modelle],
[Gedichte], [], [Filme], [Hörbücher], [],
[], [], [Comics], [], [],
)
]
#def("ephemere Medien", [
Ephemere Medien sind flüchtige, nur im Augenblick bestehende und sich stetig verändernde Medien. "In Texten, die gedrucktt vorliegen, kann man vor- und zurückblättern, Sätze mehrfach lesen, Bedeutsames anstreichen usw. Filme erlauben dergleichen nicht: die durch bloßes Anschauen und Zuhören vermittelten Eindrücke lassen sich ungleich schwerer festhalten und analysieren."#en[@PetersRolf2007_Filme[S. 116]]
], "Medium, ephemer")
Das Philosophieren mit #ix("ephemeren Medien", "Medium, ephemer") ist in dreierlei Hinsicht herausfordernd. Für die Probleme des ephemeren Charakters gibt zwei große Lösungswege: Zum einen ist es möglich Filme mehrmals zu schauen, zum anderen können während des Schauens Arbeitsblätter auszuteilen, auf denen die SuS ihre Eindrücke festhalten können.#en[Vgl. @PetersRolf2007_Filme[S. 116]] Die anderen Fragen, die sich stellen, sind:#en[Vgl. @PetersRolf2007_Filme[S. 116]]
+ Ist es legitim, nur Ausschnitte eines Films zu schauen, oder muss er vollständig gezeigt werden?
+ An welcher Stelle der Stunden- und Sequenzstruktur sollte mit Filmen philosophiert werden?
#todo[Im Bezug auf Descartes ergänzen: Reportage über Supersinne der Tiere, optische Täuschungen, Matrix, Inception, irgendwas zu Gehirn im Tank?] |
https://github.com/leyan/cetzpenguins | https://raw.githubusercontent.com/leyan/cetzpenguins/main/gallery/basicPenguin.typ | typst | MIT License | #import "@preview/cetz:0.2.2"
#import "../src/penguins.typ" :penguin,penguinInternal,anchor-coords
#set page(width: 3cm, height: 4cm)
#set align(center+horizon)
#penguin() |
https://github.com/DaAlbrecht/thesis-TEKO | https://raw.githubusercontent.com/DaAlbrecht/thesis-TEKO/main/content/Use_cases.typ | typst | Three main use cases exist.
- Replay a message based on a header value (Transaction ID) and a queue
- Replay a message based on a given time interval and a queue
- Get messages based on a given time interval and a queue
#figure(
image("../assets/use_case_diagram.svg", width: 65%),
kind: image,
caption: "Use case diagram",
)<use_case_diagram>
As mentioned in @Out_of_scope the microservice will be integrated into a
customers observability system. The observability system will have a custom
button, that allows to replay a message on button press. For this to work the
first use case is needed. The second use case is not directly related to a customer's need but a nice-to-have feature.
It is especially useful for testing purposes.
|
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/array/exponents/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": *
#set page(width: auto, height: auto, margin: 1cm)
#for exponents in ("individual", "combine-bracket", "combine") [
#metro-setup(list-exponents: exponents, product-exponents: exponents, range-exponents: exponents)
#num-list("5e3", "7e3", "9e3", "1e4")
#num-product("5e3", "7e3", "9e3", "1e4")
#num-range("5e3", "7e3")
]
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/snippets/math/fonts.md | markdown | MIT License | # Fonts
## Set math font
**Important:** The font you want to set for math should _contain_ necessary math symbols. That should be a special font with math. If it isn't, you are very likely to get _an error_ (remember to set `fallback: false` and check `typst fonts` to debug the fonts).
```typ
#show math.equation: set text(font: "Fira Math", fallback: false)
$
emptyset \
integral_a^b sum (A + B)/C dif x \
$
```
|
https://github.com/mrcinv/nummat-typst | https://raw.githubusercontent.com/mrcinv/nummat-typst/master/domace_02.typ | typst | #import "@preview/minitoc:0.1.0": *
= 2. domača naloga
Tokratna domača naloga je sestavljena iz dveh delov. V prvem delu morate
implementirati program za računanje vrednosti dane funkcije $f lr((x))$.
V drugem delu pa izračunati eno samo številko. Obe nalogi rešite na
#strong[10 decimalk] \(z relativno natančnostjo $bold(10^(- 10))$)
Uporabite lahko le osnovne operacije, vgrajene osnovne matematične
funkcije `exp`, `sin`, `cos`, …, osnovne operacije z matrikami in
razcepe matrik. Vse ostale algoritme morate implementirati sami.
Namen te naloge ni, da na internetu poiščete optimalen algoritem in ga
implementirate, ampak da uporabite znanje, ki smo ga pridobilili pri tem
predmetu, čeprav na koncu rešitev morda ne bo optimalna. Uporabite lahko
interpolacijo ali aproksimacijo s polinomi, integracijske formule,
Taylorjevo vrsto, zamenjave spremenljivk, itd. Kljub temu pazite na
#strong[časovno in prostorsko zahtevnost], saj bo od tega odvisna tudi
ocena.
Izberite #strong[eno] izmed nalog. Domačo nalogo lahko delate skupaj s
kolegi, vendar morate v tem primeru rešiti toliko različnih nalog, kot
je študentov v skupini.
Če uporabljate drug programski jezik, ravno tako kodi dodajte osnovno
dokumentacijo, teste in demo.
#minitoc(title: [Naloge], target: heading.where(depth: 2), depth:4)
== Naloge s funkcijami
<naloge-s-funkcijami>
Implementacija funkcije naj zadošča naslednjim zahtevam:
- relativna napaka je manjša od $5 dot 10^(-11)$ za vse argumente in
- časovna zahtevnost je omejena s konstanto, ki je neodvisna od argumenta.
#minitoc(title: [Naloge], target: heading.where(depth: 3))
=== Fresnelov integral \(težja)
<fresnelov-integral-težja>
Napišite učinkovito funkcijo, ki izračuna vrednosti Fresnelovega
kosinusa
$ C(x) = integral_0^x cos((pi t^2)/2) d t. $
#strong[Namig]: Uporabite pomožni funkciji
$ f(z) &= 1/(pi sqrt(2)) integral_0^oo e^(- (pi z^2 t)/2) /(sqrt(t)(t^2 + 1)) d t\
g(z) &= 1/(pi sqrt(2)) integral_0^oo (sqrt(t) e^(- (pi z^2 t)/2)) /(t^2 + 1) d t,
$
kot je opisano v @dlmf7.
=== Funkcija kvantilov za $N(0 , 1)$
<funkcija-kvantilov-za-n01>
Napišite učinkovito funkcijo, ki izračuna funkcijo kvantilov za standardno normalno
porazdeljeno slučajno spremenljivko. Funkcija kvantilov je inverzna
funkcija $Phi^(-1)(x)$ porazdelitvene funkcije:
$
Phi(x) = 1/(sqrt(2pi)) integral_(-infinity)^x e^(-t^2/2) d t.
$
Poskrbite, da bo relativna napaka za vrednosti blizu $0$ in $1$ dovolj majhna in da je
časovna zahtevnost omejena z isto konstanto na celem intervalu $(0, 1)$.
=== Integralski sinus \(težja)
<integralski-sinus-težja>
Napišite učinkovito funkcijo, ki izračuna integralski sinus
$ "Si"(x) = integral_0^x frac(sin(t), t) d t. $
Uporabite pomožni funkciji
$
f(z) &= integral_0^oo sin(t)/(t + z) = integral_0^oo e^(-z t)/(t^2 + 1) d t\
g(z) &= integral_0^oo cos(t)/(t + z) = integral_0^oo (t e^(-z t))/(t^2 + 1) d t\
"Si"(z) &= pi/2 - f(z)cos(z) - g(z) sin(z),
$
kot je opisano v @dlmf6.
=== Naravni parameter \(težja)
<besselova-funkcija-težja>
Napišite učinkovito funkcijo, ki izračuna #link("https://en.wikipedia.org/wiki/Differentiable_curve#Length_and_natural_parametrization")[naravni parameter]:
$ s(t) = integral_0^t sqrt(dot(x)(tau)^2 + dot(y)(tau)^2) d tau $
za parametrično krivuljo
$
(x(t), y(t)) = (t^3 - t, t^2 - 1).
$
Za velike vrednosti argumenta $t$ aproksimirajte funkcijo $s(1/t)^(-1)$ s polinomom.
== Naloge s števili
<naloge-s-števili>
#minitoc(title: [Naloge], target: heading.where(depth: 3))
=== Sila težnosti
<sila-težnosti>
Izračunajte velikost sile težnosti med dvema vzporedno postavljenima
enotskima homogenima kockama na razdalji 1. Predpostavite, da so vse
fizikalne konstante, ki nastopajo v problemu, enake 1. Sila med dvema
telesoma $T_1 , T_2 subset bb(R)^3$ je enaka
$ bold(F) = integral_(T_1) integral_(T_2) frac(bold(r)_1 - bold(r_2), ∥bold(r)_1 - bold(r_2)∥^2) d bold(r)_1 d bold(r)_2 dot.basic $
=== Ploščina hipotrohoide
<ploščina-hipotrohoide>
Izračunajte ploščino območja, ki ga omejuje hypotrochoida podana
parametrično z enačbama:
$ x lr((t)) = lr((a plus b)) cos lr((t)) plus b cos lr((frac(a plus b, b) t)) $
$ y lr((t)) = lr((a plus b)) sin lr((t)) plus b sin lr((frac(a plus b, b) t)) $
za parametra $a = 1$ in $b = - 11 / 7$.
#strong[Namig]: Uporabite formulo za
#link("https://sl.wikipedia.org/wiki/Plo%C5%A1%C4%8Dina#Plo%C5%A1%C4%8Dine_krivo%C4%8Drtnih_likov")[ploščino krivočrtnega trikotnika] pod krivuljo:
$ P = 1 / 2 integral_(t_1)^(t_2) lr((x lr((t)) dot(y) lr((t)) - dot(x) lr((t)) y lr((t)))) d t $
=== Povprečna razdalja \(težja)
<povprečna-razdalja-težja>
Izračunajte povprečno razdaljo med dvema točkama znotraj telesa $T$, ki je enako razliki dveh kock:
$ T = ([- 1 , 1])^3 - ([0 , 1])^3. $
Integral na produktu razlike dveh množic
$(A - B) times (A - B)$ lahko izrazimo kot vsoto integralov:
$ integral_(A - B) integral_(A - B) & f(x, y) d x d y = integral_A integral_A f(x, y) d x d y \
& - 2 integral_A integral_B f(x, y) d x d y + integral_B integral_B f(x, y) d x d y $
=== Ploščina Bézierove krivulje
<ploščina-bézierove-krivulje>
Izračunajte ploščino zanke, ki jo omejuje Bézierova krivulja dana s
kontrolnim poligonom:
$ (0 , 0) , (1 , 1) , (2 , 3) , (1 , 4) , (0 , 4) , (- 1 , 3) , (0 , 1) , (1 , 0). $
#strong[Namig]: Uporabite lahko formulo za
#link("https://en.wikipedia.org/wiki/Area#Area_in_calculus")[ploščino krivočrtnega trikotnika] pod krivuljo:
$ P = 1 / 2 integral_(t_1)^(t_2) lr((x(t) dot(y)(t) - dot(x)(t) y(t))) d t. $
== Lažje naloge \(ocena največ 9)
<lažje-naloge-ocena-največ-9>
Naloge so namenjen tistim, ki jih je strah eksperimentiranja ali pa za
to preprosto nimajo interesa ali časa. Rešiti morate eno od nalog:
=== Gradientni spust z iskanjem po premici
=== Interpolacija z baricentrično formulo
<ineterpolacija-z-baricentrično-formulo>
Napišite program, ki za dano funkcijo $f$ na danem intervalu
$lr([a , b])$ izračuna polinomski interpolant, v Čebiševih točkah.
Vrednosti naj računa z #link("https://en.wikipedia.org/wiki/Lagrange_polynomial#Barycentric_form")[baricentrično Lagrangevo interpolacijo,] po
formuli
$ l(x) = cases(delim: "{", frac(sum frac(f lr((x_j)) lambda_j, x - x_j), sum frac(lambda_j, x - x_j)) & quad x eq.not x_j, f lr((x_j)) & quad "sicer") $
Čebiševe točke so podane na intervalu $lr([- 1 , 1])$ s formulo
$ x_k = cos((2k -1)/(2n) pi), quad k = 0,1 med dots med n-1, $
vrednosti uteži $lambda_k$ pa so enake
$ lambda_k = (- 1)^k cases(delim: "{", 1 & quad 0 lt i lt n, 1 / 2 & quad i = 0 , n & quad "sicer".) $
Za interpolacijo na splošnem intervalu $lr([a , b])$ si pomagaj z
linearno preslikavo na interval $lr([- 1 , 1])$. Program uporabi
za tri različne funkcije $e^(- x^2)$ na $lr([- 1 , 1])$,
$frac(sin x, x)$ na $lr([0 , 10])$ in $lr(|x^2 - 2 x|)$ na
$lr([1 , 3])$. Za vsako funkcijo določi stopnjo polinoma, da napaka
ne bo presegla $10^(- 6)$.
=== Gauss-Legendrove kvadrature
<gauss-legendrove-kvadrature>
Izpelji #link("https://en.wikipedia.org/wiki/Gaussian_quadrature#Gauss%E2%80%93Legendre_quadrature")[Gauss-Legendreovo integracijsko pravilo] na dveh točkah
$ integral_0^h f(x) d x = A f(x_1) + B f(x_2) + R_f $
vključno s formulo za napako $R_f$. Izpelji sestavljeno pravilo za
$integral_a^b f lr((x)) d x$ in napiši program, ki to pravilo uporabi za
približno računanje integrala. Oceni, koliko izračunov funkcijske
vrednosti je potrebnih, za izračun približka za
$ integral_0^5 frac(sin x, x) d x $
na 10 decimalk natančno. _Namig_: Najprej izpelji pravilo na intervalu $[-1, 1]$ in ga
nato prevedi na poljuben interval $[x_i, x_(i+1)]$. Za oceno napake uporabite izračun z dvojnim številom korakov.
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/pagebreak_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Just a pagebreak.
// Should result in two pages.
#pagebreak()
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-04.typ | typst | Other | // Test rvalue out of bounds.
// Error: 2-17 array index out of bounds (index: 5, len: 3) and no default value was specified
#(1, 2, 3).at(5)
|
https://github.com/songoffireandice03/simple-template | https://raw.githubusercontent.com/songoffireandice03/simple-template/main/templates/physics.typ | typst | #import "maths.typ": *
#import "@preview/physica:0.9.2": *
#let sc(it) = math.class("normal",
text(font: "", stylistic-set: 1, $cal(it)$) + h(0em)
)
// The physics stuff
#let bernoulli = $p_(1) + rho g y_(1) + dfr(rho v_(1)^(2),2) = p_(2) + rho g y_(2) + dfr(rho v_(2)^(2),2)$
#let ex = $va(e)_(x)$
#let ey = $va(e)_(y)$
#let ez = $va(e)_(z)$
#let et = $va(e)_( theta )$
#let ef = $va(e)_( phi )$
#let er = $va(e)_( r )$
#let vi = $vb(hat(i))$
#let vj = $vb(hat(j))$
#let vk = $vb(hat(k))$
#let vr = $vb(hat(r))$
#let vl = $va(vb(l))$
#let vv = $va(vb(v))$
#let vA = $va(vb(A))$
#let vE = $va(vb(E))$
#let vS = $va(vb(S))$
#let vF = $va(vb(F))$
#let vB = $va(vb(F))$
#let vab(content) = $va(vb(content))$
#let pr = $lt.curly$
// Units
#let liter = $space upright(l)$
#let kelvin = $space upright(K)$
#let mK = $upright("mK")$
#let nK = $upright("nK")$
#let uK = $upright(mu K)$
#let minute = $upright("min")$
#let farad = $space upright("F")$
#let watt = $space upright("W")$
#let hertz = $upright("Hz")$
#let THz = $upright("THz")$
#let GHz = $upright("GHz")$
#let kHz = $upright("kHz")$
#let MHz = $upright("MHz")$
#let pascal = $upright("Pa")$
#let MPa = $upright("MPa")$
#let GPa = $upright("GPa")$
#let eV = $upright("eV")$
#let MeV = $upright("MeV")$
#let GeV = $upright("GeV")$
#let hr = $space upright("h")$
#let second = $space upright("s")$
#let coulomb = $space upright(C)$
#let newton = $space upright(N)$
#let volt = $upright(V)$
#let hr2 = $upright("h")$
#let second2 = $upright("s")$
#let coulomb2 = $upright(C)$
#let newton2 = $upright(N)$
#let volt2 = $upright(V)$
#let mV = $upright("mV")$
#let nV = $upright("nV")$
#let MV = $upright("MV")$
#let uV = $mu upright(V)$
#let meter = $space upright(m)$
#let meter2 = $upright(m)$
#let tesla = $space upright(T)$
#let tesla2 = $upright(T)$
#let henry = $space upright(H)$
#let henry2 = $upright(H)$
#let ohm = $space ohm$
#let ohm2 = $ohm$
#let Wb = $upright("Wb")$
#let cT = $upright("mT")$
#let kT = $upright("kT")$
#let dT = $upright("dT")$
#let pT = $upright("pT")$
#let pF = $upright("pF")$
#let nF = $upright("nF")$
#let uF = $upright(mu F)$
#let uT = $upright(mu T)$
#let cm = $upright("cm")$
#let km = $upright("km")$
#let dm = $upright("dm")$
#let pm = $upright("pm")$
#let mW = $upright("mW")$
#let mH = $upright("mH")$
#let um = $upright(mu m)$
#let nm = $upright("nm")$
#let mm = $upright("mm")$
#let us = $upright(mu s)$
#let ns = $upright("ns")$
#let ms = $upright("ms")$
#let amp = $space upright(A)$
#let mA = $upright("mA")$
#let uA = $mu upright("A")$
#let gram = $upright(g)$
#let joule = $upright(J)$
#let mJ = $upright("mJ")$
#let kJ = $upright("kJ")$
#let ug = $upright(mu g)$
#let ng = $upright("ng")$
#let mg = $upright("mg")$
#let pg = $upright("pg")$
#let mW = $upright("mW")$
#let GW = $upright("GW")$
#let uW = $upright(mu W)$
#let nW = $upright("nW")$
#let kW = $upright("kW")$
#let MW = $upright("MW")$
#let mps = $meter sl second2$
#let mps2 = $meter sl upright(s)^(2)$
#let kmph = $space km sl hr$
#let Nm = $upright("Nm")$
#let rad = $upright("rad")$
#let kg = $upright("kg")$
#let pt(content) = $dot 10^(content)$
#let Hom = math.upright("Hom")
#let degC = $degree upright(C)$
#let degF = $degree upright(F)$
#let atm = $upright("atm")$
#let bar2 = $upright("bar")$
#let const = $upright("const")$
#let cte = $upright("cte")$ |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/2044-invalid-parsed-ident_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// In this bug, the dot at the end was causing the right parenthesis to be
// parsed as an identifier instead of the closing right parenthesis.
// Issue: https://github.com/typst/typst/issues/2044
$floor(phi.alt.)$
$floor(phi.alt. )$
|
https://github.com/jonaspleyer/peace-of-posters | https://raw.githubusercontent.com/jonaspleyer/peace-of-posters/main/docs/content/showcase/2023-10-23-bwHPC-symposium/main.typ | typst | MIT License | /// IMPORT THE POSTERS PACKAGE
#import "@preview/peace-of-posters:0.4.3" as pop
// Define overall formatting defaults for the document.
// These settings can be overwritten later on.
#let spacing = 1.2em
#set page("a0", margin: 1.5cm)
#pop.set-poster-layout(pop.layout-a0)
#pop.set-theme(pop.uni-fr)
#set text(font: "Arial", size: pop.layout-a0.at("body-size"))
#let box-spacing = 1.2em
#set columns(gutter: box-spacing)
#set block(spacing: box-spacing)
#pop.update-poster-layout(spacing: box-spacing)
// Define colors as given by coroprate design of uni freiburg
#let uni_dark_blue = rgb("#1d154d")
/// START OF THE DOCUMENT
#pop.title-box(
[#box(inset: (bottom: -0.3em), image(height: 1.2em, "images/cellular_raza_dark_mode.svg")) - Novel Flexibility in Design of Agent-Based Models in Cellular Systems],
authors: "<NAME>¹, <NAME>¹",
institutes: "¹Freiburg Center for Data-Analysis and Modeling",
image: image("/UFR-Siegel-white.png"),
)
#pop.column-box()[
#set par(justify: true)
#set align(center)
Agent-Based Models (ABMs) allow researchers to describe complex cellular systems in a mechanistic manner but can also abstract over less-known processes.
It is often desirable to exchange only parts of the model eg. changing the spatial representation of cells from a spherical interaction potential to an elliptical.
Existing tools lack in flexibility and cannot change their internal representation of cells.
To solve these problems we created `cellular_raza`, a novel library that offers previously unknown flexibility in model design while retaining excellent performance.
]
#columns(2, gutter: spacing)[
#pop.column-box(
heading: [Features],
)[
#columns(2, gutter: 0.5*spacing)[
- Generic Progamming allows for unparalleled flexibility
- Parallelized (via OS-threads and Domain-decomposition)
- Produces deterministic results
#colbreak()
- Modular
- No inherent assumptions
- User has complete control over every parameter and functionality
- Free software (GPLv2.0)
]
]
#pop.column-box(heading: "Scaling Behavior")[
#figure(stack(dir: ltr,
box([#image("images/scaling_0.png")
#place(top+left, rect(text("A", fill: white), fill: uni_dark_blue, inset: 10pt))], width: 49.5%),
box(width: 1%),
box([#image("images/scaling_1.png")
#place(top+left, rect(text("B", fill: white), fill: uni_dark_blue, inset: 10pt))], width: 49.5%)
),
caption: [
(A) Linear fit $f(x)=a x$ of scaling with increasing amounts of agents.
(B) Amdahl's Law with up to $p=98.6%$ parallelized parts of the executed code resulting in a $21.5$ times speedup.
])
#align(right, text(size: 20pt)[
#super("1")Workstation, AMD 3960X (24C/48T) \@3.8GHz-4.5GHz, 64Gb DDR4 3200MT/s\
#super("2")Desktop, AMD 3700x (8C/16T) \@3.6GHz-4.4GHz, 32Gb DDR4 3200MT/s\
#super("3")Laptop, Intel 12700H (6+8C/12+8T) 45W \@3.5GHz-4.7GHz 32Gb DDR5 4800MT/s
])
]
#pop.column-box(heading: [Cellular Properties as Rust Traits])[
Abstract traits are used to define cellular interactions via force mechanics.
Users implement traits and obtain full control over cellular behavior.
#figure([
```rust
pub trait Interaction<Pos, Vel, Force, Inf = ()> {
/// Get additional information of cellular properties (ie. for
/// cell-specific interactions). For now, this can also be used
/// to get the mass of the other cell-agent. In the future, we
/// will probably provide a custom function for this.
fn get_interaction_information(&self) -> Inf;
/// Calculates the force (velocity-derivative) on the
/// corresponding external position given external velocity.
/// By providing velocities, we can calculate terms that are
/// related to friction.
fn calculate_force_between(
&self,
own_pos: &Pos,
own_vel: &Vel,
ext_pos: &Pos,
ext_vel: &Vel,
ext_info: &Inf,
) -> Option<Result<Force, CalcError>>;
}
```])
// Notice that even the types themselves such as position, force and velocity are generic, meaning this allows not only to switch between 2D and 3D but also to represent cells entirely differently as desired.
// The user is able and encouraged to modify and adjust these types as needed.
]
#pop.column-box(
heading: [Roadmap],
stretch-to-next: true,
)[#columns(2)[
- Stabilize user API
- Additional backends (GPUs, MPI)
- Multi-Scale
- Stochastic processes
#colbreak()
- Restarting simulations
- Advanced error handling
- Support common export formats (such as `*.vtk` files)
]]
#colbreak()
#pop.column-box(heading: [Branching patterns of _Bacillus subtilis_ in 2D & 3D])[
#figure(stack(dir: ltr,
box([
#image("images/bacteria_cells_at_iter_0000088000.png", width: 49.5%)
#place(top+left, dx: 10pt, dy: 10pt, rect(text("2D", fill: white), fill: uni_dark_blue, inset: 10pt))
]),
box(width: 1%),
box([
#image("images/bacteria_population-3d-0000-cropped.png", width: 49.5%)
#place(top+left, dx: 10pt, dy: 10pt, rect(text("3D", fill: white), fill: uni_dark_blue, inset: 10pt))
])
), caption: [
Spatio-Temporal patterns inspired by @kawasakiModelingSpatioTemporalPatterns1997 @matsushitaInterfaceGrowthPattern1998.
Cells ($~$500,000) consume extracellular nutrients, grow, divide and self-organize into a branched pattern.
Brighter colors indicate higher nutrient concentrations.
])
]
#pop.column-box(heading: "Cell Sorting in 3D")[
#figure(stack(dir: ltr,
box([
#image("images/cell_sorting_start.png", width: 49.5%)
#place(top+left, dx: 10pt, dy: 10pt, rect(text("A", fill: white), fill: uni_dark_blue, inset: 10pt))
]),
box(width: 1%),
box([
#image("images/cell_sorting_end.png", width: 49.5%)
#place(top+left, dx: 10pt, dy: 10pt, rect(text("B", fill: white), fill: uni_dark_blue, inset: 10pt))
]),
),
caption: [
Cells with species-specific interactions.
The initially randomized state (A) organizes itself and the two species get separated (B).
])
]
#pop.column-box(heading: [Semi-Vertex Models])[
#figure(stack(dir: ltr,
box([
#image("images/kidney_organoid_model-final.png", width: 49.5%)
#place(top+left, dx: 10pt, dy: 10pt, rect(text("A", fill: uni_dark_blue), fill: white, inset: 10pt))
]),
box(width: 1%),
box([
#image("images/free_vertex_model_end.png", width: 49.5%)
#place(top+left, dx: 10pt, dy: 10pt, rect(text("B", fill: uni_dark_blue), fill: white, inset: 10pt))
])
),
caption: [
Freely motile semi-vertex models with (A) 6 and (b) 4 vertices.
Vertices attract each other but will be repelled once inside another cell.
])
]
#pop.column-box(heading: "Sources", stretch-to-next: true)[
#set text(size: 24pt)
#bibliography("/cellular_raza.bib", title: none)
]
]
#pop.bottom-box(
stack(dir: ltr,
box(width: 20.5%, [
#set text(size: 30pt)
bwHPC Symposium
#linebreak()
23.10.2023 - Mannheim
]),
box(width: 29.75%, height: 1.25em, align(center+horizon)[
#set text(size: 35pt)
#box(image(height: 30pt, "images/github-mark-white.png"))
#link("https://github.com/jonaspleyer/")[github.com/jonaspleyer]
]),
box(width: 23.25%, align(center, image(height: 80pt, "images/cellular_raza_dark_mode.svg"))),
box(width: 26.75%, height: 1.25em, align(center+horizon, [
#set text(size: 35pt)
#box(image(height: 30pt, "images/JonasPleyer-edited.jpeg"))
#link("https/jonas.pleyer.org")[jonas.pleyer.org]
])),
),
text-relative-width: 80%,
logo: stack(dir: ltr,
image(width: 0.3*(100% - 0.5*spacing - 80%), "fdm_logo.jpg", fit: "contain"),
h(0.5*spacing),
image(width: 0.7*(100% - 0.5*spacing - 80%), "UFR-Schriftzug-white.png", fit: "contain"),
)
)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-node-09.typ | typst | Other | // Error: 7-12 only element functions can be used as selectors
#show upper: it => {}
|
https://github.com/arturfast/basic-resume-template | https://raw.githubusercontent.com/arturfast/basic-resume-template/master/basic-resume-template.typ | typst | // Basic Resume Template Artur Fast 2024
// Run this function first to format the whole document
// Include it like this: #show: format.with()
#let format(body) = {
set page(margin: (y: 1cm, x: 1cm))
set text(
font: "Ubuntu",
size: 11pt
)
show heading: set text(weight: "regular")
show heading: heading => [
#pad(top: 0pt, bottom: -15pt, [
#underline(smallcaps(heading.body))
])
#line(length: 100%, stroke: (thickness: 0pt))
]
body
}
#let exp(timeframe: "", job: "", location: "") = {
pad(left: 2%, right: 2%, [
#grid(columns: (50%, 45%), column-gutter: 5%, [#grid(rows: 2, row-gutter: 5pt, [*#job*], [#text(fill: rgb("#999999"), weight: "regular", [#location])])], grid.cell(align: horizon, [#timeframe]))
])
}
#let edu(timeframe: "", school: "", location: "", degree: "") = {
pad(left: 2%, right: 2%, [
#if degree == "" [
#grid(columns: (50%, 45%), column-gutter: 5%, [#grid(rows: 2, row-gutter: 5pt, [#school], [#text(fill: rgb("#999999"), weight: "regular", [#location])])], grid.cell(align: horizon, [#timeframe]))
] else [
#grid(columns: (50%, 45%), column-gutter: 5%, [#grid(rows: 3, row-gutter: 5pt, [#school], [#text(fill: rgb("#999999"), weight: "regular", [#location])], [*#degree*])], grid.cell(align: horizon, [#timeframe]))
]
])
}
#let maketitle(name: "", email: "", phone: "", url: "") = {
pad(y: 20pt)[
#set align(center)
#set text(font: "New Computer Modern")
#grid(columns: 3, rows: 2, row-gutter: 18pt, column-gutter: 15pt, grid.cell(colspan: 3, align: center, [#text(size: 30pt, [#smallcaps(name)])]), [#email], [#phone], [#url])
]
}
// Everything has to be wrapped up in this
#let page_layout(left: "", right: "") = {
grid(columns: (60%, 40%), [#left], [#right])
}
#let point(head: "", tail: "") = {
grid(rows: 2, [#text(fill: rgb("#999999"), weight: "regular", [#head])], [#tail], gutter: 5pt)
}
|
|
https://github.com/ludwig-austermann/typst-timetable | https://raw.githubusercontent.com/ludwig-austermann/typst-timetable/main/example/2023.typ | typst | MIT License | #import "../timetable.typ": timetable
#set page(margin: 0.5cm, height: auto)
#timetable(
toml("2023.toml"),
//language: "it",
//date: [this year],
//show-header: false,
//show-alternatives: false,
//show-description: false,
//color-theme: "Set1_9",
) |
https://github.com/SundaeSwap-finance/sundae-audits-public | https://raw.githubusercontent.com/SundaeSwap-finance/sundae-audits-public/main/example/example.typ | typst | #import "../template/audit.typ": *
#show: report.with(
client: "Example",
title: "Example audit report",
repo: "https://github.com/SundaeSwap-finance/sundae-audits",
date: "2023-01-15",
authors: (
(
name: "<NAME>",
display: text(1.3em, $pi$) + " Lanningham",
),
),
)
= Audit Manifest
Please find below the list of pinned software dependencies and files that were covered by the audit.
#software_versions(
items: (
(
name: "Staking Contracts",
version: "0.0.0",
commit: "<PASSWORD>",
),
)
)
#files_audited(
items: (
(
file: "validators/a.ak",
hash: "9916fb18fb1e6c3015270a17841acd5a8e4414e760c910bbe7e7a0fd72ed2fd3",
),
(
file: "validators/b.ak",
hash: "d14562ce6a6e190cd3074304457a2d76e3a26e3ac059bfa0918748d0d0299db8",
),
(
file: "validators/c.ak",
hash: "9311884bc97ce154eacb7c25b06f118169d058fe57862da1d3ea6e46d33a7baf",
),
(
file: "validators/d.ak",
hash: "e5d7a0ebd84f7905076e0dbc2b60d6bec5de7559fdcf792aeacb4c638bd33a19",
),
(
file: "lib/.../e.ak",
hash: "099cf3ffd3b468455d6dcbace6dec6c3386f53d23f07aa35c4090bda4acf4d50",
),
(
file: "lib/.../f.ak",
hash: "5af9ebd593cbbcbf087a00bc9f9a8daad2d47014bdca0cfc3c80e858bcac3c02",
),
)
)
#parameters(
(
(
name: "delay",
value: "1500",
),
)
)
#artifacts(
(
(
validator: "abc",
method: "mint",
hash: "41429696a31fccad078830c182fec39d0df34ec5526df3420fdb4ac132f81843",
),
)
)
#pagebreak()
= Specification
This is a protocol that seeks to do a thing.
#pagebreak()
== Detailed Specification
=== Definitions
#defn("A thing",
[A thing, that references another #ref("Other thing")]
)
#defn("Other thing",
[Another thing, referred to by #ref("A thing")],
)
#pagebreak()
=== Requirements
+ The protocol must do a thing.
+ It must do it well.
+ It must do it fast.
#transaction(
"Some Transaction",
inputs: (
(
name: "Sample UTXO",
address: "Pool Contract",
value: (
ada: 10,
),
datum: (
a: 123,
b: "xyz",
)
),
(
name: "Other UTXO",
value: (
ada: 1,
"Access NFT": 1,
),
datum: (
a: 123,
b: "xyz",
)
),
(
name: "Third UTXO",
address: "Order Contract",
value: (
ada: "N",
INDY: "M + Z",
LQ: "P"
),
datum: (
a: 123,
b: "xyz",
)
),
(
name: "Fourth UTXO",
reference: true,
value: (
ada: 1000000,
),
datum: (
a: 123,
b: "xyz",
c: 123,
)
),
(
name: "Fifth UTXO",
reference: true,
value: (
ada: 1000000,
WMT: "X + Y"
),
datum: (
a: 123,
b: "xyz",
c: 123,
d: "xyz"
)
),
),
outputs: (
(
name: "Output UTXO",
address: "Pool Contract",
value: (
ada: 2000010,
"Access NFT": 1,
),
datum: (
a: 123,
b: "xyz",
)
),
(
name: "Other Output",
address: "Order Contract",
value: (
ada: "N",
INDY: "M + Y",
LQ: "P",
),
datum: (
a: 123,
b: "xyz",
)
),
(
name: "Third Output",
address: "Order Contract",
value: (
ada: 1,
WMT: "X"
),
datum: (
a: 123,
b: "xyz",
)
),
),
signatures: (
"User A",
"User B",
),
certificates: (
"Withdraw Stake A",
),
notes: [ABC! tada!]
)
= Findings Summary
#findings(prefix: "EX", items: (
(
title: [Some Minor Inconvenience],
severity: "Minor",
category: "Incentives",
description: [
This is a small issue.
],
recommendation: [
Maybe fix #ref("Other thing")
],
resolution: (
comment: "This isn't actually an issue"
)
),
(
title: [Major issue],
severity: "Major",
category: "Access",
description: [
Some major issue with a the protocol.
],
recommendation: [
Fix it.
],
),
)) |
|
https://github.com/VZkxr/Typst | https://raw.githubusercontent.com/VZkxr/Typst/master/Seminario/Presentacion/presentation.typ | typst | #let blanco = luma(95%)
#let negro = luma(14%)
#let escarlata = rgb("EA2F15")
#let naranja = rgb("FF9900")
#let amarillo = rgb("FFD000")
#let chartreuse = rgb("C9ED36")
#let verde = rgb("00C735")
#let cerceta = rgb("00BCA3")
#let cian = rgb("00BAD4")
#let ceruleo = rgb("0086DF")
#let indigo = rgb("1D20A3")
#let morado = rgb("440483")
#let violeta = rgb("D151C8")
#let magenta = rgb("FE0086")
#let title-text-font = "Source Code Pro"
#let title-text-size = 23.69pt
#let heading-text-font = "Source Code Pro"
#let heading-text-size = 17.77pt
#let subheading-text-size = 13.33pt
#let body-text-font = "Source Serif 4"
#let body-text-size = 10pt
#let caption-text-font = "Source Sans 3"
#let caption-text-size = 7.5pt
#let rect-st = rect(radius: 36pt, fill:negro.lighten(5%), width:100%, height: 100%, inset: 0pt)
#set page(paper:"presentation-16-9", fill:negro, margin: (top:24pt,bottom:48pt, left: 36pt, right:36pt), background:[
#set align(bottom)
#rect(width:100%, height: 33%, fill:blanco)
])
#v(1fr)
#align(center, text(size: title-text-size, font: title-text-font, weight: "black", fill: blanco)[
La distribución binomial
])
#v(1fr)
#grid(columns:3, column-gutter: 1fr)[
#set align(left)
#image("UNAM-color.png", width: 33%)][
#align(left, text(fill: negro, size: body-text-size, font: body-text-font)[
Integrantes:
#v(10pt)
Name
Name
Name
]
)
][
#set align(right)
#image("FC-color.png", width: 33%)
]
#pagebreak()
#set page(margin:(right:18pt, bottom:16.5pt), background:none)
#grid(columns:(36pt,1fr), rows:(1fr,15pt), column-gutter: -10pt, row-gutter: 6pt)[
#align(horizon)[
#box(inset: (x:-100pt))[
#rotate(text(fill:blanco, size:subheading-text-size, font:heading-text-font, weight: "black")[La distribución binomial], -90deg))
]
]
][
#set align(center + horizon)
#set text(fill:blanco, size:body-text-size, font:body-text-font)
#grid(columns:2, column-gutter: 20pt)[
#rect(radius: 36pt,fill:negro.lighten(5%),width:100%,height: 100%)[
#rect(radius: 36pt,fill:negro.lighten(5%),width:80%,height: 80%)[
#align(left, text(font: title-text-font, weight: "black", fill: blanco, size: 20pt)[
Problema
])
#align(left, text(fill: blanco)[
¿Cómo podemos modelar el éxito de #text(weight: "bold")[un solo] tiro de un dado de $n$ lados con una función de probabilidad?
])
]
]][
#show image: it => block(radius: 36pt, fill:negro.lighten(5%), width:100%, height: 100%, inset: 0pt, clip: true)[#it]
#image("pexels_1.jpg", width: 100%, height: 100%)
]][][
#align(bottom)[
#set text(fill:blanco, size:caption-text-size, font:caption-text-font, weight: "semibold")
#h(36pt)
SEM I
#h(24pt)
PyE II, CCH
#h(24pt)
<NAME>
]] |
|
https://github.com/miliog/typst-penreport | https://raw.githubusercontent.com/miliog/typst-penreport/master/typst-penreport/helper/author.typ | typst | MIT No Attribution | #let getAuthorString(authors, onlyPentester) = {
let authorString = ""
for author in authors {
if (onlyPentester and author.pentester) or not onlyPentester {
authorString += author.name + ", "
}
}
authorString = authorString.slice(0, -2)
return authorString
} |
https://github.com/piepert/grape-suite | https://raw.githubusercontent.com/piepert/grape-suite/main/examples/seminar-paper01.typ | typst | MIT License | #import "/src/library.typ": seminar-paper, german-dates
#import seminar-paper: todo, blockquote, definition, sidenote
#let definition = definition.with(figured: true)
#set text(lang: "de")
#show: seminar-paper.project.with(
title: "Die Intensionalität von dass-Sätzen",
subtitle: "Intensionale Kontexte in philosophischen Argumenten",
university: [Universität Musterstadt],
faculty: [Exemplarische Fakultät],
institute: [Institut für Philosophie],
docent: [Dr. <NAME>],
seminar: [Beispielseminar],
submit-to: [Eingereicht bei],
submit-by: [Eingereicht durch],
semester: german-dates.semester(datetime.today()),
author: "<NAME>",
student-number: "0123456789",
email: "<EMAIL>",
address: [
12345 Musterstadt \
Musterstraße 67
]
)
= Einleitung
#lorem(100) #todo(lorem(20))
#lorem(100)
#blockquote[
#sidenote[Logischer Empirismus] Ich bin nämlich überzeugt, daß wir in einer durchaus endgültigen Wendung der Philosophie mitten darin stehen und daß wir sachlich berechtigt sind, den unfruchtbaren Streit der Systeme als beendigt anzusehen. Die Gegenwart ist, so behaupte ich, bereits im Besitz der Mittel, die jeden derartigen Streit im Prinzip unnötig machen; es kommt nur darauf an, sie entschlossen anzuwenden.
Diese Mittel sind in aller Stille, unbemerkt von der Mehrzahl der philosophischen Lehrer und Schriftsteller, geschaffen worden, und so hat sich eine Lage gebildet, die mit allen früheren unvergleichbar ist. Daß die Lage wirklich einzigartig und die eingetretene Wendung wirklich endgültig ist, kann nur eingesehen werden, indem man sich mit den neuen Wegen bekannt macht und von dem Standpunkte, zu dem sie führen, auf alle die Bestrebungen zurückschaut, die je als ”philosophische“ gegolten haben.
Die Wege gehen von der _Logik_ aus.
][
<NAME>: Die Wende der Philosophie. In: <NAME>, <NAME>, <NAME>, <NAME> (eds.): <NAME> Gesamtausgabe. Abt. I, Bd. 6. Wien: Springer, 2008. S. 213 f. Hervorhebungen im Original.
]
#definition[
#lorem(30)
]<important-definition>
See @important-definition and @second-important-definition.
= Hauptteil
#lorem(100)
#sidenote[#lorem(5)] #lorem(100)
== These
#lorem(200)
== Antithese
#lorem(100) #todo(lorem(20))
#lorem(200)
== Synthese
#lorem(100)
#definition[
#lorem(20)
]<second-important-definition>
#lorem(200)
== #lorem(20)
= Fazit
#lorem(100)
#lorem(100) |
https://github.com/donabe8898/typst-slide | https://raw.githubusercontent.com/donabe8898/typst-slide/main/opc/並行prog/02/02.typ | typst | MIT License | // typst compile 02.typ /home/yugo/git/donabe8898/typst-slide/opc/並行prog/02/第2回/{n}.png --format png
#import "@preview/polylux:0.3.1": *
#import themes.clean: *
#show: clean-theme.with(
aspect-ratio: "16-9",
footer: "Goであそぼう",
// short-title: "",
logo: image("02素材/gopher.svg"),
color: teal
)
#show link: set text(blue)
#set text(font: "Noto Sans CJK JP",size:18pt)
#show heading: set text(font: "Noto Sans CJK JP")
#show raw: set text(font: "JetBrains Mono")
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt
)
// TODO: 本文
#title-slide(
title: "Goの並行処理であそぼう",
subtitle: "(第二回) 並行処理はむずい",
authors: "<NAME> a.k.a donabe8898",
date: none,
// watermark: image("01素材/gopher.svg",) ,//透かしの画像
secondlogo: image("02素材/gopher.svg") // 通常ロゴの反対側に映るロゴ
)
#slide(title: "本講義のターゲット層")[
- サーバーに興味がある
- モダンな言語を習得したい
]
#slide(title: "自己紹介")[
= 岡本 悠吾 - <NAME>
#v(0.5em)
- T学科4回生
- サークル内でLinux関連の講義をやってます
= 欲しい物リスト
- 車(FR車)
- パソコン(そろそろ買い替えたい)
#v(1em)
]
// TODO: 本文
#new-section-slide("Section 7. チャネルとバッファ")
#slide(title:"バッファ")[
#v(1em)
チャネルにはバッファを持たすことができる.
= メリット
- 複数のデータを一時的に格納できる
- チャネルでやりとりできるデータの数が増える
]
#slide()[
```go
package main
import "fmt"
func main() {
ch := make(chan int, 2) // チャネル変数作成
ch <- 10 // チャネルの1番目のバッファに値を追加
fmt.Println(len(ch)) // チャネルの長さを見てみる
ch <- 20 // チャネルの2番目のバッファに値を追加
fmt.Println(len(ch)) // チャネルの長さを見てみる
}
```
]
#slide()[
```go
package main
import "fmt"
func main() {
ch := make(chan int, 2) // チャネル変数作成
ch <- 10 // チャネルの1番目のバッファに値を追加
fmt.Println(len(ch)) // チャネルの長さを見てみる
ch <- 20 // チャネルの2番目のバッファに値を追加
fmt.Println(len(ch)) // チャネルの長さを見てみる
ch <- 30 // バッファの数を超えるのでこれはエラー
fmt.Println(len(ch))
}
```
]
#slide()[
= 写経タイム!!!!
#v(1em)
- Discordに貼ったPDFのソースコードを写経(丸写し)しましょう。
- なるべく自分でタイピングすることを*強く*おすすめします
#v(1em)
- 写経できた人はVCステータスを「できた!」にしてください
- 質問がある人はテキストチャットかVCでどうぞ
]
#new-section-slide("解説")
#slide()[
```go
package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan int, 5) // バッファサイズ5のチャネル1を作成
ch2 := make(chan int, 5) // バッファサイズ5のチャネル2を作成
fmt.Printf("Start!\n") // スタート
// 2つのゴルーチン起動
go r("A", ch1)
go r("B", ch2)
// 受信チャネル
for ch := range ch1 {
fmt.Println("A channel", ch)
}
for ch := range ch2 {
fmt.Println("B channel", ch)
}
fmt.Printf("Finish!\n")
}
func process(num int, str string) {
// num秒処理
for i := 0; i <= num; i++ {
time.Sleep(1 * time.Second)
fmt.Println(i, str)
}
}
func r(str string, ch chan int) {
process(2, str)
ch <- 1
fmt.Println(str, "process 1 done")
process(1, str)
ch <- 2
fmt.Println(str, "process 2 done")
process(2, str)
ch <- 3
fmt.Println(str, "process 3 done")
close(ch)
}
```
]
#new-section-slide("Section VOID. 雑談")
#slide(title: "アノテーションコメント")[
コードに残すコメントの意味を示す.
= メリット
- 第三者にコードをわかりやすく解説できる
- 時間が経ってもすぐにコードの全貌がわかる
- 進捗が掴みやすい。何をすればいいかわかる。
]
#slide()[
```md
TODO: 追加機能を実装しますよ〜。機能が不足していますよ〜。何らかのメッセージでもありますよ〜
FIXME: 修正が必要ですよ〜
OPTIMIZE: バカほど非効率なコードですよ〜
HACK: 何も考えずに書いたコードですよ〜
REVIEW: レビューが必要なコードですよ〜
XXX: 危険なコード。今すぐ修正。 💀
CHANGED: コードの変更点ありますよ〜
NOTE: 雑記ですよ〜
WARNING: 注意必要ですよ〜
```
]
#slide()[
```go
// TODO: ch<-30から2行を削除
package main
import "fmt"
func main() {
ch := make(chan int, 2) // NOTE: チャネル変数作成
ch <- 10 // チャネルの1番目のバッファに値を追加
fmt.Println(len(ch)) // チャネルの長さを見てみる
ch <- 20 // チャネルの2番目のバッファに値を追加
fmt.Println(len(ch)) // チャネルの長さを見てみる
ch <- 30 // WARNING: バッファの数を超えるのでこれはエラー
fmt.Println(len(ch))
}
```
]
|
https://github.com/MattiaOldani/Informatica-Teorica | https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/complessità/18_risorsa_spazio.typ | typst | #import "@preview/algo:0.3.3": algo, i, d
#import "../alias.typ": *
= Spazio di memoria
Veniamo ora alla formalizzazione dell'altra importante risorsa di calcolo, ovvero lo *spazio di memoria*, inteso come quantità di memoria occupata durante la computazione.
== Complessità in spazio (1)
Data la DTM $M = (Q, Sigma, Gamma, delta, q_0, F)$ ed una stringa $x in Sigma^*$, chiamiamo $S(x)$ il numero di celle del nastro occupate (visitate, _sporcate_) durante la computazione di $M$ su $x$. Questo numero potrebbe anche essere _infinito_. La *complessità in spazio* di $M$ (_worst case_) è la funzione $s : NN arrow.long NN$ definita come $ s(n) = max{S(x) bar.v x in Sigma^* and |x| = n}. $
Da questa definizione è chiaro che, in ogni MDT, $s(n) gt.eq n$ in quanto dovrò sempre occupare almeno spazio $n$ lineare per mantenere l'input sul nastro, ma è molto probabile che le celle effettive che _sporco_ sono molte meno delle celle occupate dall'input.
_Come non considerare l'interferenza dovuta all'input?_
Per avere complessità anche sublineari, potremmo modificare leggermente la macchina e separare le operazioni del nastro, ovvero utilizzare due nastri diversi per la lettura e per la computazione:
- il *nastro di lettura* è read-only con testina two-way read-only;
- il *nastro di lavoro* è invece read-write con testina two-way.
#v(12pt)
// Da sistemare
#figure(
image("assets/dtm-doppio-nastro.svg", width: 65%)
)
#v(12pt)
La stringa in input è delimitata dai caratteri $cent$ e $dollar$ tali che $cent,dollar in.not Sigma$.
La definizione formale di questa nuova macchina è $ M = (Q, Sigma union {cent, dollar}, Gamma, delta, q_0, F), $ in cui tutto è analogo alle macchine di Turing viste finora, tranne per la funzione di transizione $delta$, ora definita come $ delta : Q times (Sigma union {cent, dollar}) times Gamma arrow.long Q times (Gamma without {blank}) times {-1, 0, 1}^2 $ con la quale $M$:
+ legge un simbolo sia dal nastro di input sia dal nastro di lavoro;
+ calcola lo stato prossimo dati i simboli letti e lo stato attuale;
+ modifica il nastro di lavoro;
+ comanda il moto delle due testine.
Anche la definizione di configurazione va leggermente modificata: ora, infatti, una *configurazione* di $M$ è una quadrupla $ C = angle.l q, i, j, w angle.r $ in cui:
- $q$ è lo stato corrente;
- $i$ e $j$ sono le posizioni della testina di input e della testina di lavoro;
- $w$ è il contenuto non blank del nastro di lavoro.
Non serve più salvare l'input perché, essendo il nastro read-only, non cambia mai.
Gli altri concetti (_computazione, accettazione, linguaggio accettato, complessità in tempo, eccetera_) rimangono inalterati con questo modello.
== Complessità in spazio (2)
A questo punto possiamo ridefinire la complessità in spazio per queste nuove macchine di Turing.
Per ogni stringa $x in Sigma^*$, il valore $S(x)$ è ora dato dal numero di celle _del solo nastro di lavoro_ visitate da $M$ durante la computazione di $x$. Dunque, la *complessità in spazio deterministica* $s(n)$ di $M$ è da intendersi come il massimo numero di celle visitate nel nastro di lavoro durante la computazione di stringhe di lunghezza $n$, quindi come prima $ s(n) = max{S(x) bar.v x in Sigma^* and abs(x) = n}. $
In questo modo misuriamo solo lo spazio di lavoro, che quindi può essere anche sublineare.
== Linguaggi e funzioni
Il linguaggio $L subset.eq Sigma^*$ è riconosciuto in *spazio deterministico* $f(n)$ se e solo se esiste una DTM $M$ tale che:
+ $L = L_M$;
+ $s(n) lt.eq f(n)$.
Per il caso specifico del *calcolo di funzioni*, solitamente si considera una terza macchina di Turing, in cui è presente un _terzo nastro_ dedicato alla sola scrittura dell'output della funzione da calcolare. Questa aggiunta ci permette di conteggiare effettivamente lo spazio per l'output e di non interferire con il nastro di lavoro.
Una funzione $f : Sigma^* arrow.long Gamma^*$ viene calcolata con *complessità in spazio $s(n)$* dalla DTM $M$ se e solo se _su ogni input x di lunghezza n_ la computazione di $M$ occupa non più di $s(n)$ celle dal nastro di lavoro.
Sfruttando queste definizioni, possiamo ovviamente definire la complessità in spazio per il riconoscimento di insiemi e per la funzione soluzione di problemi di decisione.
== Classi di complessità
Per ogni funzione $f : NN arrow.long NN$ definiamo $ dspace(f(n)) $ la *classe dei linguaggi accettati da DTM in spazio deterministico* $O(f(n))$.
Chiamiamo invece $ fspace(f(n)) $ *classe delle funzioni calcolate da DTM in spazio deterministico* $O(f(n))$.
Notiamo che le classi $dspace$ e $fspace$ *non* cambiano se aggiungiamo alle nostre DTM un _numero costante di nastri di lavoro_. Se può essere comodo possiamo quindi utilizzare DTM con $k$ nastri di lavoro aggiuntivi, separando anche il nastro di input da quello di output.
Ad esempio, riprendiamo la DTM $M$ per il linguaggio $L_"PARI" = 1 {0,1}^* 0 union 0$. Abbiamo già visto che $L_"PARI" in dtime(n)$. _E lo spazio?_
A dire il vero, non viene occupato spazio, in quanto tutto può essere fatto usando solamente gli stati. Infatti, $L_"PARI"$ è un linguaggio *regolare* e si può dimostrare che $ "REG" = dspace(1). $ In poche parole, stiamo buttando via il nastro di lavoro, trasformando la DTM in un *automa a stati finiti*. Per _buttarlo via_ devo però aumentare il numero di stati: infatti, le informazioni che _buttiamo_ dal nastro di lavoro vanno codificate in stati, che quindi aumentano di numero.
Se ad esempio consideriamo la DTM $M$ che dice se una parola è palindroma o no, essa avrà $t(n) = n^2$, _ma lo spazio?_
Dobbiamo cercare di capire che valori possono assumere i numeri che scriviamo durante la computazione. Tra $i$ e $j$, il numero più grande è sempre $j$, che al massimo vale $n$, di conseguenza $ s(n) = O(n). $ Possiamo fare meglio: questa rappresentazione scelta è *unaria*, perché _sporco_ un numero di celle esattamente uguale a $n$. Usando una rappresentazione *binaria*, il numero di celle di cui abbiamo bisogno è il numero di bit necessari a rappresentare $n$, ovvero $ s(n) = O(log(n)). $
_Possiamo usare una base del logaritmo più alta per abbassare la complessità_?
No, perché qualsiasi logaritmo può essere trasformato in un altro a meno di una costante moltiplicativa, quindi è indifferente la base utilizzata.
Ad esempio, $ O(log_2(n)) = O(frac(log_(100)(n), log_(100)(2))) = O(log_(100)(n)). $
Quindi, $ L_"PAL" in dtime(n^2) $ e $ L_"PAL" in dspace(log(n)). $
_Possiamo essere più veloci?_
Un algoritmo più "veloce" di quello che abbiamo visto, è il seguente.
#align(center)[
#table(
columns: (60%, 20%, 20%),
inset: 10pt,
align: horizon,
[*Istruzione*], [*Tempo*], [*Spazio*],
[Copia la stringa di input sul nastro di lavoro], [$n$], [$n$],
[Sposta la testina del nastro di input in prima posizione (quella del nastro di lavoro sarà alla fine)], [$n$], [-],
[Confronta i due caratteri, avanzando al testina di input e retrocedendo quella di lavoro], [$n$], [-],
[Accetta se tutti i confronti tornano, altrimenti rifiuta], [$t(n) = O(n)$], [$s(n) = O(n)$]
)
]
Questo ci mostra come abbiamo avuto un gran miglioramento per la risorsa tempo, a discapito della risorsa spazio. Spesso (_ma non sempre_) migliorare una risorsa porta al peggioramento di un'altra.
Esistono quindi diversi algoritmi per un dato problema che ottimizzano solo una delle due risorse a disposizione. Per il linguaggio $L_"PAL"$ si dimostra che $ t(n) dot s(n) = Omega(n^2). $
== Efficienza in termini di spazio
Definiamo:
- $L = dspace(log(n))$ classe dei linguaggi accettati in spazio deterministico $O(log(n))$;
- $fl = fspace(log(n))$ classe delle funzioni calcolate in spazio deterministico $O(log(n))$.
L e FL sono universalmente considerati i *problemi risolti efficientemente in termini di spazio*.
Finora, abbiamo stabilito due sinonimie:
- efficiente _in tempo_ se e solo se il _tempo è polinomiale_;
- efficiente _in spazio_ se e solo se lo _spazio è logaritmico_.
Entrambe le affermazioni trovano ragioni di carattere pratico, composizionale e di robustezza, come visto nella lezione scorsa per la risorsa tempo.
Per lo spazio, le motivazioni sono le seguenti:
- *pratico*: operare in spazio logaritmico (_sublineare_) significa saper gestire grandi moli di dati senza doverle copiare totalmente in memoria centrale (che potrebbe anche non riuscire a contenerli tutti) usando algoritmi sofisticati che si servono, ad esempio, di tecniche per fissare posizioni sull'input o contare parti dell'input (in generale procedure che siano logaritmiche in spazio).\
I dati diventano facilmente grandi e bisogna avere algoritmi che utilizzino poca memoria.
- *composizionale*: i programmi efficienti in spazio che richiamano routine efficienti in spazio, rimangono efficienti in spazio;
- *robustezza*: le classi L e FL rimangono invariate, a prescindere dai modelli di calcolo utilizzati, ad esempio DTM multi-nastro, RAM, WHILE, etc.
== Tesi di Church-Turing estesa
Come per il tempo, la *tesi di Church-Turing estesa per lo spazio* afferma che la classe dei problemi efficientemente risolubili in spazio coincide con la classe dei problemi risolti in spazio logaritmico su DTM.
Vediamo alcuni esempi di problemi risolti efficientemente in spazio:
- in L:
- testare la raggiungibilità tra due nodi di un grafo non diretto;
- parsing dei linguaggi regolari;
- parsing dei linguaggi context-free (quasi: attualmente è $s(n) = O(log^2 n)$;
- in FL:
- operazioni aritmetiche;
- permanenti di matrici booleane;
- aritmetica modulare;
Se un problema è in L o FL è anche efficientemente *parallelizzabile*. Al momento non esistono compilatori perfettamente parallelizzabili.
|
|
https://github.com/roife/resume | https://raw.githubusercontent.com/roife/resume/master/resume-cn.typ | typst | MIT License | #import "chicv.typ": *
#show: chicv
= #redact(alter: "roife")[占位符]
#fa[#phone] #redact(mark: true)[00000000000] |
#fa[#envelope] <EMAIL> |
#fa[#github] #link("https://github.com/roife")[roife] |
#fa[#globe] #link("https://roife.github.io/about")[roife.github.io] |
#fa[#location-arrow] 北京 / 上海 / 杭州
== 教育背景
#cventry(
tl: [南京大学],
tr: [2023.09 - 2026.06(预计)],
bl: [硕士,计算机科学与技术|#link("https://pascal-lab.net")[Pascal Lab],导师:李#redact(mark: true)[占]|研究方向为程序语言、程序分析与 HDL],
)[]
#cventry(
tl: [北京航空航天大学],
tr: [2019.09 - 2023.06],
bl: [本科,计算机科学与技术|GPA 3.84/4.00],
)[]
== 工作经历
#cventry(
tl: [Rust Foundation Fellowship Program],
tl_comments: redact(alter: "")[(全球共 10 人入选)],
tr: [2024.09 - 2025.06],
)[
- *维护 rust-analyzer*
- 社区贡献*排名 23/972*,解决*超过 50 个 issues*;参与维护语义分析、类型检查等多个模块,提高语义分析的正确性和项目的稳健性;并为项目添加了多项新功能,如*控制流导航*、*泛型约束展示*等;
- 为 rust-analyzer 的断行算法编写了 NEON 下的 *SIMD* 实现,使得该模块在 ARM 平台上提速 *6.5 倍*;
- *解决 v0.3.1992 版本 P0 事故*:新版本发布 4 小时后,社区发现该版本存在恶性 BUG,会导致设备计算资源耗尽且无法结束进程。本人根据反馈在 *3 小时内*定位到错误算法逻辑,设计了新算法修复了问题并重新发版。本次紧急修复有效控制了事故影响范围,避免影响全球范围内 Rust 使用者的开发工作,提升了项目稳健性。
- *开源社区日常维护*:参与社区日常维护工作,包括会议讨论,BUG 修复,PR 审核等。
]
== 奖项荣誉
- 2022 年*国家奖学金*(学年专业排名 1/195),北京航空航天大学*优秀毕业生*
- 2021 年全国大学生计算机系统能力大赛 · 编译系统设计赛(华为毕昇杯)*一等奖,排名第二*
- 蓝桥杯 C++ 程序设计竞赛北京赛区一等奖,国赛三等奖
- 另获其他各类省奖与校级学业、竞赛奖学金十余次
== 项目开发
#cventry(
tl: [Vizsla],
tl_comments: [ · 面向芯片开发的现代化 Verilog/SV IDE(Rust / SystemVerilog)],
tr: [(开发中)],
)[
- (*独立设计实现*)负责设计并编写了 IDE 的核心架构和增量计算流程,并完成了大部分的功能开发;
- 项目旨在为芯片设计配备现代 IDE 功能,完成了*代码导航*、*补全*等#redact(alter: "")[数十项]现代 IDE 特性,以提升编码效率和代码质量;
- 基于 LSP 协议和*增量计算*架构,实现了增量语义分析框架#redact(alter: "")[,性能与可用性达到世界领先水平,不逊色于商业工具]。
]
#cventry(
tl: [LLVM-Lite],
tl_comments: [ · 面向深度学习神经网络算子的轻量级端侧编译器(C++ / LLVM)],
tr: ghrepo("roife/llvm-lite", icon: true),
)[
- (*独立设计实现*)华为研究课题,作为本科毕业设计获得优秀评价;
- 本课题旨在利用端侧推理设备上神经网络的形状信息,对深度学习算子进行二次优化,以减少算子运行时的时空开销;
- 独立完成了一个轻量级的*端侧编译器*用于端侧算子的二次优化,并完成了 *LLVM 代码生成模块*的裁剪工作;
- 成功将测试样例中的深度学习算子的*运行时间降低了 6%*,并将*目标文件大小降低了 38%*。
]
#cventry(
tl: "Ayame",
tl_comments: [ · 毕昇杯比赛项目,从 C 子集到 LLVM-IR/ARMv7 编译器(Java / LLVM / ARM)],
tr: ghrepo("No-SF-Work/ayame", icon: true),
)[
- (*合作开发*)负责完成了图着色寄存器分配算法以及面向体系结构的后端优化,并负责了本地 CI 和评测系统的搭建;
- 该项目在比赛中*近一半样例中排名第一*,并在 1/3 的样例上优化效果超越 `gcc -O3` 与 `clang -O3`。
]
#cventry(
tl: [开源社区贡献],
)[
- *Rust-lang Member*,rust-analyzer contributors team:工作集中在 #ghrepo("rust-lang/rust-analyzer", icon: false),同时也贡献过 #ghrepo("rust-lang/rust", icon: false) #ghrepo("rust-lang/rust-clippy", icon: false),#ghrepo("rust-lang/rustup", icon: false),#ghrepo("rust-lang/rust-mode", icon: false) ;
- #ghrepo("llvm/llvm-project", icon: false),#ghrepo("clangd/vscode-clangd", icon: false),#ghrepo("google/autocxx", icon: false),#ghrepo("yuin/goldmark", icon: false),#link("https://github.com/roife")[更多项目见 GitHub]
]
== 专业技能
#grid(
columns: (auto, auto),
rows: (auto, auto, auto, auto, auto),
gutter: 7pt,
[*编程语言*], grid_par[多语言。特别熟悉 C, C++, Rust, Java, Python, Verilog;较熟悉 JS, Ruby, Swift, OCaml, Coq, Haskell 等。],
[*程序语言理论*], grid_par[了解形式语义、形式语言、形式化验证和计算理论的相关知识,熟悉*类型系统*的理论和实现。],
[*编译器 / IDE*], grid_par[*4 年开发经验*。熟悉编译优化和多种中间代码表示(如 SSA, CPS 等);对 LLVM 有一定了解;熟悉基于 LSP 协议和基于*增量计算*的 IDE 架构,尤其熟悉 rust-analyzer。],
[*程序分析*], grid_par[*2 年开发经验*。熟悉常见静态分析算法(如数据流分析、指针分析、IFDS 等)。],
[*系统编程*], grid_par[了解体系结构和操作系统底层知识,能进行底层的开发调试工作,熟悉 Docker、CMake 等常用工具。],
[*开发环境*], grid_par[熟悉 Emacs;习惯在 macOS 和 Linux 环境下工作;能熟练使用 AI 提高工作效率。]
)
== 其他
- *外语*:英语(CET-6);
- *助教工作*:*程序设计基础*(2020 秋),*面向对象设计与构建*(2021 秋,2022 春),*编译原理*(2024 春)。
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/pagebreak-parity_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#set page(width: 80pt, height: 30pt)
First
#pagebreak(to: "odd")
Third
#pagebreak(to: "even")
Fourth
#pagebreak(to: "even")
Sixth
#pagebreak()
Seventh
#pagebreak(to: "odd")
#page[Ninth]
|
https://github.com/quarto-ext/typst-templates | https://raw.githubusercontent.com/quarto-ext/typst-templates/main/ams/README.md | markdown | Creative Commons Zero v1.0 Universal | # Typst AMS Format
Based on the AMS template published by the Typst team at <https://github.com/typst/templates/tree/main/ams>.
**NOTE**: This format requires the pre-release version of Quarto v1.4, which you can download here: <https://quarto.org/docs/download/prerelease>.
## Installing
```bash
quarto use template quarto-ext/typst-templates/ams
```
This will install the extension and create an example qmd file that you can use as a starting place for your document.
## Using
The example qmd demonstrates the document options supported by the IEE format (`title`, `authors`, `abstract`, `bibliography`, etc.). For example, your document options might look something like this:
```yaml
---
title: "Mathematical Theorems"
authors:
- name: <NAME>
email: "<EMAIL>"
url: "www.math.sc.edu/~howard"
affiliations:
- name: University of South Carolina
department: Department of Mathematics
city: Columbia
state: SC
postal-code: 29208
abstract: |
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Curabitur ex justo, pretium nec ante mattis, ultricies
ultricies magna. Duis neque nulla, feugiat a consectetur id,
fermentum a lorem. Vivamus sit amet est interdum, eleifend
libero in, rutrum lorem.
format:
ams-typst: default
bibliography: refs.bib
---
```
This document would be rendered as:

|
https://github.com/PgBiel/typst-oxifmt | https://raw.githubusercontent.com/PgBiel/typst-oxifmt/main/tests/strfmt-tests.typ | typst | Apache License 2.0 | #import "../oxifmt.typ": strfmt
#{
// test basics (sequential args, named args, pos args)
assert.eq(strfmt("a {} b {} c {named} {0} {1}", 10, "tests", named: -24), "a 10 b tests c -24 10 tests")
// test {:?} (force usage of repr())
assert.eq(strfmt("a {} c {} d {:?}", true, "testA", "testA"), "a true c testA d \"testA\"")
// test escaping {{ }}, plus repr() on bools and dicts (and anything that can't be str()'ed)
assert.eq(strfmt("a{{}}b ={}{}= c{0}d", false, (a: "55", b: 20.3)), "a{}b =false(a: \"55\", b: 20.3)= cfalsed")
// test escaping {{ }} from inside { } formats
assert.eq(strfmt("a{b{{b}}b}", ..("b{b}b": 5)), "a5")
// test 0 prefix with numbers, but also using 0 as a non-numeric affix
assert.eq(strfmt("{:08}|{0:0<8}|{0:0>8}|{0:0^8}", 120), "00000120|12000000|00000120|000120000")
// test other kinds of affixes / fills and alignments
assert.eq(strfmt("{:a>8}, {:^20.10}, {:+05.4}, {:07}, {other:06?}", "b", 5.5, 11, -4, other: -30.0), "aaaaaaab, 5.5000000000 , +0011, -000004, -030.0")
// test base conversion (I)
assert.eq(strfmt("{:b}, {0:05b}, {:#010b}, {:05x}, {:05X}, {:+#05X}, {2:x?}, {3:X?}", 5, 5, 27, 27, 27), "101, 00101, 0b00000101, 0001b, 0001B, +0x1B, 1b, 1B")
// test base conversion (II)
assert.eq(strfmt("{:x}, {:X}, {:#X}, {:#X}, {:o}, {:#o}", 259, 259, 259, -259, 66, 66), "103, 103, 0x103, -0x103, 102, 0o102")
// some numeric tests with affixes and stuff
assert.eq(strfmt("{:-^+#10b}, {fl:+08}", 5, fl: 55.43), "--+0b101--, +0055.43")
// test scientific notation
assert.eq(strfmt("{:e}, {:.7E}, {:e}, {:010.2E}, {:+e}", 4213.4, 521.32947, 0.0241, -0.00432, 190000), "4.2134e3, 5.2132947E2, 2.41e-2, -004.32E-3, +1.9e5")
// test taking width and precision from pos args / named args (.x$ / y$ notation)
assert.eq(strfmt("{:.1$}; {woah:0france$.moment$}; {}; {2:a>1$}", 5.5399234, 9, "stringy", woah: 3.9, france: 7, moment: 2), "5.539923400; 0003.90; 9; aastringy")
// test weird precision cases
assert.eq(strfmt("{0:e} {0:+.9E} | {1:.3e} {1:.3} {2:.3} | {3:.4} {3:.4E} | {4:.2} {4:.3} {4:.5}", 124.2312, 50, 50.0, -0.02, 2.44454), "1.242312e2 +1.242312000E2 | 5.000e1 50 50.000 | -0.0200 -2.0000E-2 | 2.44 2.445 2.44454")
// test custom decimal separators (I)
assert.eq(strfmt("{}; {:07e}; {}; {}; {:?}", 1.532, 45000, -5.6, "a.b", "c.d", fmt-decimal-separator: ","), "1,532; 004,5e4; -5,6; a.b; \"c.d\"")
// test custom decimal separators (II) - weird values
assert.eq(strfmt("{}; {:015e}; {}; {}; {:?}", 1.532, 45000, -5.6, "a.b", "c.d", fmt-decimal-separator: (a: 5)), "1(a: 5)532; 000004(a: 5)5e4; -5(a: 5)6; a.b; \"c.d\"")
// test custom decimal separators (III) - ensure we can fetch it from inside
assert.eq(strfmt("5{fmt-decimal-separator}6", fmt-decimal-separator: "|"), "5|6")
}
// Issue #6: UTF-8
#{
// shouldn't crash
assert.eq(strfmt("Hello € {}", "man"), "Hello € man")
// should replace at the appropriate location
assert.eq(strfmt("Bank: {company-bank-name} € IBAN: {company-bank-iban}", company-bank-name: "FAKE", company-bank-iban: "Broken stuff"), "Bank: FAKE € IBAN: Broken stuff")
// test grapheme clusters
assert.eq(strfmt("Ĺo͂řȩ{}m̅", 5.5), "Ĺo͂řȩ5.5m̅")
// padding should use codepoint len
assert.eq(strfmt("{:€>15}", "Ĺo͂řȩ5.5m̅"), "€€€€€Ĺo͂řȩ5.5m̅")
assert.eq(strfmt("{:€>10}", "abc€d"), "€€€€€abc€d")
}
// Float edge cases
#{
assert.eq(strfmt("{}", float("nan")), "NaN")
assert.eq(strfmt("{:05.10}", float("nan")), "00NaN")
assert.eq(strfmt("{:05e}", float("nan")), "00NaN")
assert.eq(strfmt("{:05e}", float("inf")), "00inf")
assert.eq(strfmt("{:+05e}", float("inf")), "+0inf")
assert.eq(strfmt("{:05e}", -float("inf")), "-0inf")
}
// Issue #5: Thousands
#{
// Test separator
assert.eq(strfmt("{}", 10, fmt-thousands-separator: "_"), "10")
assert.eq(strfmt("{}", 1000, fmt-thousands-separator: ""), "1000")
assert.eq(strfmt("{}", 1000, fmt-thousands-separator: "_"), "1_000")
assert.eq(strfmt("{}", 100000000, fmt-thousands-separator: "_"), "100_000_000")
assert.eq(strfmt("{}", 100000000.0, fmt-thousands-separator: "_"), "100_000_000")
assert.eq(strfmt("{}", 10000000.3231, fmt-thousands-separator: "_"), "10_000_000.3231")
assert.eq(strfmt("{}", -230, fmt-thousands-separator: "_"), "-230")
assert.eq(strfmt("{}", -2300, fmt-thousands-separator: "_"), "-2_300")
assert.eq(strfmt("{}", -2300.453, fmt-thousands-separator: "_"), "-2_300.453")
assert.eq(strfmt("{}", 5555.2, fmt-thousands-separator: "€", fmt-decimal-separator: "€€"), "5€555€€2")
assert.eq(strfmt("{:010}", -23003, fmt-thousands-separator: "abc"), "-000abc023abc003")
assert.eq(strfmt("{:+013}", 23003.34, fmt-thousands-separator: "abc"), "+000abc023abc003.34")
assert.eq(strfmt("{:#b}", 255, fmt-thousands-separator: "_"), "0b11_111_111")
assert.eq(strfmt("{:#x}", -16 * 16 * 16 * 16 * 15, fmt-thousands-separator: "_"), "-0xf0_000")
assert.eq(strfmt("{:o}", -16 * 16 * 16 * 16 * 15, fmt-thousands-separator: "_"), "-3_600_000")
assert.eq(strfmt("{:?}", 5555.0, fmt-thousands-separator: "_"), "5_555.0")
assert.eq(strfmt("{:e}", 5555.2, fmt-thousands-separator: "_", fmt-decimal-separator: "heap"), "5heap5552e3")
assert.eq(strfmt("{:010}", 5555.2, fmt-thousands-separator: "_", fmt-decimal-separator: "€"), "00_005_555€2")
assert.eq(strfmt("{:€>10}", 5555.2, fmt-thousands-separator: "_", fmt-decimal-separator: "€"), "€€€5_555€2")
assert.eq(strfmt("{:€>10}", 5555.2, fmt-thousands-separator: "€a", fmt-decimal-separator: "€"), "€€5€a555€2")
// Test count
assert.eq(strfmt("{}", 10, fmt-thousands-count: 3, fmt-thousands-separator: "_"), "10")
assert.eq(strfmt("{}", 10, fmt-thousands-count: 1, fmt-thousands-separator: "_"), "1_0")
assert.eq(strfmt("{}", 1000, fmt-thousands-count: 2, fmt-thousands-separator: "_"), "10_00")
assert.eq(strfmt("{}", 10000000.3231, fmt-thousands-count: 2, fmt-thousands-separator: "_"), "10_00_00_00.3231")
assert.eq(strfmt("{}", float("nan"), fmt-thousands-count: 2, fmt-thousands-separator: "_"), "NaN")
assert.eq(strfmt("{}", float("inf"), fmt-thousands-count: 2, fmt-thousands-separator: "_"), "inf")
assert.eq(strfmt("{}", -float("inf"), fmt-thousands-count: 2, fmt-thousands-separator: "_"), "-inf")
assert.eq(strfmt("{:010}", -23003, fmt-thousands-count: 4, fmt-thousands-separator: "|"), "-0|0002|3003")
assert.eq(strfmt("{:#b}", 255, fmt-thousands-count: 1, fmt-thousands-separator: "_"), "0b1_1_1_1_1_1_1_1")
assert.eq(strfmt("{:#x}", -16 * 16 * 16 * 16 * 15, fmt-thousands-count: 2, fmt-thousands-separator: "_"), "-0xf_00_00")
assert.eq(strfmt("{:o}", -16 * 16 * 16 * 16 * 15, fmt-thousands-count: 4, fmt-thousands-separator: "_"), "-360_0000")
assert.eq(strfmt("{:05}", float("nan"), fmt-thousands-count: 2, fmt-thousands-separator: "_"), "00NaN")
assert.eq(strfmt("{:05}", float("inf"), fmt-thousands-count: 2, fmt-thousands-separator: "_"), "00inf")
assert.eq(strfmt("{:05}", -float("inf"), fmt-thousands-count: 2, fmt-thousands-separator: "_"), "-0inf")
}
// DOC TESTS
#{
// --- Usage ---
{
let s = strfmt("I'm {}. I have {num} cars. I'm {0}. {} is {{cool}}.", "John", "Carl", num: 10)
assert.eq(s, "I'm John. I have 10 cars. I'm John. Carl is {cool}.")
}
// --- Formatting options ---
{
let s1 = strfmt("{0:?}, {test:+012e}, {1:-<#8x}", "hi", -74, test: 569.4)
assert.eq(s1, "\"hi\", +00005.694e2, -0x4a---")
let s2 = strfmt("{:_>+11.5}", 59.4)
assert.eq(s2, "__+59.40000")
let s3 = strfmt("Dict: {:!<10?}", (a: 5))
assert.eq(s3, "Dict: (a: 5)!!!!")
}
// --- Examples ---
{
let s = strfmt("First: {}, Second: {}, Fourth: {3}, Banana: {banana} (brackets: {{escaped}})", 1, 2.1, 3, label("four"), banana: "Banana!!")
assert.eq(s, "First: 1, Second: 2.1, Fourth: four, Banana: Banana!! (brackets: {escaped})")
}
{
let s = strfmt("The value is: {:?} | Also the label is {:?}", "something", label("label"))
assert.eq(s, "The value is: \"something\" | Also the label is <label>")
}
{
let s = strfmt("Values: {:?}, {1:?}, {stuff:?}", (test: 500), ("a", 5.1), stuff: [a])
assert.eq(s, "Values: (test: 500), (\"a\", 5.1), [a]")
}
{
let s = strfmt("Left5 {:_<5}, Right6 {:*>6}, Center10 {centered: ^10?}, Left3 {tleft:_<3}", "xx", 539, tleft: "okay", centered: [a])
assert.eq(s, "Left5 xx___, Right6 ***539, Center10 [a] , Left3 okay")
}
{
let s = strfmt("Left-padded7 numbers: {:07} {:07} {:07} {3:07}", 123, -344, 44224059, 45.32)
assert.eq(s, "Left-padded7 numbers: 0000123 -000344 44224059 0045.32")
}
{
let s = strfmt("Some numbers: {:+} {:+08}; With fill and align: {:_<+8}; Negative (no-op): {neg:+}", 123, 456, 4444, neg: -435)
assert.eq(s, "Some numbers: +123 +0000456; With fill and align: +4444___; Negative (no-op): -435")
}
{
let s = strfmt("Bases (10, 2, 8, 16(l), 16(U):) {0} {0:b} {0:o} {0:x} {0:X} | W/ prefixes and modifiers: {0:#b} {0:+#09o} {0:_>+#9X}", 124)
assert.eq(s, "Bases (10, 2, 8, 16(l), 16(U):) 124 1111100 174 7c 7C | W/ prefixes and modifiers: 0b1111100 +0o000174 ____+0x7C")
}
{
let s = strfmt("{0:.8} {0:.2$} {0:.potato$}", 1.234, 0, 2, potato: 5)
assert.eq(s, "1.23400000 1.23 1.23400")
}
{
let s = strfmt("{0:e} {0:E} {0:+.9e} | {1:e} | {2:.4E}", 124.2312, 50, -0.02)
assert.eq(s, "1.242312e2 1.242312E2 +1.242312000e2 | 5e1 | -2.0000E-2")
}
{
let s = strfmt("{0} {0:.6} {0:.5e}", 1.432, fmt-decimal-separator: ",")
assert.eq(s, "1,432 1,432000 1,43200e0")
}
}
|
https://github.com/camp-d/Notes | https://raw.githubusercontent.com/camp-d/Notes/main/math4190.typ | typst | #set par(justify: true)
= Math 4190 Spring 2024 - Dr. <NAME>
= Properties of sets
+ Counting and Sets
$ A = (A - B) union (A sect B) $
$ B = (B - A) union (A sect B) $
$ |A union B| = |A| + |B| - |A sect B|$
formulas for cardinalities of unions/intersections of sets
$ |A union B| = |A| + |B| - |A sect B|$
$ |A union B union C| = |A| + |B| + |C| - |A sect B| - |A sect C| - |B sect C| + |A union B union C|$
general formula for set union intersection
$ | A_1 union A_2 union ..... union A_n | = sum_(i=1)^n |A_i| - sum_(i<j) | A_i sect A_j |
+ sum_(i < j < k) |A_i sect A_j sect A_k| - ...$
= Pidgeonhole principle
if you place n+1 pieces of mail into n mailboxes, then at least one mailbox will have more than one
piece of mail
Generalised Pigeonhole Principle. if $ |A| > k * |B| $ then for every total function $f : A -> B$
maps at least $k+1$ different elements to the same element of B.
= chess problem
- claim: for any coloring of a chessboard with different colors, we can find a rectangle so that the squares in the corners of the rectangle are all the same color.
= six people at a party problem
- among any six people some have shaken hands (red edge) some have not shaken hands (blue edge)
= Combinations and Permutations
I am a combinatorist by training, my phd is in combinatorics. I have never said the word k-comb/perm in anger except to say that it makes em angry.
Given a finite set of n values ${a_1, a_2, a_3,...,a_n}$
a k-permutation of n objects is a list with or without repetition of k values from the set.
a k-combination is the unordered version of the same if repetition if not allowed it is a k-subset.
- if repetition is not allowed it is a k-subset
- if repetition is allowed it is a k-multisubset
$ vec(n, k) = n!/((n-k)!k!)$
- Birthday Paradox
- with 23 people in a room, you have a 50% chance of having 2 people with the same birthday.
$365!/(365^k( 365-k )!)$
who was pingala? where did he live?
= Jan 29 2024 -- Binomial Coefficients, Pascal's Triangle,
- Recall: $ vec(n, k) = n!/((n-k)!k!)$
$(1+x)^(n+1) = (1+x)(1+x^n) = sum_(k=0)^n 1 + x vec(n, k) x^k$
-Binomial Theorem
$(x+y)^n = sum_(k=0)^n vec(n, k)x^k$
= Jan 31 2024 -- Combinations and Permutations
- How many way to write, with repetition, k numbers from 1 to n if
+ The order we write them is irreleveant
+ The order we write them is releveant
- We regard 122, 212, 221 as the same object.
- Stars and bar approach
- any string of k stars and n-1 bars | will convert to a strings of k 1's, 2'1, ... n's
- There are n+k-1 positions in which to place k stars and n-1 |'s
- There are $vec(n+k-1,k)$ ways to pick the k positions where the stars should be.
- More formally..... Hopefully.... There are n-1 positions we need to pick to plave the |'s so
$vec(n+k-1, n-1)$ ways to do it
- $vec(n+k-1, k) = (n+k-1)!/(k!(n-1!)) = vec(n+k-1, n-1)$
= N Choose K formula
- $vec(n,k) = n!/((n-k!)k!)$
- How many anagrams of MAIM
MAIM
MAMI
AMMI
MMAI
IMMA
IMAM
IAMM
MIMA
AMIM
- How many anagrams of MISSISSIPPI?
11! permutations for distinguishing between MISSISSIPPI (order matters)
= Multinomial Coeficcient
- numbers of the form $ n!/(i_1 ! i_2 ! .... i_k !) $ are sometimes written $vec(n, i_1 i_2 ... i_k)$
and are known as multinomial coeficcients.
- $(x_1 + x_2 +...... + x_n)^n = sum_(k)$
- 4^11 know the difference
= Feb 5 2024
- Something something, <NAME> cryptography.
- william tut in something park britian who gives a shit
= Proofs.... Finally
- How do we prove things?
- Write down careful definitions
- keep track of axioms/given information/assumptions
- Build sequence of deductions to arrivev at the desired result.
- quest of the peacock: good book, lots of epic virtue signaling #emoji.face.cry
= Feb 12 2024 -- Proofs part 2 (3 technically)
- Hypothesis: Every integer greater than 2 is divisible by a prime number.
= Feb 16 2024 -- Proof part 4
- $(1/10^5 sum_(-infinity)^infinity e^(-n^2/10^10))^2 ~= pi$
- What about quantified statements?
- Consider the statement $forall x, P(x) -> Q(x)$
- Converse: $forall x, Q(x) -> P(x)$
- inverse: $forall x, not P(x) -> not Q(x)$
- contrapositive: $forall x not Q(x) -> not (x)$
math club: 5:00 pm m105? floor one of M all the way down on the left.
Exam:
- True or False about predicate value of P(1,1), P(2,2), solve if there is a value of P
- Question aboout sets A = some set
- (i) is {3} element of A
- (ii) is {3} element of A
- Draw a venn diagram for some union or intersection of sets
- STATEMENT: for any horse H, if H is a palomino, h has a saddle. logic, modus ponens modus tollens
- be able to write down the converse, contrapositive, and negation of the statement.
- Consider the integers a, b: if a > 7 and b > 10 then a+b > 18.
- let P = "a > 7", q = "b > 10" and r = "a+b > 18"
- express the statement using p, q, r.
- convert the statement using OR, write down the negation of a statement as an english sentence
- calculation using binomial theorem: coefficient or otherwise. $ x^10 $ in $(x^2-1)^8$
- simple answer, no expansion.
- an inclusion - exclusion question ( dealing with sets and intersections and things )
- Question about using truth tables to determine whether two statements involving p, q. r are logically equivalent.
- counting questions, how many ways can you select 10 pizzas from 4 choices.
- pidgeonhole principle
- selecting 5 students to represent the class at some presentation, anagram of mississippi
- Basic logical laws
= Feb 26 2024
- low down triple dealing
- permutations involving dealing cards
= Feb 28 2024
- Relations, binary relations.
- properties that relations on a set A can have. i
- aside we aer looking to develop the idea of "sameness" which we will call an "equivalence relation." Clearly we alwyasy want x to be the same as x.
- reflexive: x $tilde.op$ x
- Symmetric: we'll say that $tilde.op$ is symmetric if whenever a $tilde.op$ b then b $tilde.op$ a as well
- transitivity: we call a relation transitive if whenever aRb and bRc, we must have aRc as well.
- a symmetric transitive relation on A will have the property that for any a, if there is a
b elementof a so that
- our notion of sameness will be an equivalence relation if it is (i) reflexive, (ii) symmetric, (iii) transitive.
= March 1 2024
- A function $F : A -> B$ is a particular kind of realtion on A x B it has the property that for every a, there is exactly one value f(a) $in$ b
- some particular types of function are quire useful:
- 1-to-1 injection
- onto or surjection
- both, bijection.
- we say $|A| <= |B|$ if there exists a 1-1 functions $ f : A -> B$ if onto, then $|A| >= |B|$
- cantor turned the world of mathematics upside down when he proved that there are different sizes of infinity.
= Cardinalities of sets
- There are sets bigger than |N|, proven by cantor
- Proof: take any function $ f : S -> P(S) $ we can construct a subset of s so that for any $a in S , T eq.not f(a)$ if $ a in f(a), a in.not T$
- Another proof: take any listing of the reals, we construct a number not in the list.
- Okay there are infinitely many different sizes of infinite sets.
- $ |QQ| = |NN| $
|
|
https://github.com/jens-hj/ds-exam-notes | https://raw.githubusercontent.com/jens-hj/ds-exam-notes/main/lectures/5.typ | typst | #import "../lib.typ": *
#show link: it => underline(emph(it))
#set math.equation(numbering: "(1)")
#set enum(full: true)
#set math.mat(delim: "[")
#set math.vec(delim: "[")
#set list(marker: text(catppuccin.latte.lavender, sym.diamond.filled))
#show heading.where(level: 1): it => text(size: 22pt, it)
#show heading.where(level: 2): it => text(size: 18pt, it)
#show heading.where(level: 3): it => {
text(size: 14pt, mainh, pad(
left: -0.4em,
gridx(
columns: (auto, 1fr),
align: center + horizon,
it, rule(stroke: 1pt + mainh)
)
))
}
#show heading.where(level: 4): it => text(size: 12pt, secondh, it)
#show heading.where(level: 5): it => text(size: 12pt, thirdh, it)
#show heading.where(level: 6): it => text(thirdh, it)
#show emph: it => text(accent, it)
#show ref: it => {
//let sup = it.supplement
let el = it.element
if el == none {
it.citation
}
else {
let eq = math.equation
// let sup = el.supplement
if el != none and el.func() == eq {
// The reference is an equation
let sup = if it.fields().at("supplement", default: "none") == "none" {
[Equation]
} else { [] }
// [#it.has("supplement")]
show regex("\d+"): set text(accent)
let n = numbering(el.numbering, ..counter(eq).at(el.location()))
[#sup #n]
}
else if it.citation.has("supplement") {
if el != none and el.func() == eq {
show regex("\d+"): set text(accent)
let n = numbering(el.numbering, ..counter(eq).at(el.location()))
[#el.supplement #n]
}
else {
text(accent)[#it]
}
}
}
}
=== Leading up to Finite Fields
- Used fx. in `RAID6`, see previous sections
- Any operation on one or more elements from within a set of finite elements always yields an element in that set
- Any operation should always be reversible
#image("../img/ff-defs.png", width: 70%)
==== Groups
#image("../img/ff-group.png", width: 70%)
==== Abelian Group
- *Group* with _commutativity_
==== Rings
#pad(top: -2em, image("../img/ff-rings.png"))
==== Commutative Ring
- *Ring* that satisfies _commutativity of multiplication_ $a b = b a in RR$
==== Integral Domain
- *Commutative ring* that also satisfies
- _Multiplicative identity_ e.g. $1 a = a 1 = a$
- _No zero divisors_ i.e. if $a b = 0 arrow.r.double a=0 or b=0 $
==== Field
- *Integral domain* that also satisfies
- _Multiplicative inverse_ i.e. for each $forall a in F : a != 0 arrow.r.double exists a^(-1) : a(a^(-1)) = (a^(-1))a = 1$
=== Finite Fields
#image("../img/ff.png", width: 70%)
- $"GF"(2^n)$ is very useful for binary in computer science
- Thus works well with binary and can be _executed fast on computer_
- Much of the time _modular arithmetic_ can be used to create _finite fields_
- Because of the nature of this, $p$ has to be a prime, if not it is no longer a finite field
- #image("../img/ff-not-prime.png", width: 25%)
Where you can't undo, you don't know whether 1 came from $1 times 1$ or $3 times 3$, similar case with 3.
*$G(2^n)$* is _not prime_, thus we use _polynomial arithmetic_ instead
#image("../img/ff-polynomial.png", width: 50%)
- Product breaks the finite fields guarantees
- #image("../img/ff-polynomial-2.png", width: 80%)
- Divide by some irreducible polynomial (of order $n$?)
- #image("../img/ff-polynomial-3.png", width: 30%)
_Usually you have LUT for these finite fields in an implementation, which accelerates it immensely, instead of computing these polynomials in real time_
- Sometimes tables become very big like $"GF"(2^8)$, where you might _need_ to compute
#image("../img/ff-implementation.png", width: 50%)
#image("../img/ff-implementation-2.png", width: 40%)
=== Linear Coding
- Generating a linear coded fragment/stripe $C$
$
C_i = sum a_(i j) P_j
$
#image("../img/ff-lc-1.png", width: 50%)
_Take the original fragments $P_j$, and make a *linear combination* of them, reaulting in the encoded fragments $C_i$_ \
How you pick the coefficients determines properties and performance of the system
*`RAID6`*
#image("../img/ff-raid6.png", width: 50%)
==== How to Decode (`RAID6`)
- You have some subset of the coded fragments, and you want to recover
*Example:*
- Lost 5 and 6
#image("../img/ff-raid6-decode.png", width: 50%)
Something something linear system of equations \
#ra _qaussian elimination_
==== Codes
- MDS: Maximum Distance Separable
#image("../img/ff-mds.png", width: 50%)
- Reed Solomon Vandermonde: Not systematic (and MDS code)
#image("../img/ff-reed.png", width: 60%)
- Reed Solomon Cauchy: Systematic and very constructive (designed for specific purposes)
- Many Cauchy alternatives
- #image("../img/ff-cauchy.png", width: 60%)
=== Reliable Multi-server
- Numoerous disk _failures per day_
- Failures are the _norm_
- Redundancy is _necessary_
- Replication or erasure coding
#quest-block[
Are `RAID` schemes like `RAID5` and `RAID6` a form of _erasure coding_?
]
#report-block[
*Erasure coding* and *replication* are two _distinct_ methods of redundancy, there are trade-offs for each.
With *erasure coding* you tupically have to do _more work_ to recover. \
#ra a lot of network traffic for repair \
Where with simple *striped replication* you might only have to move 1/10 a file. \
#ra little network traffic for repair \
Apparently _regenerating codes_ are codes that keep the MDS properties and reduce repair traffic.
]
#report-block[
I was _definitely_ supposed to use `PyErasure` for the final project, which I didn't \
#ra look at Lab Week 5
]
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/bugs/bad_ident.typ | typst | Apache License 2.0 |
#let true- = 1;
#let auto- = 1;
#let any- = 1;
#let none- = 1;
#let false- = 1;
#let true- = 1;
#let break- = 1;
#let continue- = 1;
#let and- = 1;
#let or- = 1;
#let not- = 1;
#let return- = 1;
#let as- = 1;
#let in- = 1;
#let include- = 1;
#let import- = 1;
#let let- = 1;
#let else- = 1;
#let if- = 1;
#let for- = 1;
#let while- = 1;
#let context- = 1;
#let set- = 1;
#let show- = 1;
#let x-true- = 1;
#let x-auto- = 1;
#let x-any- = 1;
#let x-none- = 1;
#let x-false- = 1;
#let x-true- = 1;
#let x-break- = 1;
#let x-continue- = 1;
#let x-and- = 1;
#let x-or- = 1;
#let x-not- = 1;
#let x-return- = 1;
#let x-as- = 1;
#let x-in- = 1;
#let x-include- = 1;
#let x-import- = 1;
#let x-let- = 1;
#let x-else- = 1;
#let x-if- = 1;
#let x-for- = 1;
#let x-while- = 1;
#let x-context- = 1;
#let x-set- = 1;
#let x-show- = 1;
#let show-() = 1;
#let show-(show-) = 1;
#(1pt-1pt)
#(1rad-1rad)
#(true-)
#(auto-)
#(any-)
#(none-)
#(false-)
#(true-)
#(break-)
#(continue-)
#(and-)
#(or-)
#(not-)
#(return-)
#(as-)
#(in-)
#(include-)
#(import-)
#(let-)
#(else-)
#(if-)
#(for-)
#(while-)
#(context-)
#(set-)
#(show-)
#(x-true-)
#(x-auto-)
#(x-any-)
#(x-none-)
#(x-false-)
#(x-true-)
#(x-break-)
#(x-continue-)
#(x-and-)
#(x-or-)
#(x-not-)
#(x-return-)
#(x-as-)
#(x-in-)
#(x-include-)
#(x-import-)
#(x-let-)
#(x-else-)
#(x-if-)
#(x-for-)
#(x-while-)
#(x-context-)
#(x-set-)
#(x-show-)
A and B |
https://github.com/FlorentCLMichel/quetta | https://raw.githubusercontent.com/FlorentCLMichel/quetta/main/src/quetta.typ | typst | MIT License | #import "quenya.typ": quenya
#import "gondor.typ": gondor
|
https://github.com/XcantloadX/TypstMomoTalk | https://raw.githubusercontent.com/XcantloadX/TypstMomoTalk/main/momotalk/__characters_templ.typ | typst | #import "momotalk.typ": chat, msgbox, messages
#import "momotalk.typ": COLOR_MSGBOX_SENSEI_BG
#let __wrap(name, filename) = messages.with(name, filename)
#let sensei = messages.with(none, none, direction: "right", background_color: COLOR_MSGBOX_SENSEI_BG)
#let laoshi = sensei
#let 老师 = sensei
|
|
https://github.com/chamik/gympl-skripta | https://raw.githubusercontent.com/chamik/gympl-skripta/main/main.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "@preview/ccicons:1.0.0": cc-by-sa
#import "helper.typ": *
#set document(title: [Gympl Skripta], author: "<NAME>", date: auto)
#set page(paper: "a4")
#set heading(numbering: "1.")
#set text(size: 13pt, lang: "cs")
#set footnote(numbering: "*")
#set quote(block: true)
#set par(justify: true)
#show link: it => underline(stroke: (thickness: 1pt, dash: "dotted"), offset: 2pt, it)
#show ref: it => underline(stroke: (thickness: 1pt, dash: "dotted"), offset: 2pt, it)
#let titlepage(a) = [
#set text(size: 30pt)
#align(center + horizon, heading(numbering: "I.", [#a]))
#pagebreak()
]
#[
#set page(margin: 3cm)
#set par(leading: .3em)
#set text(size: 100pt)
Gympl skripta
#set text(size: 30pt)
<NAME>
#text(size: 12pt)[#align(center + bottom)[
Naposledy aktualizováno #datetime.today().day(). #datetime.today().month(). #datetime.today().year()\
#v(.4em)\
#text(size: 30pt)[#cc-by-sa]
]]
]
#include "uvod.typ"
#pagebreak()
#[
#show outline.entry.where(
level: 1
): it => {
v(12pt, weak: true)
strong(it)
}
#outline(title: "Rejstřík", indent: auto)
]
#pagebreak()
#titlepage("Český jazyk")
#set page(numbering: "1")
#include "cj.typ"
#set page(numbering: none)
#titlepage("Anglický jazyk")
#set page(numbering: "1")
#include "anj.typ"
|
https://github.com/SkytAsul/trombinoscope | https://raw.githubusercontent.com/SkytAsul/trombinoscope/main/pages/pageRemerciements.typ | typst | MIT License | #show: it => align(horizon + center, block(width: 90%, align(left, it)))
#align(center)[= Remerciements]
#v(2em)
#set text(size: 1.2em)
#set par(justify: true)
Ce projet de trombinoscope a été mené par : <NAME>, <NAME>, <NAME>, <NAME> et <NAME>.
#v(2em)
Merci à <NAME> et <NAME> pour la mise en page du trombinoscope, à <NAME> pour la réalisation des 1#super[ère] et 4#super[ème] de couvertures et à <NAME> pour son aide dans la réalisation de ce trombinoscope. Merci à la direction de l'INSA Rennes d'avoir financé en partie ce projet de trombinoscope et finalement merci à vous les étudiants de l'avoir acheté. |
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/docs/guides/page-setup.md | markdown | Apache License 2.0 | ---
description: |
An in-depth guide to setting page dimensions, margins, and page numbers in
Typst. Learn how to create appealing and clear layouts and get there quickly.
---
# Page setup guide
Your page setup is a big part of the first impression your document gives. Line
lengths, margins, and columns influence
[appearance](https://practicaltypography.com/page-margins.html) and
[legibility](https://designregression.com/article/line-length-revisited-following-the-research)
while the right headers and footers will help your reader easily navigate your
document. This guide will help you to customize pages, margins, headers,
footers, and page numbers so that they are the right fit for your content and
you can get started with writing.
In Typst, each page has a width, a height, and margins on all four sides. The
top and bottom margins may contain a header and footer. The set rule of the
[`{page}`]($page) element is where you control all of the page setup. If you
make changes with this set rule, Typst will ensure that there is a new and
conforming empty page afterward, so it may insert a page break. Therefore, it is
best to specify your [`{page}`]($page) set rule at the start of your document or
in your template.
```example
#set rect(
width: 100%,
height: 100%,
inset: 4pt,
)
>>> #set text(6pt)
>>> #set page(margin: auto)
#set page(
paper: "iso-b7",
header: rect(fill: aqua)[Header],
footer: rect(fill: aqua)[Footer],
number-align: center,
)
#rect(fill: aqua)
```
This example visualizes the dimensions for page content, headers, and footers.
The page content is the page size (ISO B7) minus each side's default margin. In
the top and the bottom margin, there are stroked rectangles visualizing the
header and footer. They do not touch the main content, instead, they are offset
by 30% of the respective margin. You can control this offset by specifying the
[`header-ascent`]($page.header-ascent) and
[`footer-descent`]($page.footer-descent) arguments.
Below, the guide will go more into detail on how to accomplish common page setup
requirements with examples.
## Customize page size and margins { #customize-margins }
Typst's default page size is A4 paper. Depending on your region and your use
case, you will want to change this. You can do this by using the
[`{page}`]($page) set rule and passing it a string argument to use a common page
size. Options include the complete ISO 216 series (e.g. `"iso-a4"`, `"iso-c2"`),
customary US formats like `"us-legal"` or `"us-letter"`, and more. Check out the
reference for the [page's paper argument]($page.paper) to learn about all
available options.
```example
>>> #set page(margin: auto)
#set page("us-letter")
This page likes freedom.
```
If you need to customize your page size to some dimensions, you can specify the
named arguments [`width`]($page.width) and [`height`]($page.height) instead.
```example
>>> #set page(margin: auto)
#set page(width: 12cm, height: 12cm)
This page is a square.
```
### Change the page's margins { #change-margins }
Margins are a vital ingredient for good typography:
[Typographers consider lines that fit between 45 and 75 characters best length
for legibility](http://webtypography.net/2.1.2) and your margins and
[columns](#columns) help define line widths. By default, Typst will create
margins proportional to the page size of your document. To set custom margins,
you will use the [`margin`]($page.margin) argument in the [`{page}`]($page) set
rule.
The `margin` argument will accept a length if you want to set all margins to the
same width. However, you often want to set different margins on each side. To do
this, you can pass a dictionary:
```example
#set page(margin: (
top: 3cm,
bottom: 2cm,
x: 1.5cm,
))
#lorem(100)
```
The page margin dictionary can have keys for each side (`top`, `bottom`, `left`,
`right`), but you can also control left and right together by setting the `x`
key of the margin dictionary, like in the example. Likewise, the top and bottom
margins can be adjusted together by setting the `y` key.
If you do not specify margins for all sides in the margin dictionary, the old
margins will remain in effect for the unset sides. To prevent this and set all
remaining margins to a common size, you can use the `rest` key. For example,
`[#set page(margin: (left: 1.5in, rest: 1in))]` will set the left margin to 1.5
inches and the remaining margins to one inch.
### Different margins on alternating pages { #alternating-margins }
Sometimes, you'll need to alternate horizontal margins for even and odd pages,
for example, to have more room towards the spine of a book than on the outsides
of its pages. Typst keeps track of whether a page is to the left or right of the
binding. You can use this information and set the `inside` or `outside` keys of
the margin dictionary. The `inside` margin points towards the spine, and the
`outside` margin points towards the edge of the bound book.
```typ
#set page(margin: (inside: 2.5cm, outside: 2cm, y: 1.75cm))
```
Typst will assume that documents written in Left-to-Right scripts are bound on
the left while books written in Right-to-Left scripts are bound on the right.
However, you will need to change this in some cases: If your first page is
output by a different app, the binding is reversed from Typst's perspective.
Also, some books, like English-language Mangas are customarily bound on the
right, despite English using Left-to-Right script. To change the binding side
and explicitly set where the `inside` and `outside` are, set the
[`binding`]($page.binding) argument in the [`{page}`]($page) set rule.
```typ
// Produce a book bound on the right,
// even though it is set in Spanish.
#set text(lang: "es")
#set page(binding: right)
```
If `binding` is `left`, `inside` margins will be on the left on odd pages, and
vice versa.
## Add headers and footers { #headers-and-footers }
Headers and footers are inserted in the top and bottom margins of every page.
You can add custom headers and footers or just insert a page number.
In case you need more than just a page number, the best way to insert a header
and a footer are the [`header`]($page.header) and [`footer`]($page.footer)
arguments of the [`{page}`]($page) set rule. You can pass any content as their
values:
```example
>>> #set page("a5", margin: (x: 2.5cm, y: 3cm))
#set page(header: [
_<NAME> Thesis_
#h(1fr)
National Academy of Sciences
])
#lorem(150)
```
Headers are bottom-aligned by default so that they do not collide with the top
edge of the page. You can change this by wrapping your header in the
[`{align}`]($align) function.
### Different header and footer on specific pages { #specific-pages }
You'll need different headers and footers on some pages. For example, you may
not want a header and footer on the title page. The example below shows how to
conditionally remove the header on the first page:
```typ
>>> #set page("a5", margin: (x: 2.5cm, y: 3cm))
#set page(header: locate(loc => {
if counter(page).at(loc).first() > 1 [
_<NAME> Thesis_
#h(1fr)
National Academy of Sciences
]
}))
#lorem(150)
```
This example may look intimidating, but let's break it down: We are telling
Typst that the header depends on the current [location]($locate). The `loc`
value allows other functions to find out where on the page we currently are. We
then ask Typst if the page [counter]($counter) is larger than one at our current
position. The page counter starts at one, so we are skipping the header on a
single page. Counters may have multiple levels. This feature is used for items
like headings, but the page counter will always have a single level, so we can
just look at the first one.
You can, of course, add an `else` to this example to add a different header to
the first page instead.
### Adapt headers and footers on pages with specific elements { #specific-elements }
The technique described in the previous section can be adapted to perform more
advanced tasks using Typst's labels. For example, pages with big tables could
omit their headers to help keep clutter down. We will mark our tables with a
`<big-table>` [label]($label) and use the [query system]($query) to find out if
such a label exists on the current page:
```typ
>>> #set page("a5", margin: (x: 2.5cm, y: 3cm))
#set page(header: locate(loc => {
let page-counter = counter(page)
let matches = query(<big-table>, loc)
let current = page-counter.at(loc)
let has-table = matches.any(m =>
page-counter.at(m.location()) == current
)
if not has-table [
_<NAME> Thesis_
#h(1fr)
National Academy of Sciences
]
}))
#lorem(100)
#pagebreak()
#table(
columns: 2 * (1fr,),
[A], [B],
[C], [D],
) <big-table>
```
Here, we query for all instances of the `<big-table>` label. We then check that
none of the tables are on the page at our current position. If so, we print the
header. This example also uses variables to be more concise. Just as above, you
could add an `else` to add another header instead of deleting it.
## Add and customize page numbers { #page-numbers }
Page numbers help readers keep track of and reference your document more easily.
The simplest way to insert page numbers is the [`numbering`]($page.numbering)
argument of the [`{page}`]($page) set rule. You can pass a
[_numbering pattern_]($numbering.numbering) string that shows how you want your
pages to be numbered.
```example
>>> #set page("iso-b6", margin: 1.75cm)
#set page(numbering: "1")
This is a numbered page.
```
Above, you can check out the simplest conceivable example. It adds a single
Arabic page number at the center of the footer. You can specify other characters
than `"1"` to get other numerals. For example, `"i"` will yield lowercase Roman
numerals. Any character that is not interpreted as a number will be output
as-is. For example, put dashes around your page number by typing this:
```example
>>> #set page("iso-b6", margin: 1.75cm)
#set page(numbering: "— 1 —")
This is a — numbered — page.
```
You can add the total number of pages by entering a second number character in
the string.
```example
>>> #set page("iso-b6", margin: 1.75cm)
#set page(numbering: "1 of 1")
This is one of many numbered pages.
```
Go to the [`{numbering}` function reference]($numbering.numbering) to learn more
about the arguments you can pass here.
In case you need to right- or left-align the page number, use the
[`number-align`]($page.number-align) argument of the [`{page}`]($page) set rule.
Alternating alignment between even and odd pages is not currently supported
using this property. To do this, you'll need to specify a custom footer with
your footnote and query the page counter as described in the section on
conditionally omitting headers and footers.
### Custom footer with page numbers
Sometimes, you need to add other content than a page number to your footer.
However, once a footer is specified, the [`numbering`]($page.numbering) argument
of the [`{page}`]($page) set rule is ignored. This section shows you how to add
a custom footer with page numbers and more.
```example
>>> #set page("iso-b6", margin: 1.75cm)
#set page(footer: [
*American Society of Proceedings*
#h(1fr)
#counter(page).display(
"1/1",
both: true,
)
])
This page has a custom footer.
```
First, we add some strongly emphasized text on the left and add free space to
fill the line. Then, we call `counter(page)` to retrieve the page counter and
use its `display` function to show its current value. We also set `both` to
`{true}` so that our numbering pattern applies to the current _and_ final page
number.
We can also get more creative with the page number. For example, let's insert a
circle for each page.
```example
>>> #set page("iso-b6", margin: 1.75cm)
#set page(footer: [
*Fun Typography Club*
#h(1fr)
#counter(page).display(num => {
let circles = num * (
box(circle(
radius: 2pt,
fill: navy,
)),
)
box(
inset: (bottom: 1pt),
circles.join(h(1pt))
)
})
])
This page has a custom footer.
```
In this example, we use the number of pages to create an array of
[circles]($circle). The circles are wrapped in a [box]($box) so they can all
appear on the same line because they are blocks and would otherwise create
paragraph breaks. The length of this [array]($array) depends on the current page
number.
We then insert the circles at the right side of the footer, with 1pt of space
between them. The join method of an array will attempt to
[_join_]($scripting/#blocks) the different values of an array into a single
value, interspersed with its argument. In our case, we get a single content
value with circles and spaces between them that we can use with the align
function. Finally, we use another box to ensure that the text and the circles
can share a line and use the [`inset` argument]($box.inset) to raise the circles
a bit so they line up nicely with the text.
### Reset the page number and skip pages { #skip-pages }
Do you, at some point in your document, need to reset the page number? Maybe you
want to start with the first page only after the title page. Or maybe you need
to skip a few page numbers because you will insert pages into the final printed
product.
The right way to modify the page number is to manipulate the page
[counter]($counter). The simplest manipulation is to set the counter back to 1.
```typ
#counter(page).update(1)
```
This line will reset the page counter back to one. It should be placed at the
start of a page because it will otherwise create a page break. You can also
update the counter given its previous value by passing a function:
```typ
#counter(page).update(n => n + 5)
```
In this example, we skip five pages. `n` is the current value of the page
counter and `n + 5` is the return value of our function.
In case you need to retrieve the actual page number instead of the value of the
page counter, you can use the [`page`]($locate) method on the argument of the
`{locate}` closure:
```example
#counter(page).update(n => n + 5)
// This returns one even though the
// page counter was incremented by 5.
#locate(loc => loc.page())
```
You can also obtain the page numbering pattern from the `{locate}` closure
parameter with the [`page-numbering`]($locate) method.
## Add columns { #columns }
Add columns to your document to fit more on a page while maintaining legible
line lengths. Columns are vertical blocks of text which are separated by some
whitespace. This space is called the gutter.
If all of your content needs to be laid out in columns, you can just specify the
desired number of columns in the [`{page}`]($page.columns) set rule:
```example
>>> #set page(height: 120pt)
#set page(columns: 2)
#lorem(30)
```
If you need to adjust the gutter between the columns, refer to the method used
in the next section.
### Use columns anywhere in your document { #columns-anywhere }
Very commonly, scientific papers have a single-column title and abstract, while
the main body is set in two-columns. To achieve this effect, Typst includes a
standalone [`{columns}` function]($columns) that can be used to insert columns
anywhere on a page.
Conceptually, the `columns` function must wrap the content of the columns:
```example:single
>>> #set page(height: 180pt)
= Impacts of Odobenidae
#set par(justify: true)
>>> #h(11pt)
#columns(2)[
== About seals in the wild
#lorem(80)
]
```
However, we can use the ["everything show rule"]($styling/#show-rules) to reduce
nesting and write more legible Typst markup:
```example:single
>>> #set page(height: 180pt)
= Impacts of Odobenidae
#set par(justify: true)
>>> #h(11pt)
#show: columns.with(2)
== About seals in the wild
#lorem(80)
```
The show rule will wrap everything that comes after it in its function. The
[`with` method]($function.with) allows us to pass arguments, in this case, the
column count, to a function without calling it.
Another use of the `columns` function is to create columns inside of a container
like a rectangle or to customize gutter size:
```example
#rect(
width: 6cm,
height: 3.5cm,
columns(2, gutter: 12pt)[
In the dimly lit gas station,
a solitary taxi stood silently,
its yellow paint fading with
time. Its windows were dark,
its engine idle, and its tires
rested on the cold concrete.
]
)
```
### Balanced columns
If the columns on the last page of a document differ greatly in length, they may
create a lopsided and unappealing layout. That's why typographers will often
equalize the length of columns on the last page. This effect is called balancing
columns. Typst cannot yet balance columns automatically. However, you can
balance columns manually by placing [`[#colbreak()]`]($colbreak) at an
appropriate spot in your markup, creating the desired column break manually.
## One-off modifications
You do not need to override your page settings if you need to insert a single
page with a different setup. For example, you may want to insert a page that's
flipped to landscape to insert a big table or change the margin and columns for
your title page. In this case, you can call [`{page}`]($page) as a function with
your content as an argument and the overrides as the other arguments. This will
insert enough new pages with your overridden settings to place your content on
them. Typst will revert to the page settings from the set rule after the call.
```example
>>> #set page("a6")
#page(flipped: true)[
= Multiplication table
#table(
columns: 5 * (1fr,),
..for x in range(1, 10) {
for y in range(1, 6) {
(str(x*y),)
}
}
)
]
```
|
https://github.com/davystrong/umbra | https://raw.githubusercontent.com/davystrong/umbra/main/gallery/neumorphism.typ | typst | MIT License | #import "@preview/umbra:0.1.0": shadow-path
#let background-colour = color.rgb("#EFEEEE")
#let radius = 0.4cm
#set page(width: 15cm, height: 15cm, margin: 0.5cm, fill: background-colour)
#box(
{
place(shadow-path(
shadow-stops: (white.mix((background-colour, 50%)), background-colour,),
shadow-radius: radius,
(16%, 15%),
(15%, 16%),
(15%, 79%),
(16%, 80%),
(79%, 80%),
(80%, 79%),
(80%, 16%),
(79%, 15%),
closed: true,
))
place(
shadow-path(
shadow-stops: (color.rgb("#D1CDC7").mix((background-colour, 50%)), background-colour,),
shadow-radius: radius,
(21%, 20%),
(20%, 21%),
(20%, 84%),
(21%, 85%),
(84%, 85%),
(85%, 84%),
(85%, 20%),
(84%, 21%),
closed: true,
),
)
polygon(
fill: background-colour,
(16%, 15%),
(15%, 16%),
(15%, 84%),
(16%, 85%),
(85%, 84%),
(84%, 85%),
(85%, 16%),
(84%, 15%),
)
},
) |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/silky-report-insa/0.1.0/lib.typ | typst | Apache License 2.0 | // FULL DOCUMENT :
#let insa-full(
cover-top-left: [],
cover-middle-left: [],
cover-bottom-right: [],
page-header: [],
doc
) = {
set text(lang: "fr")
set page("a4")
// IMAGE
place(dx: -2.5cm, dy: -2.5cm, image("cover.jpeg", width: 20.9cm, height: 29.6cm))
// TOP-LEFT
place(
dy: 4cm,
block(
width: 9.5cm,
par(
justify: false,
text(size: 18pt, cover-top-left)
)
)
)
// middle-left
place(
dx: -1.35cm,
dy: 11.2cm,
block(
width: 7.5cm,
height: 7cm,
inset: 1cm,
align(horizon, par(
justify: false,
text(size: 16pt, cover-middle-left)
))
)
)
// BOTTOM-RIGHT
place(
dx: 7cm,
dy: 23cm,
box(
width: 8.5cm,
par(
justify: false,
text(size: 24pt, weight: "bold", cover-bottom-right)
)
)
)
counter(page).update(0)
set page(
"a4",
header-ascent: 25%,
footer: [
#place(
right,
dy: -0.6cm,
dx: 1.9cm,
image("footer.png")
)
#place(
right,
dx: 1.55cm,
dy: 0.58cm,
text(fill: white, weight: "bold", counter(page).display())
)
],
header: {
page-header
line(length: 100%)
}
)
set par(justify: true)
set figure(numbering: "1")
show figure.where(kind: image): set figure(supplement: "Figure") // par défaut, Typst affiche "Fig."
show figure.caption: it => [
#text(weight: "bold")[
#it.supplement
#context it.counter.display(it.numbering) :
]
#it.body
]
doc
}
// FULL REPORT DOCUMENT :
#let insa-report(
id: 1,
pre-title: none,
title : none,
authors: [],
date: none,
doc,
) = {
insa-full(
cover-middle-left: authors,
cover-top-left: [
#set text(size: 28pt, weight: "bold")
#if pre-title != none [
#pre-title #sym.hyph
]
TP #id\
#set text(size: 22pt, weight: "medium")
#smallcaps(title)
],
page-header: [
TP #id #sym.hyph #smallcaps(title)
#h(1fr)
#if type(date) == datetime [
#date.display("[day]/[month]/[year]")
] else [
#date
]
],
{
set math.equation(numbering: "(1)")
set text(hyphenate: false)
set heading(numbering: "I.1.")
show heading.where(level: 1): it => [
#set text(18pt)
#smallcaps(it)
]
show raw.where(block: true): it => block(stroke: 0.5pt + black, inset: 5pt, width: 100%, it)
doc
}
)
}
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/enum-03.typ | typst | Other | // Mix of different lists
- Bullet List
+ Numbered List
/ Term: List
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/goto_definition/module_select.typ | typst | Apache License 2.0 | // path: variable.typ
#let f(x) = 2;
-----
#import "variable.typ"
#(variable.f /* position after */ );
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/999_Unknown%20Set.typ | typst | #import "@local/mtgset:0.1.0": conf
#show: doc => conf("Unknown Set", doc)
|
|
https://github.com/ngoetti/knowledge-key | https://raw.githubusercontent.com/ngoetti/knowledge-key/master/template/sections/02-devops-with-gitlab.typ | typst | MIT License | #import "../utils.typ": *
= DevOps with Gitlab
#sourcecode[```yaml
default:
image: alpine:3.19.1
------
rules:
- if: $CI_COMMIT_BRANCH == "main"
rules:
- changes:
- README.md
```]
== Automated application deployment
=== Declaring deployment environments
Environments in Gitlab define where code gets deployed.
It allows to see a history of deployments and allows to rollback to earlier version.
#sourcecode[```yaml
deploy:
stage: deploy
environment:
name: production
url: https://example.com
```]
=== Kubernetes application resources
You can build images and push them into your Gitlab container registry.
Passing the Kubernetes YAML into `envsubst`, you can replace the environment variable with the actual value.
=== Deploying an application to Kubernetes
Using the Gitlab Kubernetes integration, you can easily deploy your application to Kubernetes.
- You can define multiple Kubernetes cluster to connect to and then define via “environment
scope” which environment corresponds to which Kubernetes cluster
- The Kubernetes cluster credentials are available to any job.
=== Deploy tokens and pulling secrets
We need Kubernetes authentication information so it can pull the Docker image from our Gitlab registry.
Gitlab has a feature named “deploy tokens” that can be defined per project and have a defined scope like “read_registry”.
Then you expose the deploy token with environment variables to the build environment.
In Kubernetes, you can create a secret with the type “docker-registry” and pass the deploy token
to it.
#sourcecode[```yaml
deploy:
stage: deploy
environment:
name: production
url: http://todo.deploy.k8s.anvard.org
image: roffe/kubectl:v1.13.0
script:
- kubectl delete --ignore-not-found=true secret gitlab-auth
- kubectl create secret docker-registry gitlab-auth --docker-server=$CI_REGISTRY --docker-username=$KUBE_PULL_USER --docker-password=$KUBE_PULL_PASS
- cat k8s.yaml | envsubst | kubectl apply -f –
```]
And then reference the secret from your k8s.yaml.
#sourcecode[```yaml
spec:
replica: 3
selector:
matchLabels:
app: todo
template:
metadata:
labels:
app: app
spec:
imagePullSecrets:
- name: gitlab-auth
containers:
- name: todo
image: "${DOCKER_IMAGE_TAG}"
env:
- name: NODE_ENV
value: "production"
- name: DATABASE_URL
value: "postgres://${DBUSER}:${DBPASS}@tododb/todo"
ports:
- containerPort: 3000
```]
=== Dynamic environments and review apps
Idea: Have a separate deployment for each branch for the devs to fiddle around with. (`todo-${DEPLOY_SUFFIX}`)
This can be achived by adding a DEPLOY_SUFFIX and DEPLOY_HOST to all k8s resources.
Another job is added that deletes the resources when the branch is deleted.
This job can be triggered with `on:stop: job_name` in the environment section.
== Application quality and monitoring
=== Integration and functional testing
To run integration tests, you can define services per Gitlab job, e.g., a Postgres database container.
A service is an extra container that GitLab CI will run for us as part of our build or test process.
The extra container is going to be available to the mail container.
#sourcecode[```yaml
test-10:
stage: test
image: node:10
services:
- name: postgres:10
alias: db
variables:
POSTGRES_DB: todo
POSTGRES_USER: "${DBUSER}"
POSTGRES_PASS: "${<PASSWORD>}"
DATABASE_URL: "postgres://${DBUSER}:${DBPASS}@db/todo"
script:
- ./ci-test.sh
```]
This service will be reachable as “db” from our job script.
=== Analyze code quality
Gitlab offers automated code quality checks which can run with each pipeline.
The result of the analysis will be displayed alongside the merge request.
Code quality jobs usually take quite a bit of time.
(`include: (pagebreak) - template: Code-Quality.gitlab-ci.yaml`)
=== Dynamic application security testing (DAST)
Gitlab can check an application “from outside” for security issues.
=== Application monitoring with Prometheus
Prometheus identifies metric endpoints from an application and scrapes periodically metrics from those endpoints.
If the Kubernetes integration with Gitlab is activated, Gitlab will deploy a Prometheus server to said cluster.
To define that your service has endpoints to get data from for Prometheus, you need to add annotations to the Kubernetes service. (In the kubernetes Service file)
The data can be reviewed in Gitlab directly.
Spaceships are added to the timeline to indicate when a deployment happened.
== Custom CI infrastructure
=== Launching dedicated runners
When using gitlab.com, your jobs are running on shared infrastructure.
You can also launch dedicated runners for your project and connect them to gitlab.com.
Below is the configuration page and an overview of runners assigned to the project.
When launching dedicated runners, you can assign them tags.
In your pipeline definition, you can force to run the job on dedicated runners by also mentioning the tags used for dedicated runners in the pipeline.
There is different type of runners:
- Shell: Run builds directly on runner host. Useful for building virtual machine or Docker
images.
- Docker: Run builds in Docker containers. Can be used for building Docker images through “Docker in Docker” configuration.
- Docker machine: Launches virtual machines to run builds in Docker. Useful for autoscaling.
- Kubernetes: Runs builds in Docker containers inside Kubernetes. Useful to consolidate build infrastructure when using Kubernetes.
=== Custom Kubernetes runners
You can also deploy Gitlab runners from Gitlab to a Kubernetes cluster. |
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/信息技术工程导论/main.typ | typst | The Unlicense | #import "../template.typ": *
#show: project.with(
title: "软件设计",
authors: ("absolutex",),
)
= 软件设计与开发
== 主要职责
+ 根据手柄硬件设计文档,设计手柄的软件驱动并完成开发;
+ 对接 Windows/Linux 系统,确保手柄能与 Windows/Linux 通过适当的协议进行通信;
+ #strike[编写测试计划并完成测试。]
== 系统 API 调研
=== 协议对比
// https://learn.microsoft.com/en-us/windows-hardware/drivers/hid/
- Human Interface Devices (HID) 是第一个通用的支持游戏手柄+键盘、鼠标等输入设备的协议标准。在此之前,需要通过游戏端口(D-sub)和专有协议支持游戏输入设备。1996 年 USB-IF 通过了 HID over USB 规范。HID 设备使用报告描述符来定义数据格式,如按键事件、鼠标运动等,所有现代系统都内置支持 HID 协议。
// https://en.wikipedia.org/wiki/DirectInput
- DirectInput 是一个旧版 Microsoft API,是 DirectX 库的一部分,基本兼容 DirectX 8(2001-2002)之后的所有 DirectX 游戏版本。 DirectInput 支持多种类的输入设备和自定义功能,尤其是飞行杆、力反馈设备和自定义按键。
// https://en.wikipedia.org/wiki/DirectInput#XInput
// https://learn.microsoft.com/en-us/windows/win32/xinput/xinput-and-directinput
- XInput 于 2005 年 12 月与 Xbox 360 一起推出。此规范为 Windows XP SP1 和后续操作系统中的 Xbox 360 控制器提供支持,并且被 Microsoft 描述为比 DirectInput 更容易编程且需要的设置更少。XInput 与 DirectX 版本 9 及更高版本兼容。与 DirectInput 相比,XInput 更易于使用,需要的设置更少。XInput 设备可以兼容使用 DirectInput 的游戏,不过部分功能会出现问题。(左/右 trigger 会被视为同一个;振动效果不可用)
// https://stackoverflow.com/questions/73019812/
// https://learn.microsoft.com/en-us/gaming/gdk/_content/gc/input/overviews/input-overview
- Microsoft GameInput API 是 Microsoft Game Development Kit(GDK) 的一部分,于 2021 年 6 月 24 日首次发布,具有最佳性能与100% 的线程安全。GameInput 是所有旧版输入 API(XInput、DirectInput、Raw Input、Human Interface Device (HID) 和 WinRT API)的功能超集,此外还添加了自己的新功能。2024 年 3 月,虚幻引擎 (UE5)发布了实验性插件 “Game Input for Windows” 以支持此 API。
- 手柄设计无需专门支持此 API。
=== Windows
XInput 是 Windows 上对 Xbox 手柄支持最广的协议,现代 PC 游戏大多数都优先支持 XInput。
=== Linux
Linux 内核使用通用的 HID 协议来识别和处理各种输入设备;用户也可以借助一些第三方工具(如 Wine 和 Proton)在 Linux 上运行 Windows 游戏,这些工具会模拟 Windows 环境,并将 XInput 调用映射到 Linux 下支持的接口(HID, evdev, SDL, ff-memless, uinput),从而使得游戏能够识别 XInput 手柄。
=== 总结
现代手柄(如 Xbox 系列手柄、PlayStation 手柄)大多同时支持 HID 和 XInput;前者主要是出于兼容性与跨平台考虑。因此我们制作的手柄也会支持 HID 和 XInput 协议。
// 对于标准协议无法实现的功能,还需要结合文档进一步研究。
== 嵌入式软件开发
=== 开发环境与基础设施
针对 ESP32-S3 芯片组,有几种不同的开发方式:
+ 使用 Espressif 官方的 #link("https://github.com/espressif/esp-idf", "esp-idf") 开发工具进行开发:`idf.py create-project xxx && idf.py build && idf.py flash`
- python 作为项目管理,实际开发语言为 C/C++
+ 使用 Arduino Core for ESP32,直接使用 Arduino IDE 进行开发。
+ 使用 #link("https://github.com/esp-rs/esp-idf-sys", "esp-idf-sys") 进行 Rust 和 C 语言的混合开发;cargo 作为项目管理。
=== 步骤
+ 实现各按钮/摇杆的信号输出
+ 实现硬件时钟与中断
+ 实现蓝牙协议与 USB 通信
== HID 实现
- 任务:实现手柄与主机的 HID 通信。
- 调研:ESP-IDF 官方提供了 HID 相关的 API,支持 USB HID 设备的开发。
- 任务细分:
+ 配置 USB 外设:在开发板上配置 USB 接口为 USB Device 模式,使设备可以作为 HID 设备与主机通信。
+ 定义 HID 描述符(HID Device Descriptor):该描述符告诉操作系统设备的功能(如按键、摇杆、触觉反馈等)。
- 这一步需要拿到硬件接口图。
// ```
// const uint8_t hid_report_descriptor[] = {
// 0x05, 0x01, // Usage Page (Generic Desktop)
// ...
// 0xC0 // End Collection
// };
// ```
+ 实现数据报告:HID 设备通过中断端点与主机通信,每次状态改变时发送数据包(报告)。
== XInput 实现
+ 实现数据报告格式:XInput 定义了特定的数据报告格式,支持的功能包括:按钮输入(如 A、B、X、Y 按钮等)、摇杆输入(模拟摇杆)、触发器输入(LT/RT 触发器)、震动反馈。
+ 定义 XInput HID 描述符:XInput 与标准 HID 描述符略有不同。
+ 实现数据报告:与 HID 相同,通过中断传输。
+ 实现震动反馈:为设备配置一个输出端点来接收主机的震动指令,并控制开发板上的振动马达。
== 手柄调试与测试
=== 驱动测试
==== #link("https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/driver-verifier", [Driver Verifier])
Driver Verifier 可以使 Windows 驱动程序承受各种压力和测试,以检测可能损坏系统的非法函数调用或操作,查找不当行为。
==== #link("https://github.com/Maschell/hid_test", [HID-TEST])
可视化 HID 协议的接收信息。
==== #link("https://garythegoof.github.io/X-Input-Test/", [X-Input-Test])
多方位测试 XInput 设备。
=== 兼容性测试
使用 Windows, Linux, Macos, Android 及其他系统进行测试。
#pagebreak(weak: true)
= 演讲部分
- HID 协议:需要讲 Linux 的仅支持
- XBOX 兼容性问题:
- 部分功能会出现问题:左/右 trigger 会被视为同一个;振动效果不可用
- 一些较早发布的PC游戏只适配 DirectInput,而不适配 XInput。例如 Microsoft Flight Simulator 微软模拟飞行,<NAME> 赛车拉力
- 现代手柄在兼容性上作出的努力:
- 许多第三方游戏手柄提供两种模式,可以通过硬件开关或特定的按键组合在两者之间切换。例如:罗技、雷蛇等品牌的手柄。
- Xbox 360 和 Xbox One 只支持 XInput 模式。
- 本公司:优先支持 HID 和 XInput,钱到位了再支持 DirectInput。
// - 图片解释: I2C 的时序示意图,上面是写,下面是读。
// - HID 的初始化需要设备先发出写指令,告诉设备要读哪个寄存器。然后才将自身设为读模式。
// - 游戏控制器使用定时轮询中断,因为摇杆等模拟输入设备的状态是连续的,需要不断采样位置数据,以保证游戏的流畅性。鼠标、键盘是事件中断。
//
+ 死区:在物理层面进行了移动而没有信号响应的区域
- 外死区;为了防止在摇杆推到最大时 输出值达不到1,给摇杆输出信号的数值进行增大处理,然后过滤掉大于1的部分
- 不同的外死区会对手感造成极大影响。(FPS)
+ 线性扳机
+ 十字吸附:不讲
+ 校准:碳粉摇杆会漂移
+ 非线性马达:增强手感,需要游戏配合。Xinput 和 directinput 不支持非线性手柄。
开发技术栈
- 对比单片机:自由度高很多,社区完善 |
https://github.com/olligobber/friggeri-cv | https://raw.githubusercontent.com/olligobber/friggeri-cv/master/friggeri.typ | typst | #let cv(
title,
subtitle: [],
asideContent,
mainContent,
) = {
set page(
paper: "a4",
margin: 0pt,
)
// Define some preset colours to use
let white = rgb("#ffffff")
let gray = rgb("#4D4D4D")
let lightgray = rgb("#999999")
let green = rgb("#C2E15F")
let orange = rgb("#FDA333")
let purple = rgb("#D3A4F9")
let red = rgb("#FB4485")
let blue = rgb("#6CE0F1")
let brown = rgb("#765116")
// Set up basic text properties
set par(
leading: 4pt,
)
set text(
font: "<NAME>",
fallback: false,
fill: gray,
size: 10pt,
)
let alttext(..args) = text(font: "Lato", weight:"light", ..args)
// Set up headings
let headercolors = (
blue,
red,
orange,
green,
purple,
brown,
)
// We don't actually show the numbering, but we want the data from it
set heading(numbering: "1.")
show heading.where(level:1): it => locate(loc => {
let index = counter(heading).at(loc).first()
let color = headercolors.at(index - 1, default:gray)
let start = repr(it.body).slice(1, 4)
let end = repr(it.body).slice(4, -1)
set text(size: 16pt)
[
#(text(fill:color)[#start]+text(fill:gray)[#end])
#v(3mm)
]
})
// Document header
let dochead(title, subtitle) = block(
fill: gray,
width: 100%,
height: auto,
inset: (top:1.5cm, bottom:0.8cm),
[
#set par(leading:8pt)
#set text(fill:white)
#align(
center,
text(40pt)[ #title \ ] +
alttext(14pt)[ #subtitle ]
)
]
)
// Document content
let aside(content) = align(right)[
#show heading.where(level:1): it => [
#set text(size: 14pt)
#it.body
#v(1mm)
#counter(heading).update(n => n - 1)
]
#content
]
let makeContentWithAside(asideContent, content) = block(
inset: (top: 0.5cm, left: 1cm, right: 1.5cm),
width: 100%,
height: auto,
grid(
columns: (4cm, auto),
rows: (auto),
gutter: 1cm,
aside(asideContent),
[
#set par(justify:true)
#content
]
)
)
dochead(title, subtitle)
makeContentWithAside(asideContent, mainContent)
}
// Entries environment
// Each entry should be a list of 4 pieces of content
#let entries(..entries) = {
// Define some preset colours to use
let lightgray = rgb("#999999")
let griddata = entries.pos().map(a => {
let (left, bold, weak, main) = a
(
left,
[
#block(below: 5pt, strong(bold))
#place(top+right, text(fill: lightgray, size: 8pt, weak))
#main
]
)}
).flatten()
grid(
columns: (15mm, 100% - 20mm),
rows: (auto),
column-gutter: 5mm,
row-gutter: 3mm,
..griddata
)
} |
|
https://github.com/marisbaier/Typst_eineTeXAlternative | https://raw.githubusercontent.com/marisbaier/Typst_eineTeXAlternative/main/HowToTemplate/template.typ | typst | #let template(
title: [],
body
) = {
set heading(numbering: "1.")
set math.equation(numbering: "1.")
align(center)[
#text(weight: 700, size: 20pt)[#title]
]
body
}
|
|
https://github.com/jomaway/typst-bytefield | https://raw.githubusercontent.com/jomaway/typst-bytefield/main/README.md | markdown | MIT License | # typst-bytefield
A simple way to create network protocol headers, memory maps, register definitions and more in typst.
⚠️ Warning. As this package is still in an early stage, things might break with the next version.
ℹ️ If you find a bug or a feature which is missing, please open an issue and/or send an PR.
## Example

```typst
#import "@preview/bytefield:0.0.6": *
#bytefield(
// Config the header
bitheader(
"bytes",
// adds every multiple of 8 to the header.
0, [start], // number with label
5,
// number without label
12, [#text(14pt, fill: red, "test")],
23, [end_test],
24, [start_break],
36, [Fix], // will not be shown
angle: -50deg, // angle (default: -60deg)
text-size: 8pt, // length (default: global header_font_size or 9pt)
),
// Add data fields (bit, bits, byte, bytes) and notes
// A note always aligns on the same row as the start of the next data field.
note(left)[#text(16pt, fill: blue, font: "Consolas", "Testing")],
bytes(3,fill: red.lighten(30%))[Test],
note(right)[#set text(9pt); #sym.arrow.l This field \ breaks into 2 rows.],
bytes(2)[Break],
note(left)[#set text(9pt); and continues \ here #sym.arrow],
bits(24,fill: green.lighten(30%))[Fill],
group(right,3)[spanning 3 rows],
bytes(12)[#set text(20pt); *Multi* Row],
note(left, bracket: true)[Flags],
bits(4)[#text(8pt)[reserved]],
flag[#text(8pt)[SYN]],
flag(fill: orange.lighten(60%))[#text(8pt)[ACK]],
flag[#text(8pt)[BOB]],
bits(25, fill: purple.lighten(60%))[Padding],
// padding(fill: purple.lighten(40%))[Padding],
bytes(2)[Next],
bytes(8, fill: yellow.lighten(60%))[Multi break],
note(right)[#emoji.checkmark Finish],
bytes(2)[_End_],
)
```
## Usage
To use this library through the Typst package manager import bytefield with `#import "@preview/bytefield:0.0.6": *` at the top of your file.
The package contains some of the most common network protocol headers which are available under: `common.ipv4`, `common.ipv6`, `common.icmp`, `common.icmpv6`, `common.dns`, `common.tcp`, `common.udp`.
## Features
Here is a unsorted list of features which is possible right now.
- Adding fields with `bit`, `bits`, `byte` or `bytes` function.
- Fields can be colored
- Multirow and breaking fields are supported.
- Adding notes to the left or right with `note` or `group` function.
- Config the header with the `bitheader` function. !Only one header per bytefield is processed currently.
- Show numbers
- Show numbers and labels
- Show only labels
- Change the bit order in the header with `msb:left` or `msb:right` (default)
See [example.typ](example.typ) for more information.
# Changelog
See [CHANGELOG.md](CHANGELOG.md)
|
https://github.com/jamesrswift/pixel-pipeline | https://raw.githubusercontent.com/jamesrswift/pixel-pipeline/main/src/pipeline/sorting/dependency.typ | typst | The Unlicense | #let sort(
commands
) = {
// No incoming: unnamed:
let L = ()
return commands
} |
https://github.com/MilanR312/ugent_typst_template | https://raw.githubusercontent.com/MilanR312/ugent_typst_template/main/template/methods/plot.typ | typst | MIT License | #import "@preview/plotst:0.2.0": *
|
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/2-background/factor-graphs.typ | typst | MIT License | #import "../../lib/mod.typ": *
// #v(-1em)
== Factor Graphs <s.b.factor-graphs>
// NOTES:
// Explain the concept of factor graphs
// - variables and factors
// - visually it is undirected bipartite graph
// - factorization of a joint function
// - factors are functions that determine probability, not probability in themself @alevizos_factor_2012
// - representing the factorization of a joint function
// from @loeliger_introduction_2004:
// - in probability used to represent a _probability distribution function_
//
// Properties:
// - enables efficient computation
// - enables computation of marginal distributions through the sum-product algorithm
// - generalization of constraint graphs
//
// Gaussian factor graph:
// Explaining how the
// - factors are Gaussian distributions
// - measurement or constraint of factor is represented by a measurement function $h$
// - variables are the mean and variance of the Gaussian
// Mathematically, the Hammersley-Clifford Theorom states that any positive joint distribution can be represented as a product of factors,
A factor graph is a bipartite graph with undirected edges, where the nodes are divided into two disjoint sets; variables and factors. And exemplification of a factor graph and important intuition is shown in @ex.factor-graph. The edges between nodes each connect one from each set, and represent the dependencies between the variables and factors. A factor graph represents the factorization of any positive joint distribution, $p(#m.Xb)$, as stated by the Hammersley-Clifford Theorom. That is, a product of factors for each set of related variables in the graph, which can be seen in @eq.factor-product@gbpplanner@gbp-visual-introduction@dellaert_factor_2017@loeliger_introduction_2004@alevizos_factor_2012.
$
p(#m.Xb ) = product_{i} f_i (#m.Xb _i)
$<eq.factor-product>
Interpreting this, the factors are not necessarily in themselves probabilities, but rather the functions that determine the probabilities of the variables@loeliger_introduction_2004@alevizos_factor_2012. Additionally, it can be useful to present factor graphs as energy-based models@energy-based-models, where, as seen in @eq.factor-energy@gbp-visual-introduction, each factor $f_i$ is associated with an energy $E_i > 0$:
$
f_i(#m.Xb _i) = exp(-E_i(#m.Xb _i))
$<eq.factor-energy>
#pagebreak(weak: true)
#example(
caption: [Factor Graph]
)[
#let body = [
An example factor graph is visualized in @fig.factor-graph, with variables #text(theme.green, ${v_1, dots, v_4}$) and factors #text(theme.lavender, ${f_1, dots, f_4}$). Writing out the visualized factor graph produces @eq.example.factor-graph.
$
p(v_1,v_2,v_3,v_4) = 1/Z f_1(v_1,v_2,v_3) f_2(v_3,v_4) f_3(v_3,v_4) f_4(v_4)
$<eq.example.factor-graph>
Where $Z$ is the amount of factors in the graph. As such, the joint distribution also functions as a weighting of the different factors' influence.
]
#let fig = [
#figure(
image("../../figures/out/factor-graph.svg", width: 40%),
caption: [A factor graph is a bipartite graph, where the nodes are divided into two sets; variables and factors. Variables are represented as green circles#sg, and factors as blue squares#sl. The edges between the nodes represent the dependencies between the variables and factors.],
)<fig.factor-graph>
]
#body
#fig
]<ex.factor-graph>
This presentation also gives another way of finding the #acr("MAP") estimate, by finding the state with the lowest energy in the factor graph, see @eq.map-energy@gbp-visual-introduction:
$
#m.Xb _"MAP" &= "arg min"_#m.Xb -log p(#m.Xb) \
&= "arg min"_#m.Xb sum_i E_i(#m.Xb _i)
$<eq.map-energy>
The factor graph is a generalization of constraint graphs, and can represent any joint function. Moreover, the factor graph structure enables efficient computation of marginal distributions through the sum-product algorithm@loeliger_introduction_2004@alevizos_factor_2012. The sum-product algorithm is detailed in @s.b.belief-propagation.
#figure(
image("../../figures/out/robot-factor-graph.svg", width: 60%),
caption: [Shown here are two factor graphs, one for a green#sg robot, and one for a purple#sp robot. In this specific case the two robots are close to each other, and perfectly aligned. At the top, the planning horizon is shown in blue#sl, #text(theme.lavender, $n$) times-steps into the future, #text(theme.lavender, ${t_1, t_2, dots, t_n}$). Variables are visualized as circles, and factors as squares.],
)<fig-robot-factor-graph>
In @fig-robot-factor-graph two joint factor graphs are visualized in the context of multi-agent robotics. The first variables in each factor graph $v_1$, represent the location of a green#sg and purple#sp robot respectively. Each robot has a corresponding factorgraph, where the figure shows how the two factor graphs are connected with interrobot factors $f_i$ when they are close enough to each other. Variables $v_2, dots, v_n$ represent the future predicted states of each robot respectively at timesteps $t_2, dots, t_n$, where $t_1$ is the current time.
// Below is factor graph notions in terms of the multi-agent robotic system we have developed
== Belief Propagation <s.b.belief-propagation> // The Sum-Product Algorithm <background-sum-product-algorithm>
// NOTES:
// Sum-Product Algorithm @theodoridis_machine_2020
// The sum-product algorithm is a message passing algorithm used to perform exact inference on factor graphs.
// #acr("BP") is an algorithm for marginal inference, as opposed to exact inference.
// #acr("BP") is carried out by the sum-product algorithm.@robotweb@gbpplanner@gbp-visual-introduction
Inference on a factor graph is achieved by passing messages between the variables and factors. @fig.message-passing visualizes the two major steps; #iteration.variable and #iteration.factor, each with two sub-steps; an internal update, and a message passing step, see @fig.message-passing.
// The process of performing inference#note.wording[] on a factor graph is done by passing messages between the variables and factors. @fig.message-passing visualizes the two major steps; #iteration.variable and #iteration.factor, each with two sub-steps; an internal update, and a message passing step.
#gridx(
columns: (2em, 1fr, 4em, 1fr),
[], [
#set enum(numbering: req-enum.with(prefix: "Step ", color: colors.variable))
+ Variable update
+ Variable to factor message
], [], [
#set enum(start: 3, numbering: req-enum.with(prefix: "Step ", color: colors.factor))
+ Factor update
+ Factor to variable message
]
)
#figure(
image("../../figures/out/message-passing.svg"),
caption: [The four steps of propagating messages in a factor graph. Firstly, the variables#sg are internally updated, and new messages are sent to neighboring factors#sl, who then update internally, sending the updated messaages back to neighboring variables#sg. _Note that this figure shows the #iteration.variable first, however, performing the #iteration.factor first is also a valid, the main idea is simply that they are alternating._],
)<fig.message-passing>
// #jonas[Is more context for BP and the sum-product algorithm needed?]
In #step.s1, the computation of the marginal distribution of a variable $x_i$ takes place. This is done by finding the product of all messages from neighboring factors $f_j$ to $x_i$, as seen in @eq.mp-variable-update@gbpplanner@robotweb@gbp-visual-introduction.
$
m_(x_i) = product_(s in N(i)) m_(f_s #ra x_i)
$<eq.mp-variable-update>
Secondly, in #step.s2, the variable to factor messages $m_(x_i #ra f_j)$ are computed as described in @eq-mp-variable-to-factor@gbpplanner, which is a product of all messages from neighboring factors $f_s$ except $f_j$@gbpplanner@robotweb@gbp-visual-introduction.
$
m_(x_i #ra f_j) = product_(s in N(i) \\ j) m_(f_s #ra x_i)
$<eq-mp-variable-to-factor>
The factor to variable messages $m_(f_j #ra x_i)$ are described in @eq.mp-factor-to-variable@gbpplanner, where the message is the product of the factor $f_j$ and the messages from all neighboring variables $x_i$, except $x_i$ itself@gbpplanner@robotweb@gbp-visual-introduction. This corresponds to the entire #iteration.factor, i.e. #step.s3 and #step.s4, also shown in @fig.message-passing.
$
m_(f_j #ra x_i) = sum_(X_j \\ x_i) f_j (X_j) product_(k in N(j) \\ i) m_(x_k #ra f_j)
$<eq.mp-factor-to-variable>
Originally, #acr("BP") was created for inference in trees, where each message passing iteration is synchronous. This is a simpler environment to guarantee convergence in, and in fact after one synchronous message sweep from root to leaves, exact marginals would be calculated. However, factor graphs, as explained earlier in @s.b.factor-graphs, are not necessarily trees; they can contain cycles, and as such loopy #acr("BP") is required. Loopy #acr("BP"), instead of sweeping messages, applies the message passing steps to each each at every iteration, but still in a synchronous fashion.@gbp-visual-introduction
The expansion to loopy graphs is not without its challenges, as the convergence of the algorithm is not guaranteed. As such, the problem transforms from an exact method to an approximate one. This means, that instead of minimising the factor energies through #acr("MAP") directly, loopy #acr("BP") minimizes the #acr("KL") divergence between the true distribution and the approximated distribution, which can then be used as a proxy for marginals after satisfactory optimization.@gbp-visual-introduction
Loopy #acr("BP") is derived via the Bethe free energy, which is a constrained minimization of an approximation of the #acr("KL") divergence. As the Bethe free energy is non-convex, the algorithm is not guaranteed to converge, and furthermore, it might converge to local minima in some cases. It has been shown that empirically loopy #acr("BP") is very capable of converging to the true marginals, as long as the graphs are not highly cyclic.@gbp-visual-introduction
// #todo[later mention that the specific factorgraph structure is non-cyclic in our case]
== Gaussian Belief Propagation <s.b.gaussian-belief-propagation>
// #jens[do this #emoji.face.smile]
Having introduced both Gaussian models, and #acr("BP"), #acr("GBP") can now be looked at. It is a variant of #acr("BP"), where, due to the closure properties of Gaussians, the messages and beliefs are represented by Gaussian distributions. In its base form, #acr("GBP") works by passing Gaussians around in the #gaussian.canonical, i.e. the messages and beliefs contain the precision matrix #text(theme.mauve, $Lambda$), and the information vector #text(theme.mauve, $eta$). As mentioned earlier, general #acr("BP") is not guaranteed to compute exact marginals, however, for #acr("GBP"), exact marginal means are guaranteed, and even though the variances often converge to the true marginals, there exists no such guarantee.@gbp-visual-introduction
In a factor graph, where all factors are Gaussian, and since all energy terms are additive in the #gaussian.canonical, the energy of the factor graph is also Gaussian, which means that one can represent it as a single multivariate Gaussian. See the equation for this joint distribution in @eq.gaussian-joint@gbp-visual-introduction:
$
p(#m.Xb) prop exp(-1/2 #m.Xb^top #m.Lambda #m.Xb + #m.eta^top #m.Xb)
$<eq.gaussian-joint>
==== MAP Inference <s.b.gbp.map-inference>
In the context of #acr("GBP"), the #acr("MAP") estimate can be found by the parameters $#m.Xb _"MAP"$ that maximizes the joint distribution in @eq.gaussian-joint. The total energy can then be written as @eq.gaussian-energy-total@gbp-visual-introduction:
$
nabla_#m.Xb E(#m.Xb) = nabla_#m.Xb log P(#m.Xb) = -#m.Lambda #m.Xb + #m.eta
$<eq.gaussian-energy-total>
which is the gradient of the log-probability, and can be set to zero, $nabla_#m.Xb E = 0$, to find the #acr("MAP") estimate, which, in #acr("GBP"), is reduced to the mean #m.mu, as seen in @eq.gaussian-map@gbp-visual-introduction:
$
#m.Xb _"MAP" = #m.Lambda^(-1) #m.eta = #m.mu
$<eq.gaussian-map>
==== Marginal Inference <s.b.gbp.marginal-inference>
The goal of marginal inference in #acr("GBP") is to find the per variable marginal posterior distributions. In the #gaussian.moments this looks like @eq.gaussian-marginal-moments@gbp-visual-introduction:
$
p(#m.x _i) &= integral p(#m.Xb) #h(0.25em) d #m.Xb _(-i) \
&prop exp(-1/2 (#m.x _i - #m.mu _i)^top #m.Sigma _(i i)^(-1) (#m.x _i - #m.mu _i))
$<eq.gaussian-marginal-moments>
where $#m.Xb _{-i}$ is the set of all variables except $#m.x _i$, and $#m.Sigma _(i i)$ is the $i^"th"$ diagonal element of the covariance matrix $#m.Sigma = #m.Lambda^(-1)$. The marginal posterior distribution is then a Gaussian with mean $#m.mu _i$ and variance $#m.Sigma _(i i)$. Furthermore, $#m.mu _i$ is the $i^"th"$ element of the joint mean vector $#m.mu$, as in @eq.gaussian-joint.
With the understanding from #numref(<s.b.gbp.map-inference>) and #numref(<s.b.gbp.marginal-inference>), inference in #acr("GBP") ends up being a matter of solving the linear system of equations @eq.gaussian-linear-system@gbp-visual-introduction:
$
A x = b #sym.arrow.r.double #m.Lambda #m.mu = #m.eta
$<eq.gaussian-linear-system>
Where #inference.MAP solves for the mean, #m.mu, and #inference.marginal finds the covariance, #m.Sigma, by solving for the block diagonal of $#m.Lambda^(-1)$, and indirectly also the mean, #m.mu.
=== Variable Update <s.b.gbp.variable-update>
The variable belief update happens by taking the product of incoming messages from neighboring factor nodes, here denoted as $N(i)$, as seen in @eq.gbp-variable-update@gbpplanner@gbp-visual-introduction:
$
b_i(x_i) = product_(s in N(i)) m_(f_s #ra x_i)
$<eq.gbp-variable-update>
Writing out the Gaussian message in #gaussian.canonical becomes @eq.gbp-message-canonical@gbpplanner@gbp-visual-introduction:
$
m = cal(N)^(-1) (x; mu, Lambda) prop exp(-1/2 x^top Lambda x + eta^top x)
$<eq.gbp-message-canonical>
Fortunately, as the messages are stored in #gaussian.canonical, the product in @eq.gbp-variable-update is the same as summing up the information vectors and precision matrices, as seen in @eq.gbp-variable-update-canonical@gbpplanner@gbp-visual-introduction:
$
eta_b_i = sum_(s in N(i)) eta_(f_s #ra x_i)
#h(1em)"and"#h(1em)
Lambda_b_i = sum_(s in N(i)) Lambda_(f_s #ra x_i)
$<eq.gbp-variable-update-canonical>
=== Variable to Factor Message <s.b.gbp.variable-to-factor>
The variable to factor message passing is described in @eq.gbp-variable-to-factor@gbp-visual-introduction, where the message is the product of the incoming messages from all neighboring factors $f_j$ except the factor $f_i$ itself, same as described in @eq-mp-variable-to-factor@gbpplanner:
$
m_(x_i #ra f_j) = product_(s in N(i) \\ j) m_(f_s #ra x_i)
$<eq.gbp-variable-to-factor>
Again in this case, the message is sent in the #gaussian.canonical, and as such the outgoing messages can simply be computed by summing up the information vectors and precision matrices, as seen in @eq.gbp-variable-to-factor-canonical@gbp-visual-introduction:
$
eta_(x_i #ra f_j) = sum_(s in N(i) \\ j) eta_(f_s #ra x_i)
#h(1em)"and"#h(1em)
Lambda_(x_i #ra f_j) = sum_(s in N(i) \\ j) Lambda_(f_s #ra x_i)
$<eq.gbp-variable-to-factor-canonical>
=== Factor Update <s.b.gbp.factor-update>
This step is not detailed in @gbpplanner, as it is not a regular step involving state updates. Instead, the updating of a factor describes the mathematical steps taken before passing messages to neighboring variables. Writing this step out also represents the developed software@repo more directly. The following steps take place:
#[
#set enum(numbering: box-enum.with(prefix: "Step ", color: theme.mauve))
// #set par(first-line-indent: 0em)
+ *Aggregate Messages:* Messages from neighboring variables are aggregated into a single message, as seen in @eq.gbp-factor-to-variable@gbpplanner@gbp-visual-introduction:
$
m_(f_i #ra x_j) = product_(s in N(j) \\ i) m_(x_s #ra f_i)
$<eq.gbp-factor-to-variable>
+ *Update Linearization Point:* As the factor has received new messages from neighboring variables, the linearization point is updated to the new mean, $mu_f$.
+ *Measurement & Jacobian:* The measurement residual is computed as the difference between the measurement at the initial linearization point, $h(#m.Xb _0)$, and the current measurement, $h(#m.Xb _n)$, see @eq.factor-measurement@gbp-visual-introduction:
$
h_r = h(#m.Xb _0) - h(#m.Xb _n)
$<eq.factor-measurement>
Where $#m.Xb _0$ is the configuration at $t_0$, and $#m.Xb _n$ is the configuration at the current timestep $t_n$.
+ *Factor Potential Update:* The factor potential is updated by computing the precision matrix and information vector of the factor potential, as seen in @eq.factor-potential@gbp-visual-introduction:
$
#m.Lambda _p = jacobian^top #m.Lambda _M jacobian
#h(1em)"and"#h(1em)
#m.eta _p = jacobian^top #m.Lambda _M (jacobian #m.Xb _0 + h_r)
$<eq.factor-potential>
Where $#m.Lambda _p$ and $#m.eta _p$ denotes the measurement precision matrix and information vector of the factor potential, respectively. Lastly, $#m.Lambda _M$ is the measurement precision matrix.
]
=== Factor to Variable Message <s.b.gbp.factor-to-variable>
As the factor has been updated, it is now possible to pass messages to neighboring variables. The messages to each neighboring variables has to be marginalized with respect to all other variables, that is; to find the message to variable $x_i$, margininalize out its own contribution to the aggregated message. This is best described through an example, see @ex.factor-to-variable@gbp-visual-introduction.
#example(caption: [Factor Message Marginalization@gbp-visual-introduction])[
Consider a factor $f$ connected to 3 variables; $x_1,x_2,x_3$, and we want to compute the message to be passed to variable $x_1$. Write the factor out as a Gaussian distribution, see @eq.ex.factor@gbp-visual-introduction:
$
f(mat(x_1,x_2,x_3)) = cal(N)^(-1) (mat(x_1,x_2,x_3); eta_f, Lambda_f)
$<eq.ex.factor>
Here, the two Gaussian parameters $eta_f$ and $Lambda_f$ can be expanded to see the individual contributions from each variable, as seen in @eq.ex.factor-canonical@gbp-visual-introduction:
$
eta_f = mat(eta_(f"1"); eta_(f"2"); eta_(f"3"))
#h(1em)"and"#h(1em)
Lambda_f = mat(
Lambda_(f"11"), Lambda_(f"12"), Lambda_(f"13");
Lambda_(f"21"), Lambda_(f"22"), Lambda_(f"23");
Lambda_(f"31"), Lambda_(f"32"), Lambda_(f"33")
)
$<eq.ex.factor-canonical>
As described earlier, first step is to compute the message that will passed to $x_1$, which is the product of the incoming messages from $x_2$ and $x_3$, as seen in @eq.ex.product-adjacent, as we are in the #gaussian.canonical. This is a summation, and yields the Gaussian, $cal(N) (eta_f^prime, Lambda_f^prime)$@gbp-visual-introduction:
$
eta_f^prime = mat(eta_(f"1"); eta_(f"2") + eta_(x_2 #ra f); eta_(f"3") + eta_(x_3 #ra f))
#h(1em)"and"#h(1em)
Lambda_f^prime = mat(
Lambda_(f"11"), Lambda_(f"12"), Lambda_(f"13");
Lambda_(f"21"), Lambda_(f"22") + Lambda_(x_2 #ra f), Lambda_(f"23");
Lambda_(f"31"), Lambda_(f"32"), Lambda_(f"33") + Lambda_(x_3 #ra f)
)
$<eq.ex.product-adjacent>
Now as we are passing a message to $x_1$, we have to marginalize out all other variables, $x_2$ and $x_3$. This is done by the marginalization equations given by @marginalisation for Gaussians in #gaussian.canonical. See @eq.ex.marginalization-setup and @eq.ex.marginalization for the joint distribution over variables $a$ and $b$@gbp-visual-introduction@marginalisation.
$
eta = mat(eta_a; eta_b)
#h(1em)"and"#h(1em)
Lambda = mat(
Lambda_(a a), Lambda_(a b);
Lambda_(b a), Lambda_(b b)
)
$<eq.ex.marginalization-setup>
$
eta_(M a) = eta_a + Lambda_(a b) Lambda_(b b)^(-1) eta_b
#h(1em)"and"#h(1em)
Lambda_(a a) = Lambda_(M a) - Lambda_(a b) Lambda_(b b)^(-1) Lambda_(b a)
$<eq.ex.marginalization>
Now to marginalize, perform the two steps:
#set enum(numbering: box-enum.with(prefix: "Step ", color: theme.peach))
+ *Reorder the vector $eta_f^prime$ and the matrix $Lambda_f^prime$ to bring the contribution from the recipient $x_1$ to the top.* \
_In our case no reordering is to be done, as $x_1$ is already at the top._
+ *Recognize the subblocks $a$ and $b$ from @eq.ex.marginalization-setup and @eq.ex.marginalization.* \
_In our case $a = x_1$ and $b = mat(x_2, x_3)$._
]<ex.factor-to-variable>
As such, each neighboring variable receives an updated message from the factor, in effect imposing the factor's constraints on the variables.
== Non-Linearities <s.b.non-linearities>
Non-linear factors can exist, however, to understand the impact, let us first look at linear factors. A factor is usually modeled with data $#m.d$. Equation @eq.gaussian-factor@gbp-visual-introduction shows how this is written:
$
#m.d &tilde.op h(#m.Xb _n)) + epsilon.alt
$<eq.gaussian-factor>
Here, $h(#m.Xb _n)$) represents the measurement of the state of the subset of neighboring variables, $#m.Xb _n$, to the factor, and the error term $epsilon.alt tilde.op cal(N) (0, #text(theme.mauve, $Sigma_n$))$ is white noise. Thus, finding the residual $r$ between the measurement and the model, as seen in @eq.gaussian-residual@gbp-visual-introduction, propagates the Gaussian nature of the model to the residual.
$
r = #m.d - h(#m.Xb _n)) tilde.op cal(N) (0, #text(theme.mauve, $Sigma_n$))
$<eq.gaussian-residual>
With this, looking at @f.gaussian-models, the #gaussian.moments can be rewritten with the measurement, $h(#m.Xb)$, and the model $#[email protected]@gbp-visual-introduction:
$
E(#m.Xb _n) = 1/2 h(#m.Xb _n) - #m.d)^top #text(theme.mauve, $Sigma_n$)^(-1) h(#m.Xb _n) - #m.d)
$<eq.gaussian-energy>
In case of a linear factor, the measurement function is quadratic and can be written as $h(#m.Xb _n) = jacobian #m.Xb _n + c$, where $jacobian$ is the Jacobian. This allows us to rearrange the energy onto #gaussian.canonical @eq.gaussian-canonical@gbp-visual-introduction:
$
E(#m.Xb _n) &= 1/2 #m.Xb _n^top #text(theme.yellow, $Lambda$) #m.Xb _n - #text(theme.yellow, $eta$)^top #m.Xb _n \
&"where" #text(theme.yellow, $eta$) = jacobian^top #text(theme.mauve, $Sigma_n$)^(-1) (#m.d - c) "and" #text(theme.yellow, $Lambda$) = jacobian^top #text(theme.mauve, $Sigma_n$)^(-1) jacobian
$<eq.gaussian-canonical>
However, in case of a non-linearity in $h$, the energy is also not quadratic in $#m.Xb _n$, which in turn means that the factor is not Gaussian. To achieve a Gaussian distribution for the factor in this case, it is necessary to linearize around a current estimate $#m.Xb _0$, which is from here called the #factor.lp. This linearization takes place by @eq.factor-linearization@gbp-visual-introduction:
$
h(#m.Xb _n) = h(#m.Xb _0) + jacobian(#m.Xb _n - #m.Xb _0)
$<eq.factor-linearization>
As such, we end up with a linearized factor on the form @eq.linearized-factor@gbp-visual-introduction, which ends up with a Gaussian approximation of the true non-linear distribution:
$
c = h(#m.Xb _n) - jacobian #m.Xb _n
$<eq.linearized-factor>
The underlying potential non-linearities of factors is exemplified in @ex.non-linearities, and visualized in @fig.non-linearities.
#example(caption: [Factor Linearization])[
Consider a 2D world, where a robot exists alongside a landmark. As seen in @fig.non-linearities, the robot is located at $r_0$, and the landmark at $l_0$. This figure visualizes the contour plot for the factor $f(r_0, l)$, assuming the robot's true position is known to be $r_0$ without uncertainties. The true non-linear belief of the landmark's position is visualized as a grey#sgr2 contour plot. The factor measurement function $h(r,l)$ in @eq.non-linear-measurement@gbp-visual-introduction is non-linear.
$
h(r,l) = mat(abs(r - l); arctan((l_y - r_y) / (l_x - r_x)))
$<eq.non-linear-measurement>
As such, the factor is linearized around $(r_0, l_0)$, which is shown as red contours#sr in @fig.non-linearities. In the @fig.non-linearities#text(accent, "A"), the measurement noise model corresponds to covariance $#m.SA$, and in @fig.non-linearities#text(accent, "B") the covariance is $#m.SB$, see @eq.non-linear-covariances@gbp-visual-introduction.
$
#m.SA = mat(0.25, 0; 0, 0.25)
#h(1em)"and"#h(1em)
#m.SB = mat(0.25, 0; 0, 1.0)
$<eq.non-linear-covariances>
#figure(
{
set text(theme.text)
grid(
columns: 2,
std-block(
fill: theme.lavender.lighten(75%)
)[
#image("../../figures/plots/ellipses-narrow.svg")
A: With covariance $#m.SA$
],
std-block(
fill: theme.lavender.lighten(75%)
)[
#image("../../figures/plots/ellipses-wide.svg")
B: With covariance $#m.SB$
]
)
},
caption: [A non-linear factor is visualized, where the measurement function $h(#m.Xb _n)$ is non-linear. The linearization point $l_0$#st is shown, and the robot's position#sg. The non-linear true distribution is visualized as a grey#sr contour plot underneath the linearized gaussian distribution#sgr2 on top.@gbp-visual-introduction],
)<fig.non-linearities>
]<ex.non-linearities>
The purpose of this @ex.non-linearities is to make it clear, that the accuracy of a gaussian factor is dependent on the linearity of the measurement function, $h$. As in @fig.non-linearities#text(accent, "A"), the measurement model is reasonably smooth, and the linearized gaussian factor is a fairly good approximation, however, in @fig.non-linearities#text(accent, "B") highlights how a larger variance can lead to a very poor approximation, even without straying too far from the linearization point.
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/028%20-%20Kaladesh/004_Renegade%20Prime.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Renegade Prime",
set_name: "Kaladesh",
story_date: datetime(day: 14, month: 09, year: 2016),
author: "<NAME>",
doc
)
#emph[<NAME> first left her home plane of Kaladesh when her Planeswalker spark ignited, vaulting her from imminent doom at the hands of Lieutenant Baral to the fire monasteries of Regatha. Now she's returned to try to save a mysterious renegade from arrest, only to stumble upon someone she'd thought dead for years—her mother, Pia.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"I killed your daughter today, Pia." A low voice floated in through a heavy veil of sleep and a splitting headache.
She forced her eyelids open, but was met only by darkness. Stiff vocal cords crackled words through a dry throat. "What—?"
"Just a little thing, that one." His words were oddly clipped and slow, his breathing heavy as furnace bellows. "Barely taller than my blade." The voice chuckled without humor—a low rumble that Pia could feel through the door between them.
The darkness resolved itself slowly into blurs, then thick smears of light. Her stiff hands reached out and found the cool, curving surfaces of filigreed walls. Attempts to rise to her feet proved premature.
"Of course I didn't forget you through all this...excitement. Here, I brought you this."
#emph[CLANK] . A piece of metal clattered to the floor somewhere in front of her.
"Go on. A memento for what you missed," the voice said.
She reached out a tentative hand to the object. A flat fragment, completely melted on one side and deeply etched on the other. Lightweight. Cold, and warming only slightly under the warmth of her touch, but with deep, precise carvings on the intact side. A titanium alloy prized for use in their renegade airship engines for its formability and heat resistance—though this piece was nothing more than slag on one side.
"Do you recognize it?" the voice inquired too eagerly.
As her eyes adjusted, she could make out some of the symbols, and traced the rest with her hands. A stamped swirl of motion beneath a pointed spire. Pia knew this symbol—it felt like yesterday that she and Kiran had come up with it as they left Ghirapur. A leaking spire, a symbol for the renegades, for the Ghirapur they wished they could come back to. But what was this piece? Her fingers danced over the engravings, scanning its surface. And stopped.
Below the insignia, the letters "K.N.," scrawled in the messy but deliberate hand of a craftsman who had separated from his tools. She knew exactly what it was now—a piece of Kiran Nalaar's final project.
Chandra's vent pack.
Muscles between her ribs tightened, and a sudden rush of blood filled her chest with heat. Her hands went limp and dropped the insignia.
"Oh look!" The voice beamed on the other side of the cell door. "Of course you do.
"There's not much I'd care to recall about these things," the voice continued. "Though I do recall her gaze. Shifting around the crowd, unable to stare back at me. Cowardly. Defiant."
Her senses had now almost completely returned. The blurred lights came from the aether pipes in the ceiling of a stark prison cell with a grated door. She had been taken prisoner as the Consulate had ambushed her family in the village outside of Ghirapur. This was not the reality she'd hoped to awaken into. #emph[Go back. Be a dream] . And that voice—the voice was so familiar...
"But then I realized," the voice went on with genuine enthusiasm, "she was looking for something. Or, someone perhaps?"
Oh yes. She knew that voice. The voice of the man who had hunted her family: Captain Baral.
"She was looking for you, Pia."
The air in her chest heaved out of her in a peal of outrage, though for whom she couldn't tell. Her hands flew to the grating, grasping at Baral's silhouette though he stood easily outside of her reach. Shoulders and fists flew against the cell door. Baral stared back at her, his masked face impassive.
"Am I the one who deserves your contempt?" he asked. "Wasn't it you who should have arrived to save her? To offer her some final comforting words?"
#emph[Of course. Why wasn't I there] ? something demanded inside of her.
He left without another word, as he would each time.
As his footsteps faded, she was suddenly very, very alone. Her Kiran, her Chandra, the threads of all of their lives once so tightly bound now drifted inexorably away from her in time and space. Their world, once so large and full of life, was now this cell.
Baral returned the next day, and the next. Soon a week had passed.
"She was looking for you, Pia."
The words had just become sounds to her now—recognizable though willed into meaninglessness. She steeled her nerves to speak to him for the first time.
"Don't you have better things to do than to hound a grieving widow? I have nothing left for you to take. You've won—can't you leave me alone?"
"Nalaar, our city has always defined itself through its progress. We all make sacrifices to put its welfare above our own." Baral said.
"All of us," he continued with a sharp edge entering his voice, "except the selfish few, who dare to put their interests above the city. It...pleases me to bring your kind to justice. To make you regret every shred of that fatuous defiance."
Pia raised her chin to him with a cold, pitying smile. "Then you've proven me wrong, Lieutenant. I do have something left, and it will never be yours."
He laughed, though there was a shrillness there that had not been there before, and departed down the corridor of cell doors.
It was nearly another week before he returned again.
"She was looking for you, Pia," Baral said, as he had so many times now.
Pia responded slowly, refusing to return his gaze. "And I'll return for her, for all those out there, so they know what you've done. For #emph[you] , Lieutenant."
Her hands were strong and steady now, strong enough to hurl the tiny filigreed aether lamp from her cell with alarming speed and accuracy straight through the cell grating toward Baral's face.
He raised an elbow with an instinctive grunt as the lamp hit his face and dislodged his mask with a clanging reverberation. A brilliant blue glow flared to life and encircling his body, filling the Dhund's hallway with light. It disappeared mere seconds after it formed, leaving a series of dancing spots in Pia's vision. It was far too bright and volatile to be any form of aether. No—it was something else entirely.
"You're...a mage?" Pia gasped. Her own daughter's pyromancy aside, she'd never known another mage. Magic and magic users were not just scarce, they were regulated and watched more closely than aether itself.
A long, low hiss emanated from the other side of the door. It was a sound so much smaller, so much more human than it had been inside of that mask. Pia rushed forward to the cell grating and peered out.
Baral's unmasked gaze snapped upward and their eyes met. Beneath the mask a mass of thick scar tissue wound its way across his features, parts of it still raw and red. The strong, some might even say "handsome" lines of his had face scattered and melted away.
"Your...what happened to you?"
#figure(image("004_Renegade Prime/01.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Baral paused as he reattached the clasps of his mask. "Fate is rarely fair, Nalaar." She watched the tensed, distorted muscles of his face labor through the words with reluctant fascination. "The materials that shape what we become are fixed the moment we are brought into this world. The fortunate of us will be born heroes. But there are a number of us who will be born malformed—dangerous aberrations to the course of nature. Perhaps they might even look and act like the rest that can threaten us from the shadows."
Mask secured, he carefully draped his hood over his head. "Myself, I accept my nature—I'll not hide or let others hide from the sentences they've been given. This is my destiny, to root out these hidden dangers, expose them, and bring them to justice."
Any traces of concern melted away. "Destined to wrestle with your own demons by hunting down children?"
"Children?" He barked out a humorless laugh. "Of course. Who better to misuse their abilities for selfish or misguided purposes. Besides, the years make little change to natural criminal dispositions, as you yourself evidence."
His voice became quiet, and he leaned in toward the grating in an accusatory whisper. "You asked #emph[what happened] . Your child. Your child happened, Nalaar. This—" he pressed his masked face to the grating and dragged his fingers over the sides of the mask, "#emph[this] is the work of your child."
Pia leaned in as close as she could to the grating. "A mother couldn't be prouder."
Baral slammed the grating shut with a force that sent Pia reeling backward. Cold determination tamed her fury. Now alone in the velvety darkness of the Dhund cell, she closed her eyes and listened to the staccato of her heartbeat's slowing...
...And began to plan.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("004_Renegade Prime/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Years later and far from the Dhund, <NAME> opened her eyes and blinked in the sunlight as she wiped her goggles clean on the back of a well-worn glove.
Those years had flown by as Pia had rallied a growing contingent of inventors, tinkers, artists—citizens from all over Kaladesh—devoted to uncovering and protesting the Consulate's increasingly tight grip over the city and its vital aether. "Renegades," as the Consulate called them, born from a headstrong passion to defend and celebrate the spirit of the home they had built together.
A select group of these renegades had gathered today on one of the district's many ornate, swirling rooftops high above the ground. Below them, the city was a living, moving thing, full of scintillating streams of motion formed by the shining brass of the constructs hurrying below. Banners and announcers loudly trumpeted the Inventors' Fair below, whose exhibits sprawled over the plaza in a dazzling array of shapes and colors. And in a matter of minutes, the renegades too would unveil their own unauthorized exhibit in the fairgrounds.
A loud #emph[POP] and the acrid smell of smoke caught her attention. Pia glanced over her shoulder just in time to see the young inventor's apprentice Tamni yelp and nearly lose her balance on the roof's ledge.
Pia grabbed Tamni's arm to steady her and glanced down—the apprentice's nearly finished thopter was consumed in orange flames, the brass sagging and warping.
Pia swiftly covered the flames with her glove and tossed it to the far corner of the ledge to cool. "Nothing more than a little fire. Anything I can help with?" she asked Tamni with a raised eyebrow.
Tamni hastily unfurled blueprints and fumbled with an array of measurement tools laid out in front of her. "Everything's all in the right place, isn't it? I checked everything earlier, I promise! I know we're running out of time...but I can do this!" She bit down on her lower lip while frantically scanning the diagram.
#emph[Slag, she's right—It's almost time! ] Pia said to herself. But she shook the thought away and put a reassuring arm around Tamni. "It's fine—they #emph[asked] you to be here. I'm sure you've done this a hundred times before!"
"...I, uh, you don't really mean a #emph[hundred] right? I mean I can figure it out..."
Pia stared blankly at her.
"I'm sure I can! I mean, I was sure?" Tamni shuffled her feet, embarrassed. "I might've...exaggerated my experience to get here."
#figure(image("004_Renegade Prime/03.jpg", width: 100%), caption: [Art by Ryan Pancoast], supplement: none, numbering: none)
Pia mentally applied the palm of her hand to her forehead.
"...I heard Renegade Prime was leading this! I had to see!"
Pia could hear the others around them shift impatiently. She flashed them a confident smile and waved her signal—we'll get through this, just give us a moment.
Pia raised Tamni's chin and channeled the memory of her father's best steely parental glare. "You'll be fine, but we'll need to be fast. Remember what we've learned before—a quicksmith's creations cannot tell us what's wrong unless we pay attention to them.
"These tools," she pointed at the aetherometer, pressure gauges, periodicity vanes, "give us just once piece of what we need to know. "#emph[These] tools," she touched Tamni's hands, "know many different parts of the machine from experience and intuition. They sense pressure, heat, movement, size, all at once. Go ahead, give it some power."
Tamni nervously applied some aether to the machine—the side propellers spun to life, but the back rotor remained still.
"Listen. What do you hear?" Pia said.
The sound of the rotor was a familiar high-pitched whine and regular clicking of gears. Tamni pressed her ear to its filigreed side. Beneath the normal rhythms, an unfamiliar bass tone lurked in the background. "Something's off in there, rotating out of sync."
Tamni laid her palm against the back vent. Something tapped back slowly, out of sync with the rest of the vibrations. A stray aether tube had jammed itself in the gearbox and broken, leaking volatile aether out of the machine that had caused the rotors to overheat.
"Now when we reform the metal," she encouraged Tamni, "we must pay close attention to its motions; the filigree formed by blooming aether onto metal is a complex and slightly volatile reaction." Pia opened the valve on her aether glove and guided Tamni's hand with her own.
"But you'll learn its patterns even if you don't understand it completely," Pia told her. "Listen to its movements and bend to it as it bends to you. Things will not always be as you want or need them to be, but we must continue to shape them as best we can, and they will reveal their best forms to us."
Tamni bobbed her head eagerly. "Of course, yeah—I wish they'd taught us this stuff at the workshop!"
#emph[Those are hard-earned lessons taught by time] , Pia thought to herself wryly.
The dull, oxidized metal curled and writhed around the bright glow of aether. It split into a network of glowing blue tendrils, pulsing like a living thing, revealing a bright new surface as it cooled.
Tamni watched a piece of the brass curve inward on itself, and a halting sweep of her aether torch led it into its correct place. The rotor whirred to life, lifting the tiny new thopter off the ground on freshly formed wings.
The young inventor let out a long sigh.
Almost done, now it was Pia's turn.
Goggles down, aether valve opened, the cool tingle of aether entered the tips of Pia's quicksmithing glove. From the other side of the roof, a brass cylinder was tossed her way and landed with a satisfying thump in her glove. A salvaged engine cylinder—this would do just fine.
Her deft hands flew over its surface with gentle pressure as the aether slowly released from her gloved fingertips, the brass wrapping hungrily around the exuded aether in intricate geometric shapes. The movements of the metal were rapid and unpredictable as the aether curled around it.
Pia's mind raced, her designs changing and adjusting by the second to the wild motions of the aether. Soon she had formed a center cavity, encasing a vial of aether that would power multiple rotors, then diaphanous filigree wings and fins for navigation, and finally appendages that could clutch its payload. As she completed her construction, it began to inflate and solidify from within like the wings of an insect after emerging from its chrysalis. Soon the air vibrated with the furious hum of a new thopter's wingbeats.
#figure(image("004_Renegade Prime/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
A city clock chimed the time below them, and the spired roofs around her soundlessly rotated into their new positions to optimally accommodate the late afternoon's foot traffic.
Right on time.
A heavy, callused hand clamped down on her arm. Pia turned to see a heavily built older man in the brightly polished brass and gold uniform of a Consulate lieutenant. Or at least, what passed for one at first glance.
"Venkat!" she exclaimed, planting a fist into his right shoulder. "For the—you can't go around creeping up behind people when you're in that!"
"Means that the uniform works though, wouldn't you say?" Venkat said, not bothering to suppress an impish grin as he tried to shake the numbness out of his arm. Once a high-ranking commander of the Consulate guard forces, his dissent against tightening regulations on those citizens in the Weldfast he was charged to protect had pushed his obedience to the breaking point. He appeared unexpectedly at the doorstep of Pia's workshop nearly a year ago—a location that he'd kept hidden over his many years of Consulate service.
"Besides, I'm just one of many wise enough to place their trust in you," Venkat added, tilting his head towards the gathered crowd on the roof.
"And #emph[my] trust in scoundrels like you," Pia said with a smile. A swell of pride swept through her as she surveyed the familiar faces in the crowd—like her, they were respected artisans, visionaries, creators. For all the world it could have been a midday afternoon spent talking around the workshop's tables, the air full of conversation and the smell of brewing tea. They'd shared the weight of the Consulate's tightening restrictions together, pooling together their dwindling supplies of vital Consulate aether that kept the bustling workshops, kitchens, and infirmaries of their district humming.
The renegades raised their hands to her in the ready signal—it was time.
"My friends and neighbors!" Pia called out to them. "Today we're here with a purpose—to speak up about what we've seen and to seek answers for what's been done."
The faces ahead of her nodded solemnly. Though they had all carried the burden of scarce aether, they shared the outrage for "what's been done" to Pia and her family.
"Today is a day of celebration for many," she said, sweeping a hand across the cityscape below. "Since it was created, the Inventors' Fair has always put our city's innovative spirit at the forefront. But for many of us, this year's celebration has become something very different. We found the Fair full of more and more pet Consulate projects in aether routing, security...weaponry!" Growls bubbled up from the crowd, and fists were raised.
"And at the same time, we found ourselves targeted by the very government that has sworn to protect us!" Nodding heads stared back at her from the crowd.
"They've bounded off the skies themselves to prevent you, Nadya and Kari, from gathering our own aether!" The two aerowrights locked eyes with each other and raised their fists together in unison.
"And what about the Maulfists' foundry? The Consulate took their aether and the foundry now lies powerless and vacant!" Three heavily outfitted renegades raised their hammers to Pia.
"Viprikti, your family was forced to leave your home when aether was removed from entire city blocks of the Weldfast!" A rangy older man pulled his goggles down over his eyes solemnly.
"The missions of our leaders have turned away from assisting citizens and toward sustaining their own interests. But now, my friends, my renegades, we deliver our response. You've all generously given your contributions to make this possible, and I'm proud to present it to the rest of the city. Let us be as proud, unafraid, unyielding as those who believe they can extinguish our spirits!"
Pia swiped her hand downward, and four goggled renegades signaled back. Crouching over the filigree ledge, they hurled their thopters down into the plaza below.
The machines dove through the air to opposite ends of the plaza, nearly a hundred in number. They lined themselves up into a massive column of glittering metal over the tents of the fairgrounds that rivaled the height of the city's tallest buildings.
A musical hum of mechanical wings filled the air, and the faces in the tents below snapped upward to the sight. Fairgoers grinned and pointed at the spectacle, while Consulate automata and human guards poured into the street.
As the metal of the thopters heated, their colors changed through yellows to greens to rich purples and blues, an orchestration of color and shape like a mechanical aurora. They spiraled around one another and reformed their column into a tapered cone over a swirled line—the leaking spire.
Inventors and citizens alike in the crowd cheered their approval—a stunning display worthy even of notice by the judges. The thopters began to gently descend toward the ground, like stage actors taking a final bow. Beneath them, scores of Consulate automatons gathered, hands outstretched.
From the rooftop above, Tamni gripped the edge of the railing with white knuckles.
"All part of the plan," Pia reassured her, putting a hand on her shoulder and flashing a smile at Venkat.
Hovering just over the automatons, the mass of thopters emanated a bright blue flare as they released their aether in a long pulse. The sudden rush of energy flooded into the identical automata, creating sparks of concentrated aether. They fell together in ringed rows, like so many dominoes.
"Perils of mass production..." Venkat whispered to Pia with a grin.
A lively, impersonal voice resounded through the loudspeakers below: "Good afternoon, citizens! This is a routine test of the emergency notification system. This level of the fairgrounds is now officially closed. All foot traffic and trains will be rerouted from this area as we conduct our maintenance. We thank you for your attendance and we hope you've enjoyed your time here today!"
Pia nodded at her rooftop companions.
"You should have more than enough time to return to the Weldfast before the guards return. Stay safe, and if any trouble occurs, use your distress signal and Venkat will be here to help you."
The others grinned and nodded back at her, exchanging embraces and congratulations as they departed. They scampered down the sides of the tower, though not before leaving their mark.
#figure(image("004_Renegade Prime/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Pia swung down from the rooftop onto a window ledge, her nimble artisan's hands easily finding handholds in the ornate walls. With a flying leap, she cleared the ledge from one building to the next before clambering down a garden trellis and into the streets below.
Something wild and reckless coursed through her blood as she dashed through the city, green sashes and gray-streaked hair streaming behind her.
In the shadows of the tall spires across the plaza, a tall cloaked man suddenly began weaving swiftly through the crowd, with two others following close behind.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The soft soles of Pia's boots carried her noiselessly over the pavement as she reached the steps of the Aether Hub at the edge of the Weldfast. Here she would have no problems disappearing into the neighborhood's many side streets and the tall, winding sculptures that decorated its public spaces. Her face split into a proud grin.
From behind her, a heavy hand clamped down on her arm. Even through her sleeve, it seemed to emanate an icy chill that pulled the warmth from her skin.
"Venkat, #emph[please] , I asked you—"
She turned to see not Venkat, but a tall, cloaked man whose orange face markings identified him as the Fair's Head Judge. The hand that gripped her arm was a massive claw of dark metal that even she didn't recognize as it disappeared into the man's sleeve. Flanked by two Consulate automatons, his ornate armor echoed their patterns and colors: bright, polished Consulate gold and brass. Beside him, the stately vedalken Minister of Inspections himself, <NAME>. And an elf, tall and green-eyed, looking from one side to the other in utter confusion.
"I've found you at last, Renegade Prime," the cloaked man said, aiming his metal hand at her as if he were pointing a weapon. "Do you think your little spectacle is going to matter to my Fair?"
His#emph[ Fair?!] Pia seethed. #emph[This is ] our#emph[ city!]
"We'll stop you, #emph[Head Judge] . If not today, one day soon," she fired back at him.
A pale woman clad in dark flowing silks and a glinting golden headpiece appeared opposite the Head Judge. "—#emph[Tezzeret,] " she hissed.
His head snapped up. Teeth appeared. "#emph[Vess] ," he returned, low and smoldering with anger.
Then another figure, heavily armored and out of breath, appeared next to the woman. She pushed a mop of wild, flame-colored hair back from her face—
A tide of memories washed over Pia.
#emph[...Chandra?]
Older but unmistakable. Her little girl, now even taller than Kiran had been. Clambering with bubbling laughter and monkeyish speed up onto her parents' shoulders as they strolled through the Greenbelt's gardens. Her warm palm pressed against Pia's in the market, before rushing away to explore on her own. So eager to be part of the causes that she knew her parents had devoted their lives to despite—
Despite the danger.
"...#emph[Mom?] " A voice, tiny and frail, and not at all like herself. An ember swelled in the corner of her eye, was caught by the wind, and twirled away.
A prison cell. A fallen mask. A melted metal insignia. A humorless rumble of laughter.
Pia shook her head, as if to dislodge the memories from her mind.
She could leave now. Make a run for it and disappear into the familiar streets.
But what about Chandra?
What if they brought her back through whatever hell she'd seen in the arena, with that man who had gladly torn both of their lives apart?
Consulate soldiers materialized between them, forming a wall of flesh and metal with Pia, Dovin, and Tezzeret on one side and the pale woman, the elf, and Chandra on the other.
Chandra plowed into the wall of armored soldiers, yelling something that Pia couldn't quite make out over the din of metallic footfalls. Her daughter offhandedly sidestepped an oncoming swipe from a filigree automaton, and inundated a crowd of the machines with a generous bath of flames. The heat washed over Pia's face like a breaking wave.
A veil of a fierce maternal pride blurred the scene. She wiped heat-stung eyes.
"The #emph[pyromancer] ," Baan frowned, his voice clipped and precise. He pointed a long, slim finger at the contingent of guards at his side, "Take care of this, if you please. Isolate and contain. Gearhulks in the front line—I will see no injuries on my watch. Be mindful, she is rash."
#emph[No! ] Pia screamed from the confines of her mind at Chandra. #emph[Get back! Don't let them take you again. Please!]
Chandra bellowed a familiar obscenity and threw a punch that blasted a gearhulk back in flames.
"Ah yes." Baan cocked his head to the side. "She is also fond of...creative anatomical descriptions."
Pia's jaw dropped. Had she overheard Kiran saying that...?
A line of heavily armed guards broke away from Dovin's side and began to close in around the oncoming Chandra as she pushed further into their midst. Several of them toppled, feet tangled in a hissing whirl of flowered vines that seemed to have appeared from nowhere in particular.
She had to act now. Pia tore her eyes away from Chandra and turned to face Tezzeret, eyes blazing. "My name is <NAME>, leader of the renegades. I'm prepared to enter Consulate custody."
Dovin arched a smooth, hairless brow, and a wave of surprised murmurs arose from the group of soldiers. "Indeed?" he said. Was this the fearsome Renegade Prime that they had prepared for? "You will, I trust, excuse a need to take precautions appropriate for a prisoner of your...reputation."
Unfazed, Tezzeret gestured the Consulate soldiers forward, his face lit with a feral grin that somehow never reached his calculating eyes. "Of course. Do show the criminal to her new residence," he said, flicking a hand in Pia's direction. Hands took either of her wrists, and filigree manacles clamped down on each.
"Maximum security?" Baan asked, hopefully.
"Whatever you see fit," Tezzeret said impatiently. "Now, as for the others..."
#figure(image("004_Renegade Prime/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"<NAME>," intoned one soldier, "you are hereby placed under the authority of the Consulate for the following crimes: defamation of government property, leading a conspiracy against the government, disturbing the peace, disorderly conduct, violation of the Aether Distribution Act—"
Chandra's yells drew still nearer—soon she'd be in surrounded by the growing ranks of soldiers. She had to stop her advance somehow.
"You forgot #emph[assault!] " Pia said with a swift side kick to the gut of the soldier next to her. "And the Aether Act was an appalling sham!" she added, bashing her manacled hands like a hammer against another soldier.
Immediately the hands on her arms tightened like vises and began to pull her away.
Through the wall of soldiers, Pia heard the pale woman shout to Chandra: "They have her! You can't risk it now; we have to #emph[go!] "
Pia let herself go limp as she watched the spires of the Weldfast, the renegades that had become her new family, and the daughter she had thought she'd lost all disappear from view.
#figure(image("004_Renegade Prime/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Retreat was never Liliana's favorite option.
They had lost the mass of Consulate guards in the crowded streets, and found themselves almost alone on one of Ghirapur's side streets. Here there were only a few curio sellers and an older woman dressed in vibrant green-blue robes patiently browsing their wares. The chaos of the scuffle had been smoothed over like water.
Chandra sat at the foot of a flight of dusty apartment stairs, clutching her knees to her chest, face buried in the old shawl she often wore around her waist. Silent. Liliana hadn't seen her silent for this long in some time—usually it meant she was asleep.
Nissa stood at a distance she probably felt respectful, saying nothing, slender fingers massaging her tattooed forehead.
Liliana paced beside the two, nerves strung tighter than a hangman's noose. "That man with the metal arm—I #emph[know] that man. He's—"
Searing memory flashed behind her eyes. Jace, his back stitched with ugly white scars from a manablade. Wincing in the dark as she traced fingers across them, eyes burning.
She jumped as her own jeweled rings clattered together, a discordance of metal. "He's...dangerous," she muttered, forcing her fists to uncurl. "His presence here is—it can't be coincidence."
Nissa turned her gaze to the necromancer, green eyes brimming with cold accusation. "Why did you leave without letting us know? To put yourselves in danger like that—you're fortunate #emph[I ] found you!"
Liliana's lips curled as she flicked a wrist dismissively in Nissa's direction. "Tezzeret is more threat than you could know." She raised her eyes imperiously to meet Nissa's. "And watch your tone—I'm not one to ask permission #emph[or] forgiveness."
Nissa's eyes narrowed, traces of green fire appearing at the ends of her staff. This was not lost on Liliana, who immediately smoothed her face into a mask of disaffected nonchalance.
"Why are you even here?" Liliana swiveled a wrist in the hot afternoon air, the gesturing encompassing the entire glittering plane of Kaladesh. "Did the rest of you take a #emph[vote] while we were gone? 'Gatewatch rule number #emph[whatever] , no going home without written #emph[permission] '?" She glanced over at the pyromancer expectantly, but Chandra gave no sign she'd even heard.
Nissa had. "Have you been provoking her this whole time?" she said, aghast. "I thought you—is this what you consider friendship? You...#emph[monster] . I hope this pleases you!" The elf drew herself up to her full height in front of Liliana and slammed the end of her staff into the cobblestone, unaware of the traces of green fire appearing at its ends.
It had been centuries since someone had used that tone with her—often it was the last thing they did. But Liliana had plans, plans that needed powerful allies. Instead, she had somehow found herself staring down an angry, interdimensional-monster-killing elf and what had been a delightful walking powder keg that had defused itself into a heap of despondence.
The necromancer shrugged into Nissa's accusatory stare. "We're all women here. Chandra can do as she pleases."
#emph[Monster, am I?]
The words bubbled up in her mind. Exactly what to say to cut the deepest.
"She #emph[ran] from you," she whispered up at the elf. "You #emph[didn't] follow—so she came to me."
The red of Nissa's cheeks stood out starkly against her green tattoos. Her lips parted, but nothing came out.
She'd always had a knack.
"If that's all you have to say, I've important questions to attend to." Liliana turned on her heel from the two with an impeccable toss of her hair, leaving the scent of lavender and the whirl of skirts in her wake.
From her place on the steps, Chandra lifted her head and tried to wipe her face with the back of a gauntlet. Her hands clenched and unclenched into fists as she stood up.
"I-I wanted to stay..." Chandra said as she lifted her face from the shawl. Nissa offered her a hand, but Chandra tottered to her feet on her own.
"I'm going for a walk," she mumbled to the ground and stumbled toward the street vendors. Nissa hurried after her.
The robed woman at the vendor stall completed her purchase, then placed a comforting hand on Chandra's armored shoulder.
"Seems you've had a hard day, my dear," she said softly, beaming an inviting smile at the two Planeswalkers.
Chandra bobbed her head at her and sniffled loudly. She managed a wan smile and squeezed the woman's hand back. There was something comforting and familiar to her face.
The robed woman pulled an elaborately embroidered handkerchief from around her pockets and pressed it into the pyromancer's hands. Chandra buried her face into it, wiping away tears. It smelled of rose tea with a hint of machine oil...like...home.
"Oh, that's it now, dry your tears..." the older woman said, lowering her voice as Chandra finished dabbing her eyes and blowing her nose into the handkerchief.
"We need you to be strong," she continued, her voice suddenly turned steely and clear, "when we find your mother and take her back from those Consulate soldiers, Chandra."
Chandra looked up into a face that she now recognized. "<NAME>?"
#figure(image("004_Renegade Prime/08.jpg", width: 100%), caption: [Art by Magali Villeneuve], supplement: none, numbering: none)
"It's been a while since I've seen you last, child," <NAME> said as she smoothed the wild strands of hair from Chandra's forehead and leaned the pyromancer against her shoulder. Together, the three made their way down Ghirapur's winding streets, deep into the secret walkways that Mrs. Pashiri knew best.
#figure(image("004_Renegade Prime/09.png", height: 40%), caption: [], supplement: none, numbering: none)
|
|
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/docs/guide/quill-guide.typ | typst | MIT License | #import "template.typ": *
#import "@preview/tidy:0.3.0"
#let version = toml("/typst.toml").package.version
#show link: set text(fill: rgb("#1e8f6f"))
#show: project.with(
title: "Quill",
authors: ("Mc-Zen",),
abstract: [Quill is a library for creating quantum circuit diagrams in #link("https://typst.app/", [Typst]). ],
date: datetime.today().display("[month repr:long] [day], [year]"),
version: version,
url: "https://github.com/Mc-Zen/quill"
)
#v(4em)
#outline(depth: 2, indent: 2em)
#pagebreak()
= Introduction
#pad(x: 1cm)[_@gate-gallery features a gallery of many gates and symbols and how to create them. In @demo, you can find a variety of example figures along with the code. @tequila introduces an alternative model for creating and composing circuits._]
Would you like to create quantum circuits directly in Typst? Maybe a circuit for quantum teleportation?
#figure[#include("../../examples/teleportation.typ")]
Or one for phase estimation? The code for both examples can be found in @demo.
#figure[#include("../../examples/phase-estimation.typ")]
This library provides high-level functionality for generating these and more quantum circuit diagrams.
For those who work with the LaTeX packages `qcircuit` and `quantikz`, the syntax will be familiar. The wonderful thing about Typst is that the changes can be viewed instantaneously which makes it ever so much easier to design a beautiful quantum circuit. The syntax also has been updated a little bit to fit with concepts of the Typst language and many things like styling content is much simpler than with `quantikz` since it is directly supported in Typst.
= Basics
A circuit can be created by calling the #ref-fn("quantum-circuit()") function with a number of circuit elements.
// #example(
// ```typ
// #quantum-circuit(
// lstick($|0〉$), gate($H$), phase($ϑ$),
// gate($H$), rstick($cos ϑ/2 lr(|0〉)-sin ϑ/2 lr(|1〉)$)
// )
// ```)
#example(
```typ
#quantum-circuit(
1, gate($H$), phase($theta.alt$), meter(), 1
)
```
)
A quantum gate is created with the #ref-fn("gate()") command. To make life easier, instead of calling `gate($H$)`, you can also just put in the gate's content `$H$`. Unlike `qcircuit` and `quantikz`, the math environment is not automatically entered for the content of the gate which allows for passing in any type of content (even images or tables). Use displaystyle math (for example `$ U_1 $` instead of `$U_1$` to enable appropriate scaling of the gate for more complex mathematical expressions like double subscripts etc.
#pagebreak()
Consecutive gates are automatically joined with wires. Plain integers can be used to indicate a number of cells with just wire and no gate (where you would use a lot of `&`'s and `\qw`'s in `quantikz`).
#example(
```typ
#quantum-circuit(
1, $H$, 4, meter()
)
```
)
A new wire can be created by breaking the current wire with `[\ ]`:
#example(
```typ
#quantum-circuit(
1, $H$, ctrl(1), 1, [\ ],
2, targ(), 1
)
```
)
We can create a #smallcaps("cx")-gate by calling #ref-fn("ctrl()") and passing the relative distance to the desired wire, e.g., `1` to the next wire, `2` to the second-next one or `-1` to the previous wire. Per default, the end of the vertical wire is just joined with the target wire without any decoration at all. Here, we make the gate a #smallcaps("cx")-gate by adding a #ref-fn("targ()") symbol on the second wire. In order to make a #smallcaps("cz")-gate with another control circle on the target wire, just use `ctrl(0)` as target.
== Multi-Qubit Gates and Wire Labels
Let's look at a quantum bit-flipping error correction circuit. Here we encounter our first multi-qubit gate as well as wire labels:
#example(vertical: true,
```typ
#quantum-circuit(
lstick($|psi〉$), ctrl(1), ctrl(2), mqgate($E_"bit"$, n: 3), ctrl(1), ctrl(2),
targ(), rstick($|psi〉$), [\ ],
lstick($|0〉$), targ(), 2, targ(), 1, ctrl(-1), 1, [\ ],
lstick($|0〉$), 1, targ(), 2, targ(), ctrl(-1), 1
)
```
)
Multi-qubit gates have a dedicated command #ref-fn("mqgate()") which allows to specify the number of qubits `n` as well as a variety of other options. Wires can be labelled at the beginning or the end with the #ref-fn("lstick()") and #ref-fn("rstick()") commands, respectively. Both create a label "sticking" out from the wire.
#pagebreak()
Just as multi-qubit gates, #ref-fn("lstick()") and #ref-fn("rstick()") can span multiple wires, again with the parameter `n`. Furthermore, the brace can be changed or turned off with `brace: none`. If the label is only applied to a single qubit, it will have no brace by default but in this case a brace can be added just the same way. By default it is set to `brace: auto`.
#example(vertical: true,
```typ
#quantum-circuit(
lstick($|000〉$, n: 3), $H$, ctrl(1), ctrl(2), 1,
rstick($|psi〉$, n: 3, brace: "]"), [\ ],
1, $H$, ctrl(0), 3, [\ ],
1, $H$, 1, ctrl(0), 2
)
```
)
== All about Wires
In many circuits, we need classical wires. This library generalizes the concept of quantum, classical and bundled wires and provides the #ref-fn("setwire()") command that allows all sorts of changes to the current wire setting. You may call `setwire()` with the number of wires to display and optionally a `stroke` setting:
#example(vertical: false,
```typ
#quantum-circuit(
1, $A$, meter(n: 1), [\ ],
setwire(2, stroke: blue), 2, ctrl(0), 2, [\ ],
1, $X$, setwire(0), 1, lstick($|0〉$), setwire(1), $Y$,
)
```
)
The `setwire()` command produces no cells and can be called at any point on the wire. When a new wire is started, the default wire setting is restored automatically (see @circuit-styling on how to customize the default). Calling `setwire(0)` removes the wire altogether until `setwire()` is called with different arguments. More than two wires are possible and it lies in your hands to decide how many wires still look good. The distance between bundled wires can also be specified:
#example(vertical: false,
```typ
#quantum-circuit(
setwire(4, wire-distance: 1.5pt), 1, $U$, meter()
)
```
)
#pagebreak()
== Slices and Gate Groups
In order to structure quantum circuits, you often want to mark sections to denote certain steps in the circuit. This can be easily achieved through the #ref-fn("slice()") and #ref-fn("gategroup()") commands. Both are inserted into the circuit where the slice or group should begin and allow an arbitrary number of labels through the `labels` argument (more on labels in @labels). The function `gategroup()` takes two positional integer arguments which specify the number of wires and steps the group should span. Slices reach down to the last wire by default but the number of sliced wires can also be set manually.
#example(
```typ
#quantum-circuit(
1, gate($H$), ctrl(1),
slice(label: "1"), 1,
gategroup(3, 3, label: (content:
"Syndrome measurement", pos: bottom)),
1, ctrl(2), ctrl(0), 1,
slice(label: "3", n: 2,
stroke: blue),
2, [\ ],
2, targ(), 1, ctrl(1), 1, ctrl(0), 3, [\ ],
4, targ(), targ(), meter(target: -2)
)
```
)
== Labels <labels>
Finally, we want to show how to place labels on gates and vertical wires. The function #ref-fn("gate()") and all the derived gate commands such as #ref-fn("meter()"), #ref-fn("ctrl()"), #ref-fn("lstick()") etc. feature a `label` argument for adding any number of labels on and around the element. In order to produce a simple label on the default position (for plain gates this is at the top of the gate, for vertical wires it is to the right and for the #ref-fn("phase()") gate it is to the top right), you can just pass content or a string:
#example(
```typ
#quantum-circuit(
1, gate($H$, label: "Hadamard"), 1
)
```
)
If you want to change the position of the label or specify the offset, you want to pass a dictionary with the key `content` and optional values for `pos` (alignment), `dx` and `dy` (length, ratio or relative length):
#example(
```typ
#quantum-circuit(
1, gate($H$, label: (content: "Hadamard", pos: bottom, dy: 0pt)), 1
)
```
)
#pagebreak()
Multiple labels can be added by passing an array of labels specified through dictionaries.
#example(
```typ
#quantum-circuit(
1, gate(hide($H$), label: (
(content: "lt", pos: left + top),
(content: "t", pos: top),
(content: "rt", pos: right + top),
(content: "l", pos: left),
(content: "c", pos: center),
(content: "r", pos: right),
(content: "lb", pos: left + bottom),
(content: "b", pos: bottom),
(content: "rb", pos: right + bottom),
)), 1
)
```
)
Labels for slices and gate groups work just the same. In order to place a label on a control wire, you can use the `wire-label` parameter provided for #ref-fn("mqgate()"), #ref-fn("ctrl()") and #ref-fn("swap()").
#example(
```typ
#quantum-circuit(
1, ctrl(1, wire-label: $phi$), 2,
swap(1, wire-label: (
content: rotate(-90deg, smallcaps("swap")),
pos: left, dx: 0pt)
), 1, [\ ], 10pt,
1, ctrl(0), 2, swap(0), 1,
)
```
)
#pagebreak()
= Gate Placement <gate-placement>
By default, all gates are placed automatically and sequentially. In this, `quantum-circuit()` behaves similar to the built-in `table()` and `grid()` functions. However, just like with `table.cell` and `grid.cell`, it is also possible to place any gate at a certain column `x` and row `y`. This makes it possible to simplify redundant code.
Let's look at an example of preparing a certain graph state:
#example(
```typ
#quantum-circuit(
..range(4).map(i => lstick($|0〉$, y: i, x: 0)),
..range(4).map(i => gate($H$, y: i, x: 1)),
2,
ctrl(2), 1, ctrl(1), 1, [\ ],
3, ctrl(2), ctrl(0), [\ ],
2, ctrl(0), [\ ],
3, ctrl(0)
)
```
)
Note, that it is not possible to add a second gate to a cell that is already occupied. However, it is allowed to leave either `x` or `y` at `auto` and manually set the other. In the case that `x` is set but `y: auto`, the gate is placed at the current wire and the specified column. In the case that `y` is set and `x: auto`, the gate is placed at the current column and the specified wire but the current column is not advanced to the next column. The parameters `x` and `y` are available for all gates and decorations.
Manual placement can also be helpful to keep the source code a bit more cleaner. For example, it is possible to move the code for a `gategroup()` or `slice()` command entirely to the bottom to enhance readability.
#example(text-size: .9em,
```typ
#quantum-circuit(
1, $S^dagger$, $H$, ctrl(0), $H$, $S$, 1, [\ ],
3, ctrl(-1),
gategroup(2, 5, x: 1, y: 0, stroke: purple,
label: (pos: bottom, content: text(purple)[CY gate])),
gategroup(2, 3, x: 2, y: 0, stroke: blue,
label: text(blue)[CX gate]),
)
```
)
#pagebreak()
= Circuit Styling <circuit-styling>
The #ref-fn("quantum-circuit()") command provides several options for styling the entire circuit. The parameters `row-spacing` and `column-spacing` allow changing the optical density of the circuit by adjusting the spacing between circuit elements vertically and horizontically.
#example(
```typ
#quantum-circuit(
row-spacing: 5pt,
column-spacing: 5pt,
1, $A$, $B$, 1, [\ ],
1, 1, $S$, 1
)
```
)
The `wire`, `color` and `fill` options provide means to customize line strokes and colors. This allows us to easily create "dark-mode" circuits:
#example(
```typ
#box(fill: black, quantum-circuit(
wire: .7pt + white, // Wire and stroke color
color: white, // Default foreground and text color
fill: black, // Gate fill color
1, $X$, ctrl(1), rstick([*?*]), [\ ],
1,1, targ(), meter(),
))
```
)
Furthermore, a common task is changing the total size of a circuit by scaling it up or down. Instead of tweaking all the parameters like `font-size`, `padding`, `row-spacing` etc. you can specify the `scale` option which takes a percentage value:
#example(
```typ
#quantum-circuit(
scale: 60%,
1, $H$, ctrl(1), $H$, 1, [\ ],
1, 1, targ(), 2
)
```
)
Note, that this is different than calling Typst's built-in `scale()` function on the circuit which would scale it without affecting the layout, thus still reserving the same space as if unscaled!
#pagebreak()
For an optimally layout, the height for each row is determined by the gates on that wire. For this reason, the wires can have different distances. To better see the effect, let's decrease the `row-spacing`:
#example(
```typ
#quantum-circuit(
row-spacing: 2pt, min-row-height: 4pt,
1, $H$, ctrl(1), $H$, 1, [\ ],
1, $H$, targ(), $H$, 1, [\ ],
2, ctrl(1), 2, [\ ],
1, $H$, targ(), $H$, 1
)
```
)
Setting the option `equal-row-heights` to `true` solves this problem (manually spacing the wires with lengths is still possible, see @fine-tuning):
#example(
```typ
#quantum-circuit(
equal-row-heights: true,
row-spacing: 2pt, min-row-height: 4pt,
1, $H$, ctrl(1), $H$, 1, [\ ],
1, $H$, targ(), $H$, 1, [\ ],
2, ctrl(1), 2, [\ ],
1, $H$, targ(), $H$, 1
)
```
)
// #example(
// ```typ
// #quantum-circuit(
// scale: 60%,
// 1, gate($H$), ctrl(1), gate($H$), 1, [\ ],
// 1, 1, targ(), 2
// )
// ```, [
// #quantum-circuit(
// baseline: "=",
// 2, ctrl(1), 2, [\ ],
// 1, gate($H$), targ(), gate($H$), 1
// ) =
// #quantum-circuit(
// baseline: "=",
// phantom(), ctrl(1), 1, [\ ],
// phantom(content: $H$), ctrl(0), phantom(content: $H$),
// )
// ])
There is another option for #ref-fn("quantum-circuit()") that has a lot of impact on the looks of the diagram: `gate-padding`. This at the same time controls the default gate box padding and the distance of `lstick`s and `rstick`s to the wire. Need really wide or tight circuits?
#example(
```typ
#quantum-circuit(
gate-padding: 2pt,
row-spacing: 5pt, column-spacing: 7pt,
lstick($|0〉$, n: 3), $H$, ctrl(1),
ctrl(2), 1, rstick("GHZ", n: 3), [\ ],
1, $H$, ctrl(0), 1, $H$, 1, [\ ],
1, $H$, 1, ctrl(0), $H$, 1
)
```
)
#pagebreak()
= Gate Gallery <gate-gallery>
#[
#set par(justify: false)
#import "gallery.typ": gallery
#gallery
]
#pagebreak()
= Fine-Tuning <fine-tuning>
The #ref-fn("quantum-circuit()") command allows not only gates as well as content and string items but only `length` parameters which can be used to tweak the spacing of the circuit. Inserting a `length` value between two gates adds a *horizontal space* of that length between the cells:
#example(
```typ
#quantum-circuit(
$X$, $Y$, 10pt, $Z$
)
```
)
In the background, this works like a grid gutter that is set to `0pt` by default. If a length value is inserted between the same two columns on different wires/rows, the maximum value is used for the space. In the same spirit, inserting multiple consecutive length values result in the largest being used, e.g., inserting `5pt, 10pt, 6pt` results in a `10pt` gutter in the corresponding position.
Putting a a length after a wire break item `[\ ]` produces a *vertical space* between the corresponding wires:
#example(
```typ
#quantum-circuit(
$X$, [\ ], $Y$, [\ ], 10pt, $Z$
)
```
)
#pagebreak()
= Annotations
*Quill* provides a way of making custom annotations through the #ref-fn("annotate()") interface. An `annotate()` object may be placed anywhere in the circuit, the position only matters for the draw order in case several annotations would overlap.
The `annotate()` command allows for querying cell coordinates of the circuit and passing in a custom draw function to draw globally in the circuit diagram. // This way, basically any decoration
Let's look at an example:
#example(
```typ
#quantum-circuit(
1, ctrl(1), $H$, meter(), [\ ],
1, targ(), 1, meter(),
annotate((2, 4), 0, ((x1, x2), y) => {
let brace = math.lr($#block(height: x2 - x1)}$)
place(dx: x1, dy: y, rotate(brace, -90deg, origin: top))
let content = [Readout circuit]
context {
let size = measure(content)
place(
dx: x1 + (x2 - x1) / 2 - size.width / 2,
dy: y - .6em - size.height, content
)
}
})
)
```
)
First, the call to `annotate()` asks for the $x$ coordinates of the second and forth column and the $y$ coordinate of the zeroth row (first wire). The draw callback function then gets the corresponding coordinates as arguments and uses them to draw a brace and some text above the cells. Optionally, you can specify whether the annotation should be drawn above or below the circuit by adding `z: above` or `z: "below"`. The default is `"below"`.
Note, that the circuit does not know how large the annotation is by default. For this reason, the annotation may exceed the bounds of the circuit. This can be fixed by letting the callback return a dictionary with the keys `content`, `dx` and `dy` (the latter two are optional). The content should be measurable, i.e., not be wrapped in a call to `place()`. Instead the placing coordinates can be specified via the keys `dx` and `dy`.
Another example, here we want to obtain coordinates for the cell centers. We can achieve this by adding $0.5$ to the cell index. The fractional part of the number represents a percentage of the cell width/height.
#example(
```typ
#quantum-circuit(
1, $X$, 2, [\ ],
1, 2, $Y$, [\ ],
1, 1, $H$, meter(),
annotate((1.5, 3.5, 2.5), (0.5, 1.5, 2.5), z: "above",
((x0, x1, x2), (y0, y1, y2)) => {
(
content: path(
(x0, y0), (x1, y1), (x2, y2),
closed: true,
fill: rgb("#1020EE50"), stroke: .5pt + black
),
)
})
)
```
)
#pagebreak()
= Custom Gates
Quill allows you to create totally customized gates by specifying the `draw-function` argument in #ref-fn("gate()") or #ref-fn("mqgate()"). You will not need to do this however if you just want to change the color of the gate or make it round. For these tasks you can just use the appropriate arguments of the #ref-fn("gate()") command.
_Note, that the interface for custom gates might still change a bit. _
When the circuit is laid out, the draw function is called with two (read-only) arguments: the gate itself and a dictionary that contains information about the circuit style and more.
Let us look at a little example for a custom gate that just shows the vertical lines of the box but not the horizontal ones.
#let quill-gate = ```typ
#let draw-quill-gate(gate, draw-params) = {
let stroke = draw-params.wire
let fill = if gate.fill != none { gate.fill } else { draw-params.background }
box(
gate.content,
fill: fill, stroke: (left: stroke, right: stroke),
inset: draw-params.padding
)
}
```
#box(inset: 1em, quill-gate)
We can now use it like this:
#example(scope: (draw-quill-gate: (gate, draw-params) => {
let stroke = draw-params.wire
let fill = if gate.fill != auto { gate.fill } else { draw-params.background }
box(
gate.content,
fill: fill, stroke: (left: stroke, right: stroke),
inset: draw-params.padding
)
}),
```typ
#quantum-circuit(
1, gate("Quill", draw-function: draw-quill-gate), 1,
)
```
)
The first argument for the draw function contains information about the gate. From that we read the gate's `content` (here `"Quill"`). We create a `box()` with the content and only specify the left and right edge stroke. In order for the circuit to look consistent, we read the circuit style from the draw-params. The key `draw-params.wire` contains the (per-circuit) global wire stroke setting as set through `quantum-circuit(wire: ...)`. Additionally, if a fill color has been specified for the gate, we want to use it. Otherwise, we use `draw-params.background` to be conform with for example dark-mode circuits. Finally, to create space, we add some inset to the box. The key `draw-params.padding` holds the (per-circuit) global gate padding length.
It is generally possible to read any value from a gate that has been provided in the gate's constructor. Currently, `content`, `fill`, `radius`, `width`, `box` and `data` (containing the optional data argument that can be added in the #ref-fn("gate()") function) can be read from the gate. For multi-qubit gates, the key `multi` contains a dictionary with the keys `target` (specifying the relative target qubit for control wires), `num-qubits`, `wire-count` (the wire count for the control wire) and `extent` (the amount of length to extend above the first and below the last wire).
All built-in gates are drawn with a dedicated `draw-function` and you can also take a look at the source code for ideas and hints.
#pagebreak()
= Function Documentation
#[
#set text(size: 9pt)
#show raw.where(block: false, lang: "typc"): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
#show heading: set text(size: 1.2em)
#show heading.where(level: 3): it => { align(center, it) }
#columns(2,[
This section contains a complete reference for every function in *quill*.
// #set raw(lang: none)
#set heading(numbering: none)
#{
let parse-module = tidy.parse-module.with(
label-prefix: "quill:",
scope: (quill: quill)
)
let show-module = tidy.show-module.with(
show-module-name: false,
first-heading-level: 2,
show-outline: false,
style: tidy.styles.default
)
let show-outline = tidy.styles.default.show-outline.with(style-args: (enable-cross-references: true))
let docs = parse-module(read("/src/quantum-circuit.typ"))
let docs-gates = parse-module(read("/src/gates.typ"))
let docs-decorations = parse-module(read("/src/decorations.typ"))
[*Quantum Circuit*]
show-outline(docs)
[*Gates*]
show-outline(docs-gates)
[*Decorations*]
show-outline(docs-decorations)
set text(size: .9em)
show-module(docs)
v(1cm)
show-module(docs-gates)
v(1cm)
show-module(docs-decorations)
let docs-tequila = parse-module(read("/src/tequila-impl.typ"))
colbreak()
heading(outlined: false)[Tequila]
v(2mm)
show-outline(docs-tequila)
show-module(docs-tequila)
}
])
]
#pagebreak()
= Demo <demo>
#show raw.where(block: true): set text(size: 0.9em)
This section demonstrates the use of the *quantum-circuit* library by reproducing some figures from the famous book _Quantum Computation and Quantum Information_ by Nielsen and Chuang @nielsen_2022_quantum.
== Quantum Teleportation
Quantum teleportation circuit reproducing the Figure 4.15 in @nielsen_2022_quantum.
#insert-example("../../examples/teleportation.typ")
== Quantum Phase Estimation
Quantum phase estimation circuit reproducing the Figure 5.2 in @nielsen_2022_quantum.
#insert-example("../../examples/phase-estimation.typ")
#pagebreak()
== Quantum Fourier Transform:
Circuit for performing the quantum Fourier transform, reproducing the Figure 5.1 in @nielsen_2022_quantum.
#insert-example("../../examples/qft.typ")
== Shor Nine Qubit Code
Encoding circuit for the Shor nine qubit code. This diagram reproduces Figure 10.4 in @nielsen_2022_quantum
#table(columns: (2fr, 1fr), align: horizon, stroke: none,
block(raw({
let content = read("/examples/shor-nine-qubit-code.typ")
content.slice(content.position("*")+1).trim()}, lang: "typ"), fill: gray.lighten(90%), inset: .8em),
include("/examples/shor-nine-qubit-code.typ")
)
#pagebreak()
== Fault-Tolerant Measurement
Circuit for performing fault-tolerant measurement (as Figure 10.28 in @nielsen_2022_quantum).
#insert-example("../../examples/fault-tolerant-measurement.typ")
== Fault-Tolerant Gate Construction
The following two circuits reproduce figures from Exercise 10.66 and 10.68 on construction fault-tolerant $pi/8$ and Toffoli gates in @nielsen_2022_quantum.
#insert-example("../../examples/fault-tolerant-pi8.typ")
#insert-example("../../examples/fault-tolerant-toffoli1.typ")
#insert-example("../../examples/fault-tolerant-toffoli2.typ")
#pagebreak()
= Tequila <tequila>
_Tequila_ is a submodule of *Quill* that adds a completely different way of building circuits.
#example(
```typ
#import tequila as tq
#quantum-circuit(
..tq.build(
tq.h(0),
tq.cx(0, 1),
tq.cx(0, 2),
),
)
```
)
This is similar to how _QASM_ and _Qiskit_ work: gates are successively applied to the circuit which is then layed out automatically by packing gates as tightly as possible. We start by calling the `tq.build()` function and filling it with quantum operations. This returns a collection of gates which we expand into the circuit with the `..` syntax.
Now, we still have the option to add annotations, groups, slices, or even more gates via manual placement.
The syntax works analog to Qiskit. Available gates are `x`, `y`, `z`, `h`, `s`, `sdg`, `sx`, `sxdg`, `t`, `tdg`, `p`, `rx`, `ry`, `rz`, `u`, `cx`, `cz`, and `swap`. With `barrier`, an invisible barrier can be inserted to prevent gates on different qubits to be packed tightly. Finally, with `tq.gate` and `tq.mqgate`, a generic gate can be created. These two accept the same styling arguments as the normal `gate` (or `mqgate`).
Also like Qiskit, all qubit arguments support ranges, e.g., `tq.h(range(5))` adds a Hadamard gate on the first five qubits and `tq.cx((0, 1), (1, 2))` adds two #smallcaps[cx] gates: one from qubit 0 to 1 and one from qubit 1 to 2.
With Tequila, it is easy to build templates for quantum circuits and to compose circuits of various building blocks. For this purpose, `tq.build()` and the built-in templates all feature optional `x` and `y` arguments to allow placing a subcircuit at an arbitrary position of the circuit.
As an example, Tequila provides a `tq.graph-state()` template for quickly drawing graph state preparation circuits.
The following example demonstrates how to compose multiple subcircuits.
#example(scale: 74%,
```typ
#import tequila as tq
#quantum-circuit(
..tq.graph-state((0, 1), (1, 2)),
..tq.build(y: 3,
tq.p($pi$, 0),
tq.cx(0, (1, 2)),
),
..tq.graph-state(x: 6, y: 2, invert: true, (0, 1), (0, 2)),
gategroup(x: 1, 3, 3),
gategroup(x: 1, y: 3, 3, 3),
gategroup(x: 6, y: 2, 3, 3),
slice(x: 5)
)
```
)
#block(breakable: false)[
To demonstrate the creation of templates, we give the (simplified) implementation of `tq.graph-state()` in the following:
#example(
```typ
#let graph-state(..edges, x: 1, y: 0) = tq.build(
x: x, y: y,
tq.h(range(num-qubits)),
edges.map(edge => tq.cz(..edge))
)
```
)
]
// This makes it easier to generate certain classes of circuits, for example in order to have a good starting point for a more complex circuit.
Another built-in building block is `tq.qft(n)` for inserting a quantum fourier transform (QFT) on $n$ qubits.
#example(scale: 80%,
```typ
#quantum-circuit(..tequila.qft(y: 1, 4))
```
)
#bibliography("references.bib")
|
https://github.com/DawodGAMIETTE/ENSEA_template-Typst | https://raw.githubusercontent.com/DawodGAMIETTE/ENSEA_template-Typst/master/README.md | markdown | # ENSEA - Typst Template
<p align="center"> <img src="typst-banner.png" </p>
Custom templates for documents made at ENSEA.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/ref-05.typ | typst | Other |
#show ref: it => {
if it.element != none {
if it.element.func() == text {
let element = it.element
"["
element
"]"
} else if it.element.func() == underline {
let element = it.element
"{"
element
"}"
} else {
it
}
} else {
it
}
}
@txt
Ref something unreferable <txt>
@under
#underline[
Some underline text.
] <under>
|
https://github.com/donabe8898/typst-slide | https://raw.githubusercontent.com/donabe8898/typst-slide/main/opc/単発/linux02/main.typ | typst | MIT License | #import "@preview/polylux:0.3.1": *
#import themes.metropolis: *
#show: metropolis-theme.with(
aspect-ratio: "16-9",
footer: "ArchLinuxの勧誘"
// short-title: "ArchLinuxの勧誘",
// short-author: "donabe8898",
// short-date: none,
// color-a: rgb("#0C6291"),
// color-b:rgb("#A63446"),
// color-c:rgb("#FBFEF9"),
// progress-bar: true
)
#show link: set text(blue)
#set text(font: "Noto Sans CJK JP",weight: "light", size: 18pt)
#show heading: set text(font: "Noto Sans CJK JP")
#show raw: set text(font: "Noto Sans Mono CJK JP")
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt
)
// タイトル
#title-slide(
title:"ArchLinuxの勧誘",
subtitle: "オタク向けデスクトップOSをインストールする",
author: "<NAME>",
date: "2024-3-15",
extra: "OECU Programming Circle "
)
// 目的
#slide()[
= 本講義の目的
#v(0.1em)
=== 建前
OSの構成要素をディストロで学ぶ
=== 本音
オタク御用達のディストリビューションの利点を知る
]
// ほんへ
#slide(title: "What's ArchLinux?")[
== Linux Distributionの一つ
- ディストリビューション: 頒布物
- Linuxはカーネルの名前なのでユーザーアプリケーションは別のやつを使う.
== 有名なディストロ
- Ubuntu
== Archは星の数ほどあるDistroの一つ
]
#slide(title: "Linuxディストロの利用例")[
- ゲームやwebのサーバー
- 一番よくある使われ方
- Minecraft(JE,BE)やnginx, Apache鯖など...
- デスクトップOS
- C,C++での競技プログラミング
- Webプログラミング
- 携帯電話
- Android
]
// KISSの法則
#slide(title: "ArchLinuxの最大の特徴")[
]
#slide(title: "ArchLinuxの最大の特徴")[
= A. KISSの法則に沿った開発・運営
]
#slide(title: "KISS")[
= KISSの法則
=== Keep it simple stupid.
- シンプルで愚鈍(愚直)にする
#v(2em)
- 設計を単純にする
- 必要のない機能は実装しない
- ソフトウェア開発において、度々議論に挙がるマインド
#v(1em)
*KISSを体現したディストロ = Arch Linux*
]
// ArchLinux特徴
#slide(title: "ArchLinux利用のメリット")[
= その1. シンプル
#v(1em)
- インストール直後の環境
- カーネル, ドライバー, シェル, コマンド, パッケージマネージャー
- その他自分が入れたもの
- インストール直後の容量
- メモリ: 150MB程度 | ドライブ: 700MB 程度
=== 最小限の物しか入らない
でもOSとしては成り立ってる
]
#slide(title: "ArchLinux利用のメリット")[
= その2. ローリング・リリース
#v(1em)
- ローリング・リリース
- OS固有のバージョン番号が無い
- 個々のソフトウェアが常にアップデートされ続けられる
- 同じOSが常に変わり続ける
#v(1em)
]
#slide(title: "ArchLinuxの特徴")[
= その3. ドキュメントが充実している
#v(1em)
- ArchLinux Wiki
- URL: #link("https://wiki.archlinux.jp/index.php/メインページ")
- *情報量が多すぎて*StackOverflowや知恵袋を見ても解決できなかった問題ががあっさり直る
- UNIX全体に通用する知識
= #text(fill:red)[ArchLinux使いでなくでも必見]
]
#slide(title: "ArchLinuxの特徴")[
= その4. コンピュータに少しだけ強くなる
#v(1em)
- なにか起きたら自分で何とかしてスタンス
- 問題発生→原因究明→ドキュメント閲覧→解決
- グラフィカルなインストーラは無い
- パーティション割りやネットワーク設定などは自分でどうぞ
#text(fill:red)[毎日使えばちょっとは詳しくなる...かも?]
]
#slide(title: "ArchLinuxの特徴")[
= その5. Arch Build System
#v(1em)
- ソースコードのビルドとpacman用パッケージの作成を自動化するためのシステム
- portsみたいなもの
- `PKGBUILD`ファイルに手順を書けば、ソースコードの取得, コンパイル, パッケージング, インストールまで全て自動化できる
]
#slide(title: "ArchLinuxの特徴")[
= Arch User Repository
- `PKGBUILD`を一般ユーザーが配布
- *Google Chrome, VSCode, Spotify, Slack*
- ライセンスの関係でpacmanに登録できない
- *pacmanにあるソフトの開発版*
- 試験的に使ってみたい人向け
- `hogehoge-git`
]
#slide(title: "まとめ")[
ArchLinuxとは
- *自由*で*シンプル*な*拡張性の高い*Linux
== おすすめできる人
- DIY好き. 自作PCとかやる人
- 新しいモノ好き
#v(1em)
== おすすめできない人
- めんどくさがり
- Linux触ったこと無い人(Ubuntuから入れてくれ)
]
#focus-slide()[
*let's install ✫*
]
#slide(title: "ArchLinuxをインストール")[
#v(1em)
検索「ArchLinux インストール」
ArchLinuxと似たようなOS
- Gentoo Linux
- ソフトウェアはソースからコンパイルする主義
- ドM向き
- FreeBSD
- Not Linux
- 正統派UNIXを使いたいならコレ
- ディスク使用率が高い場合でも安定して動作(鯖向き)
]
|
https://github.com/dainbow/MatGos | https://raw.githubusercontent.com/dainbow/MatGos/master/themes/34.typ | typst | #import "../conf.typ": *
= Центральная предельная теорема для независимых одинаково распределённых случайных величин с конечной дисперсией
#definition[
Последовательность случайных величин $seq(xi)$ сходится к случайной величине $xi$ *по распределению*,
если $forall f : RR -> RR$ -- непрерывной ограниченной функции выполнено
#eq[
$EE f(xi_n) ->_(n -> oo) EE f(xi)$
]
Обозначение $xi_n ->_d xi$.
]
#definition[
Пусть $xi$ -- случайная величина.
*Характеристической функцией* случайной величины $xi$ называется #strike("преобразование Фурье")
#eq[
$phi_xi (t) = EE e^(i xi t)$
]
]
#theorem(
"Непрерывности для характеристической функции",
)[
Пусть $seq(xi)$ -- последовательность случайных величин, $seq(phi)$ -- соотстветствующая
последовательность характеристических функций.
Тогда если
#eq[
$forall t in RR : exists lim_(n -> oo) phi_n (t) = phi(t)$
]
где $phi(t)$ непрерывна в нуле, то $phi(t)$ является характеристической функцией
некоторой случайной величины $xi$, причём $xi_n ->_d xi$.
]
#theorem(
"О производных характеристической функции",
)[
Пусть $EE abs(xi)^n < +oo$ для $n in NN$.
Тогда $forall s <= n$:
+ $phi^((s)) (t) = EE ((i xi)^s e^(i t xi))$
+ $EE xi^s = (phi^((s))_xi (0)) / i^s$
+ $phi_xi (t)$ раскладывается в вид
#eq[
$phi_xi (t) = sum_(k = 0)^n (i t)^k / k! EE xi^k + (i t)^n / n! epsilon_n (t)$
]
где $abs(epsilon_n (t)) <= 3 EE abs(xi)^n$ и $epsilon_n (t) ->_(t -> 0) 0$
]
#theorem(
"ЦПТ для НОРСВ",
)[
Пусть $seq(xi)$ -- независимые одинаково распределённые случайные величины, $EE xi_1 = a, 0 < VV xi_1 < +oo$.
Обозначим $S_n := xi_1 + ... + xi_n$. Тогда
#eq[
$(S_n - EE S_n) / sqrt(VV S_n) ->_d cal(N)(0, 1)$
]
]
#proof[
Обозначим $T_n := (S_n - EE S_n) / sqrt(VV S_n)$. По теореме непрерывности
достаточно проверить, что характеристическая функция $T_n$ сходится к $e^(-t^2 / 2)$ -- характеристической
функции $cal(N)(0, 1)$ (которая равна также $e^(-t^2 / 2)$)
Обозначим $eta_j := (xi_j - a) / sigma$. Тогда $seq(eta)$ -- тоже НОРСВ, причём $EE eta_j = 0, VV eta_j = EE eta_j^2 = 1$.
Тогда
#eq[
$T_n = (S_n - n a) / sqrt(n sigma^2) = (eta_1 + ... + eta_n) / sqrt(n)$
]
Посчитаем характеристическую функцию $T_n$:
#eq[
$phi_(T_n) (t) = EE e^(i t T_n) = EE e^(i t / sqrt(n) (eta_1 + ... + eta_n)) attach(=, t: "независимость") \ product_(k = 1)^n phi_(eta_k) (t / sqrt(n)) = phi^n_(eta_1)(t / sqrt(n)) attach(=, t: "т. о производных") \
(1 + i t / sqrt(n) EE eta_1 - t^2 / (2n) EE eta_1^2 + o(1 / n))^n = (1 - t^2 / 2n + o(1 / n))^n ->_(n -> oo) e^(-t^2 / 2)$
]
]
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/007%20-%20Theros/005_The%20Consequences%20of%20Attraction.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Consequences of Attraction",
set_name: "Theros",
story_date: datetime(day: 09, month: 10, year: 2013),
author: "<NAME>",
doc
)
The vole had crept too close. Xandria had been waiting for most of the day and night and through the rain. The rain was cold and lashing, but comforting in a way. It was like being touched by someone. Besides, she would not die from sickness. She would not die at all. The same could not be said of the vole.
The hunger was constant. There was no large game on the islands, but the others rarely deigned to feast on the smaller creatures. Those were mostly left to her. She had wondered what would happen if she stopped eating, but at some point the hunger became compulsory. She must eat.
Nyx was obscured by the dark clouds, and Xandria could barely see her own feet perched on the rocky outcropping, but she heard the vole scrabble close, and she began to sing. The scrabbling stopped and was replaced by a dreamy pattering of tiny clawed feet. Her voice filled the dark, wet night, overcoming the sounds of rain and wind and fury, overcoming fear. She hoped that was true, that there was no fear at the end.
The vole crept right in front of her. Although she still couldn't see it, she could smell it, the wet fur, the life of it. As it crawled onto her leg and up her body, she could hear its tiny heartbeat, now synchronized with the tempo of her song, as it quested ever further for the music's origin. She opened her mouth wide as the vole crawled on to her face. She relished the feel of its fur on her face as it entered her mouth before she crunched hard on its spine, breaking the body in two.
The feel of blood and muscle in her mouth was the strength she needed to tear and swallow the rest of the tiny carcass. It was never easy to eat this way, even after so many years, so many awful meals. She hoped the vole's last thought was of her beautiful song.
Another song erupted in the night air, and then several more. Xandria whirled back to the watery darkness, wondering what had drawn the attention of the others, and over the ocean she saw lights. A ship. Xandria lifted her wings and launched off her rock, swooping close to the water before flying toward the lights. The lights from the ship offered a feeble glimpse of the curling waves and driving rain, although she didn't need to see to navigate around this stretch of rock and ocean.
The ship was a trireme out of Meletis, large and majestic, likely staffed by seasoned sailors and warriors, presumably on a trade route. The ship was far off course to be on this edge of the Siren Sea. Perhaps it was the storm, perhaps it was carelessness, perhaps a fatal bravery that sometimes seemed to grip men. Xandria never knew which, and by then had stopped caring. These encounters between men and the others always ended the same.
There were twenty or so of the others, swooping in and out and unleashing bursts of song. The ship was important enough to have a mage on deck, and some form of magic protected his ears as he hurled fire at the others to keep them at bay. The other crew members on deck had no magic to protect them—many of them walked willingly over the railing of the ship, some of them grabbed in the embrace of an other, some of them plummeting to the dark water below, struggling to stay afloat to continue hearing that glorious song. Most of the oarsmen had stopped rowing at this point, most of them entranced, and even the deaf ones knew how this would likely end.
#figure(image("005_The Consequences of Attraction/01.jpg", width: 100%), caption: [], supplement: none, numbering: none)
The mage had failed to bring down a single one of the others. It was one thing to fight in the light, while dry and on land, quite another to be in this hell. Xandria gave some momentary thought of aiding this man. He looked young and handsome, from what she could see each time a burst of light came from his hands, but this too was a path she had been down before. The others couldn't hurt her, but the last time she interfered they had drawn every living creature from the islands for weeks. It was then she realized that madness would be her eternal companion, not death, until finally they had relented or grown bored with their sport, and they left her to her birds and fish and rats. She would not help this man.
And then one of the others swooped in behind him and gouged out some of his back and shoulders with her talons. He must have screamed but the sound was drowned out in the rain and in the songs. Xandria flew in closer, looking down on the scene illuminated in the ship's deck lights. Whatever protective magic the mage was using vanished in the assault, and he stood there, blood pouring from his back, one of his shoulders and arms dangling by threads of muscle and bone. But his face, so recently dominated by rage and fear, now looked serene. Happy. He approached the other and her beautiful song. Did he know what awaited there? How could he not?
Xandria looked away as the other began feasting. The beautiful melodies that had filled the wet air were now replaced by sounds of eating and slaughter, and the unfortunate cries of the deaf who could only be placated by violent ends. Xandria looked at the others, willing them to look at her, to acknowledge her, something to fill this emptiness. But the others refused to be distracted from their feasting and raucous cries to each other, only hissing when she came too close. Xandria flew from the ship, back into the darkness.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
He was beautiful, and his name was Ninis. She remembered little else about him. They had both been young scholars in Meletis, and while she was shy and far more comfortable around books than people, it had been impossible not to notice him.
It should have been impossible for him to notice her. No one noticed her. But after an ethics class together he approached her, fascinated by her insights. They talked for hours that day. And they talked for hours more for the next several days, walking throughout the academy halls, talking and talking until one night they walked onto the beaches outside the school, and they stayed together throughout the night.
When she woke up on the beach the next morning, and he was still beside her, in all his beauty, she could not believe how happy she was. He was beautiful. He was smart. And he was hers.
She stood and stretched, enjoying the luxurious morning, the sun a mere red shimmer over the blue conjoining of sky and sea. A trick of the light played over the water, dancing to and fro, and only gradually did Xandria realize that the light was coalescing, forming into a #emph[shape] . The #emph[shape] began to move from the middle of the water toward the beach.
Even immediately after everything happened, she couldn't recall more than a #emph[shape] . The #emph[shape] was accompanied by a soft susurration, a murmuring nothingness that failed to catch the ears the same way the #emph[shape] failed to catch her eyes. She knew that something was horribly wrong. She moved to wake up Ninis, shaking him roughly, but he did not stir.
#emph[He will not wake.] The voice was directly in her mind, and it hurt. #emph[I do not want him disturbed further.] The shape hovered over the sand a few feet away from them. This was a god in front of her, one of the pantheon that ruled #emph[Theros] from the land of Nyx, the night sky. Which one, she could not say, and at this proximity it did not matter. She thumped onto the sand on her knees, head bowed in pain.
"I'm sorry, I'm sorry..."
#emph[You loved something that was mine.]
"We didn't know." Blind panic drove her words. Each time the voice spoke, the pain increased, and when the voice left her head the low susurration grew louder.
#emph[Worse, you attracted something that was mine.]
"We didn't know. I didn't know! He didn't tell me! Please. Please."
#emph[Know? Why does your knowledge matter? Or his? I marked him as mine when he was a baby in his mother's arms. A perfect combination of body and mind not seen on this land for countless generations before or after. Mine. And you dared to love him. You dared to have him love you.]
She was on her knees, huddled close, weeping, begging, and even though her head was down and her eyes closed, she could see the #emph[shape] reach out, reach out and touch her.
#emph[You will learn the consequences of attraction.]
She screamed.
#figure(image("005_The Consequences of Attraction/02.jpg", width: 100%), caption: [], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Xandria woke the next morning on her rocky island, the scream from her dreams still echoing in her mind. She rarely dreamed about that day anymore, the day her old life ended. She stretched her wings and flew to find her breakfast.
Despite the realities of her existence, she still felt joy every time she flew. As a girl, she dreamt of running over hills and plains and suddenly being able to take off from the ground and fly.
Flying was exactly like those dreams. In those first few days after her transformation, she delighted in her newfound powers—flight, her beautiful voice, the power to captivate most living creatures around her. She loved her wings, their black, soft, feathers; her wings that unfurled to catch the wind, or that she could hug close to her body to keep her warm.
The first morning after the jealous god had wreaked its vengeance, she woke up on this same island and immediately flew off, somewhere, anywhere. Her plan was to find civilization, and from there find her way back to Meletis. There would be someone, a teacher, a mage, a priest, someone who could help her navigate her way back to being human, back to Ninis.
In the middle of the ocean, out of sight of the islands, she discovered the truth of the one of the last two sentences the god spoke to her before it left. #emph[You shall not leave.] Over time, she found she was trapped, an invisible leash linked her to her island. She could roam far, a number of leagues, but it was only ocean and other islands dominated by her ilk circumscribed by her divine fence.
It took longer for her to discover the truth of the last sentence the god spoke to her. #emph[You shall not die.]
She was brought back to the present by the silvery flash of movement below her. Most mammals and birds were smart enough to avoid her and her kind. Treats like the vole the night before were an exception. But there were always fish. Fish never seemed to learn. Two of them jumped out of the water and she stunned them briefly with a burst of song, then grabbed their flailing bodies and gobbled them down. She had never liked the taste of fish before her change, and many thousands of fish meals later the taste was not better. But she had to eat. She turned back toward the island.
Another path had been possible, back in those first few days. Back when she first discovered she was not alone on these islands. She had certainly heard of sirens before, when she was human, but had never seen one. And while she could see her reflection in the waters of the ocean, she had not believed it real. It was not her. She would be cured, be healed, be reunited with Ninis.
The sirens had been waiting for her when she returned from that first journey. She could not deny their beauty. Slender and long-legged, and those beautiful black wings gently flapping in the ocean breeze. They opened their mouths, and Xandria reflexively turned away, the horror stories of a siren's song a part of her childhood, the same as every citizen of Meletis. But instead of song, she heard raucous cries and trills, which Xandria was surprised to realize she understood as neatly as if they spoke human tongue.
They beckoned her to follow them, and she did. She still thought of this situation as temporary, as the early part of an adventure, like one of the stories she had so loved as a child, the happy ending awaiting her with a confident destiny. But it was better to make peace with these creatures, and besides, she had thought to herself, maybe one of these sirens would one day be the key to her rescue. If stories were any guide to life, surely one of them would be.
They brought her to a horror.
Two men lay on the beach, shipwrecked sailors from a small sailboat that had washed ashore. One of them had had most of his guts torn out, blood and fleshy tubes spread out in a wide aura beneath him, melting into the sands. But he still breathed, at least for a little longer. The other man seemed mostly unharmed, although in a stupor, as he refused to look at anything but the sand in front of his face. Her mind raced at how to help these men. She knew little of medicine but she had to do something.
#figure(image("005_The Consequences of Attraction/03.jpg", width: 100%), caption: [], supplement: none, numbering: none)
The sirens around her started singing. Both men stirred, the fatally wounded man even picking up what guts he could and gathered them close to his body as he struggled to stand. Failing to do that, he crawled in labored starts toward the voices. It was the first time Xandria had heard a siren's song. It was certainly a pretty melody, but it sounded no different to her than that of a well-trained singer at a festival. But for these men, the sirens' song had all the impact promised by legend.
At first, Xandria thought the voices had some sort of healing property. The injured man was moving with an animation she would have thought impossible, but then suddenly the last of the man's innards gave way and he fell down dead. The other sirens immediately set upon the corpse, tearing and grinding, #emph[feasting] .
The disgust she felt was only overcome by her horror at seeing his healthy shipmate walk right up to one of the sirens, rapture on his face. She had no time to scream a warning as the siren walked up to the man and snapped off most of his neck with one bite. The man crumpled to the ground and Xandria could still see his serene smile bizarrely matched with his dead eyes. All she could see was Ninis's eyes, and pictured them cold, dead, glassy.
She screeched, all human sounds failing her as she flew at the murderer. The siren squawked in surprise and flew away from her, eating. The other sirens turned and flew toward her. They grabbed her arms and her legs, even her wings, and they brought her down to the ground. She struggled and cursed, and demanded they stop this travesty. They laughed at her, and each one pecked at her cheek, tearing out a small bit of flesh and muscle, and they continued to laugh as they chewed and then spit out a small piece of her. The pain was immense, and she would have described it as the worst pain of her life except even it paled in comparison to when the god had touched her.
After each siren had its bloody mouthful, they rose up and left her there, in between the two ravaged corpses, now little more than skeletons. She thought she would die, and she realized with sadness that she welcomed the release. But no death occurred. Later, she got up and looked into the water and was both fascinated and horrified by her smooth cheek, with no sign of the previous injury.
But from that moment, the sirens refused to speak with her, refused to even look at her. She had attempted to stop their predations on humans several times, and had even come to look forward to their violence against her, as some kind of tangible proof that she mattered. Until the time when they changed their tactics and instead drove all her food away. That had broken her.
#emph[You shall not leave. You shall not die.]
She had not left. She had not died. She could curse the gods for many things, but not for lying.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
When she returned to her island from the morning's hunt, still hungry despite the fish, she came across a human body lying on her beach. His clothes were tattered rags, worn away by the sea and rocks. He was probably one of the oarsmen from the ship the other sirens attacked the night before, one of those who had fallen off the deck in search of that alluring song.
#figure(image("005_The Consequences of Attraction/04.jpg", width: 100%), caption: [], supplement: none, numbering: none)
The body moved.
In all the years Xandria had been living on the island, she had not seen another human while by herself. Always the others were around, cultivating and protecting their food from her interference. She was startled about the feeling in her chest. She could not identify it, could not catalogue it, she could only know she had not felt it in a very long time.
She approached the body, the #emph[person] , and knelt down beside him. She turned him over, gingerly, with softness and care. His mouth burbled up some sea water, and he woke, gasping and crying.
Hope. She felt hope. A human. She was touching a human. She was touching #emph[someone] . He was breathing, but still not looking at anything, just gasping and crying. She continued to stroke his arm softly, marveling at the feel. He finally opened his eyes fully, and looked at her. He screamed.
"No!" she shouted, but it came out as a screech. It had been so long. She slowed down, forcing herself to remember what it was like. Human speech was still possible.
"No!" this time it came out as she intended. Human. Her voice sounded horrible to her ears. Foreign and monstrous, but still human. "I can help you. I won't hurt you. I'm not like... them."
The man clearly wanted to be away, but also had little strength to move. His eyes were wide, his pupils tiny flecks, as he struggled to breathe and inch himself away from her.
"Who... who are you? Where am I?" His accent sounded strange to her, not from Meletis. Perhaps a sailor from Akros, working on a Meletis vessel.
"You are all right, you are all right. I am a friend." She tried to make her voice sing-song without actually singing. She was talking with another human. She could do this.
"My ship, my friends, where..." he looked around frantically, as if he could find his friends if only he moved quickly enough.
"They're dead. Everyone is dead. Your ship was attacked by..."
"You!" The man snarled but he could not move. He just sat there, breathing heavily, the panic in his eyes replaced by rage.
"No! Not me. Them. I am not them. Please, I am not them. You must help me. Please." She could not stop the tears. It had been a long time since she had cried. Those first few days, hundreds of years ago, the tears had been constant. But the tears had stopped when she realized there was no one there to see them.
The man looked confused, but some of the rage left his face, so she continued. "Your name, what is your name? I am Xandria. Xandria from Meletis."
"Tolios. Tolios from Meletis." Xandria was confused. He sounded like no Meletian she knew. Had it truly been so long?
"Why was your ship so far from its course, so close to... this place?"
Tolios turned his head and spat. "Chakros. That damned mage insisted we reach shore by dawn. There have been strange reports of new creatures at the border. We were sent to investigate. It was Chakros's first command, and he was determined to be there first, before the other ships. When the storm came, the captain prepared a path far to the north, but Chakros demanded we cut south through the storm instead. I thought the captain would throw him overboard then, but instead we traveled through these infested straits. Did the mage make it?"
"No, dead like the rest."
"Good, good. There's that at least. And how does a monster like you hail from Meletis?"
She was so thrilled to be asked a question, to be looking at another human face and conversing, that she was not dismayed by his blunt description. It was fine to be a monster as long as there was conversation and touch. He even smiled. It was a beautiful smile. He lifted one hand up to scratch his ear, but kept the other arm carefully still. Perhaps it was broken. She hoped she could fix it.
"It's a very long story. I would love to tell you about it. But are you hungry? Are you well? I can help, if you need it." She gazed at his face, his body, looking for other signs of injury or sickness. She knew she would have to get him hidden, safely stowed away before the others came. This time she would fight. She would fight them all if she had to.
Tolios continued to smile. "There's something torn up in my back. Can you take a look?" Xandria felt a surge of panic. She hadn't seen any blood or obvious injury when she first came across the body, and now he might die from her oversight. She moved to examine him. The man moved with a speed she had not thought possible, the dagger in that previously still hand coming out of nowhere aimed straight at her face. Song burst from her lips.
Tolios continued to sit, awkwardly twisted, as the dagger fell onto the sands below. The smile on his face had been replaced by a look more familiar to her. A different smile. A smile she trusted.
"Why? Why? I wanted to help you!" She slapped Tolios in the head, and he flopped to the ground. Her talons left deep gouges in his cheek. When she stopped singing, the fear and panic returned to his face, and she resumed her song to pacify him.
She sang through her tears, through her heartbreak, and Tolios looked at her adoringly, crawling closer to her.
#emph[How flimsy they are.] The thought came to her unbidden. But she couldn't deny its truth. Humans were so #emph[weak] . Death, sorcery, gods, monsters... humans were beholden to these forces they could not comprehend nor control. And all their cares came to an end for a song.
Her song.
#figure(image("005_The Consequences of Attraction/05.jpg", width: 100%), caption: [Shipwreck Singer | Art by Daarken], supplement: none, numbering: none)
Xandria heard the flapping of wings behind her, and she turned her head. All the others were there, flying behind her. But instead of their usual screeches of hatred and rejection, they simply hovered, looking at her. Looking directly at her. One of them approached her and smiled.
She smiled at Xandria. An other... a siren... was smiling at her. Xandria turned back to Tolios while still singing, watching his vacant eyes and delightful smile. The other sirens drew closer, and Xandria could feel their heat, feel their hunger. They crowded around her, but gently, softly. They reached out their hands and stroked her feathers and her back, cooing and trilling, but not singing. The singing was all hers.
The sun was now directly overhead, but its warmth paled to what Xandria was feeling. She stepped closer to Tolios, her song lifting in the air, becoming louder, more insistent. Drool dropped from the corner of Tolios's mouth, and his eyes expected ecstasy to come. Xandria stepped closer, closer.
She opened her mouth wide and bit into his neck with a ferocious bite. His blood and flesh gushed into her mouth, the taste immediately satisfying in a way that no vole or fish had ever been.
Now the sirens behind her started singing. Their voices carried far along the ocean air, singing a song she had never heard before, but felt she had known all her life. The sirens made no attempt to share in the meal. The food was all hers as the songs of the sirens, the songs of her sisters, filled the heavens.
He was delicious.
|
|
https://github.com/FuryMartin/I-QinShiHuang-Money | https://raw.githubusercontent.com/FuryMartin/I-QinShiHuang-Money/master/lib.typ | typst | Creative Commons Zero v1.0 Universal | #import "@preview/tablex:0.0.8": gridx, hlinex
#let invoice(
title: none,
vice-title: none,
invoice-date: "始皇帝十七年",
items: none,
pay: none,
recipient: none,
signature: none,
thanks: none,
) = {
set text(lang: "zh", region: "cn")
set page(paper: "a4", margin: (x: 20%, y: 20%, top: 8%, bottom: 5%))
show heading.where(
level: 1
): it => block(width: 100%)[
#set text(20pt, weight: "regular")
#smallcaps(it.body)
]
let format_currency(number, locale: "zh") = {
number
}
set text(2em)
align(center, smallcaps[
#set text(size: 2.5em)
#set par()
*#title*
])
align(center,[
#set par(leading: 0.40em)
#set text(size: 2em)
#vice-title \
])
align(left,[
#set par(leading: 0.40em)
#set text(size: 1em)
#recipient.location \
*#recipient.name*
])
v(0.5em)
let num_to_chinese(id) = {
if id == 1 { "壹" }
else if id == 2 { "贰" }
else if id == 3 { "叁" }
else if id == 4 { "肆" }
else if id == 5 { "伍" }
else if id == 6 { "陆" }
else if id == 7 { "柒" }
else if id == 8 { "捌" }
else if id == 9 { "玖" }
else if id == 10 { "拾" }
else { "" };
}
// 返回空字符串以防止索引超出范围
let items = items.enumerate().map(
((id, item)) => ([#str(num_to_chinese(id + 1))], [#item.description], [#format_currency(item.price)钱],),
).flatten()
[
#set text(number-type: "lining", 1em)
#gridx(
columns: (auto, 10fr, auto),
align: (
(column, row) =>
if column == 0 { center }
else if column == 1 { center }
else { right }
),
hlinex(),
[*编号*],
[*条目*],
[*计*],
hlinex(),
..items,
hlinex(),
[],
align(right,[总计]),
[#format_currency(pay.total)钱],
hlinex(start: 3),
)
]
align(center, [
*#invoice-date*
#set text(size: 1.2em)
])
align(center,[
#thanks \
#signature
#set text(size: 1.2em)
])
}
|
https://github.com/falkaer/resume | https://raw.githubusercontent.com/falkaer/resume/main/style.typ | typst | MIT License | #let left_column_size = 25%
#let grid_column_gutter = 8pt
#let main_color = rgb("#c72e2f")
#let heading_color = main_color
#let job_color = rgb("#737373")
#let dateformat = "[month]/[year]"
#let setup(author: "", body) = {
set document(author: author, title: "Resume")
set page(
paper: "a4",
numbering: "1 / 1",
header: [
#set align(right)
#set text(fill: luma(25%), size: 10pt)
Last updated #datetime.today().display("[month repr:short] [day padding:none], [year]")
],
number-align: center,
margin: 1.25cm,
)
set text(
font: ("Latin Modern Sans", "Inria Sans"),
hyphenate: false,
lang: "en",
fallback: true,
)
show math.equation: set text(weight: 400)
set list(marker: box(circle(radius: 0.2em, stroke: heading_color), inset: (top: 0.2em)))
set enum(numbering: (n) => text(fill: heading_color, [#n.]))
show heading.where(level: 1): element => [
#text(element.body, fill: heading_color, weight: 400)
]
show heading.where(level: 2): element => [
#text(element.body, size: 0.8em)
]
show heading.where(level: 3): element => [
#text(element.body, size: 1em, weight: 400, style: "italic")
]
body
}
#let experience(subject, location, from, to) = {
grid(
columns: (auto, 1fr),
{
heading([#subject,], level: 2)
text(location, weight: 400, style: "italic")
}, align(
right,
[
#from.display(dateformat) -- #if to == none [Present] else { to.display(dateformat) }
],
),
)
}
#let iconlink(icon, url, desc) = {
link(url)[
#align(horizon)[
#box(height: 1em, baseline: 20%)[#pad(right: 0.1em)[#image(icon)]]
#text(desc)
]
]
}
#let icontext(icon, desc) = {
align(horizon)[
#box(height: 1em, baseline: 20%)[#pad(right: 0.1em)[#image(icon)]]
#text(desc)
]
}
|
https://github.com/Julien-cpsn/typst-chromo | https://raw.githubusercontent.com/Julien-cpsn/typst-chromo/main/README.md | markdown | MIT License | # [Chromo](https://github.com/julien-cpsn/typst-chromo)
Generate printer tests directly in Typst.
For now, only generates with CMYK colors (as it is by far the most used).
I personally place one of these test on all my exam papers to ensure the printer's quality over time.
## Documentation
To import any of the functions needed, you may want to use the following line:
```typst
#import "@preview/chromo:0.1.0": square-printer-test, gradient-printer-test, circular-printer-test, crosshair-printer-test
```
### Square test
```typst
#square-printer-test()
```
### Gradient test
```typst
#gradient-printer-test()
```
### Circular test
```typst
#circular-printer-test()
```
### Crosshair test
```typst
#crosshair-printer-test()
```
## Contributors
- [Julien-cpsn](https://github.com/julien-cpsn)
|
https://github.com/DaAlbrecht/lecture-notes | https://raw.githubusercontent.com/DaAlbrecht/lecture-notes/main/computer_networks/ip_protocols.typ | typst | MIT License | #import "../template.typ": *
#set table(
fill: (x, y) =>
if x == 0 or y == 0 {
gray.lighten(40%)
},
align: right,
)
#show table.cell.where(x: 0): strong
#show table.cell.where(y: 0): strong
= ICMP (Internet Control Message Protocol)
ICMP is a key protocol in the Internet protocol suite, primarily used by network devices (like routers) to send error messages and operational information.
It helps communicate success or failure in network communications, such as when a service is unavailable or a host cannot be reached.
Unlike TCP or UDP, ICMP is not used to exchange data between systems and is mainly used for network diagnostics (e.g., ping and traceroute).
ICMP for IPv4 is defined in RFC 792, while ICMPv6 (for IPv6) is defined in RFC 4443.
It handles diagnostic tasks, error reporting, and control functions, and operates at the network layer (Layer 3 of the OSI model).
ICMP messages are contained within IP packets but are treated as a special case, often directing error messages back to the source IP of the original packet.
== Datagram structure
ICMP messages consist of an ICMP header and a variable-length data section.
=== ICMP header
The ICMP header is a fixed-size structure that contains the following fields:
- *Type*: Specifies the type of ICMP message (e.g., echo request, echo reply, destination unreachable).
- *Code*: Provides additional information about the ICMP message type.
- *Checksum*: Used to verify the integrity of the ICMP message.
- *Rest of header*: Contains additional fields specific to the ICMP message type.
The ICMP header is followed by the data section, which varies in size and structure based on the ICMP message type.
#figure(
image("../resources/icmp_header.png", width: 120%),
caption: [ICMP header structure],
) <icmpheader>
#pagebreak()
==== Common ICMP message types
#table(
columns: (auto,auto,1fr,auto),
align: (center+horizon,center+horizon,left,center+horizon),
table.header([Type], [Code], [Description], [Sent by]),
[3],[1],[Destination Unreachable,Indicates that the destination is unreachable],[Router],
[3],[0],[Network Unreachable,The destination network is unreachable],[Router],
[4],[0],[Redirect Datagram for the Network,Redirects the packet to another network],[Router],
[0],[0],[Echo Reply,Response to an echo request],[Host],
[11],[0],[Time Exceeded,Indicates that the time to live (TTL) has expired],[Router],
)
= NAT (Network Address Translation)
Network Address Translation (NAT) is a method used to modify network address information in IP packet headers while in transit across a traffic routing device.
== NAT implementation classifications
NAT can be implemented in various ways, each with its own characteristics and use cases:
#table(
columns: (1fr,2fr,1fr),
table.header(repeat: true,
[Type], [Description],[Figure]),
align: (center+horizon,left,center+horizon),
[Static NAT (one-to-one NAT)],
[Once an internal address (iAddr:iPort) is mapped to an external address (eAddr:ePort), any packets from iAddr:iPort are sent through eAddr:ePort.
\
\
Any external host can send packets to iAddr:iPort by sending packets to eAddr:ePort.
],
image("../resources/Full_Cone_NAT.svg.png", width: 90%),
[(Address)-restricted-cone NAT],
[Once an internal address (iAddr:iPort) is mapped to an external address (eAddr:ePort), any packets from iAddr:iPort are sent through eAddr:ePort.
\
\
An external host (hAddr:any) can send packets to iAddr:iPort by sending packets to eAddr:ePort only if iAddr:iPort has previously sent a packet to hAddr:any. "Any" means the port number doesn't matter.
],
image("../resources/Restricted_Cone_NAT.svg.png", width: 90%),
[Port-restricted cone NAT],
[Once an internal address (iAddr:iPort) is mapped to an external address (eAddr:ePort), any packets from iAddr:iPort are sent through eAddr:ePort.
\
\
An external host (hAddr:hPort) can send packets to iAddr:iPort by sending packets to eAddr:ePort only if iAddr:iPort has previously sent a packet to hAddr:hPort.
],
image("../resources/Port_Restricted_Cone_NAT.svg.png", width: 90%),
[Symmetric NAT],
[The combination of one internal IP address plus a destination IP address and port is mapped to a single unique external source IP address and port; if the same internal host sends a packet even with the same source address and port but to a different destination, a different mapping is used.
\
\
Only an external host that receives a packet from an internal host can send a packet back.
],
image("../resources/Symmetric_NAT.svg.png", width: 90%),
)
#pagebreak()
== DHCP (Dynamic Host Configuration Protocol)
The Dynamic Host Configuration Protocol (DHCP) automates the assignment of IP addresses and network parameters to hosts within a network, which is especially helpful for large-scale networks.
Rather than manually configuring IP settings for each device, DHCP allows a DHCP server to dynamically allocate IP addresses, subnet masks, DNS server addresses, routers, and other parameters to clients (DHCP clients) during their boot process.
DHCP evolved from the BOOTP protocol and is backward compatible with it.
It supports both automatic and dynamic IP address assignments, where dynamic assignments require periodic renewal by the client.
Servers maintain records of allocated and available IP addresses.
DHCP can also assign fixed IP addresses to specific clients via server configuration.
The process is entirely automatic, eliminating the need for manual configuration, and helps simplify network management, particularly in environments with many devices.
DHCP messages are encapsulated within UDP packets, which are in turn encapsulated within IP packets.
#pagebreak()
== DHCP Frame Structure
DHCP messages consist of a fixed-size header and a variable-length options field.
- *Op*: Specifies the message type (e.g., request, reply).
- *Htype*: Specifies the hardware address type (e.g., Ethernet).
- *Hlen*: Specifies the hardware address length.
- *Hops*: Used by relay agents to forward messages.
- *Xid*: Transaction ID to match requests and replies.
- *Secs*: Time elapsed since the client began the DHCP process.
- *Flags*: Flags field.
- *Ciaddr*: Client IP address.
- *Yiaddr*: Your IP address (server).
- *Siaddr*: Server IP address.
- *Giaddr*: Gateway IP address.
- *Chaddr*: Client hardware address.
- *Sname*: Server name.
- *File*: Boot file name.
- *Options*: Variable-length field containing DHCP options.
#figure(
image("../resources/dhcp_header.png", width: 120%),
caption: [DHCP header structure],
) <dhcpheader>
#pagebreak()
== DHCP Message Types
DHCP messages can be classified into the following types and passed as the *Op* field in the DHCP header:
#table(
columns: (1fr,1fr,3fr),
align: (center+horizon,center+horizon,left),
table.header([Value], [Message Type], [Description]),
[1],[DHCPDISCOVER],[Broadcast message from the client to discover DHCP servers on the network.],
[2],[DHCPOFFER],[Unicast message from the server to offer IP address and configuration parameters to the client.],
[3],[DHCPREQUEST],[Broadcast message from the client to request offered parameters from a specific server.],
[4],[DHCPDECLINE],[Broadcast message from the client to decline the offered parameters.],
[5],[DHCPACK],[Unicast message from the server to acknowledge the client's request and provide configuration parameters.],
[6],[DHCPNAK],[Unicast message from the server to indicate that the client's requested parameters are not available.],
[7],[DHCPRELEASE],[Broadcast message from the client to release the assigned IP address.],
[8],[DHCPINFORM],[Unicast message from the client to request additional configuration parameters.],
)
== Sequence of DHCP Message Exchange
The DHCP process involves a series of messages exchanged between the client and server to allocate an IP address and other network parameters.
#figure(
image("../resources/DHCP_session.svg.png", width: 30%),
caption: [DHCP message exchange sequence],
) <dhcpsequence>
#pagebreak()
= Security Considerations
== ICMP Attack vectors
ICMP can be used for various attacks, such as ICMP flood attacks, ping of death, and ICMP redirect attacks.
- *ICMP flood*: Overwhelms a target with ICMP echo requests, consuming network resources and causing a denial of service.
- *Ping of death*: Sends oversized ICMP packets to crash the target system.
- *ICMP redirect*: Redirects traffic to a malicious host, allowing attackers to intercept and manipulate data.
Preventing ICMP attacks involves filtering ICMP traffic, disabling ICMP echo requests, and implementing intrusion detection systems to detect and block malicious ICMP traffic.
== ARP Attack vectors
ARP spoofing used to be a common attack vector.
It involves sending forged ARP messages to associate an attacker's MAC address with the IP address of a legitimate host, allowing the attacker to act as a man in the middle and intercept traffic intended for the legitimate host.
Preventing ARP attacks involves using static ARP entries, implementing ARP spoofing detection tools, and securing network devices to prevent unauthorized access.
== DHCP Attack vectors
- *DHCP starvation*: Exhausts available IP addresses by sending a large number of DHCP requests, preventing legitimate clients from obtaining IP addresses.
- *DHCP spoofing*: Impersonates a DHCP server to provide false IP addresses and network parameters to clients, allowing attackers to intercept and manipulate network traffic.
Preventing DHCP attacks involves using DHCP snooping, port security, and DHCP authentication mechanisms to verify the legitimacy of DHCP servers and clients.
|
https://github.com/MichaelFraiman/TAU_template | https://raw.githubusercontent.com/MichaelFraiman/TAU_template/main/mfraiman-problem.typ | typst | // File that defines problem something
// The style file defines the prob with preapplied arguments
// In the future it should probably be changed to #set
#let problem(
problem_counter, //counter used to display problem number (ProblemNumber)
inline_counter, //InlineCounter
body,
prob_word: "Problem", //problem name
prob_punct: ".", //punctuation
answer: "",
solution: "",
note: none,
display_answer: true, //locate(loc => {answ_disp.at(loc)}),
answ_word: "Answer",
display_solution: true, //locate(loc => {sol_disp.at(loc)}),
qed_symbol: sym.floral,
sol_word: "Solution",
les_num: none, //str(les_num.at(loc))
les_num_symb: "", //les_num_symb.at(loc)
) = {
{
set text(
weight: 900
)
problem_counter.step()
context {
let l_n = none
if type(les_num) == state {
if les_num.get() == none {
l_n = none
} else {
l_n = str(les_num.get())
}
} else {
l_n = les_num
}
smallcaps({
prob_word + [ ]
if l_n != none {
l_n + les_num_symb + [.]
}
problem_counter.display()
if note != none {
text(weight: "medium")[ (#note)]
}
prob_punct + [ ]
})
}
}
inline_counter.update(0)
body
inline_counter.update(0)
if answer != "" { // fix
parbreak()
text(weight: 900)[#answ_word. ]
answer
}
//if display_solution == true { doesn't work???
inline_counter.update(0)
if solution != "" {
parbreak()
text(weight: 900)[#sol_word. ]
solution
if qed_symbol != none {
h(1fr) + qed_symbol
}
}
//}
} |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/minerva-report-fcfm/0.2.0/README.md | markdown | Apache License 2.0 | # Minerva Report FCFM
Template para hacer tareas, informes y trabajos, para estudiantes y académicos de la Facultad de Ciencias Físicas y Matemáticas de la Universidad de Chile que han usado templates similares para LaTeX.
## Guía Rápida
### [Webapp](https://typst.app)
Si utilizas la webapp de Typst puedes presionar "Start from template" y buscar "minerva-report-fcfm" para crear un nuevo proyecto con este template.
### Typst CLI
Teniendo el CLI con la versión 0.11.0 o mayor, puedes realizar:
```sh
typst init @preview/minerva-report-fcfm:0.1.0
```
Esto va a descargar el template en la cache de typst y luego va a iniciar el proyecto en la carpeta actual.
## Configuración
La mayoría de la configuración se realiza a través del archivo `meta.typ`,
allí podrás elegir un título, indicar los autores, el equipo docente, entre otras configuraciones.
El campo `autores` solo puede ser `string` o un `array` de strings.
La configuración `departamento` puede ser personalizada a cualquier organización pasandole un diccionario de esta forma:
```typ
#let departamento = (
nombre: (
"Universidad Técnica Federico Santa María",
"Factultad"
)
)
```
Las demás configuraciones pueden ser un `content` arbitrario, o un `string`.
### Configuración Avanzada
Algunos aspectos más avanzados pueden ser configurados a través de la show rule que inicializa el documento `#show: minerva.report.with( ... )`, los parámetros opcionales que recibe la función `report` son los siguientes:
| nombre | tipo | descrición |
|-----------|-------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| portada | (meta) => content | Una función que recibe el diccionario `meta.typ` y retorna una página. |
| header | (meta) => content | Header a aplicarse a cada página. |
| footer | (meta) => content | Footer a aplicarse a cada página. |
| showrules | bool | El template aplica ciertas show-rules para que sea más fácil de utilizar. Si quires más personalización, es probable que necesites desactivarlas y luego solo utilizar las que necesites. |
#### Show Rules
El template incluye show rules que pueden ser incluidas opcionalmente.
Todas estas show rules pueden ser activadas agregando:
```typ
#show: minerva.<nombre-función>
```
Justo después de la línea `#show minerva.report.with( ... )` reemplazando `<nombre-función>`
por el nombre de la show rule a aplicar.
##### primer-heading-en-nueva-pag (activada por defecto)
Esta show rule hace que el primer heading que tenga `outlined: true` se muestre en una
nueva página (con `weak: true`). Notar que al ser `weak: true` si la página ya de por
si estaba vacía, no se crea otra página adicional, pero para que la página realmente
se considere vacía no debe contener absolutamente nada, incluso tener elementos invisibles
va a causar que se agregue una página extra.
##### operadores-es (activada por defecto)
Cambia los operadores matemáticos que define Typst por defecto a sus contrapartes en
español, esto es, cambia `lim` por `lím`, `inf` por `ínf` y así con todos.
##### formato-numeros-es
Cambia los números dentro de las ecuaciones para que usen coma decimal en vez
de punto decimal, como es convención en el español. Esta show rule no viene
activa por defecto.
|
https://github.com/Goldan32/brilliant-cv | https://raw.githubusercontent.com/Goldan32/brilliant-cv/main/modules_hu/professional.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Szakmai Tapasztalat")
#cvEntry(
title: [Junior Beágyazott Szoftvermérnök],
society: [Flex],
logo: "",
date: [2022 - ],
location: [Budapest],
description: list(
[Új funkciók implementálása beágyazott környezetben yocto felhasználásával],
[Patch-ek létrehozása külső szoftverekhez],
[Suggested and implemented a firmware component version handler tool in C, that can be utilized through multiple projects],
[Különböző firmware komponensek verzióját olvasó és megjelenítő szoftver készítése C nyelven, az ötlettől a megvalósításig]
),
tags: ("OpenBMC", "Yocto Project", "C", "C++", "BASH", "CMake")
)
#cvEntry(
title: [Szoftverfejlesztő Gyakornok],
society: [Flex],
logo: "",
date: [2021 - 2022],
location: [Budapest],
description: list(
[Alacsony szintű programozás és tesztek írása a firmware csapat tagjaként],
[Összetetteb beágyazott programok készítése és dokumentáció írása],
),
tags: ("C", "Aurix", "Python", "Makefile")
)
#cvEntry(
title: [Hallgatói Önkormányzati Képviselő],
society: [Budapesti Műszaki és Gazdaságtudományi Egyetem],
logo: "",
date: [2020 - 2021],
location: [Budapest],
description: list(
[Email-es kommunikáció hallgatókkal egyetemi szabályozásokkal kapcsolatban],
[Hallgatók érdekeinek képviselete különböző üléseken],
)
) |
https://github.com/piepert/typst-seminar | https://raw.githubusercontent.com/piepert/typst-seminar/main/main.typ | typst | #import "slides.typ": *
#import "th_bipartite.typ": *
#import "slide_footnotes.typ": *
#import "slide_sections.typ": *
#import "latex_symbol.typ": latex-symbol
#show "La!!TeX": [La]+[!TeX]
#show "La!TeX": [#h(-0.2em)#latex-symbol#h(-0.3em)]
#set heading(numbering: "1.1.1.")
#set text(lang: "de")
#show link: set text(blue)
#let task(description, solution) = [
#slide[
#counter("main_task_counter").step()
#text(size: 1.25em, strong([Aufgabe ]+locate(loc => counter("main_task_counter").at(loc).first())))
#par(justify: true, description)
]
#slide[
#text(size: 1.25em, strong([Lösung ]+locate(loc => counter("main_task_counter").at(loc).first())))
#solution]
]
#show: slides.with(
authors: "<NAME>",
email: text(size: 0.75em, "<EMAIL>"),
title: "Typst — Hat La!TeX ausgedient?",
subtitle: "Eine kurze Einführung in Typst",
short-title: "Shorter title for slide footer",
date: "2. Juni 2023",
theme: bipartite-theme(),
typography: (math-font: "New Computer Modern Math")
)
#slide[
#outline(depth: 1)
]
#new-section("Kurzes Kennenlernen")
/*
- Wer hat schonmal LaTeX benutzt? → Ihr werdet euch glücklich schätzen
- Wer hatte das IP-Modul? → Macht es einfacher
*/
#new-section("Probleme von La!TeX")
#slide(title: "Alles begann mit...")[
#align(center)[
#image("img/donald_e_knuth.png", height: 75%)
<NAME>#slide-footnote("Foto: Brian Flaherty / The New York Times") #text(size: 0.75em, "(geb. 10. Januar 1938)")
]
/*
- Autor von TeX und METAFONT, entwickelt ab 1977
- bekanntestes Werk neben TeX: The Art of Computer Programming
- TeX extra für sein Buch entwickelt, weil er besondere ästhetische Ansprüche hatte, die die Verleger nicht erfüllen konnten
*/
]
#slide(title: "Dann kam...")[
#align(center)[
#image("img/leslie_lamport.png", height: 75%)
<NAME>#slide-footnote("Foto: <NAME> / Quanta Magazine") #text(size: 0.75em, "(geb. 7. Februar 1941)")
]
/*
- Autor von LaTeX, entwickelt ab Anfang 1980
- LaTeX als Sammlung von Makros zur Erweiterung und Vereinfachung von TeX
*/
]
#slide(title: "Die Probleme")[
+ Riesige Programmgröße
+ Auswahl an Compilern
+ Unverständliche Fehler
]
#slide(title: "Größe des Programms")[
#align(center)[
#image("img/installation_size_latex.png", width: 60%)
Verglichen mit `21MB` des Typst-Compilers...
#image("img/installation_size_typst.png", width: 60%)
]
/*
- Installationsgrößen können stark variieren, 300MB..7GB
- unglaublich viele Pakete
*/
]
#slide(title: "Die Vielfalt")[
„La!TeX“ ist kein Programm, sondern:
- pdfLaTeX // Unicode-Charakter mit 0-Breite zwischen "La" und "TeX"
- LuaTeX
- XeTeX
- MikTeX
- KaTeX
- ...
]
#slide(title: "Beispiel-Fehlermeldung (Typst)")[
#columns(2, [
Typst:
```typst
$a+b
```
#colbreak()
#set text(size: 16pt)
```
error: expected dollar sign
┌─ test.typ:1:5
│
1 │ $a+b
│ ^
```
])
]
#slide(title: "Beispiel-Fehlermeldung (La!TeX)")[
#columns(2, [
#v(2em)
La!TeX:
#set text(size: 22pt)
```tex
\documentclass{article}
\begin{document}
$a+b
\end{document}
```
#colbreak()
#set text(size: 8pt)
#raw(read("latex_error.log"))
])
]
#slide(title: "Mehr Beispiel-Fehlermeldung")[
#set text(size: 18pt)
#table(columns: (auto, auto),
inset: 0.5em,
[Typst], [La!TeX],
```typ
#set par(leading: [Hello])
^^^^^^^
expected integer, found content
```,
```latex
\baselineskip=Hello
Missing number, treated as zero.
Illegal unit of measure (pt inserted).
```,
```typ
#heading()
^^
missing argument: body
```,
```latex
\section
Missing \endcsname inserted.
Missing \endcsname inserted.
...
```,
)
#set text(size: 12pt)
(aus: <NAME>: #emph["Typst -- A Programmable Markup Language for Typesetting."] Masterarbeit an der TU Berlin, 2022.)
]
#new-section("Die Lösung aller Probleme(?)")
#slide(title: "Typst")[
#align(center, block(width: 60%)[
#set text(size: 0.65em)
#grid(columns: (auto, auto),
gutter: 1em,
[ #image(height: 40%, width: auto, "img/martin_haug.png")
<NAME>\
(Webentwicklung)
],
[ #image(height: 40%, width: auto, "img/laurenz_maedje.png")
<NAME>\
(Compilerentwicklung)
])
#set text(size: 0.75em)
#link("https://typst.app/about/"), (letzter Zugriff: 26.05.2023, 10:16)
])
#align(horizon)[#block(align(top)[
- 2019 Projektstart an TU Berlin
- entstanden aus Frustration über LaTeX
])]
]
#slide(title: "Das Ziel")[
_"Während bestehende Lösungen langsam, schwer zu bedienen oder einschränkend sind, ist Typst sorgfältig entworfen, um leicht erlernbar, flexibel und schnell zu sein. Dafür haben wir eine komplett eigene Markupsprache und Textsatzengine von Grund auf entwickelt. Dadurch sind wir in allen Bereichen des Schreib- und Textsatzprozesses innovationsfähig."_
#set text(size: 0.5em)
#link("https://www.tu.berlin/entrepreneurship/startup-support/unsere-startups/container-profile/startups-2023-typst"), (letzter Zugriff: 03.05.2023, 10:13)
]
#slide(title: "Ein kleiner Vergleich")[
#set text(size: 20pt)
#align(horizon, table(columns: (auto, auto, auto),
inset: 1em,
stroke: none,
[La!TeX], [Typst], [Ergebnis],
align(top, ```latex
\documentclass{article}
\begin{document}
\begin{enumerate}
\item Dies
\item Ist
\item Eine
\item Liste!
\end{enumerate}
\end{document}
```),
align(top, ```typst
+ Dies
+ Ist
+ Eine
+ Liste!
```), align(top)[
+ Dies
+ Ist
+ Eine
+ Liste!
]))
]
#new-section("Die Web-App")
#slide(title: "Ab ans Werk!")[
#set text(size: 20pt)
Vorteile:
- alle Dateien online
- verschiedene Projekte erstellbar
- guter online Editor
- als Team gleichzeitig an Dateien arbeiten
- eingebaute Dokumentation
#link("https://typst.app/")
Temporäre Accounts (mit $1 <= #[`N`] <= 15$):
- E-Mail: `<EMAIL>`
- Passwort: `<PASSWORD>`
Link zur Präsentation: #link("https://github.com/survari/typst-seminar")
/*
- Browser und Website öffnen
- Anmeldung per tmp-Acc. oder eigene Accounts erstellen
*/
]
#new-section("Grundlegende Formatierung")
/*
- Titel
- Fett, Kursiv
- Listen
- Bilder
- Set und Show-Regeln
- Schriftgröße und -farbe ändern
- Textausrichtung
- Mathematik (Dokumentation mit Symbolen)
*/
#slide(title: "Überschriften")[#{
let code = ```
// Hier ein Kommentar,
// er wird ignoriert!
= Überschrift 1!
== Überschrift 2!
=== Überschrift 3!
Text
Neuer Abstatz!
```
table(stroke: none,
columns: (1fr, auto),
align(top, text(size: 20pt, raw(lang: "typst", code.text))), align(top)[
#strong[
#text(size: 36pt, [1. Überschrift 1!])
#text(size: 30pt, [1.1. Überschrift 2!])
#text(size: 24pt, [1.1.1. Überschrift 3!])
]
Text
Neuer Absatz!
])
}]
#slide(title: "Absätze")[#{
let code = ```
= Mein cooler Titel
In Typst beginnt ein neuer Absatz, sobald im Code eine freie Zeile steht.
Leider sind standardmäßig Absätze linksbündig und nicht Blocksatz. Wie man das ändert, lernen wir gleich!
```
// Absatz-Abstand mal ein bisschen anpassen, damit man es
// sieht, damit es aber nicht wie eine leere Zeile wirkt
set block(spacing: 0.75em)
table(stroke: none,
columns: (50%, 50%),
align(top, text(size: 20pt, raw(lang: "typst", code.text))),
align(top)[
#strong(text(size: 28pt, [\1. Mein cooler Titel]))
#set text(size: 20pt)
In Typst beginnt ein neuer Absatz, sobald im Code eine freie Zeile steht.
Leider sind standardmäßig Absätze linksbündig und nicht Blocksatz. Wie man das ändert, lernen wir gleich!
])
}]
#slide(title: "Listen")[#{
let code = ```
+ Eine numerierte Liste
+ Kann sehr schön sein!
1. So geht sie auch!
2. Jawohl!
- Und hier nicht-nummeriert!
- Ganz ohne Nummern!
```
table(stroke: none,
columns: (1fr, auto),
align(top, text(size: 20pt, raw(lang: "typst", code.text))),
align(top, text(size: 20pt, eval("["+code.text+"]"))))
}]
#slide(title: "Schriftart")[#{
let code = ```
#text(font: "Arial", [Hallo Welt!])
#text(font: "Courier New", [Hallo Welt!])
#text(font: "New Computer Modern", [Hallo Welt!])
```
table(stroke: none,
columns: (1fr, auto),
align(top, text(size: 20pt, raw(lang: "typst", code.text))),
align(top, text(size: 20pt, eval("["+code.text+"]"))))
}]
#slide(title: "Content, Strings, Scripts")[
#set text(size: 20pt)
- zwei Arten von Inhalten in Typst:
- Content in `[...]`
- Scripts in `{...}`
- von Content zu Script mit `#`
- jedes Dokument ist grundlegend Content
#v(1em)
#table(columns: (50%, 50%),
stroke: none,
```typ
#strong([Hier ist Content in Script.])
#{
strong([Fett!])
[Auch hier ist Content in Script!]
}
#{ 3/4 }
```, align(top)[
#strong([Hier ist Content.])
#{
strong([Fett!])
[Auch hier ist Content in Script!]
}
#{ 3/4 }
])
]
#slide(title: "Text" + slide-footnote(link("https://typst.app/docs/reference/syntax/")))[#{
let code = ```
*Hallo!* #strong([Hallo!])
_Hallo!_ #emph([Hallo!])
Hallo!#super([Hallo!])
Hallo!#sub([Hallo!])
#text(fill: red, [Hallo rot!])
#text(fill: rgb("#ff00ff"), [Hallo pink!])
#text(fill: rgb("#ff00ff"), strong([Hallo pink!]))
```
table(stroke: none,
columns: (1fr, auto),
align(top, text(size: 20pt, raw(lang: "typst", code.text))),
align(top, text(size: 20pt, eval("["+code.text+"]"))))
}]
#slide(title: "Ausrichtung")[#{
let code = ```
#align(left, [Hallo!])
#align(center, [Hallo!])
#align(right, [Hallo!])
#align(right, strong([Hallo!]))
```
table(stroke: none,
columns: (60%, 1fr),
align(top, text(size: 20pt, raw(lang: "typst", code.text))),
align(top, text(size: 20pt, eval("["+code.text+"]"))))
}]
#task[Wie realisiert man das Folgende in Typst?
#block(stroke: black,
inset: 1em, [
#align(center, emph[Ein Brief an Lorem])
#lorem(20)
])
][
```typ
#align(center, emph[Ein Brief an Lorem])
#lorem(20)
```
]
#slide(title: "Abstände #1")[#{
let code = ```
#align(right, [Vertikaler])
#v(2cm)
Horizontaler #h(2cm) Abstand
```
table(stroke: none,
columns: (1fr, auto),
align(top, text(size: 18pt, raw(lang: "typst", code.text))),
align(top, text(size: 18pt, eval("["+code.text+"]"))))
}]
#slide(title: "Abstände (Vertikal)")[#{
let code = ```
Listen-Beispiel von Folie 21 mit vertikalen Abständen.
+ Eine numerierte Liste
+ Kann sehr schön sein!
#v(2em)
1. So geht sie auch!
2. Jawohl!
#v(2em)
- Und hier nicht-nummeriert!
- Ganz ohne Nummern!
```
table(stroke: none,
columns: (50%, 50%),
align(top, text(size: 18pt, raw(lang: "typst", code.text))),
align(top, text(size: 18pt, eval("["+code.text+"]"))))
}]
#slide(title: "Abstände (Horizontal)")[#{
let code = ```
+ Gott kommen aufgrund seines vollkommenen Wesens alle vollkommenen Eigenschaften zu.
+ Zu existieren ist vollkommener als nicht zu existieren.
+ Also ist Existenz eine vollkommene Eigenschaft.
+ Also existiert Gott. #h(1fr) QED
```
table(stroke: none,
columns: (auto),
align(top, text(size: 18pt, raw(lang: "typst", code.text))),
v(1em),
align(top, text(size: 18pt, eval("["+code.text+"]"))))
}]
#slide(title: "Bilder")[#{
let code = ```
#image(height: 50%, "leslie_lamport.png")
```
table(stroke: none,
columns: (auto),
align(top, text(size: 20pt, raw(lang: "typst", code.text))),
align(top + center, v(1em) + image(width: 50%, "img/leslie_lamport.png")))
}]
#slide(title: [`#block()` und `#box()`])[#{
let code = ```
Das lässt sich mit `#block` machen: #block(stroke: black, inset: 0.5em, [ `#block()` erzeugt einen Zeilenumbruch und lässt sich über Seiten brechen. Es hat viele optionale Argumente.])
So sieht's aus.
```
table(stroke: none,
columns: (auto, auto),
align(top, text(size: 18pt, raw(lang: "typst", code.text))),
align(top, text(size: 18pt, eval("["+code.text+"]"))))
}]
#slide(title: [`#block()` und `#box()`])[#{
let code = ```
Hingegen: #box(stroke: black, inset: 2pt, [`#box()`]) erzeugt #box(stroke: (bottom: black), inset: 2pt, [keinen]) Zeilenumbruch und lässt sich #box(stroke: (bottom: black), inset: 2pt, [nicht]) über Seiten brechen. Man kann damit aber Dinge zum Beispiel umrahmen. Zum Unterstreichen sollte man aber eher #underline[`#underline`] benutzen.
```
table(stroke: none,
columns: (auto, auto),
align(top, text(size: 18pt, raw(lang: "typst", code.text))),
align(top, text(size: 18pt, eval("["+code.text+"]"))))
}]
#slide(title: "Tabellen")[#{
let code = ```
#table(
columns: (auto, 3cm, auto),
[Hallo1!],
[2a],
[Hallo3!],
[Welt1!],
[2b],
[Welt3!]
)
```
table(stroke: none,
columns: (1fr, auto),
align(top, text(size: 18pt, raw(lang: "typst", code.text))),
align(top, text(size: 18pt, eval("["+code.text+"]"))))
}]
#slide(title: "Mathematik")[#{
let code = ```
$ sum_(k=0)^n k = 1 + ... + n $
$ A = pi r^2 $
$ "area" = pi dot.op "radius"^2 $
$ cal(A) :=
{ x in RR | x "is natural" } $
$ frac(a^2, 2) $
```
table(stroke: none,
columns: (60%, 40%),
align(top, text(size: 18pt, raw(lang: "typst", code.text))),
align(top, text(size: 18pt, [
#set text(font: "New Computer Modern Math")
#eval("["+code.text+"]")
])))
}]
#task[Wie realisiert man das Folgende in Typst?
#table(columns: (auto, auto),
strong[Formel], strong[Zugeschrieben],
$a^2 + b^2 = c^2$, [Pythagoras],
$c <= a + b$, [Unbekannt])
][
```typ
#table(columns: (auto, auto),
strong[Formel], strong[Zugeschrieben],
$a^2 + b^2 = c^2$, [Pythagoras],
$c <= a + b$, [Unbekannt])
```
]
#slide(title: "Set-Regeln" + slide-footnote(link("https://typst.app/docs/reference/styling/")))[#{
let code = ```
Hier ist noch die Standard-Schriftart! Q
#set text(font: "New Computer Modern", fill: blue)
Q Ab jetzt ist alles vollkommen in der anderen Schriftart und sogar blau!
#set par(first-line-indent: 1.5em, justify: true)
Ab jetzt wird jede erste Zeile eines Absatzes eingerückt und Blocksatz!
Wirklich, versprochen! #lorem(20)
```
table(stroke: none,
columns: (1fr, 1fr),
align(top, text(size: 18pt, raw(lang: "typst", code.text))),
align(top, text(size: 18pt, eval("["+code.text+"]"))))
}]
#slide(title: "Show-Regeln" + slide-footnote(link("https://typst.app/docs/reference/styling/")))[#{
let code = ```
#show heading: set text(red)
=== Hallo!
==== Welt!
// aus dem offiziellem
// Typst-Tutorial
#show "Project": smallcaps
#show "badly": "great"
We started Project in 2019
and are still working on it.
Project is progressing badly.
```
table(stroke: none,
columns: (60%, auto),
align(top, text(size: 20pt, raw(lang: "typst", code.text))),
align(top, text(size: 20pt, eval("["+code.text+"]"))))
}]
#task[Wie realisiert man das Folgende in Typst? Hinweis: Die `show`-Regel ist nicht auf `#lorem()` anwendbar.
#block(inset: 1em, stroke: black, [
#set par(justify: true)
#show "Typst": strong
In Typst sind show- und set-Regeln sehr mächtig. Kann man Sie, kann man auch Typst. Typst soll immer fett gedruckt werden. Der Absatz ist Blocksatz. _Kleine Wiederholung: Wie macht man in Typst nochmal etwas kursiv?_
])
][
```typ
#set par(justify: true)
#show "Typst": strong
In Typst sind show- und set-Regeln sehr mächtig. Kann man Sie, kann man auch Typst. Typst soll immer fett gedruckt werden. Der Absatz ist Blocksatz. _Kleine Wiederholung: Wie macht man in Typst nochmal etwas kursiv?_
```
]
#slide[
#table(columns: (50%, 50%),
stroke: none,
inset: 1em, [
#set text(size: 12pt)
#align(left, raw(lang: "latex", read("Beispiele/MatheDeltaEpsilon/edk_latex.tex")))
], align(top)[
#set text(size: 12pt)
#align(left, raw(lang: "typst", read("Beispiele/MatheDeltaEpsilon/edk_typst.typ")))
])
]
#slide[
#align(center, [
#image(width: 90%, "Beispiele/MatheDeltaEpsilon/edk_latex.svg")
#image(width: 90%, "Beispiele/MatheDeltaEpsilon/edk_typst.svg")
])
]
#new-section("Die Typst-Dokumentation...")
#slide[
- #link("https://typst.app/docs") als Nachschlagwerk
- Dokumentation ist wichtig!
]
#slide(title: [Doku-Beispiel: `image`-Funktion])[#{
[`image` kann noch ein bisschen was!]
let code = ```
#image("leslie_lamport.png")
```
table(stroke: none,
columns: (auto),
align(top, text(size: 20pt, raw(lang: "typst", code.text))),
align(top + center, v(1em) + [
#image("img/leslie_lamport.png")
]))
}]
#slide(title: [Doku-Beispiel: `image`-Funktion])[#{
[`image` kann noch ein bisschen was!]
let code = ```
#image(height: 50%, "leslie_lamport.png")
```
table(stroke: none,
columns: (auto),
align(top, text(size: 20pt, raw(lang: "typst", code.text))),
align(top + center, v(1em) + [
#image(height: 50%, "img/leslie_lamport.png")
]))
}]
#slide(title: [Doku-Beispiel: `image`-Funktion])[#{
// Wie komme ich jetzt an die ganzen Informationen, was
// image alles kann? -> Dokumentation!
[`image` kann noch ein bisschen was!]
let code = ```
#image(fit: "stretch", width: 100%, height: 100%, "leslie_lamport.png")
```
table(stroke: none,
columns: (auto),
align(top, text(size: 20pt, raw(lang: "typst", code.text))),
align(top + center, v(1em) + block(height: 50%, width: 100%, [
#image(fit: "stretch", width: 100%, height: 100%, "img/leslie_lamport.png")
])))
}]
#slide[#image("img/doku_image_1.png", fit: "contain")]
#slide[#image("img/doku_image_2.png", fit: "contain")]
#slide[#image("img/doku_image_3.png", fit: "contain")]
#slide[#image("img/doku_image_4.png", fit: "contain")]
#slide[#image("img/doku_image_5.png", fit: "contain")]
#slide[
Beispiel bei `#enum()`:
#image("img/doku_image_6.png", fit: "contain")
]
#slide[
Beispiel bei `#enum()`:
#image("img/doku_image_7.png", height: 80%)
]
#task[Welcher Parameter kann durch eine `set`-Regel wie verändert werden, damit man eine nummerierte Listen (`#enum()`) wie folgt formatieren kann? Die Dokumentation hilft!
#block(inset: 1em, width: 100%, stroke: black, [
#set enum(numbering: "I.")
+ Element 1
+ Element 2
+ Element 3
])
][
```typ
#set enum(numbering: "I.")
+ Element 1
+ Element 2
+ Element 3
```
]
#task[Welcher Parameter kann durch eine `set`-Regel wie verändert werden, damit man eine nicht-nummerierte Listen wie folgt formatieren kann? Die Dokumentation hilft!
#block(inset: 1em, width: 100%, stroke: black, [
#set list(marker: ">")
- Element 1
- Element 2
- Element 3
])
][
```typ
#set list(marker: ">")
- Element 1
- Element 2
- Element 3
```
]
#new-section("Eigene Templates und Skripts")
/*
- Seite bearbeiten, Seitengröße, Header, Footer, ...
- Skripten (aufpassen: pure functions!)
*/
// Irrelevant, kann man nachschlagen:
// ----------------------------------
// #slide(title: "Mehrere Typst-Dateien verwenden")[
// #set text(size: 20pt)
// #table(stroke: none,
// columns: (50%, 50%),
// image("img/file_list2.png", width: 90%), [
// `chapter1.typ`:
// #pad(left: 1em)[```typst
// == Kapitel 1
// #lorem(10)
// ```]
// `chapter2.typ`:
// #pad(left: 1em)[```typst
// == Kapitel 2
// #lorem(10)
// ```]
// ])
// `main.typ`:
// #pad(left: 1em)[```typst
// = Mein tolles Buch
// Hier, Kapitel!
// #include "chapter1.typ"
// #include "chapter2.typ"
// ```]
// ]
#slide(title: "Eigene Funktionen und Variablen #1")[#{
let code = ```
#let var = 3.14159
#let double(e) = {
return 2*e
}
$pi$ ist etwa #var! \
$tau$ ist etwa #double(var)!
$pi approx var$ \
$tau approx double(var)$
```
table(stroke: none,
columns: (60%, auto),
align(top, text(size: 20pt, raw(lang: "typst", code.text))),
align(top, text(size: 20pt, eval("["+code.text+"]"))))
}]
#slide(title: "Eigene Funktionen und Variablen #2")[
Eine Einschränkung: wir arbeiten mit #emph[Pure Functions].
#{
let code = ```
#let var = 2
#let change_var(new_v) = {
var = new_v
return var
}
#change_var(100)
```
table(stroke: none,
columns: (50%, auto),
align(top, text(size: 18pt, [Folgendes geht nicht:] + par(raw(lang: "typst", code.text)))),
align(top, text(size: 18pt, [
Fehler:
```typc
#let change_var(new_v) = {
var = new_v
``` ```
^^^
variables from outside the function are read-only and cannot be modified
```])))
}]
#slide(title: "Eigene Funktionen und Variablen #3")[#{
set text(size: 22pt)
let code = ```
#let names = ("Peter", "Petra", "Josef", "Josefa")
#let greet(names) = {
[Hallo ]
names.join(last: " und ", ", ")
[! #names.len() wundervolle Namen!]
}
#greet(names)
```
raw(lang: "typst", code.text)
v(1em)
eval("["+code.text+"]")
}]
// Kann man auch nachschlagen:
// ---------------------------
// #slide(title: "Funktionen auslagern")[
// #set text(size: 20pt)
// #table(stroke: none,
// columns: (50%, 50%),
// image("img/file_list.png", width: 90%), [
// `greet_me.typ` definiert:
// - `greet(names)`
// - `double(n)`
// ])
// ```typst
// #import "greet_me.typ": *
// #import "greet_me.typ": greet
// ```
// ]
#task[Es soll eine Funktion erstellt werden, die zwei Zahlen addiert und das Ergebnis #text(red, [rot]) und #strong[fett] formatiert. Etwa so:
#let add(a, b) = strong(text(red, [#(a+b)]))
```typ
#add(20, 40)
```
#add(20, 40)
][
#set text(18pt)
#grid(columns: (auto, auto),
gutter: 1em,
[Viele Möglichkeiten:
```typ
#let add(a, b) = strong(text(red, [#(a+b)]))
#add(20, 40)
```
oder mit `#str()` Zahlen zu Strings machen:
```typ
#let add(a, b) = strong(text(red, str(a+b)))
#add(20, 40)
```], align(top)[oder mit Klammern:
```typ
#let add(a, b) = {
let result = a+b
strong(text(red, str(result)))
}
#add(20, 40)
```
])
]
#new-section("Typst kann noch mehr!")
/*
- Bibliographie
- Figuren und Referenzen
- Dokumentation zeigen!!!
- Raytracing (https://github.com/elteammate)
*/
#slide(title: "Figuren und Referenzen" + slide-footnote(link("https://typst.app/docs/reference/meta/figure/")))[
#align(center, table(stroke: none,
columns: (auto),
align(left, text(size: 18pt, raw(lang: "typst",
```
@glacier shows a glacier. Glaciers
are complex systems.
#figure(
image("glacier.jpg", height: 80%),
caption: [A curious figure.],
) <glacier>
```.text) + v(1em))),
image(height: 50%, "img/figures_and_references.png")))
]
#slide(title: "Bibliographie" + slide-footnote(link("https://typst.app/docs/reference/meta/bibliography/")))[
#align(center, table(stroke: none,
columns: (auto, auto),
align(left)[#text(size: 14pt)[`works.bib`: ```bib
@article{netwok,
title={At-scale impact of the {Net Wok}: A culinarically holistic investigation of distributed dumplings},
author={<NAME> and <NAME>},
journal={Armenian Journal of Proceedings},
volume={61},
pages={192--219},
year={2020},
publisher={Automattic Inc.}
}
@article{arrgh,
title={The Pirate Organization},
author={<NAME>.},
}
```]],
align(left, text(size: 18pt, raw(lang: "typst",
```
This was already noted by
pirates long ago. @arrgh
Multiple sources say ...
#cite("arrgh", "netwok").
#bibliography("works.bib")
```.text) + v(1em))) +
image(height: 50%, "img/bibliography.png")))
]
#slide(title: "Raytracing")[
#image("img/raytracer.png")
Voll funktionsfähiger Raytracer für 3D-Rendering.#slide-footnote([Autor: ] + link("https://github.com/elteammate"))
]
#new-section("Abschluss und Weiteres")
#slide(title: [Was noch fehlt#slide-footnote(link("https://github.com/typst/typst/issues/712"))])[
- #strike[Fußnoten] (am 20.05.2023 mit v0.4.0 hinzugefügt)
- Paketmanager #text(size: 20pt, fill: rgb("#8a8a8a"))[(kurzfristige Alternative: GitHub)]
- StackOverflow #text(size: 20pt, fill: rgb("#8a8a8a"))[(kurzfristige Alternative: Discord)]
]
#slide(title: [Erwartete Neuerungen#slide-footnote(link("https://github.com/typst/typst/issues/712"))])[
#block[#align(top)[
- die komplette Überarbeitung der Layout-Engine
- Paketmanager
- Verbesserung des Mathe-Layouts
- HTML Output
- https://typst.app/docs/roadmap
]]
]
#slide(title: "Wer sollte Typst (nicht) benutzen?")[#box[#align(top)[
// Todo: ausbauen und kritische Auseinandersetzung mit Typst, Fragen erläutern:
/*
Warum sollte ich Typst benutzen, wenn doch eh überall LaTeX läuft?
- Henne-Ei-Problem
- Können wir uns nicht auch für neue Technologien begeistern, einfach weil wir sie cool finden? Wie soll sich irgendetwas jemals durchsetzen, wenn wir immer nur denken "Ja aber früher haben wir das anders gemacht."?
LaTeX hat viel mehr Pakete. Typst hat nichtmal TikZ.
- Alternativen: mit TikZ SVG generieren und in Typst einbingen, oder GraphViz benutzen
- https://github.com/johannes-wolf/typst-canvas als Grundbibliothek
Allgemein: Henne-Ei-Problem. Kann man nicht auch mal Dinge aus interesse machen? Können wir uns nichtmal auch einfach für neue technologien interessieren? Brauche ich die ganzen "Möglichkeiten", das LaTeX-Monster, wirklich?
*/
#set text(size: 20pt)
#set list(marker: text(fill: green, emoji.checkmark))
#underline[*Pros:*]
- #strong[steile] Lernkurve
- viele Programmierer-Ansätze, extrem einfach erweiterbar
- aktive Community
- schnelle Kompilierzeit
- online IDE
- verständliche Fehlermeldungen
#set list(marker: text(fill: red, [✗]))
#underline[*Cons:*]
- viele Programmierer-Ansätze
- komplexes Layouting (keine Floating Figures)
- Pure Functions können schwer sein (States, Counter, ...)
- bisher keine Unterstützung durch große Journals
- kein zentrales Paketmanagement
#emph[(Stand: 25.05.2023)]
]]]
#slide(title: "Weiteres")[
#set text(size: 18pt)
*Übrigens:* Diese gesamte Präsentation wurde alleine in Typst erstellt.
- Typst Dokumentation: https://typst.app/docs/
- Offizielles Typst-Tutorial: https://typst.app/docs/tutorial
- Offizieller Typst-Discord: https://discord.gg/2uDybryKPe
- Code für diese Präsentation und weitere Beipsiele: https://github.com/survari/typst-seminar
- Masterarbeit von <NAME> über Typst: https://www.user.tu-berlin.de/laurmaedje/programmable-markup-language-for-typesetting.pdf
- Masterarbeit von <NAME> über Typst: https://www.user.tu-berlin.de/mhaug/fast-typesetting-incremental-compilation.pdf
- Lambdas, States und Counter: https://typst.app/project/rpnqiqoQNfxXjHQmpJ81nF
- Liste mit Typst-Projekten: https://github.com/qjcg/awesome-typst
]
|
|
https://github.com/mdm/igotist | https://raw.githubusercontent.com/mdm/igotist/main/examples/test.typ | typst | #import "../igotist.typ"
#igotist.normalizecoordinates("a1", "1-1", "J8", (1, 1), "19-19", skip-i: true)
#let diagram = igotist.makediagram("diag1")
#igotist.addstones(diagram, "d16", "e16", color: white)
// #igotist.addlabels(diagram, "16-4", "4-16")
#igotist.addmarks(diagram, "16-4", "4-16")
#igotist.addmarks(diagram, "4-10", "3-10", type: "cross")
#igotist.addstones(diagram, "3-10", color: black)
#igotist.addmoves(diagram, "8-10", start: 1)
#igotist.addmoves(diagram, "10-10", start: 55)
#igotist.addmoves(diagram, "12-10", start: 253)
#igotist.showdiagram(diagram)
#context diagram.get().marks.first().keys() |
|
https://github.com/mariunaise/HDA-Thesis | https://raw.githubusercontent.com/mariunaise/HDA-Thesis/master/glossary.typ | typst | #import "@preview/glossarium:0.4.1": print-glossary
#counter(heading).update(0)
#heading(numbering: none)[Glossary]
#print-glossary((
(key: "hda", short: "HDA", plural: "HDAs", long: "helper data algorithm", longplural: "helper data algorithms"),
(key: "cdf", short: "CDF", plural: "CDFs", long: "cumulative distribution function", longplural: "cumulative distribution functions"),
(key: "ecdf", short: "eCDF", plural: "eCDFs", long: "empirical Cumulative Distribution Function", longplural: "empirical Cumulative Distribution Functions"),
(key: "ber", short: "BER", plural: "BERs", long: "bit error rate", longplural: "bit error rates"),
(key: "smhdt", short: "SMHD", plural: "SMHDs", long: "S-Metric Helper Data method"),
(key: "puf", short: "PUF", plural: "PUFs", long: "physical unclonable function", longplural: "physical unclonale functions"),
(key: "tmhdt", short: "TMHD", plural: "TMHDs", long: "Two Metric Helper Data method"),
(key: "bach", short: "BACH", long: "Boundary Adaptive Clustering with Helper data")
))
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/styling/set.typ | typst | // General tests for set.
--- set-instantiation-site ---
// Test that text is affected by instantiation-site bold.
#let x = [World]
Hello *#x*
--- set-instantiation-site-markup ---
// Test that lists are affected by correct indents.
#let fruit = [
- Apple
- Orange
#list(body-indent: 20pt)[Pear]
]
- Fruit
#[#set list(indent: 10pt)
#fruit]
- No more fruit
--- set-text-override ---
// Test that block spacing and text style are respected from
// the outside, but the more specific fill is respected.
#set par(spacing: 4pt)
#set text(style: "italic", fill: eastern)
#let x = [And the forest #parbreak() lay silent!]
#text(fill: forest, x)
--- set-scoped-in-code-block ---
// Test that scoping works as expected.
#{
if true {
set text(blue)
[Blue ]
}
[Not blue]
}
--- closure-path-resolve-in-layout-phase ---
// Test relative path resolving in layout phase.
#let choice = ("monkey.svg", "rhino.png", "tiger.jpg")
#set enum(numbering: n => {
let path = "/assets/images/" + choice.at(n - 1)
move(dy: -0.15em, image(path, width: 1em, height: 1em))
})
+ Monkey
+ Rhino
+ Tiger
--- set-if ---
// Test conditional set.
#show ref: it => {
set text(red) if it.target == <unknown>
"@" + str(it.target)
}
@hello from the @unknown
--- set-if-bad-type ---
// Error: 19-24 expected boolean, found integer
#set text(red) if 1 + 2
--- set-in-expr ---
// Error: 12-26 set is only allowed directly in code and content blocks
#{ let x = set text(blue) }
--- set-vs-construct-1 ---
// Ensure that constructor styles aren't passed down the tree.
// The inner list should have no extra indent.
#set par(leading: 2pt)
#list(body-indent: 20pt, [First], list[A][B])
--- set-vs-construct-2 ---
// Ensure that constructor styles win, but not over outer styles.
// The outer paragraph should be right-aligned,
// but the B should be center-aligned.
#set list(marker: [>])
#list(marker: [--])[
#rect(width: 2cm, fill: conifer, inset: 4pt, list[A])
]
--- set-vs-construct-3 ---
// The inner rectangle should also be yellow here.
// (and therefore invisible)
#[#set rect(fill: yellow);#text(1em, rect(inset: 5pt, rect()))]
--- set-vs-construct-4 ---
// The inner rectangle should not be yellow here.
A #box(rect(fill: yellow, inset: 5pt, rect())) B
--- show-set-vs-construct ---
// The constructor property should still work
// when there are recursive show rules.
#show enum: set text(blue)
#enum(numbering: "(a)", [A], enum[B])
|
|
https://github.com/ilsubyeega/circuits-dalaby | https://raw.githubusercontent.com/ilsubyeega/circuits-dalaby/master/Type%201/common.typ | typst | #let answer(text) = block(
fill: rgb(212, 224, 251),
inset: 12pt,
radius: 4pt,
above: 6pt,
text
) |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/cite-show-set_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#show cite: set text(red)
A @netwok @arrgh.
B #cite(<netwok>) #cite(<arrgh>).
#show bibliography: none
#bibliography("/assets/files/works.bib")
|
https://github.com/Fr4nk1inCs/typst-homework | https://raw.githubusercontent.com/Fr4nk1inCs/typst-homework/master/readme.md | markdown | MIT License | # Typst Homework
> I'm archiving this project since I've migrated it into [typreset](https://github.com/Fr4nk1inCs/typreset)
A simple template for homeworks in [Typst](https://typst.app).
|
https://github.com/retypejs/jscanny | https://raw.githubusercontent.com/retypejs/jscanny/main/README.md | markdown | MIT License | # jscanny
[](https://github.com/retypejs/jscanny/releases) [](https://github.com/retypejs/jscanny/tags) [](https://github.com/retypejs/jscanny/blob/main/LICENSE)
Painless string scanning.
A JavaScript/TypeScript rewrite of [`typst/unscanny`](https://github.com/typst/unscanny).
## Contributing
Feel free to open an [issue](https://github.com/retypejs/jscanny/issues) or create a [pull request](https://github.com/retypejs/jscanny/pulls)!
## Installation
```
npm install @retypejs/jscanny
```
## Usage
`jscanny` is published as a CommonJS (CJS) module that you can `require()` as well as an ECMAScript module (ESM) that you can `import`.
If you happen to encounter a "Could not find a declaration file for module '@retypejs/jscanny'. '/path/to/node_modules/@retypejs/jscanny/dist/cjs/src/index.js' implicitly has an 'any' type." error, try adding `"moduleResolution": "nodenext"` in the `tsconfig.json` file of your TypeScript project like so:
```json
{
"compilerOptions": {
"moduleResolution": "nodenext"
}
}
```
### CommonJS
```js
const { Scanner, Char } = require('@retypejs/jscanny');
const { None, Some, Option } = require('@retypejs/jscanny');
```
### ESM
```js
import { Scanner, Char } from '@retypejs/jscanny';
import { None, Some, Option } from '@retypejs/jscanny';
```
## Example
Recognizing and parsing a simple comma-separated list of floats.
```js
const s = new Scanner(' +12 , -15.3, 14.3 ');
let nums = [];
while (!s.done()) {
s.eatWhitespace();
let start = s.cursor;
s.eatIf(['+', '-']);
s.eatWhile(Char.isAsciiDigit);
s.eatIf('.');
s.eatWhile(Char.isAsciiDigit);
nums.push(parseFloat(s.from(start)));
s.eatWhitespace();
s.eatIf(',');
}
assert.deepEqual(nums, [12, -15.3, 14.3]);
```
## Testing
This JavaScript/TypeScript rewrite of [`unscanny`](https://github.com/typst/unscanny) passes the exact same tests as [`unscanny`](https://github.com/typst/unscanny) (compare [`jscanny/tests/scanner.test.ts`](https://github.com/retypejs/jscanny/blob/main/tests/scanner.test.ts) to the tests defined in [`unscanny/src/lib.rs`](https://github.com/typst/unscanny/blob/main/src/lib.rs)).
```sh
git clone https://github.com/retypejs/jscanny.git # Clone this repository
npm install # Install dependencies
npm run build # Compile TypeScript to JavaScript
npm run test # Run all tests
```
## License
[MIT](https://github.com/retypejs/jscanny/blob/main/LICENSE) © [<NAME>](https://github.com/bastienvoirin)
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/docs/blocky.typ | typst | Apache License 2.0 | /* This is X */
#let x /* ident */ = 1;
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/035_Core%202019.typ | typst | #import "@local/mtgset:0.1.0": conf
#show: doc => conf("Core 2019", doc)
#include "./035 - Core 2019/001_Chronicle of Bolas: The Twins.typ"
#include "./035 - Core 2019/002_Chronicle of Bolas: The First Lesson.typ"
#include "./035 - Core 2019/003_Chronicle of Bolas: Things Unseen.typ"
#include "./035 - Core 2019/004_Chronicle of Bolas: Whispers of Treachery.typ"
#include "./035 - Core 2019/005_Chronicle of Bolas: Blood and Fire.typ"
#include "./035 - Core 2019/006_Chronicle of Bolas: A Familiar Stranger.typ"
#include "./035 - Core 2019/007_Chronicle of Bolas: Perspectives.typ"
#include "./035 - Core 2019/008_Chronicle of Bolas: The Unwritten Now.typ"
#include "./035 - Core 2019/009_Unbowed, Part 1.typ"
#include "./035 - Core 2019/010_Unbowed, Part 2.typ"
#include "./035 - Core 2019/011_Unbowed, Part 3.typ"
|
|
https://github.com/benjamineeckh/kul-typst-template | https://raw.githubusercontent.com/benjamineeckh/kul-typst-template/main/tests/test-work/test2.typ | typst | MIT License | #import "@preview/hydra:0.5.1": hydra
#let hydra-settings = context {
if calc.odd(here().page()) {
let headings = query(selector(heading).before(here()))
let entry = hydra(skip-starting:true, 1)
if entry != none{
align(left, emph(entry))
v(-0.8em)
line(length: 100%)
}
} else {
let entry = hydra(skip-starting:true, 2)
if entry != none{
align(right, emph(entry))
v(-0.8em)
line(length: 100%)
}
}
}
#set page(paper: "a7", margin: (top: 2em), numbering: "1", header: hydra-settings)
#show heading.where(level: 1): it => {
pagebreak(weak: true, to: "odd")
v(1em)
it
}
= main header
#lorem(20)
== a subheader
#lorem(150)
= a NEW heading
aaa
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Reading/跟李沐学AI(论文)/Transformer.typ | typst | // ---
// order: 4
// ---
#import "/src/components/TypstTemplate/lib.typ": *
#show: project.with(
title: "d2l_paper",
lang: "zh",
)
#let softmax = math.op("softmax")
#let QKV = $Q K V$
#let qkv = QKV
#let Concat = math.op("Concat")
#let MultiHead = math.op("MultiHead")
#let Attention = math.op("Attention")
#let head = $"head"$
#let dm = $d_"model"$
#let FFN = math.op("FFN")
= Attention is All You Need
- 时间:2017.6
== 创新点
#grid(
columns: 2,
grid.cell(align: left)[
- seq2seq 模型一般使用 encoder-decoder 结构,过去的一些工作使用 CNN 和 RNN 辅以 seq2seq 模型,而 Transformer 模型则完全基于 attention 机制,并且效果很好。另外,自注意力机制很重要,但并不是本文第一次提出
- 卷积好的地方在于可以做多个输出通道,每个输出通道认为是识别一种特定的模式。Transformer 吸收这一思想而提出 multi-head 概念
- 可以看到,Tranformer 的特点在于并行度高但计算消耗大
],
fig("/public/assets/Reading/limu_paper/Transformer/img-2024-09-16-23-42-29.png")
)
== 模型结构
- 总体模型架构
#grid2(
fig("/public/assets/Reading/limu_paper/Transformer/img-2024-09-16-23-42-29.png.png"),
fig("/public/assets/Reading/limu_paper/Transformer/2024-09-19-11-34-06.png"),
)
- 左边是编码器右边是解码器,解码器之前的输出作为当前的输入(所以这里最下面写的是output)
- Nx 表示由 $N$ 个 Block 构成,字面意思上的堆叠,最后一层 encoder 的输出将会作为每一层 decoder 的输入
- 一共有三种 Attention,但区别之在于输入 #qkv 来源以及 Attention score 是否采用掩码
- 具体注意力的计算,一般有两种做法,一种是如果 #qkv 长度不同可以用 addictive attention(可学参数较多);另一种是如果长度相同可以用 scaled dot-product attention
=== 形状解释与步骤细分
#grid2(
fig("/public/assets/Reading/limu_paper/Transformer/img-2024-09-16-23-55-54.png"),
fig("/public/assets/Reading/limu_paper/Transformer/img-2024-09-16-23-56-14.png")
)
- 首先是 Q K V 的形状
$
Q: RR^(n times d_k), K: RR^(m times d_k), V: RR^(m times d_v)
$
$K, V$ 个数成配对,$Q, K$ 长度都为 $d_k$ 允许 scaled dot-product attention。
- 对单个注意力头而言,经过
$
Attention(Q, K, V) = softmax((Q K^T) / sqrt(d_k))V
$
中间 $Q, K$ 得到形状为 $n times m$ 的矩阵,表示 $n$ 个 query 对 $m$ 个 key 的相似度,经过 (masked) softmax 后与 $V$ 相乘,得到了 $n times d_v$ 的输出,也即对每个 query,我们都得到了 $V$ 的某种加权平均。这里除以 $sqrt(d_k)$ 的原因是:算出来的权重差距较大,经过 softmax 后 $1, 0$ 差距悬殊,采用这个数字从实践上刚好适合。
- 对多头注意力而言
$
MultiHead(Q, K, V) = Concat(head_1, head_2, ..., head_h)W^O \
"where" head_i = Attention(Q W_i^Q, K W_i^K, V W_i^V)
$
令 $h=8$ 也就是有 8 个头,论文中 $dm=512$ 指的是多头拼接后的向量长度,于是 $d_k = d_v = dm \/ h = 64$,每次我们把 #QKV 经过 Linear 从 $512$ 变为 $64$,然后再在最后一维 concat 起来,最后再经过一个 Linear 从 $512$ 到 $512$。实际上点积型 attention 的注意力层可学的参数就在 Linear 中,我们希望将它分出 $h$ 个通道让它在不同的语义空间上学习不同的模式。
- 然后是 Position-wise Feed-Forward Networks
$
FFN(x) = max(0, x W_1 + b_1)W_2 + b_2
$
#grid(
columns: 2,
[
经过(自或交叉)注意力后,再经过 concat 和 Linear 后将通道融合得到 $n times dm$ 的输出,随后经过两层全连接层,从 $dm$ 到 $d_(f f)=2048$,再从 $d_(f f)$ 到 $dm$。这里的 Position-wise 的是说,每个样本用的是同一个 MLP(而不是真的全连接)。可以这么想:通过注意力层学到了不同 query 的语义特征(汇聚所有我感兴趣的信息),然后用同一个 MLP 将它们做变换(但 query 之间不能融合)来减少参数量并一定程度有助于泛化
],
fig("/public/assets/Reading/limu_paper/Transformer/img-2024-09-17-00-47-10.png")
)
当然上图是训练的时候($n$ 个 query 并行),测试的时候则是一个个来,但依旧是同一个 MLP,有点像 RNN
=== Batch Norm & Layer Norm
- BatchNorm,在train的时候,一般是取小批量里的均值和方差,在预测的时候用的是全局的均值和方差。#link("https://zhuanlan.zhihu.com/p/24810318")[什么是批标准化 (Batch Normalization) - 知乎]
- 在输入为变长的情况下我们不使用 BatchNorm,而是使用 LayerNorm
#fig("/public/assets/Reading/limu_paper/Transformer/2024-09-19-11-45-41.png")
- 一个简单的记法:xxx-norm 就是按 xxx 方向进行归一化,或者说按 xxx 方向切,还可以说是不分解 xxx。对于二维和三维的 xxx-norm 都是适用的。
- 以 batch-norm 为例,二维就是顺着 batch 方向切,即纵切;三维需要注意,一定保留了序列方向不被分解,再结合按照 batch 方向切,就得出了蓝色框切法
- 而 Layer-norm 顺着 Layer 的方向,在这里就是 seq 方向切,即横切
#fig("/public/assets/Reading/limu_paper/Transformer/2024-09-19-12-11-20.png")
- 但事实上好像这种理解还是有问题,似乎文本的 LN 是一行而不是一个面
- 关于 BN 和 LN 以及它们的代码可以参考 #link("https://zhuanlan.zhihu.com/p/656647661")[对比pytorch中的BatchNorm和LayerNorm层]
文本中的 LayerNorm 本质上是一种 InstanceNorm
== (李沐版)代码实现的一些细节
- 论文里没有代码,不过有开源,但不看那个,看得是李沐的版本
- 之前以为多头注意力就是一个 attention 里有多个 attention,但其实多头还是一个整体大的 attention,然后在里面把 $d$ 拆分成多个。之所以可以这样写是因为分数计算使用的是 DotProductAttention,这个是 $Q K$直接做内积,不需要学习参数。所以代码本质还是使用一个 attention,只不过因为每个 attention 本质都一样,所以可以并行计算。本质上就是重用batch这一维的并行性来做多头的同时计算
- 具体来说:输入是 $b,n,d$,把它拆分成$b,n,h,d_i$,permute 成 $b,h,n,d_i$,再融合前两维成 $b h,n,d_i$。这样送进 attention 模块使得它并没感知到输入被分头了。最后将输出做逆操作回去就行了
- Encoder 按下不表,而 Decoder 部分相对复杂
- 训练阶段,输出序列的所有 token 在同一时间处理,但在算 softmax 的时候使用 mask,因此 `key_values` 等于完整的 `X`,然后需要做 `dec_valid_lens`
- 预测阶段,输出序列是一句话内一个一个 token 处理的,输入 `X` 的 shape 为$(b, n_t, d)$,其 $n$ 是变化的,`key_values` 通过 concat 包含直到当前时间步 $t$ 为止第 $i$ 个 decoder 块的输出表示
- 这里多多少少有点体现出 Transformer 对于变长数据的灵活性
- 我们利用 `state` 三元组来传输块与块之间 enc 与 dec 之间的数据,分别保存:encoder 输出,encoder 输出的有效长度以及每个 decoder 块的输出表示
```python
class DecoderBlock(nn.Module):
# ...
def forward(self, X, state):
enc_outputs, enc_valid_lens = state[0], state[1]
if state[2][self.i] is None:
key_values = X
else:
key_values = torch.cat((state[2][self.i], X), axis=1)
state[2][self.i] = key_values
if self.training:
batch_size, num_steps, _ = X.shape
# dec_valid_lens的形状:(batch_size,num_steps),
# 其中每一行是[1,2,...,num_steps]
dec_valid_lens = torch.arange(
1, num_steps + 1, device=X.device).repeat(batch_size, 1)
else:
dec_valid_lens = None
```
- |
|
https://github.com/LilNick0101/Bachelor-thesis | https://raw.githubusercontent.com/LilNick0101/Bachelor-thesis/main/content/coding.typ | typst | #pagebreak()
= Codifica
In questo capitolo vengono descritte come le varie parti dell'architettura sono state codificate nel progetto e il funzionamento delle singole schermate dell'applicazione.
== Interfaccia grafica
Durante la codifica sono stato in grado di utilizzare gli strumenti offerti dal toolkit UI *Jetpack Compose* per creare l'interfaccia grafica dell'applicazione, in particolare in _Compose_ ogni elemento dell'interfaccia grafica è rappresentato da un *Composable*, cioè una funzione _Kotlin_ annotata con l'annotazione `@Composable` che consente anche di codificare nuovi _Composable_; questi componenti rappresentano elementi dell'interfaccia grafica, come per esempio pulsanti, testi o immagini, oppure elementi di layout come colonne o righe.
Per lo stile dei _Composable_ ho usato _Material Design 3_ dato che _Jetpack Compose_ fornisce un'implementazione immediata di _Material Design 3_ e dei suoi elementi UI; lo stile dei _Composable_ può essere cambiato passando dei parametri alle funzioni _Composable_ (per esempio, font del testo, forma o colore).
Un modo per modificare l'aspetto e il comportamento di un _Composable_ è passargli un `Modifier`, utile per modificare le dimensioni, il layout, il comportamento, l'aspetto e per elaborare l'input utente.
Le destinazioni dei schermi sono state implementate usando una libreria esterna che permette di definire le destinazioni tramite funzioni annotate con l'annotazione `@Destination` (vedi #link(label("navigation-destination"),[Destinazione di navigazione]) nell'appendice) e sono usate per navigare tra le schermate dell'applicazione: per esempio quando si vuole passare dalla schermata della lista dei luoghi alla schermata del dettaglio di un luogo, si usa la funzione `navigate` che, quando un luogo viene selezionato dalla lista, prende come parametro l'identificatore del luogo selezionato.
In queste destinazioni viene estratto lo stato dell'interfaccia dal _ViewModel_ e lo viene fatto passare alla schermata di destinazione, che sarà un _Composable_, inoltre vengono impostate le funzioni del _ViewModel_ da invocare in risposta del input utente.
Il punto d'inizio dell'applicazione è la classe `MainActivity` (vedi #link(label("main-activity"),[MainActivity]) nell'appendice), una classe che estende `ComponentActivity` e possiede un ciclo di vita associato al ciclo di vita dell'applicazione (per esempio quando si fa partire l'applicazione o viene messa in background). Nel progetto ho dovuto semplicemente implementare la funzione `onCreate` che viene chiamata quando viene creato il processo dell'applicazione e redirige l'utente verso la destinazione iniziale, in questo caso la lista dei luoghi.
== Classi ViewModel
Per le classi *ViewModel* ho creato delle classi che ereditano dalla classe _ViewModel_ del framework di _Android_ (vedi #link(label("view-model"),[Classi ViewModel]) nell'appendice), una classe _ViewModel_ per schermata.
Il ciclo di vita di queste classi è gestito dal framework stesso e una caratteristica delle classi _ViewModel_ è che rappresentano dei titolari di stato della schermata a cui sono associati: lo stato della schermata, infatti, viene codificato in un oggetto che ogni volta che subisce una modifica, aggiorna la schermata riflettendo la modifica.
Usando _Hilt_, sono stato in grado di iniettare le dipendenze all'interno dei _ViewModel_, che possono essere repository o classi _UseCase_ se richiesto: per esempio il _ViewModel_ della schermata di visualizzazione del dettaglio di un luogo ha bisogno del repository dei luoghi e del repository degli utenti, allora viene creata una classe _UseCase_ (vedi #link(label("use-case"),[Classi UseCase]) nell'appendice) che contiene i due repository iniettati (tramite _Hilt_): la caratteristica principale delle classi _UseCase_ è che contengono una sola funzione che viene poi invocata nel _ViewModel_.
== Sorgenti dati
Per la gestione e la persistenza dei dati come già scritto l'applicazione usufruisce di due sorgenti dati, quella locale e quella remota:
- Il *database locale*, la fonte di riferimento principale implementata utilizzando _Room_: innanzitutto ho creato una classe di database (#link(label("database-class"),[Classe Database]) nell'appendice) che crea il database, se non esiste già, ed offre dei metodi per ottenere i DAO (Vedi #link(label("room-dao"),[Interfacce DAO]) nell'appendice) per ogni tipo di risorsa dati (luoghi, utenti ...), ogni DAO offre dei metodi per ottenere, inserire, aggiornare e cancellare elementi del database; ogni metodo dei DAO è annotato con l'annotazione `@Insert` o `@Update` o `@Delete` o `@Query`: queste annotazioni sono usate da _Room_ per generare il codice necessario per eseguire le query al database. I dati vengono salvati e ritornati come oggetti immutabili.
- La comunicazione alla sorgente dati *remota* viene effettuata tramite _Ktor_: per ogni tipo di risorsa dati (luoghi, utenti ...) ho creato una classe che si occupa di caricare e di ottenere dati per quella risorsa (Vedi #link(label("api-classes"),[Classi API]) nell'appendice), le risposte sono in JSON e vengono deserializzate in oggetti _Kotlin_ usando la libreria *Kotlinx.serialization*, libreria che viene usata anche per serializzare oggetti _Kotlin_ in JSON per l'invio di dati. Le risposte possono essere:
- `200`: la risposta contiene i dati richiesti;
- `201`: L'utente ha creato nuovi dati con successo;
- `422`: la risposta contiene un messaggio di errore a causa di un errore di validazione dei dati, l'utente deve correggere i dati e riprovare;
- `404`: la risposta contiene un messaggio di errore da parte del client, può essere causato da un errore di connessione.
Entrambe le sorgenti dati vengono iniettate nei repository tramite _Hilt_: per esempio nel repository dei luoghi ho iniettato il DAO dei luoghi, che consente di accedere ai luoghi nel database locale, e la classe API, che si occupa di caricare i luoghi dalla sorgente dati remota.
#figure(
image("../resources/images/grafico-repo.png", width: 60%),
caption: [Relazione tra repository e sorgenti dati.]
) <repository>
== Autenticazione utenti
Per quanto riguarda l'autenticazione utenti mi sono servito di *AWS Cognito*: quando un utente accede con il suo account, gli viene conferito un token segreto con il quale è in grado di accedere al suo profilo, di caricare nuovi luoghi o recensioni e di salvare nuovi luoghi nel proprio account; questo token viene allegato nel header della richiesta HTTP, se non è un token valido allora la richiesta ritorna ```401 unauthorized```.
== Schermate applicazione
In seguito, descriverò più in dettaglio il funzionamento delle singole schermate dell'applicazione.
#include "./AppOverview.typ"
== Repository codice
Il codice dell'applicazione è stato caricato su un repository *Bitbucket* aziendale.
Per la gestione dei _branch_ si è utilizzato un _gitflow_ standard: ogni funzionalità è stata sviluppata su un ramo di sviluppo separato.
Quando una funzionalità veniva considerata finita, veniva aperta una _Pull request_, nella quale il codice veniva controllato dai colleghi in azienda, e dopo che la _Pull request_ veniva approvata, si passava al merge con il ramo di sviluppo principale.
= Validazione
Alla fine del tirocinio le funzionalità che effettivamente sono state codificate sono:
- *F1*: Lista dei luoghi (con funzione di ordinamento e filtraggio);
- *F2*: Mappa dei luoghi (con funzione di filtraggio);
- *F3*: Visualizzazione in dettaglio di un luogo;
- *F4*: Caricamento di un luogo;
- *F5*: Pagina di login;
- *F6*: Pagina del profilo utente, con lista dei luoghi caricati e dei luoghi salvati.
Per mancanza di tempo è stato deciso di tralasciare le seguenti funzionalità che erano state pianificate:
- *F7*: Registrazione di un nuovo account;
- *F8*: Lista delle recensioni di un luogo;
- *F9*: Caricamento di una nuova recensione di un luogo.
#pagebreak()
== Requisiti soddisfati
In conclusione, alla codifica sono stati soddisfatti i seguenti requisiti (per vedere la tabella dei requisiti soddisfatti, vedi #link(label("requisiti-soddisfatti"),[Tabella requisiti soddisfatti]) nell'appendice):
- Per la *lista dei luoghi* tutti i requisiti sono stati soddisfatti: un utente può visualizzare la lista dei luoghi, selezionare un luogo dalla lista per vederne i dettagli, ordinare la lista dei luoghi per distanza, valutazione o data di caricamento e filtrare la lista dei luoghi per caratteristiche, per prezzo, per nome o per orario di apertura;
- Per la *mappa dei luoghi* tutti i requisiti sono stati soddisfatti: un utente può visualizzare la mappa dei luoghi, selezionare un luogo dalla mappa per vederne i dettagli e filtrare la mappa dei luoghi come per la lista dei luoghi (ma non di ordinarla);
- Per la *visualizzazione in dettaglio di un luogo* tutti i requisiti sono stati soddisfatti: un utente può visualizzare le informazioni in dettaglio di un luogo, cioè la posizione geografica, le caratteristiche di un luogo, gli orari di apertura, i contatti, le immagini di un luogo e il numero di recensioni;
- Nella *lista dei luoghi*, nella *mappa dei luoghi* e nella *visualizzazione in dettaglio di un luogo*, se l'utente è registrato, è possibile salvare un luogo nei preferiti o rimuovere un luogo già salvato dai preferiti;
- Per il *caricamento di un luogo* tutti i requisiti sono stati soddisfatti: un utente registrato può caricare un nuovo luogo, inserendo il nome del luogo, la posizione geografica del luogo, i contatti del luogo, una descrizione del luogo, gli orari di apertura del luogo e una o più immagini del luogo;
- Per la *pagina di login* un ospite può accedere solo con un account _Google_, dato che non è stata implementata la funzionalità di registrazione di un nuovo account;
- Per la *pagina del profilo utente* un utente registrato può visualizzare il suo profilo utente, visualizzare i suoi dati personali, visualizzare la lista dei luoghi preferiti salvati, visualizzare la lista dei luoghi caricati da lui e di effettuare il logout;
- I *requisiti di vincolo* sono stati soddisfatti tutti eccetto che le componenti sviluppate non sono state documentate per mancanza di tempo;
- I *requisiti di qualità* sono stati soddisfatti tutti.
== Requisiti non soddisfatti
I seguenti requisiti non sono stati soddisfatti:
- La funzionalità di *registrazione di un nuovo account* non è stata implementata: un ospite non può creare un nuovo account, ma può accedere solo usando un account _Google_; //Fa ridere ma è così
- La funzionalità di *visualizzazione della lista delle recensioni di un luogo* non è stata implementata: un utente non può visualizzare la lista delle recensioni di un luogo;
- La funzionalità di *caricamento di una nuova recensione* di un luogo non è stata implementata: un utente registrato non può caricare una nuova recensione di un luogo;
- L'unico *requisito di vincolo* non soddisfatto è che le componenti sviluppate non sono state documentate per mancanza di tempo.
== Riepilogo requisiti
#figure(
table(
columns: (1fr, 1fr, 1fr, 1fr),
align: horizon,
[*Tipo di requisito*], [*Sodisfatti*], [*Totali*], [*Percentuale*],
[Funzionali], [41], [49], [83.67%],
[Vincolo], [3], [4], [75%],
[Qualità], [3], [3], [100%],
[Totali], [47], [56], [83.92%],
),
caption: [Riepilogo requisiti soddisfatti dopo la codifica.]
)
Tutti requisiti di qualità sono stati soddisfatti, mentre alcuni requisiti funzionali e di vincolo non sono stati soddisfatti; In totale sono stati soddisfatti più dell'80% dei requisiti totali.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/space-03.typ | typst | Other | // Test font change after space.
Left #text(font: "IBM Plex Serif")[Right].
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/edu/seminars/2024-10-09.typ | typst | = Техники организации обучения в онлайн и оффлайн средах
== В оффлайн среде
*Что важно учитывать?*
- Есть ли нужное оборудование, есть ли к нему доступ?o
- Подходит ли расстановка мебели
*Варианты организации парт:*
- *Классическая рассадка*:
Подходящие форматы:
- Лекция
- Контрольные
- *Рассадка кластерами*:
Подходящие форматы:
- Групповая работа
- Дебаты
- Проектные задания
- *Рассадка полукругом*:
Подходящие форматы:
- Обсуждение проектов/ докладов
- Дискуссия
- Групповая рефлексия
Кабинет должен работать на достижение образовательного результата
*Note*: рассадка сама ничего не сделает, она только способствует
образовательному процессу
*Что важно в оффлайн уроке?*
- Четкая структура изложения
- Наличие примеров
- Контакт с классом
- Доброжелательная атмосфера
- Качество речи
- Движения, жесты
== В онлайн среде
*Что важно учитывать?*
- Закладывать время на технические неполадки
- Убедиться в наличии доступа к онлайн платформе (у себя и у учеников)
*Что важно в онлайн уроке?*
- Четкие инструкции
- Качество видео, аудио
Онлайн сильно ограничивает в возможностях
== Смешанное обучение
Хорошо работает на гуманитарных дисциплинах
== Технология "ротация станций"
- Есть несколько "станций":
- онлайн обучение (индивидуально на компьютере)
- фрональная работа с учителем
- работа в группе (коллективный проект)
- За занятие (пару) каждый ученик проходит все три станции
- Класс разделяется на несколько групп по уровню (с каждой группой можно
работать по-разному)
Преимущества:
- Повышение учебной мотивации
- Повышение учебных результатов
- Разный уровень сложности для разных учеников
Часть организационной части можно возложить на тьютора (особенно актуально для
младших классов)
== Технология "перевернутый класс"
Ученики теорию проходят дома, а отрабатывают на уроке с учителем.
*Зачем нужно?*
- Ученики имеют разный темп освоения
- Больше времени на уроке
- Разный темп
Уровни запоминания и понимания уходят на дом
*Что нужно для осуществления? Основные шаги:*
- Составить план
- Сделать видеозапись
- Поделиться материалом
- Обсудить материал
- Использовать групповые активности
- Сбор обратной связи
== Техника "Проектное обучение"
Студенты обучаются в процессе выполнения некоторого проекта от начала и до конца
*Ключевые принципы*:
- Конструктивистский подход
- Релевантный контекст
- Совместное обучение
- Самостоятельность
*Виды проектов*:
- *Условные проекты*: проект "ни для кого" (то есть нет заказчика)
- *Реалистичный проект*: проект, близкий к реальному; например, прототип
- *Реальный проект*
*Минусы*:
- Требует много времени и усилий
- Сложность управления
- Неспособность покрыть всю программу
|
|
https://github.com/Skimmeroni/Appunti | https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Metodi%20Algebrici/Strutture/Generatori.typ | typst | Creative Commons Zero v1.0 Universal | #import "../Metodi_defs.typ": *
Sia $(G, *)$ un gruppo e sia $n$ un numero intero. Viene detta *potenza
n-esima* di $g$ l'elemento $g^(n) in G$ ottenuto ricorsivamente nel seguente
modo:
$ g^(n) = cases(
1_(*) & "se" n = 0,
g^(n - 1) * g & "se" n > 0,
(g^(-1))^(-n) & "se" n < 0
) $
#example[
- Si consideri il gruppo $(ZZ, +)$. Ricordando che, in questo caso,
$1_(+) = 0$, l'elemento $3^(4)$ di $ZZ$ viene calcolato come:
$ 3^(4) = 3^(3) + 3 = 3^(2) + 3 + 3 =
3^(1) + 3 + 3 + 3 = 3^(0) + 3 + 3 + 3 + 3 = 0 + 3 + 3 + 3 + 3 = 12 $
- Si consideri il gruppo $(ZZ_(7), +)$. Ricordando che, in questo
caso, $1_(+) = [0]_(7)$, l'elemento $([4]_(7))^(4)$ di $ZZ_(7)$
viene calcolato come:
$ ([4]_(7))^(4) = ([4]_(7))^(3) + [4]_(7) = ([4]_(7))^(2) + [4]_(7) +
[4]_(7) = ([4]_(7))^(1) + [4]_(7) + [4]_(7) + [4]_(7) = \
([4]_(7))^(0) + [4]_(7) + [4]_(7) + [4]_(7) + [4]_(7) =
[0]_(7) + [4]_(7) + [4]_(7) + [4]_(7) + [4]_(7) = [16]_(7) =
[2]_(7) $
- Si consideri il gruppo $(QQ - {0}, dot)$. Ricordando che, in questo
caso, $1_(dot) = 1$, l'elemento $(frac(3, 2))^4$ di $QQ - {0}$
viene calcolato come:
$ (frac(3, 2))^(4) = (frac(3, 2))^(3) dot frac(3, 2) = (frac(3, 2))^(2)
dot frac(3, 2) dot frac(3, 2) = (frac(3, 2))^(1) dot frac(3, 2) dot
frac(3, 2) dot frac(3, 2) = (frac(3, 2))^(0) dot frac(3, 2) dot
frac(3, 2) dot frac(3, 2) dot frac(3, 2) = 1 dot frac(3, 2) dot
frac(3, 2) dot frac(3, 2) dot frac(3, 2) = frac(81, 16) $
]
#lemma[
Sia $(G, *)$ un gruppo e siano $m$ e $n$ due numeri naturali. Per un
qualsiasi $g in G$, valgono:
#grid(
columns: (0.5fr, 0.5fr),
[$ g^(m) * g^(n) = g^(m + n) $],
[$ (g^(m))^(n) = g^(m dot n) $]
)
]
// #proof[
// Dimostrabile, da aggiungere
// ]
Dato un gruppo $(G, *)$ e scelto $g in G$ si definisce *sottogruppo
ciclico generato da* g il sottogruppo di $(G, *)$ cosí definito:
$ (angle.l g angle.r, *) space "dove" space angle.l g angle.r =
{g^(n): n in ZZ} $
#example[
- Si consideri il gruppo $(ZZ^(+), dot)$. Si ha $angle.l 3 angle.r
= {3^(n) : n in ZZ} = {1, 3, 9, 27, 81, ...} subset.eq ZZ^(+)$;
- Si consideri il gruppo $(ZZ_(5), +)$. Si ha $angle.l [3]_(5) angle.r
= {([3]_(5))^(n) : n in ZZ} = {[0]_(5), [3]_(5), [1]_(5), [4]_(5),
[2]_(5), ...} subset.eq ZZ_(5)$;
- Si consideri il gruppo $(RR, +)$. Si ha $angle.l pi angle.r
= {pi^(n) : n in ZZ} = {0, pi, 2 pi, 3 pi, 4 pi, ...} subset.eq RR$.
]
#lemma[
Dato un gruppo $(G, *)$ e scelto $g in G$, il sottogruppo
$(angle.l g angle.r, *)$ di $(G, *)$ é abeliano.
]
#lemma[
Sia $(G, *)$ un gruppo e sia $(H, *)$ un suo sottogruppo.
Se $H$ contiene $g in G$, allora contiene anche $angle.l
g angle.r$.
]
#proof[
Innanzitutto, si noti come $g^(0) = 1_(*)$ sia certamente membro
di $H$ per per definizione di sottogruppo. Sempre per definizione
di sottogruppo, per qualsiasi $h, k in H$ vale $h * k in H$.
Essendo $g in H$ per ipotesi, certamente vale $g * g in H$, ma
$g * g = g^(2)$. Allo stesso modo, se $g^(2) in H$, allora $g^(2)
* g in H$, ma $g^(2) * g = g^(3)$, e via dicendo. Si ha quindi per
induzione che $H$ contiene $angle.l g angle.r = {g^(n): n in ZZ}$.
]
Un gruppo $(G, *)$ si dice *ciclico* se esiste $g in G$ tale per cui
$angle.l g angle.r = G$.
#example[
- Il gruppo $(ZZ, +)$ é ciclico. Infatti, $angle.l 1 angle.r
= {0, -1, 1, -2, 2, -3, 3, ...} = ZZ$;
- Il gruppo $(ZZ_(n), +)$ con $n in NN$ é ciclico. Infatti,
$angle.l [1]_(n) angle.r = {[0]_(n), [1]_(n), ..., [n - 1]_(n),
[0]_(n), [1]_(n), ...} = ZZ_(n)$;
]
Dato un gruppo $(G, *)$ e scelto $g in G$, la cardinalitá di $angle.l g
angle.r$ prende il nome di *ordine* o di *periodo* di $g$, e viene indicata
con $o(g)$. Se $o(g)$ é infinito, si dice che $g$ é _di ordine_ (_di periodo_)
infinito, altrimenti si dice che é _di ordine_ (_di periodo_) finito.
#theorem[
Sia $(G, *)$ un gruppo e sia $g$ un suo elemento. Se esiste un numero
intero positivo $m$ tale per cui $g^(m) = 1_(*)$, allora $angle.l g
angle.r$ é un insieme finito, e l'ordine di $g$ coincide con il piú
piccolo di questi $m$. Se non esiste alcun $m$ con queste caratteristiche,
allora $angle.l g angle.r$ é un insieme infinito.
]
// #proof[
// Dimostrabile, da aggiungere
// ]
#example[
#set math.mat(delim: none)
- Il gruppo $(ZZ, +)$ ha un solo elemento con ordine finito. Tale
elemento é $0$, il cui ordine é $1$, in quanto $angle.l 0 angle.r
= {0, 0, 0 + 0, 0 + 0 + 0, ...} = {0, 0, 0, 0, ...} = {0}$;
- Il gruppo $(QQ - {0}, dot)$ ha due soli elementi con ordine finito.
Tali elementi sono $1$ e $-1$, rispettivamente di ordine $1$ e $2$.
Infatti:
$ mat(angle.l 1 angle.r &= {1, 1, 1 dot 1, 1 dot 1 dot 1, ...} =
{1, 1, 1, 1, ...} = {1};
angle.l -1 angle.r &= {1, (-1), (-1) dot (-1), (-1) dot (-1) dot
(-1), ...} = {1, -1, 1, -1, ...} = {1, -1}) $
- Il gruppo $(ZZ_(6), +)$ é interamente costituito da elementi con ordine
finito. Infatti:
$ mat(
o([0]_(6)) &=
abs({[0]_(6)\, [0]_(6)\, [0]_(6) + [0]_(6)\, [0]_(6) + [0]_(6) + [0]_(6)\, ...}) =
abs({[0]_(6)}) = 1;
o([1]_(6)) &=
abs({[0]_(6)\, [1]_(6)\, [1]_(6) + [1]_(6)\, [1]_(6) + [1]_(6) + [1]_(6)\, ...}) =
abs({[0]_(6)\, [1]_(6)\, [2]_(6)\, [3]_(6)\, [4]_(6)\, [5]_(6)}) = 6;
o([2]_(6)) &=
abs({[0]_(6)\, [2]_(6)\, [2]_(6) + [2]_(6)\, [2]_(6) + [2]_(6) + [2]_(6)\, ...}) =
abs({[0]_(6)\, [2]_(6)\, [4]_(6)}) = 3;
o([3]_(6)) &=
abs({[0]_(6)\, [3]_(6)\, [3]_(6) + [3]_(6)\, [3]_(6) + [3]_(6) + [3]_(6)\, ...}) =
abs({[0]_(6)\, [3]_(6)}) = 2;
o([4]_(6)) &=
abs({[0]_(6)\, [4]_(6)\, [4]_(6) + [4]_(6)\, [4]_(6) + [4]_(6) + [4]_(6)\, ...}) =
abs({[0]_(6)\, [2]_(6)\, [4]_(6)}) = 3;
o([5]_(6)) &=
abs({[0]_(6)\, [5]_(6)\, [5]_(6) + [5]_(6)\, [5]_(6) + [5]_(6) + [5]_(6)\, ...}) =
abs({[0]_(6)\, [1]_(6)\, [2]_(6)\, [3]_(6)\, [4]_(6)\, [5]_(6)}) = 6
) $
]
#lemma[
Per ogni gruppo $(G, *)$, l'unico elemento che ha ordine $1$ é $1_(*)$.
]
#theorem[
Nel gruppo simmetrico $(S_(n), compose)$, un ciclo di lunghezza $r$
ha ordine $r$. Piú in generale, una permutazione $f$ del gruppo
simmetrico $(S_(n), compose)$ che sia prodotto di $t$ cicli disgiunti
di lunghezza $r_(1), r_(2), dots, r_(t)$ ha per ordine il minimo comune
multiplo di $r_(1), r_(2), dots, r_(t)$.
]
Sia $(G, *)$ un gruppo e sia $S subset.eq G$. Il sottogruppo di $(G, *)$
che contiene $(S, *)$ e che sia contenuto in ogni sottogruppo di $(G, *)$
contenente $(S, *)$ prende il nome di *sottogruppo generato da* $S$ e si
indica con $angle.l S angle.r$:
$ angle.l S angle.r = sect.big_(H lt.eq G, S subset.eq H) H $
Nel caso particolare in cui $S$ sia costituito da un solo elemento,
il sottogruppo generato da $S$ coincide con il sottogruppo _ciclico_
generato da $S$.
#theorem[
Sia $(G, *)$ un gruppo e sia $S subset.eq G$. Il sottogruppo
generato da $S$ puó essere scritto come:
$ angle.l S angle.r = {product_(i = 1)^(n) s_(i)^(epsilon_(i)):
s_(i) in S, epsilon_(i) = plus.minus 1, n in NN} $
]
// #proof[
// Dimostrabile, da aggiungere
// ]
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/114.%20ramenprofitable.html.typ | typst | ramenprofitable.html
Ramen Profitable
Want to start a startup? Get funded by
Y Combinator.
July 2009Now that the term "ramen profitable" has become widespread, I ought
to explain precisely what the idea entails.Ramen profitable means a startup makes just enough to pay the
founders' living expenses. This is a different form of profitability
than startups have traditionally aimed for. Traditional profitability
means a big bet is finally paying off, whereas the main importance
of ramen profitability is that it buys you time.
[1]In the past, a startup would usually become profitable only
after raising and spending quite a lot of money. A company making
computer hardware might not become profitable for 5 years, during
which they spent $50 million. But when they did
they might have revenues of $50 million a year. This kind of
profitability means the startup has succeeded.Ramen profitability is the other extreme: a startup that becomes
profitable after 2 months, even though its revenues are only $3000
a month, because the only employees are a couple 25 year old founders
who can live on practically nothing. Revenues of $3000 a month do
not mean the company has succeeded.
But it does share something with the one
that's profitable in the traditional way: they don't need to raise
money to survive.Ramen profitability is an unfamiliar idea to most people because
it only recently became feasible. It's still not feasible for a
lot of startups; it would not be for most biotech startups, for
example; but it is for many software startups because they're now
so cheap. For many, the only real cost is the founders'
living expenses.The main significance of this type of profitability is that you're
no longer at the mercy of investors. If you're still losing money,
then eventually you'll either have to raise more
or shut down. Once you're
ramen profitable this painful choice goes away.
You can still raise money, but you don't have to do it now.* * *The most obvious advantage of not needing money is that
you can get better terms. If investors know you need money, they'll
sometimes take advantage of you. Some may even deliberately
stall, because they know that as you run out of money you'll become
increasingly pliable.But there are also three less obvious advantages of ramen profitability.
One is that it makes you more attractive to investors. If you're
already profitable, on however small a scale, it shows that (a) you
can get at least someone to pay you, (b) you're serious about
building things people want, and (c) you're disciplined enough to
keep expenses low.This is reassuring to investors, because you've addressed three of
their biggest worries. It's common for them to fund companies that
have smart founders and a big market, and yet still fail. When
these companies fail, it's usually because (a) people wouldn't pay
for what they made, e.g. because it was too hard to sell to them,
or the market wasn't ready yet, (b) the founders solved the wrong
problem, instead of paying attention to what users needed, or (c)
the company spent too much and burned through their funding before
they started to make money. If you're ramen profitable, you're
already avoiding these mistakes.Another advantage of ramen profitability is that it's good for
morale. A company
tends to feel rather theoretical when you first start it. It's
legally a company, but you feel like you're lying when you call it
one. When people start to pay you significant amounts, the company
starts to feel real. And your own living expenses are the milestone
you feel most, because at that point the future flips state. Now
survival is the default, instead of dying.A morale boost on that scale is very valuable in a startup, because
the moral weight of running a startup is what makes it hard. Startups
are still very rare. Why don't more people do it? The financial
risk? Plenty of 25 year olds save nothing anyway. The long hours?
Plenty of people work just as long hours in regular jobs. What keeps
people from starting startups is the fear of having so much
responsibility. And this is not an irrational fear: it really is
hard to bear. Anything that takes some of that weight off you will
greatly increase your chances of surviving.A startup that reaches ramen profitability may be more likely
to succeed than not. Which is pretty exciting, considering the
bimodal distribution of outcomes in startups: you either fail or
make a lot of money.The fourth advantage of ramen profitability is the least obvious
but may be the most important. If you don't need to raise money,
you don't have to interrupt working on the company to do it.Raising money is terribly distracting.
You're lucky if your
productivity is a third of what it was before. And it can last for
months.I didn't understand (or rather, remember) precisely why raising
money was so distracting till earlier this year. I'd noticed that
startups we funded would usually grind to a halt when they switched
to raising money, but I didn't remember exactly why till YC raised
money itself. We had a comparatively easy time of it; the first
people I asked said yes; but it took months to work out the
details, and during that time I got hardly any real work done. Why?
Because I thought about it all the time.At any given time there tends to be one problem that's the most
urgent for a startup. This is what you think about as you fall
asleep at night and when you take a shower in the morning. And
when you start raising money, that becomes the problem you think
about. You only take one shower in the morning, and if you're
thinking about investors during it, then you're not thinking about
the product.Whereas if you can choose when you raise money, you can pick a time
when you're not in the middle of something else, and you can probably
also insist that the round close fast. You may even be able to
avoid having the round occupy your thoughts, if you don't care
whether it closes.* * *Ramen profitable means no more than the definition implies. It
does not, for example, imply that you're "bootstrapping" the
startup—that you're never going to take money from investors.
Empirically that doesn't seem to work very well. Few startups
succeed without taking investment. Maybe as startups get cheaper
it will become more common. On the other hand, the money is there,
waiting to be invested. If startups need it less, they'll be able
to get it on better terms, which will make them more inclined to
take it. That will tend to produce an equilibrium.
[2]Another thing ramen profitability doesn't imply is <NAME>'s idea
that you should put your
business model in beta when you put your
product in beta. He believes you should get
people to pay you from the beginning. I think that's too constraining.
Facebook didn't, and they've done better than most startups. Making
money right away was not only unnecessary for them, but probably
would have been harmful. I do think Joe's rule could be useful for
many startups, though. When founders seem unfocused, I sometimes
suggest they try to get customers to pay them for something, in the
hope that this constraint will prod them into action.The difference between Joe's idea and ramen profitability is that
a ramen profitable company doesn't have to be making money the way
it ultimately will. It just has to be making money. The most
famous example is Google, which initially made money by licensing
search to sites like Yahoo.Is there a downside to ramen profitability? Probably the biggest
danger is that it might turn you into a consulting firm. Startups
have to be product companies, in the sense of making a single thing
that everyone uses. The defining quality of startups is that they
grow fast, and consulting just can't scale the way a product can.
[3]
But it's pretty easy to make $3000 a month consulting; in
fact, that would be a low rate for contract programming. So there
could be a temptation to slide into consulting, and telling
yourselves you're a ramen profitable startup, when in fact
you're not a startup at all.It's ok to do a little consulting-type work at first. Startups
usually have to do something weird at first. But remember
that ramen profitability is not the destination. A startup's
destination is to grow really big; ramen profitability is a trick
for not dying en route.Notes[1]
The "ramen" in "ramen profitable" refers to instant ramen,
which is just about the cheapest food available.Please do not take the term literally. Living on instant ramen
would be very unhealthy. Rice and beans are a better source of
food. Start by investing in a rice cooker, if you don't have one.Rice and Beans for 2n
olive oil or butter
n yellow onions
other fresh vegetables; experiment
3n cloves garlic
n 12-oz cans white, kidney, or black beans
n cubes Knorr beef or vegetable bouillon
n teaspoons freshly ground black pepper
3n teaspoons ground cumin
n cups dry rice, preferably brown
Put rice in rice cooker. Add water as specified on rice package.
(Default: 2 cups water per cup of rice.) Turn on rice cooker and
forget about it.Chop onions and other vegetables and fry in oil, over fairly low
heat, till onions are glassy. Put in chopped garlic, pepper, cumin,
and a little more fat, and stir. Keep heat low. Cook another 2 or
3 minutes, then add beans (don't drain the beans), and stir. Throw
in the bouillon cube(s), cover, and cook on lowish heat for at least
10 minutes more. Stir vigilantly to avoid sticking.If you want to save money, buy beans in giant cans from discount
stores. Spices are also much cheaper when bought in bulk.
If there's an Indian grocery store near you, they'll have big
bags of cumin for the same price as the little jars in supermarkets.[2]
There's a good chance that a shift in power from investors
to founders would actually increase the size of the venture business.
I think investors currently err too far on the side of being harsh
to founders. If they were forced to stop, the whole venture business
would work better, and you might see something like the increase
in trade you always see when restrictive laws are removed.Investors
are one of the biggest sources of pain for founders; if they stopped
causing so much pain, it would be better to be a founder; and if
it were better to be a founder, more people would do it.[3]
It's conceivable that a startup could grow big by transforming
consulting into a form that would scale. But if they did that
they'd really be a product company.Thanks to <NAME> for reading drafts of this.Japanese Translation
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/footnote-refs_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
A footnote #footnote[Hi]<fn> \
A reference to it @fn
|
https://github.com/rabarbra/cv | https://raw.githubusercontent.com/rabarbra/cv/main/cv_en.typ | typst | #import "render.typ": render
#render(
yaml("cv.en.yml")
) |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/call-05.typ | typst | Other | #let f(x) = x
// Error: 2-6 expected function, found integer
#f(1)(2)
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/019_Magic%20Origins.typ | typst | #import "@local/mtgset:0.1.0": conf
#show: doc => conf("Magic Origins", doc)
#include "./019 - Magic Origins/001_Chandra’s Origin: Fire Logic.typ"
#include "./019 - Magic Origins/002_Liliana's Origin: The Fourth Pact.typ"
#include "./019 - Magic Origins/003_Jace’s Origin: Absent Minds.typ"
#include "./019 - Magic Origins/004_Gideon’s Origin: Kytheon Iora of Akros.typ"
#include "./019 - Magic Origins/005_Nissa’s Origin: Home.typ"
|
|
https://github.com/NOOBDY/formal-language | https://raw.githubusercontent.com/NOOBDY/formal-language/main/q7.typ | typst | The Unlicense | #let q7 = [
7. Which of the following languages are regular? Justify each answer.
+ $L = {w c w | w in {a, b}^ast}$.
Not regular, proof:
Let language $L$ be regular, pumping length $p$.
Let $|w| = p, w = x y, c w = z$, $x y^i != w "if" i > 1 qed$.
+ $L = {x y | x, y in {a, b}^ast "and" |x| = |y|}$.
Not regular, proof:
Let language $L$ be regular, pumping length $p$.
Let $|x| = p, x = i j, y = k, |i j^n| != |k| "if" n > 1 qed$
+ $L = {a^n | n "is a prime number"}$.
Not regular, proof:
Let language $L$ be regular, pumping length $p$.
Let $a^p = a^x a^1 a^z, a^x a^(1i) a^z $
$ &"If" x+1+z >= 3 and i = 2, a^p in.not L \
because &"For all prime number" p >= 3, p + 1 = 2n, (n in NN) \
&"If" x+1+z = 2 and i = 3, a^p in.not L \
because &2 + 2 = 4 "not a prime" $
+ $L = {a^m b^n | gcd(m, n) = 17}$.
Not regular, proof:
Let $L = {w = a^(17s)b^(17t) | gcd(s, t) = 1}, p' >= p$
Let $ w &= a^(17p')b^(17t) = underbrace(a^(p-i), "x") underbrace(a^i, "y") underbrace(a^(17p'-p)b^(17t), "z") \
x y^i z &= a^(17p'+(k-1)i)b^(17t) $
Proof
$ exists.not i "s.t." forall k in NN, gcd(17p'+(k-1)i, 17t) = 17$
Case 1. if $gcd(i, 17) = 1$
$ gcd(17p'+(k-1)i, 17t) = 1 "when" gcd(k-1, 17) eq.not 17 $
Case 2. if $gcd(i, 17) = 17$
Let $i = 17 alpha$
$ gcd(17(p' + alpha(k-1)), 17t) = 17 \
gcd(p' + alpha(k-1), t) = t "when" k = (t - p') / alpha + 1 $
]
|
Subsets and Splits