repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/v411e/optimal-ovgu-thesis | https://raw.githubusercontent.com/v411e/optimal-ovgu-thesis/main/abstract.typ | typst | MIT License | #import "components.typ": body-font, variable-pagebreak
#let oot-abstract(lang: "en", is-doublesided: none, body) = {
set text(lang: lang)
v(0.1fr)
align(center,
text(font: body-font, 1em, weight: "semibold",
if lang == "de" [Zusammenfassung]
else [Abstract]
)
)
linebreak()
text(body)
v(1fr)
variable-pagebreak(is-doublesided)
} |
https://github.com/benjamineeckh/kul-typst-template | https://raw.githubusercontent.com/benjamineeckh/kul-typst-template/main/tests/test2/test2.typ | typst | MIT License | #import "../../src/lib.typ": template
#show: template.with(
// Your title goes here
title: "Doing some very fancy and complicated testing for some new and innovative thing",
// Give or only the year you started in (eg: 2024), or a tuple with the start and end year (eg: (2024, 2040))
academic-year: 2023,
// Change to the correct subtitle, i.e. "Tesi di Laurea Triennale",
// "Master's Thesis", "PhD Thesis", etc.
subtitle: "Master's Thesis",
// Change to your name and student number
authors: (
(name: "<NAME>",
student_number: "r9808098"),
(name: "<NAME>",
student_number: "r0485974395"),
),
promotors: ("A first guy", "some other guy"),
// Add as many co-supervisors as you need or remove the entry
// if none are needed
evaluators: ("idk", "someone else"),
// Change to your supervisor's name
supervisors: (
"Some supervisor",
),
// Customize with your own school and degree
affiliation: (
university: "KU Leuven",
school: "Master in Engineering science",
degree: "Computer science",
elective: "Software engineering",
color: (background-color:(0, 0, 1, 0), text-color:black)
),
// Change to "it" for the Italian template
lang: "en",
// University logo
logo: "../../../resources/logokuleng.svg",
electronic-version:true,
// Hayagriva bibliography is the default one, if you want to use a
// BibTeX file, pass a .bib file instead (e.g. "works.bib")
// bibliography: bibliography("bib.yml"),
preface: lorem(200),
abstract: lorem(500),
// Add as many keywords as you need, or remove the entry if none
// are needed
keywords: none
)
#lorem(100)
= ty |
https://github.com/chinabobo/resume-template | https://raw.githubusercontent.com/chinabobo/resume-template/main/README.md | markdown | MIT License | # resume-template
resume template by [Typst](https://typst.app).
## Showcases
 |
https://github.com/SillyFreak/typst-scrutinize | https://raw.githubusercontent.com/SillyFreak/typst-scrutinize/main/src/utils/scope.typ | typst | MIT License | #let scope(open, close, body, open-data: none, close-data: none) = {
[#metadata(open-data) #open]
body
[#metadata(close-data) #close]
}
#let enclosing(open, close, loc: auto) = {
let loc = loc
if loc == auto {
loc = here()
}
let find-delimiter(candidates, pos, neg) = {
let depth = 0
for candidate in candidates {
assert.eq(candidate.func(), metadata)
assert(candidate.label in (pos, neg))
if candidate.label == neg {
// negative find: depth increases
depth += 1
} else if depth > 0 {
// positive find: depth decreases
depth -= 1
} else {
// positive find: delimiter found
return candidate
}
}
// nothing found: no enclosing scope
// since only properly closed scopes should exist, we should find ourselves at depth 0
assert.eq(depth, 0)
none
}
let sel = selector(open).or(close)
let from = find-delimiter(query(sel.before(loc)).rev(), open, close)
let to = find-delimiter(query(sel.after(loc)), close, open)
// since only properly closed scopes should exist, we should have found both open and close, or neither
assert.eq(from != none, to != none)
(from, to)
}
#let scoped-selector(open, close, sel, loc: auto) = {
let (from, to) = enclosing(open, close, loc: loc)
if from != none { sel = sel.after(from) }
if to != none { sel = sel.before(to) }
sel
}
|
https://github.com/dainbow/MatGos | https://raw.githubusercontent.com/dainbow/MatGos/master/themes/14.typ | typst | #import "../conf.typ": *
= Теорема об ограниченной сходимости для интеграла Лебега
#definition[
Пусть $angle.l a, b angle.r$ -- конечный промежуток ($[a, b], (a, b), (a, b], [a, b)$)
*Брусом* в $RR^n$ назовём
#eq[
$P = times.big_(k = 1)^n angle.l a_k, b_k angle.r$
]
Объёмом бруса $P$ назовём число $abs(P) = product_(k = 1)^n (b_k - a_k)$
]
#definition[
*M* называется *элементарным множеством*, если оно представимо дизъюнктным
объёдинением конечного числа брусьев.
Объёмом элементарного множества $M = union.sq.big_(i = 1)^n P_i$ назовём $abs(M) = sum_(i = 1)^n abs(P_i)$
]
#lemma[
Совокупность элементарных множеств является кольцом множеств.
В качестве единицы будем брать $K_I = [-1 / 2, 1 / 2]^n$.
Совокупность элементарных подмножеств $K_I$ образует алгебру множеств.
]
#definition[
*Внешней мерой Жордана* множества $A$ называется
#eq[
$mu^*_cal(J) (A) = inf_(A subset union_(i = 1)^r M_i) sum_(i = 1)^r abs(M_i)$
]
где инфимум берётся по всем покрытиям множества $A$ конечным числом элементарных
множеств.
]
#definition[
*Внешней мерой Лебега* множества $A$ называется
#eq[
$mu^* (A) = inf_(A subset union_(i = 1)^oo M_i) sum_(i = 1)^oo abs(M_i)$
]
где инфимум берётся по всем покрытиям множества $A$ счётным числом элементарных
множеств.
]
#definition[
Пусть $A subset K_I$.
Тогда *внутренней мерой Лебега (Жордана)* назовём
#eq[
$mu_*^((cal(J))) (A) := 1 - mu^*_((cal(J))) (K_I without A)$
]
]
#definition[
Множество $A subset K_I$ называется измеримым по Лебегу (Жордану), если
#eq[
$mu_((cal(J)))^* (A) = mu_*^((cal(J))) (A)$
]
При этом общее значение соответствующих внешних и внутренних мер называется
просто мерой.
]
#theorem(
"Критерий измеримости",
)[
Множество $A subset K_I$ измеримо по Лебегу (Жордану) тогда и только тогда,
когда
#eq[
$forall epsilon > 0 : exists M_epsilon "элементарное" : space mu_((cal(J)))^* (A triangle.t M_epsilon) < epsilon$
]
]
#definition[
*Лебеговым множеством* функции $f : E -> RR, R subset RR^n$ называется
#eq[
$E_a (f) = {x in E | f(x) < a}$
]
]
#definition[
Функция $f : E -> RR$, где $E$ -- измеримое подмножество $RR^n$, называется
*измеримой*, если
#eq[
$forall a in RR : space E_a (f) "измеримое"$
]
]
#definition[
Пусть $f$ -- ограниченная измеримая функция, определённая на измеримом по Лебегу
множестве $E$. И $Q$ -- разбиение области значений функции $f$.
Тогда *интегральной суммой Лебега* назовём
#eq[
$S(Q, f, seq(end: n, idx: i, t)) = sum_(i = 1)^N f(t_i) mu(E_i)$
]
где $E_i = {x in E | f(x) in [y_(i - 1), y_i)}$
]
#theorem(
"Критерий/определение интеграла Лебега для ограниченных функций",
)[
Если $f$ -- ограниченная измеримая на измеримом по Лебегу множестве $E subset RR^n$,
то она интегрируема по Лебегу на $E$, причём
#eq[
$integral_E f dif mu(x) = lim_(Delta(Q) -> 0) S(Q, f, seq(end: n, idx: i, t))$
]
]
#definition[
Назовём *срезкой* неотрицательной функции $f$ для $N in NN$:
#eq[
$f_[N] (x) = cases(f(x)\, f(x) <= N, N \, f(x) > N)$
]
]
#theorem(
"Критерий/определение интеграла Лебега для измеримых неотрицательных функций",
)[
Если $f$ -- измеримая неотрицательная функция, определённая на измеримом
множестве $E$ конечной меры, то
#eq[
$lim_(N -> oo) integral_E f_[N] dif mu(x) = integral_E f(x) dif mu(x)$
]
]
#theorem(
"Лебега о предельном переходе под знаком интеграла",
)[
Пусть
- $seq(f)$ -- измеримые на множестве $E subset RR^n$ конечной меры
- $\ f_m attach(->, t: "п.н.") f$ на $E$
- $forall n in NN : space abs(f_n (x)) <= F(x)$ при почти всех $x in E$, где $F$ -- произвольная
суммируемая функция на $E$
Тогда $f$ суммируема на $E$, причём
#eq[
$integral_E f dif mu(x) = lim_(n -> oo) integral_E f_n dif mu(x)$
]
]
#proof[
Совершив предельный переход $n -> oo$ мы можем утверждать, что $abs(f(x)) <= F(x)$ при
почти всех $x in E$ -- значит $f$ суммируемая на $E$.
Осталось доказать равенство интеграла и предела интегралов.
Как мы знаем, из сходимости почти всюду следует сходимость по мере:
#eq[
$forall epsilon > 0 : lim_(n -> oo) mu(E_m (epsilon) := {x in E | norm(f_m - f) >= epsilon}) = 0$
]
Другими словами
#eq[
$forall epsilon > 0: forall delta > 0 : exists M in NN : forall m > M : space mu(E_m (epsilon)) < delta$
]
Оценим разность интеграла и предела интегралов:
#eq[
$abs(integral_E (f - f_m) dif mu(x)) <= integral_E_m abs(f_m - f) dif mu(x) + integral_(E without E_m) abs(f_m - f) dif mu(x) <= \
2 integral_E_m F dif mu(x) + epsilon mu(E without E_m) < epsilon (mu(E) + 2)$
]
Что и требовалось.
]
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/closure-06.typ | typst | Other | // For loop bindings.
#{
let v = (1, 2, 3)
let f() = {
let s = 0
for v in v { s += v }
s
}
test(f(), 6)
}
|
https://github.com/brayevalerien/Learning-Typst | https://raw.githubusercontent.com/brayevalerien/Learning-Typst/main/tutorial/02_formatting/formating.typ | typst | MIT License | In this document, I learn more about formating in Typst.
These first two paragraphs are writen before any rule is set, so they are simply using the default formating.
= Setting rules
#par(justify: true)[
This paragraph, is justified. That's because I used the "par" function (called using "\#par"), with the argument "justify" set to "true", and surrounded this paragraph by this function call. It is inconvenient to do it this way; indeed, if I wanted to have my whole document justified, I would need to surround it entirely with many functions.
]
If I write another paragraph, like this one, out of the "par" function, then it returns to default formating, where paragraphs are not justified but left aligned. To justify all paragraphs in my document, I can set a rule about paragraphs.
In order to do so, I use the "set" keyword, called like a function using "\#set". Let's set a rule to justify all the paragraphs in this document.
#set par(justify: true)
Now that this rule is set, I can write freely, because when Typst compiler will call the "par" function, the "justify" argument will always be set to "true" by default. You can clearly see that this paragraph is justified even though it is not surrounded by anything. Pretty intuitive! Setting several rules at the top of the document should allow me to dictate how this document should be formated and it makes changing the formating super easy.
= Setting up the page
There are many rules that can be set, mainly for the following functions:
- text
- page
- par
- heading
- document
All of them are pretty self-explanatory, except for "document", which allows me to set metadata in the compiled pdf.
Let's set some rules, following the example in the Typst tutorial about formatting @formattingtutorial.
#set text(
font: "New Computer Modern",
size: 10pt
)
#set page(
paper: "a6",
margin: (x: 1.8cm, y: 1.5cm),
)
#set par(
justify: true,
leading: 0.52em,
)
Would you look at that! A totally new format for the text, the page and the paragraphs! All of this in the same document.
= Section title
#lorem(15)
Lorem Ipsum @lipsum is very convenient for testing formatting and the Typst function "lorem" can quickly generate sample text. These formated paragraphs are justified and use 52% font height for separation.
#lorem(25)
Notice how the rule we set change the page format (it's now using A6 format), and the margin size. All of this without importing a single package, and by using only a few lines of intuitive code!
We can also set attributes about headers format, such as their numbering. Headers are currently unumbered, which is uncommon and not really practical for any serious work. I'll set a rule to number headers, using arabic numbers for the first level header and letters for second level headers.
#set heading(numbering: "1.a")
= First level section title
See!
Note that the numbering starts at one even though we already defined other sections, because we only set the numbering rule before this sections.
== Second level section title
#lorem(20)
== Another second level section title
What will happen if I use a level three header? My rule does not set how it should be numbered...
=== Third level section title
Looks like it's using the second level header numbering rule.
=== Another third level section title
#lorem(20)
=== Final third level section title
#lorem(20)
#figure(
image("cat.png", width: 75%),
caption: [An angry looking cat]
)
Sorry, I could not resist the urge to put a cat picture here... At least I can check that I remember how to create figures with captions and include images, something we learned in the previous chapter.
#lorem(30)
= Show rule
The show rule is unique since it allows me to set a way to display things. For instance, if I wanted to display "bonjour" as an _italicized_ word each time I use it, instead of surrounding it with underscores each time, I could use the show rule in the following way.
#show "bonjour": _ => box[_bonjour_]
Let's test it out: bonjour! Seems like it works perfectly fine, I can now type bonjour without worying about it's format. Even cooler, I can very easily change how bonjour is displayed, simply by changing the rule. Any change to this show rule will affect anything that comes after.
The example given in the documentation @formattingtutorial is pretty cool because it demonstrates how this rule can be used to always display a logo next to a specific name.
#bibliography("ref.bib")
|
https://github.com/rayfiyo/myTypst | https://raw.githubusercontent.com/rayfiyo/myTypst/main/README.md | markdown | BSD 3-Clause "New" or "Revised" License | # myTypst
- typst で色々な書類を書くためのテンプレート
- Template for writing any document with typst
## mystyle_report
- 私の環境でのレポート用
## note
- ノート(メモ)用
- 表紙がない
## report
- レポート用
## test
- 試験的に使うディレクトリ
---
# 参考文献
## GitHub
- [修論用のTypstのテンプレート](https://github.com/yukukotani/typst-coins-thesis)
- [日本語文書向け Typst テンプレート(大学生向け&自己流)](https://github.com/stepney141/my_typst_template)
- [Typst で日本語論文を書くときのテンプレート](https://github.com/kimushun1101/typst-jp-conf-template)
- PDF: [https://kimushun1101.github.io/typst-jp-conf-template/typst-jp-conf.pdf](https://kimushun1101.github.io/typst-jp-conf-template/typst-jp-conf.pdf)
## article
- https://zenn.dev/monaqa/articles/2023-04-19-typst-introduction
- https://zenn.dev/chantakan/articles/ed80950004d145
- http://www-het.phys.sci.osaka-u.ac.jp/~yamaguch/j/typst.html
- https://qiita.com/gomazarashi/items/ddef3d0db22a9f1e08ba
---
# 補足: font について
## 利用可能なフォントの確認方法
```
typst fonts
```
## フォントの追加方法
このレポジトリにある typst ファイルは
`Noto Serif CJK JP` や `Noto Sans CJK JP` を多様している(依存している).<br>
これらを追加する例をあげてみる.
### 方法1: インストール
Arch Linux では次で可能
```
sudo pacman -S noto-fonts noto-fonts-cjk noto-fonts-emoji
```
先ほどのコマンドで追加が確認できない場合(typst 0.12.0 (737895d7) など)では,
[後述の環境変数に追加](#環境変数に追加)を行う.
### 方法2: ローカルで指定
例えば`mystyle_report/`の構成のように,フォントを格納するディレクトリを作成する(ここでの例は`fonts/`).<br>
次に,そのディレクトリにフォントファイルを格納する.フォントの種類は次の4つが可能らしい.
`.ttf`,`.ttc`,`.otf`,`.otc`
その後,コンパイル等のたびに`--font-path`オプションを使えば良い.適用できているか確認する方法の例は次.
```
typst fonts --font-path ./fonts/
```
先ほどのコマンドで追加が確認できない場合(typst 0.12.0 (737895d7) など)では,
[後述の環境変数に追加](#環境変数に追加)を行う.
### 環境変数に追加
`TYPST_FONT_PATHS` という環境変数にフォントがあるパスを追加する.
.ttf があるフォルダを直接指定せず,親ディレクトリを指定しても良い(その分遅くなるが).
私は,`/usr/share/fonts/noto-cjk/` を指定している.
例えば fish shell だと次を設定ファイルに**追記**する.
```
set -gx TYPST_FONT_PATHS /usr/share/fonts/noto-cjk/
```
bash であれば次を**実行**する.
```
export TYPST_FONT_PATHS=/usr/share/fonts/noto-cjk/
```
前述の通り,親ディレクトリの`/usr/share/fonts/` を指定しても正常に動作する(その分遅くなるが).
### Windows環境
以下が必要になるかもしれないとの情報を見かけた記憶がある.
```
typst --font-path /System/Library/Fonts watch main.typ
```
|
https://github.com/akai-omurbek/Typst-CV | https://raw.githubusercontent.com/akai-omurbek/Typst-CV/main/README.md | markdown | # Simple one-page CV using [Typst](https://github.com/typst/typst)

Hi, everyone! This is my take on a reproducible CV powered by Typst. This one is very, ***very*** raw. I have to work on it a bit more in the future. The layout is optimal for one page (the main / sidebar separation) - otherwise it might look shabby. [Click here](cv.pdf) to take a look at the example pdf.
## Usage
1. Clone the repository:
```sh
git clone https://github.com/akai-omurbek/Typst-CV
cd Typst-CV
```
2. Change the `YAML` file `cv_info.yml` - that one is pretty straightforward
3. Compile your CV:
```sh
typst compile cv.typ
```
4. Open `cv.pdf` file with a reader of your choice.
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/scholarly-tauthesis/0.4.0/template/preamble.typ | typst | Apache License 2.0 | /** preamble.typ
*
* A file for defining your own commands and functions. To use
* the commands defined here in another file, this file needs to
* be imported there:
*
* #import "path/to/preamble.typ": *
*
* imports all symbols without qualifying them, and
*
* #import "path/to/preamble.typ"
*
* requires that you qualify each command with the name of this
* module: preamble.command. A few command definitions are
* defined as an example.
*
***/
#let vector(input) = $upright(bold(input))$
#let position = $vector(x)$
#let velocity = $vector(v)$
#let acceleration = $vector(a)$
#let matrix(input) = $upright(bold(input))$
// A command for a complicated word.
#let eeg = [electroencephalography]
#let EEG = [EEG]
// Derivatives.
#let derivative(num,den) = $(dif #h(0.1em) num)/(dif #h(0.1em) den)$
#let partialderivative(num,den) = $(partial #h(0.1em) num)/(partial #h(0.1em) den)$
//// Printing numbers with a thousands-separator.
/** strInGroupsOf(ss,gg)
*
* Displays a given string ss in groups of gg.
*
***/
#let strInGroupsOf(ss, gg, reverse : true) = {
if not type(ss) == str {
panic("strWithThousandsSep: I only accept string arguments. Received a " + str(type(ss)))
}
if not type(gg) == int and gg >= 0 {
panic("strWithThousandsSep: the second argument needs to be a non-negative integer.")
}
let graphs = ss.clusters()
let strlen = graphs.len()
let maxcontinues = calc.max(
calc.quo(strlen, gg),
0
)
let iters = strlen + maxcontinues
let continuecount = 0
let ii = 0
let condition = if reverse { (it,lim) => it < lim } else { (it,lim) => it <= lim }
while condition(ii,iters) {
let dist = if reverse { iters - ii } else { ii }
let rr = calc.rem(dist, gg+1)
let dd = graphs.at(ii - continuecount)
if rr == 0 and ii != 0 { h(0.2em) }
if rr == 0 {
continuecount += 1
} else {
$dd$
}
ii += 1
}
}
/** intWithThousandsSep
*
* Displays an integer with some kerning as a
* thousands-separator.
*
***/
#let intWithThousandsSep(nat) = {
if not type(nat) == int {
panic("This function only accepts integer arguments")
}
if nat < 0 { $-$ }
let string = repr(calc.abs(nat))
strInGroupsOf(string, 3)
}
/** floatWithThousandsSep
*
* Displays a floating point number with some kerning as a
* thousands-separator.
*
* The implementation is stupid, because typst cannot convert
* floats to bytes, and even if it did, the documentation does
* not tell whether typst floats conform to the IEEE floating
* point standard or not.
*
***/
#let floatWithThousandsSep(ff) = {
if not type(ff) == float {
panic("This function only accepts floating point arguments")
}
let sf = str(ff)
let whole_and_fract = sf.split(".")
let first = whole_and_fract.first()
let last = whole_and_fract.last()
let (whole, decim) = if whole_and_fract.len() == 2 {
(first, last)
} else {
(first, none)
}
let wholesep = strInGroupsOf(whole, 3)
if decim == none {
$#wholesep$
} else {
let decimsep = strInGroupsOf(decim, 3, reverse : false)
$#wholesep.#decimsep$
}
}
/** num(nn)
*
* Typesets a given integer or float with some kerning as a
* thousands separator.
*
***/
#let num(nn) = {
if type(nn) == int {
intWithThousandsSep(nn)
} else if type(nn) == float {
floatWithThousandsSep(nn)
} else {
panic("num: I can only separate ints and floats. Received " + str(type(nn)))
}
}
//// Unit definitions.
#let extracttext(cc) = {
if type(cc) == content {
let ff = cc.fields()
let text = ff.at("text", default: none)
if text != none {
return text
}
let body = ff.at("body", default: none)
if body == none {
panic("Found neither text nor body in given content.")
}
extracttext(body)
} else {
panic("Cannot extract text from non-content values.")
}
}
#let unit(symbol) = $upright(symbol)$
#let intregex = regex("^(?:-)?\d+$")
#let floatregex = regex("^(:?-)?\d+\.\d+$")
#let unitful(nn,uu) = {
let nr = if type(nn) == content {
let text = extracttext(nn)
let intmatches = text.matches(intregex)
let flomatches = text.matches(floatregex)
if not intmatches == () {
int(text)
} else if not flomatches == () {
float(text)
} else {
panic("unitful: Could not convert content text into a number")
}
} else {
nn
}
$num(nr)#h(0.1em)unit(uu)$
}
//// SI units.
#let meter = unit([m])
#let gram = unit([g])
#let second = unit([s])
#let newton = unit([N])
#let joule = unit([J])
#let time = unit([t])
#let bar = unit([bar])
#let mmHg = unit([mmHg])
#let pascal = unit([Pa])
//// Unit prefixes.
#let femto = unit([f])
#let nano = unit([n])
#let micro = unit([μ])
#let milli = unit([m])
#let centi = unit([c])
#let deci = unit([d])
#let kilo = unit([k])
#let mega = unit([M])
#let giga = unit([G])
#let tera = unit([T])
#let peta = unit([P])
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-118A0.typ | typst | Apache License 2.0 | #let data = (
("WARANG CITI CAPITAL LETTER NGAA", "Lu", 0),
("WARANG CITI CAPITAL LETTER A", "Lu", 0),
("WARANG CITI CAPITAL LETTER WI", "Lu", 0),
("WARANG CITI CAPITAL LETTER YU", "Lu", 0),
("WARANG CITI CAPITAL LETTER YA", "Lu", 0),
("WARANG CITI CAPITAL LETTER YO", "Lu", 0),
("WARANG CITI CAPITAL LETTER II", "Lu", 0),
("WARANG CITI CAPITAL LETTER UU", "Lu", 0),
("WARANG CITI CAPITAL LETTER E", "Lu", 0),
("WARANG CITI CAPITAL LETTER O", "Lu", 0),
("WARANG CITI CAPITAL LETTER ANG", "Lu", 0),
("WARANG CITI CAPITAL LETTER GA", "Lu", 0),
("WARANG CITI CAPITAL LETTER KO", "Lu", 0),
("WARANG CITI CAPITAL LETTER ENY", "Lu", 0),
("WARANG CITI CAPITAL LETTER YUJ", "Lu", 0),
("WARANG CITI CAPITAL LETTER UC", "Lu", 0),
("WARANG CITI CAPITAL LETTER ENN", "Lu", 0),
("WARANG CITI CAPITAL LETTER ODD", "Lu", 0),
("WARANG CITI CAPITAL LETTER TTE", "Lu", 0),
("WARANG CITI CAPITAL LETTER NUNG", "Lu", 0),
("WARANG CITI CAPITAL LETTER DA", "Lu", 0),
("WARANG CITI CAPITAL LETTER AT", "Lu", 0),
("WARANG CITI CAPITAL LETTER AM", "Lu", 0),
("WARANG CITI CAPITAL LETTER BU", "Lu", 0),
("WARANG CITI CAPITAL LETTER PU", "Lu", 0),
("WARANG CITI CAPITAL LETTER HIYO", "Lu", 0),
("WARANG CITI CAPITAL LETTER HOLO", "Lu", 0),
("WARANG CITI CAPITAL LETTER HORR", "Lu", 0),
("WARANG CITI CAPITAL LETTER HAR", "Lu", 0),
("WARANG CITI CAPITAL LETTER SSUU", "Lu", 0),
("WARANG CITI CAPITAL LETTER SII", "Lu", 0),
("WARANG CITI CAPITAL LETTER VIYO", "Lu", 0),
("WARANG CITI SMALL LETTER NGAA", "Ll", 0),
("WARANG CITI SMALL LETTER A", "Ll", 0),
("WARANG CITI SMALL LETTER WI", "Ll", 0),
("WARANG CITI SMALL LETTER YU", "Ll", 0),
("WARANG CITI SMALL LETTER YA", "Ll", 0),
("WARANG CITI SMALL LETTER YO", "Ll", 0),
("WARANG CITI SMALL LETTER II", "Ll", 0),
("WARANG CITI SMALL LETTER UU", "Ll", 0),
("WARANG CITI SMALL LETTER E", "Ll", 0),
("WARANG CITI SMALL LETTER O", "Ll", 0),
("WARANG CITI SMALL LETTER ANG", "Ll", 0),
("WARANG CITI SMALL LETTER GA", "Ll", 0),
("WARANG CITI SMALL LETTER KO", "Ll", 0),
("WARANG CITI SMALL LETTER ENY", "Ll", 0),
("WARANG CITI SMALL LETTER YUJ", "Ll", 0),
("WARANG CITI SMALL LETTER UC", "Ll", 0),
("WARANG CITI SMALL LETTER ENN", "Ll", 0),
("WARANG CITI SMALL LETTER ODD", "Ll", 0),
("WARANG CITI SMALL LETTER TTE", "Ll", 0),
("WARANG CITI SMALL LETTER NUNG", "Ll", 0),
("WARANG CITI SMALL LETTER DA", "Ll", 0),
("WARANG CITI SMALL LETTER AT", "Ll", 0),
("WARANG CITI SMALL LETTER AM", "Ll", 0),
("WARANG CITI SMALL LETTER BU", "Ll", 0),
("WARANG CITI SMALL LETTER PU", "Ll", 0),
("WARANG CITI SMALL LETTER HIYO", "Ll", 0),
("WARANG CITI SMALL LETTER HOLO", "Ll", 0),
("WARANG CITI SMALL LETTER HORR", "Ll", 0),
("WARANG CITI SMALL LETTER HAR", "Ll", 0),
("WARANG CITI SMALL LETTER SSUU", "Ll", 0),
("WARANG CITI SMALL LETTER SII", "Ll", 0),
("WARANG CITI SMALL LETTER VIYO", "Ll", 0),
("WARANG CITI DIGIT ZERO", "Nd", 0),
("WARANG CITI DIGIT ONE", "Nd", 0),
("WARANG CITI DIGIT TWO", "Nd", 0),
("WARANG CITI DIGIT THREE", "Nd", 0),
("WARANG CITI DIGIT FOUR", "Nd", 0),
("WARANG CITI DIGIT FIVE", "Nd", 0),
("WARANG CITI DIGIT SIX", "Nd", 0),
("WARANG CITI DIGIT SEVEN", "Nd", 0),
("WARANG CITI DIGIT EIGHT", "Nd", 0),
("WARANG CITI DIGIT NINE", "Nd", 0),
("WARANG CITI NUMBER TEN", "No", 0),
("WARANG CITI NUMBER TWENTY", "No", 0),
("WARANG CITI NUMBER THIRTY", "No", 0),
("WARANG CITI NUMBER FORTY", "No", 0),
("WARANG CITI NUMBER FIFTY", "No", 0),
("WARANG CITI NUMBER SIXTY", "No", 0),
("WARANG CITI NUMBER SEVENTY", "No", 0),
("WARANG CITI NUMBER EIGHTY", "No", 0),
("WARANG CITI NUMBER NINETY", "No", 0),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
("WARANG CITI OM", "Lo", 0),
)
|
https://github.com/phinixplus/docs | https://raw.githubusercontent.com/phinixplus/docs/master/source/config.typ | typst | Other | #let font-sans = "IBM Plex Sans"
#let font-serif = "IBM Plex Serif"
#let font-mono = "Inconsolata Nerd Font"
#let text-fg-color = luma(15%)
#let interj-fg-color = luma(35%)
#let inv-text-fg-color = luma(100%)
#let text-weight-normal = 400
#let text-weight-bold = 700
#let heading-fg-color = luma(0%)
#let heading-weight = 400
#let table-bg-color = luma(10%)
#let code-bg-color = luma(90%)
#let code-fg-color = luma(80%)
#let code-weight = 500
#let text-size-1 = 8pt
#let text-size-2 = 10pt
#let text-size-3 = 12pt
#let text-size-4 = 14pt
#let text-size-5 = 16pt
|
https://github.com/andreasKroepelin/typst-notebook | https://raw.githubusercontent.com/andreasKroepelin/typst-notebook/main/README.md | markdown | MIT License | # Typst notebook

This is a small template to write a notebook using [Typst](https://typst.app).
## Getting started
Put the file `template-notebook.typ` in the directory where you want to store
your notebook.
Then, create a `notebook.typ` file similar to the following:
```typ
#import "template-notebook.typ": notebook
// not necessary, but I think the font works good for a notebook
#set text(font: "Inria Sans")
#show: notebook.with(
title: [My cool notebook],
author: [My name],
tags: (
tag-1: orange,
tag-2: aqua,
)
)
= Note 1
Something about @tag-1.
#lorem(10)
@tag-1 @tag-2
= Note 2
Refer to @note-1.
#lorem(10)
@tag-2
= Note 3
TODO do something
DONE something else
TODO do another thing
```
This produces the following document:

## Features
### The document itself
Using this template creates a document with a single ever-growing page.
This is achieved by using `#set page(height: auto)`.
The width of that page can be configured using the `width` argument in the
template function:
```typ
#show: notebook.with(
// ...
width: 80em,
)
```
### Creating notes
By using a level-one heading (`= Heading`), you create a new note.
It is automatically assigned a label based on its title text that is printed next
to the title for convenience, so that you know what to refer to.
### Keeping track of TODOs
Whenever you put `TODO` somewhere in your notes, it is recognised, printed in
red, and the containing note is added to a list of TODOs at the top of the
document.
When there are more than one TODOs in one note, a counter next to the title
informs you about that fact.
The title in the TODO list is a link to that note.
### Referring to other notes
As explained above, each note automatically gets its label.
The name of the label can be found next to the title in the document.
By using Typst's reference syntax, you can link to that note (e.g. `@note-1` for
a note that was created with `= Note 1`).
### Using tags
At the top of your code, when you apply the template function, you can give a list
of tags in the form of a Typst dictionary.
The keys are the names of the tags and the values are the colors they are supposed
to have.
The name of the tag is printed in white per default.
If, however, you want to have a tag with a very light color, that can become an
issue.
In that case, you can use a more complex syntax:
```typ
tags: (
tag-1: red,
tag-2: (color: silver, text-color: black),
)
```
For `tag-1: red`, we could therefore also write
`tag-1: (color: red, text-color: white)`.
You can refer to a tag in your notes again using the refernce syntax.
For example, `@tag-1` creates a link to an overview of `tag-1` at the top of the
document.
In this overview, you can find all notes that mention this tag and by clicking
any of their titles in this list you can jump to that note.
### Entry overview
Also at the top of the document, you can find an automatic table of contents
with all then entries in your notebook.
## Considerations for choosing the PDF viewer
Some PDF viewers like `evince` on Linux have a _preview_ feature that comes in
really handy here.
For example, if you look at the TODO overview in the example doument above and
want to know what kind of TODOs you have for Note 3 without jumping there, you
can just hover the mouse pointer over the title:
https://github.com/andreasKroepelin/typst-notebook/assets/42342396/6738663c-ca16-40e1-aaeb-ebe006955878
## Shell support
In `scripts/note.fish`, you can find a utility function for the fish shell to
create new notes more easily.
If you copy this file to `~/.config/fish/functions/`, you can call it as
`note "Some title"` in fish and it creates a new file `some-title.typ` with content
```typ
= Some title
```
and adds
```typ
#include "some-title.typ"
```
to `notebook.typ`.
If you omit the title argument (i.e. you just call `note`), it uses the current
date in the form `2023-jun-01` as the title.
Contributions porting this script to other shells are welcome.
|
https://github.com/Mc-Zen/tidy | https://raw.githubusercontent.com/Mc-Zen/tidy/main/examples/example-demo.typ | typst | MIT License | /// #set text(size: .9em)
/// ```/// #example(`example-demo.flashy[We like our code flashy]`)```
/// #example(`example-demo.flashy[We like our code flashy]`)
/// ```/// #example(`example-demo.flashy[Large previews will be scaled automatically to fit]`)```
/// #example(`example-demo.flashy[Large previews will be scaled automatically to fit]`)
/// ```/// #example(`example-demo.flashy[Change code to preview ratio]`, ratio: 2)```
/// #example(`example-demo.flashy[Change code to preview ratio]`, ratio: 2)
/// ```/// #example(`example-demo.flashy(map: color.map.vlag)[Huge preview]`, scale-preview: 200%)```
/// #example(`example-demo.flashy(map: color.map.vlag)[Huge preview]`, scale-preview: 200%)
/// ```/// #example(`flashy[Add to scope]`, scope: (flashy: example-demo.flashy, i: 2))```
/// #example(`flashy[Add to scope #i ...]`, scope: (flashy: example-demo.flashy, i: 2))
///
/// \
///
/// ```/// #example(`Markup *mode*`, mode: "markup")```
/// #example(`Markup *mode*`, mode: "markup")
/// ```/// #example(`e^(i phi) = -1`, mode: "math")```
/// #example(`e^(i phi) = -1`, mode: "math")
///
/// \
///
/// ```/// #example(`example-demo.flashy(map: color.map.crest)[Very extremely long examples might maybe require the need of vertical layouting]`, dir: ttb)```
/// #example(`example-demo.flashy(map: color.map.crest)[Very extremely long examples might maybe require the need of vertical layouting]`, dir: ttb)
///
/// - body (content):
/// - map (array):
/// -> content
#let flashy(body, map: color.map.spectral) = highlight(
body, fill: gradient.linear(..map)
) |
https://github.com/QuadnucYard/cswc-lecture-report-typst | https://raw.githubusercontent.com/QuadnucYard/cswc-lecture-report-typst/main/README.md | markdown | MIT License | # 东南大学吴健雄学院人文讲座听课报告模板(Typst)
## 环境
Typst 0.11.1
需要系统字体支持:宋体,仿宋,微软雅黑,Times New Roman。
## 使用方法
考虑到其性质,本模板没有发布到官方渠道。
下载 `lib.typ` 和 `main.typ`,修改 `main.typ` 内容,填写讲座相关信息和报告正文。
主文件 `show` 语句后所有内容都会出现在表格正文部分。
```typ
// 修改讲座相关信息
#show: lec-report.with(
stu-id: "61520000",
stu-name: "漫游者",
time: "2024/04/01",
loc: "健雄书院报告厅",
speaker: "穹天帝",
subject: "现代排版工具Typst的使用",
)
// 后面均为报告正文
```
## 效果图

## 尚存问题
正文部分设置行占比为 `1fr`,当内容超出单元格时,会溢出而非使表格扩展到第 2 页。此时请考虑减少正文行间距,或修改 `rows` 为 `auto`。
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/snippets/layout/shapes.md | markdown | MIT License | # Shaped boxes with text
(I guess that will make a package eventually, but let it be a snippet for now)
```typ
/// author: JustForFun88
#import "@preview/oxifmt:0.2.0": strfmt
#let shadow_svg_path = `
<svg
width="{canvas-width}"
height="{canvas-height}"
viewBox="{viewbox}"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<!-- Definitions for reusable components -->
<defs>
<filter id="shadowing" >
<feGaussianBlur in="SourceGraphic" stdDeviation="{blur}" />
</filter>
</defs>
<!-- Drawing the rectangle with a fill and feGaussianBlur effect -->
<path
style="fill: {flood-color}; opacity: {flood-opacity}; filter:url(#shadowing)"
d="{vertices} Z" />
</svg>
`.text
#let parallelogram(width: 20mm, height: 5mm, angle: 30deg) = {
let δ = height * calc.tan(angle)
(
( + δ, 0pt ),
(width + δ * 2, 0pt ),
(width + δ, height),
(0pt, height),
)
}
#let hexagon(width: 100pt, height: 30pt, angle: 30deg) = {
let dy = height / 2;
let δ = dy * calc.tan(angle)
(
(0pt, dy ),
( + δ, 0pt ),
(width + δ, 0pt ),
(width + δ * 2, dy ),
(width + δ, height),
( + δ, height),
)
}
#let shape_size(vertices) = {
let x_vertices = vertices.map(array.first);
let y_vertices = vertices.map(array.last);
(
calc.max(..x_vertices) - calc.min(..x_vertices),
calc.max(..y_vertices) - calc.min(..y_vertices)
)
}
#let shadowed_shape(shape: hexagon, fill: none,
stroke: auto, angle: 30deg, shadow_fill: black, alpha: 0.5,
blur: 1.5, blur_margin: 5, dx: 0pt, dy: 0pt, ..args, content
) = layout(size => context {
let named = args.named()
for key in ("width", "height") {
if key in named and type(named.at(key)) == ratio {
named.insert(key, size.at(key) * named.at(key))
}
}
let opts = (blur: blur, flood-color: shadow_fill.to-hex())
let content = box(content, ..named)
let size = measure(content)
let vertices = shape(..size, angle: angle)
let (shape_width, shape_height) = shape_size(vertices)
let margin = opts.blur * blur_margin * 1pt
opts += (
canvas-width: shape_width + margin,
canvas-height: shape_height + margin,
flood-opacity: alpha
)
opts.viewbox = (0, 0, opts.canvas-width.pt(), opts.canvas-height.pt()).map(str).join(",")
opts.vertices = "";
let d = margin / 2;
for (i, p) in vertices.enumerate() {
let prefix = if i == 0 { "M " } else { " L " };
opts.vertices += prefix + p.map(x => str((x + d).pt())).join(", ");
}
let svg-shadow = image.decode(strfmt(shadow_svg_path, ..opts))
place(dx: dx, dy: dy, svg-shadow)
place(path(..vertices, fill: fill, stroke: stroke, closed: true))
box(h((shape_width - size.width) / 2) + content, width: shape_width)
})
#set text(3em);
#shadowed_shape(shape: hexagon,
inset: 1em, fill: teal,
stroke: 1.5pt + teal.darken(50%),
shadow_fill: red,
dx: 0.5em, dy: 0.35em, blur: 3)[Hello there!]
#shadowed_shape(shape: parallelogram,
inset: 1em, fill: teal,
stroke: 1.5pt + teal.darken(50%),
shadow_fill: red,
dx: 0.5em, dy: 0.35em, blur: 3)[Hello there!]
``` |
https://github.com/ivaquero/book-control | https://raw.githubusercontent.com/ivaquero/book-control/main/02-传递函数.typ | typst | #import "@local/scibook:0.1.0": *
#show: doc => conf(
title: "传递函数",
author: ("ivaquero"),
header-cap: "现代控制理论",
footer-cap: "github@ivaquero",
outline-on: false,
doc,
)
= 传递函数
<传递函数>
== 弹簧阻尼系统
范式
$ F(s) H(s) = X(s) $
其中,
- $F(s)$:输入的 Laplace 变换
- $H(s)$:传递函数
- $X(s)$:输出的 Laplace 变换
对等号两边做 Laplace 逆变换,可得
== 冲激函数
=== 连续型
连续型冲激函数定义为
$ δ(t) = cases(∞ quad & t = 0, 0 & t ≠ 0) $
单位冲激函数,又称为 Dirac $δ$函数,满足
- $t ≠ 0$时,$δ(t) = 0$
- $∫_(-∞)^∞ δ(t) dd(t) = 1$
#tip[
$δ$函数的宽度为 0,面积为 1,仅存在于数学中
]
=== 离散型
根据$δ$函数定义,构建离散型冲激函数
$ δ(t)_Δ = cases(frac(1, Δ T) quad & 0 < t < Δ T, 0 & "else") $
显然,$Δ T$内的冲激为
$ frac(1, Δ T) Δ T = 1 $
== 输入与输出
#figure(
table(
columns: 2,
align: center + horizon,
inset: 4pt,
stroke: frame(rgb("000")),
[$f(t)$], [$x(t)$],
[$δ(t)_Δ$], [$h_Δ(t)$],
[$δ(t - i Δ T)_Δ$], [$h_Δ(t - i Δ T)$],
[$A δ(t - i Δ T)_Δ$], [$A h_Δ(t - i Δ T)$],
[], [],
),
caption: [输入与输出],
supplement: "表",
kind: table,
)
表格中,$A = Δ T f(i Δ T)$,在$t = i Δ T$时刻,有
$ x(t) = ∑_(i = 0)^i Δ T f(i Δ T) h_Δ(t - i Δ T) $
令$lim_(Δ T → 0)$,则$Δ T = dd(τ)$,$i Δ T = τ$,从而有
$
x(t) &= ∫_0^t f(τ) h(t - τ) dd(τ)\
&= f(t) ∗ h(t)
$
这就是#strong[卷积的定义],$∗$即为卷积运算(米字号,不是$*$)。
#tip[
$x(t)$是系统对$t$时刻前所有响应的和,而冲激响应$h(t)$可以完全定义 LTI 系统
]
= Laplace 变换
<Laplace-变换>
== 与卷积
Laplace 变换定义为
$ F(s) = ℒ[f(t)] = ∫_0^(∞) f(t) e^(-s t) dd(t) $
由之前的卷积的定义
$ ℒ[x(t) ∗ h(t)] = ∫_0^(∞)∫_0^t x(τ)h(t - τ) dd(τ) e^(-s t) dd(t) $
变换积分顺序,可以写成
$ ℒ[f(t) ∗ h(t)] = ∫_0^(∞)∫_τ^(∞) f(τ)h(t - τ) e^(-s t) dd(t, τ) $
令$u = t - τ ∈ [0, ∞)$,则$t = u + τ$,$dd(t) = dd(u)$,从而有
$
ℒ[f(t) ∗ h(t)]
&= ∫_0^(∞)∫_0^(∞) f(τ)h(u) e^(-s(u + τ)) dd(u, τ) \
&= ∫_0^(∞) f(τ)e^(-s τ) dd(τ) ∫_0^(∞) h(u) e^(-s u) dd(u) \
&= ℒ[f(s)] ℒ[h(s)] \
&= F(s)H(s)
$
#tip[
上面这个性质非常重要,它将复杂的卷积运算转化成了简单的乘积运算。
]
#theorem[
若
$ y (0) = y ̇ (0) = y ̈ (0) = … = y^((n-1))(0) = 0 $
则
$ ℒ (dv(y(t), t, n)) = s^n ℒ[y(t)] = s^n Y(s) $
]
== 时域与频域
通过 Laplace 变换,将函数从时域转化至频域
$ f(t) F(s) $
即
$ ℒ[f(t)] = F(s) = ∫_0^∞ f(t) e^(-s t) dd(t) $
得到复数
$ s = σ + ω i $
此时,函数的图像就从二维转换成了三维。
当$σ = 0$时
$ F(s) = F(ω) = ∫_0^∞ f(t) e^(-j ω t) dd(t) $
$F(j ω)$-$j ω$的图像即为$f(t)$的 Fourier 变换。
== 收敛域
Laplace 变换后,要保证
- 分子 > $0$- 分子的每一部分都 > $0$
所以,还要加上关于$s$的收敛域(region of convergence,ROC)。如
$
ℒ[e^(-a t)] = ∫_0^∞ e^(-a t) e^(-s t) dd(t) = underbrace(∫_0^(+∞) e^(-(s + a))t) dd(t), 可 积
$
$e^(-a t)$的 Laplace 变换存在的条件是上式的积分可积
令$s = σ + j ω$
$
ℒ[e^(-a t)] = ∫_0^(+∞) e^(-a t) e^(-(σ + j ω)t) dd(t) = ∫_0^(+∞) e^(-(a + σ))t e^(-j ω t) dd(t)
$
由 Euler 公式
$ e^(-j ω t) = cos ω t - i sin ω t $
则$|e^(-j ω t)| = 1$,故可积取决于$e^(-(a + σ))t$,即
$ σ > - a $
#pagebreak()
= 常用 Laplace 变换
<常用-Laplace-变换>
== 指数函数
对函数$f(t) = e^(-a t)$
$
ℒ[e^(-a t)] &= ∫_0^∞ e^(-a t) e^(-s t) dd(t)
= ∫_0^∞ e^(-(a + s))t dd(t)
= frac(1, a + s)
$
显然,θ
$ ℒ[1] = 1 / s $
== 三角函数
Laplace 变换是一种线性变换。对线性系统
$ ℒ[a f(t) + b g(t)] = a F(s) + b G(s) $
由 Euler 公式
$
e^(i θ) &= cos θ + i sin θ\
e^(i (-θ)) &= cos θ - i sin θ
$
得
$ sin θ = frac(e^(i θ) - e^(-i θ), 2 i) $
于是
$
ℒ[sin(a t)] &= ℒ (frac(e^(i a t), 2 i)) - ℒ (frac(e^(-i a t), 2 i))\
&= 1 / 2i (ℒ[e^(i a t)]) - ℒ[e^(-i a t)] (\
&= 1 / 2i (frac(1, s - a i) - frac(1, s + a i))\
&= frac(a, s^2 + a^2)
$
同理
$
ℒ[cos(a t)] = frac(s, s^2 + a^2)\
ℒ[sinh(a t)] = frac(a, s^2 - a^2)\
ℒ[cosh(a t)] = frac(s, s^2 - a^2)
$
== 导数
分部积分
$ ∫f^′(t) g(t) dd(t) = f(t) g(t) - ∫f(t) g^′(t) dd(t) $
有
$
ℒ[f^′(t)] &= ∫_0^(+∞) f^′(t) e^(-s t) dd(t)\
&= f(t) e^(-s t) bar.v_0^∞ - ∫_0^(+∞) f(t)(-s e^(-s t))) dd(t)\
&= lim_(t → ∞) f(∞) e^(-s t) - f(0) + s ∫_0^(+∞) f(t) e^(-s t) dd(t)\
&= s F(s) - f(0)
$
#tip[
因为初始条件$f(0)$往往被选定为$0$,所以
$ ℒ[f^′(t)] = s F(s) $
]
进而有
$ ℒ[f^″(t)] = s^2 F(s) - s f(0) - f^′(0) $
以及
$ ℒ[∫_0^t f(τ) dd(t)] = 1 / s F(s) $
== 逆变换
通过 Laplace 变换求解微分方程主要有 3 步
+ Laplace 变换:$ℒ[f(x)], med t → s$
+ 求解代数方程
+ Laplace 逆变换:$ℒ^(-1)[f(x)], med s → t$
指数
$ ℒ (- frac(1, s + a)) = e^(-a t) $
三角函数
$
sin 2 t &= frac(e^(-2 i t) - e^(2 i t), 2 i)\
cos 2 t &= frac(e^(-2 i t) + e^(2 i t), 2)
$
#pagebreak()
= 系统设计
<系统设计>
== 电路系统
#figure(
image("./images/model/circuit.drawio.png", width: 25%),
caption: [电路],
supplement: "图",
)
由 KCL 有
$ e^′ = L i^″ + R i^′ + 1 / C i $
令初始条件为$0$,等式两边进行导数的 Laplace 变换,得
$ s E[s] = L s^2 I_(s) + s R I_(s) + 1 / C I_(s) $
从而有
$ I(s) = frac(s, L s^2 + R s + 1/C) E[s] $
转换为框图形式,即有
#figure(
diagram(
spacing: (2em, 2em),
node-stroke: 1pt,
mark-scale: 80%,
let (M, A, B) = ((4, 1), (2, 1), (6, +1)),
node(
M,
text($frac(s, L s^2 + R s + 1\/C)$, size: 1.2em),
height: 2.5em,
corner-radius: 3pt,
),
edge(A, M, $E(s)$, "-|>"),
edge(M, B, $I(s)$, "-|>"),
),
caption: "",
supplement: "\n图",
)
中间的函数即输出函数与输入函数的比值,称为#strong[传递函数(transfer function)]。
== 流体系统
#figure(
image("./images/model/liquid.drawio.png", width: 40%),
caption: [流体系统],
supplement: "图",
)
由上图
$ dv(h, t) + frac(g, R A) h = q_(i n) / A $
令
- $A = 1$
- $x = h$
- $u = q_(i n)$
得
$ x ̇(t) + g / R x(t) = u(t) $
两端做 Laplace 变换,得
$ s X(s) + g / R X(s) = U(s), med x(0) = 0 $
从而有,开环传递函数$G(s)$
$ G(s) = frac(X(s), U(s)) = frac(1, s + g/R) $
当$u(t) = C$,则
$ lim_(t → ∞) h = C R / g $
对闭环系统,此时引入参考值$V(s)$,输入值变成了$X(s) H(s)$
#figure(
diagram(
spacing: (2em, 2em),
node-stroke: 1pt,
mark-scale: 80%,
let (R, O, T, H, A) = ((1, 1), (2, 2), (4, 1), (4, 2), (5, 1.5)),
node(R, $V(s)$, height: 2em, corner-radius: 3pt),
node(O, text($+ quad -$, size: 0.6em), inset: 1em, radius: 1em),
node(T, $D(s)G(s)$, height: 2em, width: 6em, corner-radius: 3pt),
node(H, $H(s)$, height: 2em, width: 6em, corner-radius: 3pt),
edge(R, O, "-|>", corner: left),
edge(
O,
T,
text($V(s)-X(s)H(s)$, size: 0.6em),
"-|>",
corner: right,
label-pos: 0.7,
),
edge(T, A, text($X(s)$, size: 0.6em), "-", corner: right, label-pos: 0.4),
edge(A, H, "-", corner: right),
edge(H, O, text($X(s)H(s)$, size: 0.6em), "-|>"),
),
caption: "闭环系统",
supplement: "\n图",
)
由
$ (V - X H)(D G) = X $
得,闭环传递函数
$ X = V frac(D G, 1 + H D G) $
于是可知
#figure(
diagram(
spacing: (2em, 2em),
node-stroke: 1pt,
mark-scale: 80%,
let (M, A, B) = ((4, 1), (2, 1), (6, +1)),
node(M, $frac(D G, 1 + H D G)$, height: 2em, corner-radius: 3pt),
edge(A, M, $V$, "-|>"),
edge(M, B, $X$, "-|>"),
),
caption: "",
supplement: "\n图",
)
== 非零初始条件
对一阶方程
$ x ̇(t) + a x(t) = u(t) $
当$x(0) = 0$时,有
$ G(s) = frac(X(s), U(s)) = frac(1, s + a) $
当$x(0) ≠ 0$时,有
$ G(s) = frac(X(s), U(s) + x(0)) = frac(1, s + a) $
对 LTI 系统,根据叠加原理,$x(0)$为另一输入,令其为$U_2(s)$,有
$ ℒ^(-1)[U_2(s)] = ℒ^(-1)[x(0)] $
即
$ U_2(t) = x(0) δ(t) $
其中,$δ(t)$为单位冲击,$x(0)$为冲击幅度。
|
|
https://github.com/Zuttergutao/Typstdocs-Zh-CN- | https://raw.githubusercontent.com/Zuttergutao/Typstdocs-Zh-CN-/main/testfile/symbol.typ | typst | output all symbols
#math.dif
$ dif $
ss:
type: ieee
title: 这是某本书的参考表七日
author: 悟性, 王朝, 但是
|
|
https://github.com/noahjutz/AD | https://raw.githubusercontent.com/noahjutz/AD/main/notizen/sortieralgorithmen/mergesort/merge_inplace.typ | typst | #import "/components/num_row.typ": num_row, arrowed
#let nums = (12, 23, 34, 34, 45, 7, 17, 18, 38, 43)
#let n = nums.len()
#let a1f = 0
#let a2f = calc.div-euclid(n, 2)
#let a1s(nums) = {
return nums.enumerate()
.filter(((i, x)) => x in (12, 23, 34, 45))
.map(((i, x)) => i)
}
#let a2s(nums) = {
return nums.enumerate()
.filter(((i, x)) => x in (7, 17, 18, 38, 43))
.map(((i, x)) => i)
}
#let min_idx(nums, a1f, a2f) = {
if nums.at(a1f) <= nums.at(a2f) {
return a1f
} else {
return a2f
}
}
#let numrow(nums, a1f, a2f) = num_row(
nums,
hl_primary: a1s(nums).filter(n => n != a1f),
hl_secondary: a2s(nums).filter(n => n != a2f),
hl_tertiary: (a1f, a2f),
arrow: (
from: min_idx(nums, a1f, a2f),
to: a1f
),
labels: (
(a1f, a1f+1, arrowed[`a1f`]),
(a2f, a2f+1, arrowed[`a2f`])
)
)
#let step(step, nums, a1f, a2f) = {
for i in range(step) {
let minidx = min_idx(nums, a1f, a2f)
nums.insert(a1f, nums.remove(minidx))
a1f += 1
if minidx == a2f {a2f += 1}
}
return (nums, a1f, a2f)
}
#table(
columns: (auto,) + (1fr,) * nums.len(),
align: center,
..for i in range(3) {
numrow(
..step(i, nums, a1f, a2f)
)
}
)
#align(center, [...]) |
|
https://github.com/dashuai009/dashuai009.github.io | https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/__template/style.typ | typst | #let conf(doc) = {
let quote(body) = {
rect(fill: luma(240), stroke: (left: 0.25em))[
#body
]
}
show raw.line: it => {
text(fill: gray)[#it.number]
h(1em)
it.body
}
set text(font: ( "Noto Sans SC", "Source Han Sans"), lang: "zh", region: "cn")
set par(leading: 1em)
set page(width: 35em, height: auto, margin: 0.5em)
doc
} |
|
https://github.com/galaxia4Eva/galaxia4Eva | https://raw.githubusercontent.com/galaxia4Eva/galaxia4Eva/main/notes/reading-lists/Software/Julia.md | markdown | # Organisational
1. https://julialang.org/community/
# Triage
1. [Home · JuliaNotes.jl](https://m3g.github.io/JuliaNotes.jl/stable/)
2. [Building static websites in Julia](https://franklinjl.org/)
- [OpenSourc.ES](https://opensourc.es/)
- [<NAME> | Moin.](https://ronnybergmann.net/)
- [<NAME>](https://fredrikekre.se/)
- [Home](https://jacobzelko.com/)
- [Home - Huijzer.xyz](https://huijzer.xyz/)
- [<NAME>](https://rmsrosa.github.io/en/)
3. [Tier 3 target proposal: x86_64-unknown-none (freestanding/bare-metal x86-64) · Issue #462 · rust-lang/compiler-team · GitHub](https://github.com/rust-lang/compiler-team/issues/462)
4. https://viralinstruction.com/posts/latency/
5. https://discourse.julialang.org/t/building-julia-documentation-using-typst/97498
6. https://discourse.julialang.org/t/anyone-crazy-enough-to-develop-a-pure-julia-gui-toolbox/74002
7. https://towardsdatascience.com/6-julia-frameworks-to-create-desktop-guis-and-web-apps-9ae1a941f115
8. https://github.com/JuliaInterop/OctCall.jl
9. https://github.com/AlgebraicJulia/CompTime.jl
10. https://github.com/queryverse/Query.jl
11. https://github.com/aviatesk/JET.jl
12. https://docs.julialang.org/en/v1/manual/embedding/
13. https://github.com/korsbo/Latexify.jl
14. https://github.com/simonschoelly/KittyTerminalImages.jl
15. https://github.com/MakieOrg/Makie.jl
16. https://ahsmart.com/assets/pages/data-wrangling-with-data-frames-jl-cheat-sheet/DataFramesCheatSheet_v1.x_rev1.pdf
17. https://www.youtube.com/watch?v=Q8fj8QbVpZM
18. |
|
https://github.com/npujol/chuli-cv | https://raw.githubusercontent.com/npujol/chuli-cv/main/modules/languages.typ | typst | MIT License | #import "styles.typ": *
#let render-language(nivel: 2) = {
for k in range(0, 5) {
if k < nivel {
box(circle(
radius: language-style.radius,
fill: colors.accent,
))
}
else {
box(
circle(
radius: language-style.radius,
fill: colors.inactive,
))
}
h(language-style.margins.between-tags)
}
} |
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/styleMoleben.typ | typst | #import "SK/texts.typ": *
#let velebenie(vozhlas, verse) = [
#header[Velebenie:]
#vozhlas
#note[(Opakuje sa po každom verši)]
#primText[Verše:]
#pad(left:30pt)[
#let c = counter("verse")
#c.update(1)
#table(
columns: (auto, auto),
stroke: none,
align: (x, y) => (right, left).at(x),
..verse.map(v => (primText[#c.display("i"); #c.step()],[#v])).flatten()
)
]
]
#let chvaly() = [
#K[Modlime sa k Pánovi.]
#L[Pane, zmiluj sa.]
#K[Svätý si, Bože náš, a medzi svätými prebývaš a my ti vzdávame slávu, Otcu i Synu i Svätému Duchu, teraz i vždycky i na veky vekov.]
#L[Amen.]
#K[Všetko, čo dýcha, nech chváli Pána.]
#L[Všetko, čo dýcha, nech chváli Pána.]
#note[(Opakujeme po každom verši)]
#vers[Chváľte Pána v jeho svätyni.]
#vers[Chváľte ho na jeho vznešenej oblohe.]
]
#let nadpis = (
"Mt": "Čítanie zo svätého evanjelia podľa Matúša",
"Lk": "Čítanie zo svätého evanjelia podľa Lukáša",
"Mk": "Čítanie zo svätého evanjelia podľa Marka",
"Jn": "Čítanie zo svätého evanjelia podľa Jána"
)
#let evanjelium(evajnelista, txt) = [
#header[Evanjelium]
#K[Aby nás uznal za hodných vypočuť sväté evanjelium, <NAME> prosme.]
#L[Pane, zmiluj sa (3x).]
#K[Premúdrosť, pozorne počúvajme sväté evanjelium. Pokoj všetkým!]
#L[I tvojmu duchu.]
#K[#nadpis.at(evajnelista)]
#L[Sláva tebe, Pane, sláva tebe.]
#K[Vnímajme!]
#txt
#L[Sláva tebe, Pane, sláva tebe.]
#note[Ľud si sadne.]
]
#let verse(vozhlas, verse) = [
#if (vozhlas != none and verse != none) [
#header[Verše]
#primText[Vozhlas: ] #vozhlas
#note[(Ľud opakuje po každom verši)]
#let c = counter("verse")
#c.update(1)
#table(
columns: (auto, auto),
stroke: none,
align: (x, y) => (right, left).at(x),
..verse.map(v => (primText[#c.display("i"); #c.step()],[#v])).flatten()
)
]
]
#let stichiry(values) = [
#header[Stichiry]
#let (..all, last) = values
#let i = 0
#while i < all.len() {
stich(..all.at(i))
if i+1 < all.len() {
vers(all.at(i+1))
}
i = i+2
}
#sit(..last)
]
#let modlitba(txt) = [
#note[Ľud si kľakne.]
#K[V pokore kľaknime a v pokoji <NAME> prosme.]
#L[Pane, zmiluj sa #note[(3x)].]
#K[#txt]
#L[Amen.]
#note[Ľud si sadne.]
]
#let ektenia(prosby) = [
#header[Ekténia]
#let (first, ..all) = prosby
#K[#first]
#L[Pane, zmiluj sa #note[(3x po každej prosbe)].]
#for it in all [
#it\
]
#L[Amen.]
] |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/import-12.typ | typst | Other | // Error: 9-20 file not found (searched at typ/compiler/lib/0.2.1)
#import "lib/0.2.1"
|
https://github.com/glambrechts/slydst | https://raw.githubusercontent.com/glambrechts/slydst/main/README.md | markdown | MIT License | # Slydst
Create simple static slides with Typst.
Slydst allows the creation of slides using Typst headings.
This simplicity comes at the expense of dynamic content such as subslide animations.
For more complete and complex slides functionalities, see other tools such as Polylux.
## Usage
To start, just use the following preamble (only the title is required).
```typst
#import "@preview/slydst:0.1.1": *
#show: slides.with(
title: "Insert your title here", // Required
subtitle: none,
date: none,
authors: (),
layout: "medium",
ratio: 4/3,
title-color: none,
)
Insert your content here.
```
Then, insert your content.
- **Level-one headings** corresponds to new sections.
- **Level-two headings** corresponds to new slides.
- Blank space can be filled with **vertical spaces** like `#v(1fr)`.
```typst
== Outline
#outline()
= First section
== First slide
#figure(image("figure.png", width: 60%), caption: "Caption")
#v(1fr)
#lorem(20)
```
## Components
Definitions, theorems, lemmas, corollaries and algorithms boxes are also available.
```typst
#definition(title: "An interesting definition")[
#lorem(20)
]
```
## Documentation
### `slides`
- `content`: `content` - content of the presentation
- `title`: `str` - title (required)
- `subtitle`: `str` - subtitle
- `date`: `str` - date
- `authors`: `array` of `content` or `content` - list of authors or author content
- `layout`: `str in ("small", "medium", "large")` - layout selection
- `ratio`: `float` or `ratio` or `int` - width to height ratio
- `title-color`: `color` or `gradient` - color of title and headings
### `definition`, `theorem`, `lemma`, `corollary`, `algorithm`
- `content`: `content` - content of the block
- `title`: `str` - title of the block
## Example
<kbd><img src="svg/example-01.svg" width="300"></kbd> <kbd><img src="svg/example-02.svg" width="300"></kbd> <kbd><img src="svg/example-03.svg" width="300"></kbd> <kbd><img src="svg/example-04.svg" width="300"></kbd> <kbd><img src="svg/example-05.svg" width="300"></kbd> <kbd><img src="svg/example-06.svg" width="300"></kbd> <kbd><img src="svg/example-07.svg" width="300"></kbd> <kbd><img src="svg/example-08.svg" width="300"></kbd> <kbd><img src="svg/example-09.svg" width="300"></kbd> <kbd><img src="svg/example-10.svg" width="300"></kbd>
|
https://github.com/Woodman3/modern-ysu-thesis | https://raw.githubusercontent.com/Woodman3/modern-ysu-thesis/main/layouts/page-header.typ | typst | MIT License | #import "../utils/style.typ": 字号, 字体
#import "../utils/custom-numbering.typ": custom-numbering
#import "../utils/custom-heading.typ": heading-display, active-heading, current-heading,header-display
#import "../utils/unpairs.typ": unpairs
#let page-header(
twoside: false,
fonts: (:),
// 其他参数
numbering: custom-numbering.with(first-level: "第1章 ", depth: 4, "1.1 "),
heading-align: (center, auto),
// 页眉
header-render: auto,
header-vspace: 0em,
display-header: true,
stroke-width: 0.5pt,
reset-footnote: true,
..args,
it,
) = {
set page(..(if display-header {
(
header: {
// 重置 footnote 计数器
if reset-footnote {
counter(footnote).update(0)
}
locate(loc => {
// 5.1 获取当前页面的一级标题
if header-render == auto {
// let cur-heading = current-heading(level: 1, loc)
let first-level-heading = if calc.rem(loc.page(), 2)==1 {
heading-display(active-heading(level: 1,prev:false, loc))
} else {
"燕山大学本科生毕业设计(论文)"
}
header-display(first-level-heading)
} else {
header-render(loc)
}
v(header-vspace)
})
}
)
} else {
(
header: {
// 重置 footnote 计数器
if reset-footnote {
counter(footnote).update(0)
}
}
)
}))
it
} |
https://github.com/jordanqt327/Typst-Pruebas | https://raw.githubusercontent.com/jordanqt327/Typst-Pruebas/main/README.md | markdown | # Typst-Pruebas
Repositorio dedicado a experimentar y aprender el uso de Typst. Aquí se encuentran ejemplos, pruebas y ejercicios.
|
|
https://github.com/drupol/master-thesis | https://raw.githubusercontent.com/drupol/master-thesis/main/src/thesis/accessibility.typ | typst | Other | #import "imports/preamble.typ": *
#pagebreak(weak: true)
#heading("Accessibility", level: 1, outlined: false)
This master thesis has been written with a focus on accessibility to ensure it
can be easily read and understood by a diverse audience, including individuals
with disabilities. The following measures have been taken to enhance
accessibility:
- Links: all hyperlinks within this document are underlined and clearly
distinguishable from regular text. This visual cue helps users identify
clickable links easily.
- Symbols and notation: specific symbols and notation have been used
consistently throughout the document to aid comprehension. Mathematical
symbols, special characters, and other notation are presented in a clear and
readable manner.
- Text formatting: the document uses high-contrast text formatting and font
sizes that are readable across different devices and screen resolutions. The
`New Computer Modern` #cite(<NewComputerModern>,form:"normal") font is used,
chosen for its clarity and readability, especially in mathematical and
technical contexts.
- Margins: the margins have been alternately adapted to ensure that when the
document is printed, it is suitable for binding and easy to read. This
consideration enhances the physical accessibility of the printed document.
- Headings and structure: the document is structured with clear headings and
subheadings to facilitate navigation. This hierarchical organisation assists
readers in quickly finding relevant sections.
- Language and terminology: plain language and concise terminology have been
employed to ensure that the content is comprehensible to a broad audience,
including those for whom English is not their first language.
- Glossary: a #link(<glossary>)[glossary] is included, containing the
most common abbreviations used throughout the document. This aids readers in
quickly understanding the abbreviations and acronyms, improving overall
comprehension. Additionally, comprehensive lists of
#link(<list-of-definitions>)[definitions], #link(<list-of-figures>)[figures],
and #link(<list-of-tables>)[tables] are provided.
- Accessible file formats: the document is available in multiple file formats,
to accommodate various reading preferences and assistive technologies.
- Bibliography links: in line with the #gls("IEEE") citation style, numbers in
brackets are used to link references in the
#link(<bibliography>)[bibliography]. This method provides a clear and
consistent way to reference sources, enhancing the readability and
accessibility of the document.
- Images: all images in this document are in #gls("SVG") format. This vectorial
format ensures that images are scalable without loss of quality, providing
clear and accessible visuals on different devices and screen resolutions.
|
https://github.com/pank-su/report_3 | https://raw.githubusercontent.com/pank-su/report_3/master/main.typ | typst | #import "templates/index.typ": *
#import "templates/utils.typ": *
#import "libs/tablex.typ": *
// Тут указываем только авторов [authors] и название работы [title]
#show: index.with(authors: ("<NAME>", ), title: [ОТЧЁТ О ПРАКТИКЕ])
// ch -- center heading
#ch("Введение")
Производственная практика проходила на предприятии ООО “ВАЛДАЙ РОБОТЫ”. Основной вид деятельности предприятия: «Производство промышленных роботов и робототехнических устройств»
Структура предприятия представлена на рисунке @org_structure.
#figure(
image(ip("org_structure.png")),
caption: "Структура организации"
) <org_structure>
Практика будет проходить в отделе разработки ПО, в подотделе разработки ПО высокого уровня.
Перед отделом стоят цели разработки автономной работы роботизированных устройств, а также разработки связанного с этим ПО, например, программ для операторов устройств.
Отдел не имеет фиксированных требований к конкретному программному обеспечению, что позволяет использовать наиболее подходящие инструменты для каждой задачи. В настоящий момент работа ведется с помощью следующих программ:
\1. Редактор исходного кода Visual Studio Code:
Описание: Популярный редактор с открытым исходным кодом, разработанный Microsoft.
Преимущества:
| Поддержка подсветки синтаксиса для различных языков программирования.
| Множество расширений, добавляющих дополнительные функции, такие как отладка, автодополнение кода и интеграция с системами контроля версий.
| Кроссплатформенность (доступен для Windows, macOS и Linux).
Использование: В отделе используется для написания кода на различных языках программирования, таких как C++, Python, JavaScript и Go.
\2. IDE Keil µVision:
Описание: Интегрированная среда разработки (IDE) для микроконтроллеров семейства ARM Cortex-M.
Преимущества:
| Встроенный компилятор, отладчик и симулятор.
| Поддержка различных отладочных инструментов, таких как J-Link и ULINK.
| Библиотека готовых к использованию программных модулей.
Использование: В отделе используется для разработки программного обеспечения для микроконтроллеров, используемых в различных проектах.
\3. Git:
Описание: Система контроля версий, позволяющая отслеживать изменения в файлах и коде.
Преимущества:
| Позволяет работать над проектами совместно с другими разработчиками.
| Помогает отслеживать историю изменений и откатывать к предыдущим версиям.
| Обеспечивает децентрализованное хранение кода.
Использование: В отделе используется для контроля версий исходного кода, документации и других файлов.
\4. Gitea:
Описание: Локальный Git-сервер, позволяющий хранить и управлять Git-репозиториями.
Преимущества:
| Позволяет работать с Git-репозиториями в локальной сети без доступа к интернету.
| Обеспечивает более высокий уровень безопасности и контроля над кодом.
| Прост в установке и использовании.
Использование: В отделе используется для хранения Git-репозиториев, доступ к которым требуется только сотрудникам отдела.
#pagebreak()
= Разработка технического задания
Разработанное техническое задание представлено в приложении А.
#pagebreak()
= Проектирование приложения
== Анализ предметной области
Назначение разрабатываемой системы состоит в создании альтернативного мультиплатформенного открытого приложения для воспроизведения музыки из сервиса Яндекс Музыка. Это приложение будет обеспечивать единые функциональные возможности в различных версиях. Основные проблемы, которые система должна решить, включают отсутствие возможности совместного прослушивания музыки различными пользователями, ограниченный набор настроек, закрытость системы. Решением этих проблем будет распространение исходного кода для дальнейшей модернизации системы, а также возможность инсталляции дополнительных модулей сторонних разработчиков.
Система будет обладать рядом функциональных возможностей, включая прослушивание музыки из библиотеки Яндекс Музыка, перемешивание треков, цикличное прослушивание, функцию "Моя волна" для бесконечного потока треков, а также возможность установки плагинов от сторонних разработчиков. Кроме того, пользователи смогут проводить совместное прослушивание треков и настраивать цветовую схему приложения.
Дизайн системы будет выполнен в стиле Material You с применением основных принципов и элементов этого дизайна. Подобные продукты на рынке включают Яндекс Музыка, Spotify и Apple Music, однако они не обладают всеми необходимыми функциями, предложенными разрабатываемой системой.
Система будет тиражируемой и доступной для пользователей во всех странах, где доступно приложение Яндекс Музыка. Предполагается обмен данными с API Яндекс Музыка. К моменту реализации она будет предоставлена на бесплатной основе для неограниченного числа пользователей. Приложение разработано для широкого круга пользователей и не требует дополнительного обучения для использования. Единственный необходимый канал связи - интернет, который также необходим для загрузки треков. Данные хранятся распределённо, частично в самом приложении, частично на серверах Яндекс Музыка. Учитываются привычки пользователей при использовании аналогичных приложений, чтобы облегчить переход на новую систему.
== Проектирование структуры приложения
Для разработки приложения будет использован фреймворк Kotlin Multiplatform, из-за чего код распределён на:
| common (общий) -- код, который будет работать на всех платформах;
| native -- код, который работает нативно на каждой платформе (android, jvm, windows, iOS, MacOS). @kmp
При этом в common части будет использована концепция Clean Architecture и паттерн MVVM, благодаря чему приложение было разделено на несколько слоев:
| data -- слой получения данных;
| ui -- слой пользовательского интерфейса;
| viewmodel -- смежный слой, между data и ui;
| model -- вспомогательные модели для интерфейса.
Итоговая структура приложения представлена на рисунке @structure.
#figure(
image(ip("structure.png")),
caption: "Структура мобильного приложения"
) <structure>
Для навигации будет использована библиотека Appyx, которая представляет навигацию в виде графов, для более простого её использования была создана диаграмма путей пользователя, представленная на рисунке @userflow.
#figure(
image(ip("userflow.png")),
caption: "Пути пользователя"
) <userflow>
== Проектирование базы данных
В ходе проектирования работы приложения, было принято решение разрабатывать приложение используя offline first подход.
Offline First - это подход к разработке программного обеспечения, при котором основное внимание уделяется обеспечению надежной работы приложения в условиях отсутствия интернет-соединения или при низкой его стабильности. Главная идея заключается в том, чтобы приложение могло выполнять основные функции даже в отсутствие активного сетевого соединения. @offlinefirst
Для сохранение данных в приложении была спроектирована база данных, полная схема которой представлена на рисунке @dbScheme. Логическая структура таблиц представлена на таблицах @firstTable\-@lastTable.
#figure(
image(ip("dbScheme.png"), height: 70%),
caption: "Схема базы данных"
) <dbScheme>
Таблица @firstTable содержит сведения об альбомах.
#figure(
tablex(columns: 5, repeat-header: true,
[Признак ключа], [Имя поля], [Тип данных поля], [Назначение],
[Ограничения],
[PK],
[id],
[INTEGER],
[Уникальный идентификатор альбома],
[\>0, NOT NULL, AI],
[],
[title],
[TEXT],
[Название альбома],
[],
[],
[trackCount],
[INTEGER],
[Количество треков в альбоме],
[],
[],
[cover],
[TEXT],
[Ссылка на обложку альбома],
[],
),
caption: "Описание логической структуры таблицы ALBUM",
supplement: "Таблица",
kind: table
) <firstTable>
Таблица @albumArtist является вспомогательной таблицей для для связи многие ко многим исполнителя к альбомам.
#figure(
tablex(columns: 5, repeat-header: true,
[Признак ключа], [Имя поля], [Тип данных поля], [Назначение],
[Ограничения],
[],
[albumId],
[INTEGER],
[Идентификатор альбома],
[NOT NULL, \ FK(ALBUM.id)],
[],
[artistId],
[INTEGER],
[Идентификатор исполнителя],
[NOT NULL, \ FK(ARTIST.id)]
),
caption: "Описание логической структуры таблицы ALBUM_ARTIST",
supplement: "Таблица",
kind: table
) <albumArtist>
Таблица @albumTrack - вспомогательная таблица для для связи многие ко многим музыкального трека к альбомам.
#figure(
tablex(columns: 5, repeat-header: true,
[Признак ключа], [Имя поля], [Тип данных поля], [Назначение],
[Ограничения],
[],
[albumId],
[INTEGER],
[Идентификатор альбома],
[NOT NULL, \ FK(ALBUM.id)],
[],
[trackId],
[INTEGER],
[Идентификатор трека],
[NOT NULL, \ FK(TRACK.id)],
[],
[position],
[INTEGER],
[Позиция трека в альбоме],
[NOT NULL,\ CHECK \(position \>\= 0)]
),
caption: "Описание логической структуры таблицы ALBUM_TRACK",
supplement: "Таблица",
kind: table
) <albumTrack>
Таблица @artist содержит информацию об исполнителях.
#figure(
tablex(columns: 5, repeat-header: true,
[Признак ключа], [Имя поля], [Тип данных поля], [Назначение],
[Ограничения],
[PK],
[id],
[INTEGER],
[Уникальный идентификатор исполнителя],
[\>0, NOT NULL],
[],
[name],
[TEXT],
[Имя исполнителя],
[NOT NULL],
[],
[cover],
[TEXT],
[Ссылка на обложку исполнителя],
[],
),
caption: "Описание логической структуры таблицы ARTIST",
supplement: "Таблица",
kind: table
) <artist>
Таблица @track содержит информацию о треках.
#figure(
tablex(columns: 5, repeat-header: true,
[Признак ключа], [Имя поля], [Тип данных поля], [Назначение],
[Ограничения],
[PK],
[id],
[INTEGER],
[Уникальный идентификатор трека],
[NOT NULL],
[],
[title],
[TEXT],
[Название трека],
[],
[],
[duration],
[INTEGER],
[Продолжительность трека (в секундах)],
[],
[],
[link],
[TEXT],
[Ссылка на трек],
[DEFAULT NULL],
[],
[isExplicit],
[INTEGER],
[Флаг эффективности (0 или 1)],
[NOT NULL, \ CHECK \ (isExplicit IN (0, 1)) DEFAULT 0],
[],
[linkDateUpda-ted],
[TEXT],
[Время последнего обновления ссылки на трек],
[],
),
caption: "Описание логической структуры таблицы TRACK",
supplement: "Таблица",
kind: table
) <track>
Таблица @lastTable содержит информацию о пользователях.
#figure(
tablex(columns: 5, repeat-header: true,
[Признак ключа], [Имя поля], [Тип данных поля], [Назначение],
[Ограничения],
[PK],
[uid],
[TEXT],
[Уникальный идентификатор пользователя],
[NOT NULL, UNIQUE],
[],
[displayName],
[TEXT],
[Отображаемое имя пользователя],
[NOT NULL],
[],
[avatarLink],
[TEXT],
[Ссылка на аватар пользователя],
[NOT NULL, UNIQUE],
[],
[token],
[TEXT],
[Токен пользователя],
[NOT NULL],
[],
[isPlus],
[INTEGER],
[Флаг подписки (0 или 1)],
[NOT NULL, \ CHECK(isPlus IN (0, 1))],
[],
[yandexMusicId],
[INTEGER],
[Идентификатор пользователя в Яндекс.Музыке],
[UNIQUE],
),
caption: "Описание логической структуры таблицы USER",
supplement: "Таблица",
kind: table
) <lastTable>
#pagebreak()
= Разработка дополнения к техническому заданию, модификация приложения
Основанием для выпуска протокола разногласий №1 к техническому заданию является решения производителя в связи с практическими результатами эксплуатации приложения "Yay!". Протокол разногласий к техническому заданию указан в приложении Б.
При окончании составления протокола разногласий было принято решение
выпуска дополнения к техническому заданию.
Дополнение к техническому заданию представлено в приложении В.
#pagebreak()
= Оценка качества информационной системы
В ходе ручного тестирования приложения была составлена таблица @cringe_table. Оценивание происходит
от 0 до 1 с пояснением оценки в комментарии. Оценивание было произведено экспертным методом.
#figure(
table(
columns: (2fr, 1fr, 3fr),
align: center,
table.header(
[Критерий], [Оценка], [Комментарий]
),
[Функциональность], [0.5], [Заявленная функциональность реализована не в полном составе
],
[Скорость работы], [0.8], [При воспроизведении музыкальной композиции в приложении наблюдались небольшие задержки],
[Дизайн интерфейса], [0.9], [Дизайн соответствует стандартам Material Design 3],
[Удобство использования], [0.7], [
Разработка интерфейса проводилась группой учащихся и тестировалась на рабочей группе: преподаватели.
Фокус группа показала что интерфейс прост в понимании.],
[Безопасность данных], [1], [Из личных данных пользователя хранится только аутентификационный токен пользователя],
[Совместимость с различными устройствами и платформами], [0.6], [Работает на устройствах с операционными системами: Windows, Linux, Android, MacOS]
),
caption: "Оценка качества приложения",
) <cringe_table>
Помимо качественности приложения, необходимо оценить и его надежность. Критерии и метрики для оценки надежности представлены в ГОСТе 28195-89.
Фактор надёжности включает в себя два критерия:
| Устойчивость функционирования – способность обеспечивать продолжение работы программы после возникновения отклонений, вызванных сбоями технических средств, ошибками во входных данных и ошибками обслуживания;
| Работоспособность – способность программы функционировать в заданных режимах и объёмах обрабатываемой информации в соответствии с программными документами при отсутствии сбоев технических средств.
Оценка каждого из критериев включает в себя оценки метрик. В своей оценке каждая из метрик содержит оценки так называемых оценочных элементов. Каждый оценочный элемент обозначается кодом, составленным из 5 символов. Оценочные элементы и их коды приведены в таблице @fuck_table и на рисунке @fuck_table2.
#let results = csv("./src/tables/fuck.csv")
#figure(
table(
columns: 4,
table.header([Код элемента], [Наименование],[Метод оценки],[Оценка]),
..results.flatten(),
),
caption: "Оценочные элементы"
) <fuck_table>
#figure(
image(ip("fuck2.png")),
caption: "Оценочные элементы (продолжение)"
) <fuck_table2>
Оценим надёжность системы. Сначала определим оценочные элементы используемых метрик и занесём в таблицу @fuck_table3.
#let results2 = csv("./src/tables/fuck2.csv")
#figure(
table(
columns: 4,
table.header([Код оценочного
элемента], [Метод оценки],[Выбранное значение],[Обоснование]),
..results2.flatten(),
),
caption: "Определение оценочных элементов"
) <fuck_table3>
По полученным значениям оценочных элементов рассчитываются задействованные согласно данной фазе проектирования метрики. Оценка метрик представлена в таблице @fuck_table4.
#figure(
table(
columns: 3,
table.header([№],[Метрики],[Оценка]),
[1], [Средства восстановления при ошибках при вводе], [(0.8 + 0.8 + 0.3 + 0.2 + 0.8 + 0.7 + 0.8) / 7 = 0.76],
[2], [Средства восстановления при сбоях оборудования ], [Отсутствуют],
[3], [Реализация управления средствами восстановления], [0.6],
[4], [Функционирование в заданных режимах], [0.4],
[5], [Обеспечение обработки заданного объема информации], [(1 + 1) / 2 = 1]
),
caption: "Оценка метрик"
) <fuck_table4>
Далее необходимо выбрать весовой коэффициент для каждой метрики. Он определяет значимость этой метрики для дальнейшего расчёта. Для каждого критерия сумма весов входящих в него метрик должна равняться единице.
Весовые коэффициенты метрик указаны в таблице @fuck_table5.
#figure(
table(
columns: 2,
table.header([Метрика],[Весовой коэффициент]),
[Средства восстановления при ошибках при вводе], [0.1],
[Средства восстановления при сбоях оборудования], [Отсутствует],
[Реализация управления средствами восстановления], [0.1],
[Функционирование в заданных режимах], [0.8],
[Обеспечение обработки заданного объема информации], [0.6]
),
caption: "Оценка метрик"
) <fuck_table5>
Далее считаются абсолютные показатели каждому критерию фактора надёжности. Для этого необходимо суммировать произведение веса и оценки каждый метрики внутри каждого критерия.
Показатели каждому критерию указаны в таблице @fuck_table6.
#figure(
table(
columns: 2,
table.header([Критерий],[Оценка]),
[Устойчивость функционирования], [0.76 \* 0.1 + 0.8 \* 0.1 = 0.156],
[Работоспособность], [0.8 \* 0.4 + 1 \* 0.6 = 0.92],
),
caption: "Оценка метрик"
) <fuck_table6>
Выберем весовой коэффициент для каждого критерия. Как и для метрик, весовой коэффициент определяет значимость данного критерия для дальнейшего расчёта. Сумма весов должна равняться единице.
Весовые коэффициенты представлены в таблице .
#figure(
table(
columns: 2,
table.header([Критерий],[Весовой коэффициент]),
[Устойчивость функционирования], [0.3],
[Работоспособность], [0.7],
),
caption: "Оценка метрик"
) <fuck_table7>
Получим, что K = 0,156 \* 0,3 + 0,92 \* 0,7 = 0,69. Что означает, что надёжность программы удовлетворяет требованиям.
#pagebreak()
= Тестирование
== План тестирования
В таблице, представлены идентификационные данные тест-плана.
#figure(
table(
columns: 2,
// table.header([Параметр], [])
[Идентификатор плана тестирования], [Yay-Master-6d0c1e19],
[Короткое имя], [YM],
[Автор], [<NAME>],
),
caption: "Информация об тест-плане"
)
=== Введение
Цель: описать набор тестов, которые необходимо выполнить для проверки функциональности и удобства использования приложения "Yay".
Уровень: Мастер
=== Тестовые сценарии
- Проверить работу на всех обозначенных операционных системах.
- Проверить авторизацию с помощью логина и пароля.
- Проверить авторизацию с помощью токена.
- Воспроизвести музыку.
=== Функции подлежащие тестированию
- авторизация через Яндекс;
- прослушивание музыки из библиотеки Яндекс Музыка;
=== Функции не подлежащие тестированию
- совместное прослушивание треков двумя разными пользователями.
- функция "Моя волна", которая обеспечивает бесконечный поток музыки;
- возможность установить плагины от сторонних разработчиков;
- переключение цветовой схемы приложения;
=== Программные или аппаратные зависимости
Система должна работать на современных системах: Windows 10-11 с поддержкой DirectX 12, MacOS версии выше Catalina, Linux 6.0 и выше с визуальным окружением Gnome 40 и выше, Android 10 и выше, IOS 16 и выше.
=== Зависимости и риски
| Сторонние библиотеки: Приложение может зависеть от сторонних библиотек, которые могут иметь свои уязвимости. Это может привести к проблемам безопасности, если эти уязвимости не будут должным образом устранены.
| Внешние сервисы: Приложение может зависеть от внешних сервисов, которые могут быть недоступны или работать некорректно. Это может привести к сбоям в работе приложения.
== Тест-кейс
// Аннотация к тестам приведена в таблице @anotation.
#figure(
table(columns: (1fr, 1fr),
[Название проекта],[Yay],
[Рабочая версия],[0.1],
[Имя тестирующего], [<NAME>],
[Дата теста], [07.04.2024]
),
caption: "Аннотация к тестам",
) <anotation>
В таблице @test_data приведены тестовые данные для автоматических тестов.
#figure(
table(columns: 2,
table.header(
[Имя], [Данные]),
[Email], [<EMAIL>],
[Password], [<PASSWORD>],
[Token], [#text("<KEY>")]
),
caption: "Тестовые данные"
) <test_data>
В таблице @tests2 приведены автоматические тесты.
#figure(
table(columns: (1.2fr, 1.3fr, 2fr, 3fr, 1.7fr, 1.7fr, 1.4fr),
table.header([Тестовый пример №], [Приоритет тестирования], [Краткое изложение теста],
[Этапы теста], [Ожидаемый результат], [Фактический результат], [Статус]),
[ТП-01], [Высокий], [Запуск приложения на всех операционных системах], [
-- Запуск приложения на Android;
-- Запуск приложения на Linux;
-- Запуск приложения в веб.
],[Запуск приложения без вылетов],[Запуск приложения без вылетов],[Пройден],
[ТП-02], [Высокий], [Авторизация с помощью логина и пароля], [
-- Выбор способа авторизации с помощью логина и пароля;
-- Ввод логина и пароля;
-- Нажать кнопку "Войти".
], [Отображение главной страницы приложения], [Отображение главной страницы приложения], [Пройден],
[ТП-03], [Высокий], [Авторизация с помощью токена], [
-- Выбор способа авторизации с помощью токена;
-- Ввод токена;
-- Нажать кнопку "Войти".
], [Отображение главной страницы приложения], [Отображение главной страницы приложения], [Пройден],
[ТП-04], [Высокий], [Воспроизведение музыки], [-- Пройти авторизацию любым способом;
-- Войти в любой альбом или плейлист;
-- Нажать по любому треку.
], [Воспроизведение музыкальной композиции], [Воспроизведение музыкальной композиции], [Пройден]
),
caption: "Автоматические тесты",
) <tests2>
== Выводы о тестировании
Тестирование показало, что приложение "Yay" соответствует всем поставленным требованиям. Не было обнаружено никаких критических ошибок или сбоев.
#pagebreak()
= Внедрение
Поскольку наше приложение ориентировано на развлечения и предназначено для широкой аудитории, не привязанной к определенным компаниям, процесс его внедрения будет представлен как публикация в магазине приложений.
== План внедрения
1. Подготовка ресурсов
1. Создание учётной записи разработчика в магазине приложения
2. Подготовка материалов для публикации:
- Скомпилированное приложение;
- Иконки в необходимых форматах;
- Скриншоты;
- Описание;
- Категория приложения.
2. Отправка на модерацию
3. Публикация
4. Маркетинг и продвижение
- Закупка рекламы в различных соц. сетях
- Создание сайта приложения
== Стратегии, цели и сценарии внедрения
+ Стратегии:
- Привлечение внимания:
- Использование ярких и привлекательных мультимедийных материалов
для захвата внимания пользователей в магазине приложений.
- Запуск маркетинговых кампаний, направленных на увеличение
видимости приложения в поисковой выдаче магазина.
- Удержание пользователей:
- Разработка интересного и привлекательного контента, способного
удерживать пользователей в приложении на протяжении длительного
времени.
- Внедрение системы вознаграждений, достижений и других механик,
стимулирующих возвращение пользователей.
- Масштабирование:
- Анализ рынка и поиск новых возможностей для расширения аудитории и
увеличения числа загрузок приложения.
- Разработка стратегии расширения на другие платформы и рынки.
+ Цели:
- Увеличение числа загрузок:
- Основная цель - добиться максимального числа загрузок приложения в
первые недели после публикации.
- Измерение успеха по числу установок и показателям конверсии.
- Повышение вовлеченности пользователей:
- Целью является создание приложения, способного удерживать
пользователей и мотивировать их к долгосрочному использованию.
- Измерение успеха по метрикам удержания, частоте и
продолжительности сеансов и т.д.
- Увеличение доходов:
- Увеличение доходов от покупок в приложении или от рекламы.
- Измерение успеха по объему выручки и другим метрикам монетизации.
+ Сценарии внедрения:
- Бесплатное приложение с рекламой:
- Приложение предоставляется пользователям бесплатно, но
монетизируется за счет показа рекламы.
- Стратегия внедрения: акцент на привлечении как можно большего
числа пользователей, чтобы увеличить объем показов рекламы.
- Фримиум-модель:
- Приложение предоставляется бесплатно, но пользователи могут
покупать дополнительный контент или функции внутри приложения.
- Стратегия внедрения: предоставление базового функционала
бесплатно, а затем стимулирование пользователей к покупке
премиум-контента.
- Платное приложение:
- Пользователи платят за загрузку и использование приложения.
- Стратегия внедрения: создание высококачественного и уникального
контента, который стоит своей цены, и акцент на его преимуществах
в маркетинговых кампаниях.
== Автоматизация процесса внедрения информационной системы
Для автоматизации процесса внедрения можно использовать GitHub Actions, которые позволят при создании нового релиза делать публикацию в необходимых магазинах приложений.
#pagebreak()
= Обеспечение безопасности программного обеспечения
Для обеспечения безопасности программного обеспечения необходимо предпринять ряд мер для минимизации актуальных угроз информационной безопасности в процессе разработки. Анализ существующих угроз поможет определить эффективные стратегии противодействия.
== Анализ угроз безопасности
При недостаточном соблюдении мер безопасности любое программное обеспечение подвержено различным угрозам конфиденциальности и целостности данных. Однако, когда речь идет о созданных модулях, потенциальные угрозы могут возникнуть во время процесса конструирования и интеграции ПО. Это объясняется тем, что при проектировании модулей обычно уделяется основное внимание математическим аспектам, требования формулируются минимально, а тестирование функционала часто производится вручную, что не всегда способствует выявлению потенциальных уязвимостей и вредоносных компонентов.
Из этого вытекает ряд возможных угроз, о которых будет рассказано далее.
== Перечень возможных угроз безопасности ПО
- Риск внедрения уязвимостей в исходный код программы в процессе её разработки.
- Опасность появления уязвимостей в программе через использование уязвимых компонентов, заимствованных у сторонних разработчиков программного обеспечения.
- Угроза возникновения уязвимостей в программе из-за ошибок в эксплуатационной документации, допущенных в процессе их создания и хранения.
== Перечень мер, предпринятых для обеспечения безопасности ПО
Для предотвращения упомянутых угроз безопасности ПО, учитывая особенности выбранного языка и фреймворка, были предприняты следующие шаги:
- Применение инструментов статического анализа кода: Ktlint, Detekt.
- Проведение код-ревью: на протяжении разработки проводились регулярные обзоры кода руководителем отдела разработки.
- Использование безопасных библиотек и фреймворков: в процессе разработки применялись только проверенные и популярные библиотеки и фреймворки, которые мало подвержены уязвимостям.
- Защита доступа к коду: исходный код хранился на локальном git-сервере, что повышало уровень защиты от непроизвольного внедрения уязвимостей.
- Использование системы контроля версий: Git (локальный сервер Gitea).
- Соблюдение государственных стандартов при написании документации.
== Выводы об обеспечении безопасности информации для напиcанного приложения
После тщательного анализа потенциальных угроз безопасности мы приняли ряд мер для предотвращения возможных инцидентов в контексте разработанной системы. Эти действия значительно снижают вероятность возникновения угроз, повышая уровень безопасности модулей и обеспечивая их надежное функционирование во взаимодействии с остальными компонентами робота, исключая риски информационных угроз.
// #pagebreak()
#pagebreak()
= Разработка руководства системному программисту
Руководство системному программисту предоставлено в приложении Г.
#pagebreak()
#ch("Заключение")
В ходе выполнения производственной практики по направлению ПМ03 "Сопровождение и обслуживание программного обеспечения компьютерных систем" все поставленные задачи и цели были успешно достигнуты.
Основное внимание было уделено обеспечению безопасности разработанных модулей. Это включало в себя тщательный анализ потенциальных уязвимостей, внедрение соответствующих мер по защите и проведение тестирования безопасности. Благодаря этим усилиям модули стали более надежными и защищенными от возможных атак.
Кроме того, была разработана подробная сопроводительная документация к каждому модулю, что обеспечит пользователям более глубокое понимание и использование нового функционала, а также упростит поддержку и сопровождение программного обеспечения.
Был разработан и представлен план внедрения написанных программных модулей, что позволит эффективно интегрировать их в уже существующую систему и использовать в реальных производственных условиях.
Таким образом, можно с уверенностью заключить, что производственная практика была выполнена успешно, демонстрируя высокий профессионализм и компетентность.
#pagebreak()
#ch("Список использованных источников")
#bibliography("bibliography.yml", title: none, full: true, style: "gost-r-705-2008-numeric")
#pagebreak()
#ch("Приложение А Разработка технического задания")
#counter(heading).update(0)
#show heading.where(level: 1): it => [ #it]
#fh("Введение")
Настоящее техническое задание распространяется на разработку кроссплатформенного приложения под названием «Yay»
Предложенное приложение - альтернатива приложению "Яндекс Музыка", включающее все функции оригинального приложения и решающее проблемы: отсутствие возможности совместного прослушивания музыки различными пользователями, отсутствие множества настроек, закрытость системы, путём распространение исходного кода для дальнейшей модернизации системы, обеспечение возможности установки дополнительных модулей (plug-in'ов) сторонних разработчиков.
Основная цель разрабатываемой программы — предоставить альтернативное мультиплатформенное открытое приложение по воспроизведению музыки из сервиса Яндекс Музыка, обеспечивающее единство функций в различных версиях.
#fh("Основание для разработки")
Основание для разработки является задание на производственную практику предприятия "Валдай роботы".
#fh("Назначение разработки")
#fhh("Функциональное назначение")
Создание альтернативного приложения для сервиса Яндекс Музыка, с возможностью прослушивания музыки различными пользователями, расширенными настройками, открытым исходным кодом для модернизации, и возможностью инсталляции дополнительных модулей от сторонних разработчиков. Это приложение предоставит мультиплатформенный и открытый доступ к функциям Яндекс Музыки, обеспечивая единство и удобство использования на различных устройствах.
#fhh("Эксплуатационное назначение")
Обеспечение пользователям доступа к сервису Яндекс Музыка через различные устройства (мобильные устройства, планшеты, компьютеры) с возможностью совместного прослушивания музыки, расширенными настройками, а также с возможностью установки дополнительных модулей от сторонних разработчиков для улучшения функциональности приложения. Это приложение предназначено для использования конечными пользователями с целью удобного и качественного доступа к музыкальному контенту.
#fh("Требование к информационной системе")
#fhh("Требование к функциональным характеристикам")
Функциональными характеристиками системы являются:
- авторизация через Яндекс;
- прослушивание музыки из библиотеки Яндекс Музыка;
- перемешивание треков в альбоме или плейлисте;
- цикличное прослушивание треков в альбоме или одно трека;
- функция "Моя волна", которая обеспечивает бесконечный поток музыки;
- возможность установить плагины от сторонних разработчиков;
- совместное прослушивание треков;
- переключение цветовой схемы приложения;
- защита от необдуманных и случайных действий пользователя;
- совместное прослушивание треков двумя разными пользователями.
Входными данными являются:
- логин и пароль пользователя.
Выходными данными является:
- список музыкальных композиций;
- подборки музыкальных композиций под пользователей;
#fhh("Требование к надёжности")
| Приложение должно корректно работать на всех обозначенных операционных системах (Windows, IOS, MacOS, Linux, Android);
| Обработка некорректных входных данных, путём выдачи информационного сообщения пользователям;
| Корректная работа без подключения к интернету;
| Время восстановление системы после отказа не должно быть более 1 минуты;
Действия оператора в ходе отказа:
- Закрыть программу;
− Проверить подключение к интернету;
− Очистить кэш и данные приложения;
− Открыть программу заново.
#fhh("Условия эксплуатации")
Наличие у пользователя устройства, который выполняет минимальные требования, перечисленные в пункте 1.1.4.4 Требования к составу и параметрам технических средств.
4.3.1 Климатические условия эксплуатации
Требований к климатическим условиям эксплуатации не предъявляется.
4.3.2 Требования к видам обслуживания
Обслуживание не требуется.
4.3.3 Требования к численности и квалификации персонала
Персонал не требуется.
\
#fhh("Требования к составу и параметрам технических средств")
- Операционная система: Windows, macOS, Linux, Android;
- Минимальное кол-во оперативной памяти: 4 Гб;
- Минимальная видеокарта: Intel HD Graphics;
- Минимальный процессор: Intel Core i3 2.5GHz;
- Минимальный объем доступной памяти жёсткого диска: 100 Мб;
- Минимальное разрешение экрана: 1080x600;
#fhh("Требования к информационной и программной совместимости")
4.5.1 Требования к исходным кодам и языкам программирования
Исходные коды программы должны быть написаны на языке Kotlin.
4.5.2 Требования к программным средствам, используемым программой
Среда разработки приложения - IntelliJ IDEA Community Edition.
Библиотеки используемые приложением: Exposed, Compose Multiplatform, Kotlin Multiplatform.
Базы данных используемые приложением: PostgreSQL, SQLite.
Система должна работать на современных системах: Windows 10-11 с поддержкой DirectX 12, MacOS версии выше Catalina, Linux 6.0 и выше с визуальным окружением Gnome 40 и выше, Android 10 и выше.
#fhh("Требования к графическому дизайну")
Система должна выполнять следующие требования к графическому дизайну:
| Интуитивный адаптивный интерфейс под разные экраны и соотношения;
| В стиле Material You, с применением основных принципов и элементов этого дизайна.
| Возможность изменить тему интерфейса.
#fhh("Требования к программной документации")
Состав программной документации:
– "Yay!". Техническое задание (ГОСТ 19.201 78);
– "Yay!". Руководство системного программиста. (ГОСТ 19.503-79);
#fh("Стадии и этапы разработки")
- Составление Технического задания – 1 апреля 2024;
- Разработка приложения – 8 апреля 2024;
#fh("Порядок контроля и приёма работы")
Приём программы должен осуществляться руководителем производственной практики от предприятия (<NAME>).
#pagebreak()
#ch("Приложение Б Протокол разногласий")
#grid(columns: (1fr, 10pt, 1fr),
align: center,
gutter: 10pt,
text("УТВЕРЖДАЮ"),
text(""),
text("СОГЛАСОВАНО"),
text("Технический директор"),
text(""),
text("Практикант,\n Разработчик RMS"),
v(5pt), v(5pt), v(5pt),
grid.cell(align: right)[В.П. Косов],
text(""),
grid.cell(align: right)[В.Д. Панков],
grid.cell(align: right)["8" апреля 2024 г.],
[],
grid.cell(align: right)["8" апреля 2024 г.]
)
#v(42pt)
#align(center)[ПРОТОКОЛ РАЗНОГЛАСИЙ \
К ТЕХНИЧЕСКОМУ ЗАДАНИЮ \
НА РАБОТУ]
#v(18pt)
#align(center)[«Разработка мобильного приложения «Музыкальный плеер»» \ под названием «Yay»
]
#pagebreak()
#cfh0("Протокол разногласий к ТЗ «Yay»")
#table(
columns: (1fr, 1.2fr, 1fr),
inset: 10pt,
table.header(
align(center)[Автор], align(center)[Замечание], align(center)[Комментарий]
),
[<NAME>. ], [Пункт 4.4 Добавить поддержку операционной системы IOS], [#highlight(fill: red)[Не принято] \ В связи закрытости системы и запретом использования данной техники во многих государственных учереждениях],
[<NAME>.], [Пункт 4.4 Повысить системные требования приложения, из-за проблем работы приложения на текущих], [#highlight(fill: green)[Принято] \ Решение проблем с производственностью могло бы занять много времени],
[<NAME>.], [Пункт 4.1 Добавить функцию: Авторегулирование громкости композиции ], [#highlight(fill: red)[Не принято] \ Решение исполнителя ],
[<NAME>.], [Пункт 4.5.2 Добавить библиотеку для работу с базой данных SQLDelight и загрузки изображений Coil], [#highlight(fill: green)[Принято] \ Эти библиотеки упростят процесс разработки],
[<NAME>], [Пункт 5 Передвинуть этап разработки на более долгий срок], [#highlight(fill: green)[Принято] \ Требование заказчика]
)
#pagebreak()
#ch("Приложение В Дополнение к техническому заданию")
#v(5pt)
#grid(columns: (1fr, 10pt, 1fr),
align: center,
gutter: 10pt,
text("УТВЕРЖДАЮ"),
text(""),
text("СОГЛАСОВАНО"),
text("Технический директор"),
text(""),
text("Практикант,\n Разработчик RMS"),
v(5pt), v(5pt), v(5pt),
grid.cell(align: right)[В.П. Косов],
text(""),
grid.cell(align: right)[<NAME>],
grid.cell(align: right)["11" апреля 2024 г.],
[],
grid.cell(align: right)["12" апреля 2024 г.]
)
#v(42pt)
#align(center)[ДОПОЛНЕНИЕ №1 \
К ТЕХНИЧЕСКОМУ ЗАДАНИЮ \
НА РАБОТУ]
#v(18pt)
#align(center)[«Разработка мобильного приложения «Музыкальный плеер»» \ под названием «Yay»
]
#v(18pt)
#table(
columns: (1fr, 1fr),
inset: 10pt,
table.header(
align(center)[Имеется], align(center)[Должно быть]
),
[4.4 Требования к составу и параметрам технических средств
| Операционная система: Windows, macOS, Linux, Android;
| Минимальное кол-во оперативной памяти: 4 Гб;
| Минимальная видеокарта: Intel HD Graphics;
| Минимальный процессор: Intel Core i3 2.5GHz;
| Минимальный объем доступной памяти жёсткого диска: 100 Мб;
| Минимальное разрешение экрана: 1080x600;
], [4.4 Требования к составу и параметрам технических средств
| Операционная система: Windows, macOS, Linux, Android;
| Минимальное кол-во оперативной памяти: 6 Гб;
| Минимальная видеокарта: AMD Radeon R7 360;
| Минимальный процессор: AMD FX 4300;
| Минимальный объем доступной памяти жёсткого диска: 1 Гб;
| Минимальное разрешение экрана: 600x600;
],
[4.5.2 Требования к программным средствам, используемым программой
Среда разработки приложения - IntelliJ IDEA Community Edition.
Библиотеки используемые приложением: Exposed, Compose Multiplatform, Kotlin Multiplatform.
Базы данных используемые приложением: PostgreSQL, SQLite.
Система должна работать на современных системах: Windows 10-11 с поддержкой DirectX 12, MacOS версии выше Catalina, Linux 6.0 и выше с визуальным окружением Gnome 40 и выше, Android 10 и выше.
],
[4.5.2 Требования к программным средствам, используемым программой
Среда разработки приложения - IntelliJ IDEA Ultimate Edition.
Библиотеки используемые приложением: SQLDelight, Compose Multiplatform, Kotlin Multiplatform, Ktor, Coil.
Базы данных используемые приложением: PostgreSQL, SQLite.
Система должна работать на современных системах: Windows 11 с поддержкой DirectX 12, MacOS версии выше Catalina, Linux 6.0 и выше с визуальным окружением Gnome 40 и выше, Android 10 и выше.
],
[5 Стадии и этапы разработки
-- Составление Технического задания – 1 апреля 2024;
-- Разработка приложения – 8 апреля 2024;
],[5 Стадии и этапы разработки
-- Составление Технического задания – 1 апреля 2024;
-- Разработка приложения – 28 апреля 2024;
]
)
#v(1fr)
#table(
columns: (1fr, 1fr),
inset: 10pt,
align(center)[Технический директор],
align(center)[#set par(justify: true, leading: 1em)
Практикант, \ Разработчик RMS],
align(end)[#set par(justify: true, leading: 1em)
<NAME> \ "30" апреля 2024 г.],
align(end)[#set par(justify: true, leading: 1em)
<NAME> \ "30" апреля 2024 г.]
)
#pagebreak()
#ch("Приложение Г Руководство системному программисту")
#counter(heading).update(0)
#fh("Общие сведения о программе")
#fhh("Назначение программы")
"Yay!" -- кроссплатформенное приложение, представляющее из себя альтернативный клиент сервиса Яндекс Музыка. Оно включает все основные
функции оригинального приложения и обладает дополнительными, такими как:
совместное прослушивание, система плгаинов и генерация темы приложения на основе обложки трека.
#fhh("Функции программы")
- авторизация через Яндекс;
- прослушивание музыки из библиотеки Яндекс Музыка;
- перемешивание треков в альбоме или плейлисте;
- цикличное прослушивание треков в альбоме или одно трека;
- функция "Моя волна", которая обеспечивает бесконечный поток музыки;
- возможность установить плагины от сторонних разработчиков;
- совместное прослушивание треков;
- переключение цветовой схемы приложения;
- защита от необдуманных и случайных действий пользователя;
- совместное прослушивание треков двумя разными пользователями.
#fhh("Минимальный состав технических средств")
| Операционная система: Windows, macOS, Linux, Android;
| Минимальное кол-во оперативной памяти: 6 Гб;
| Минимальная видеокарта: AMD Radeon R7 360;
| Минимальный процессор: AMD FX 4300;
| Минимальный объем доступной памяти жёсткого диска: 1 Гб;
| Минимальное разрешение экрана: 600x600;
#fhh("Требование к персоналу")
Требование к персоналу не требуется
#fh("Структура программы")
Программа структурно состоит из:
\1. Основное приложение (Kotlin)
1.1. Нативные функции на определённой платформе
1.2. Общие функции, выполняющиеся на всех платформах
\2. API Яндекс Музыка
\3. Локальная база данных Sqlite
Диграмма компонентов представлена на рисунке @fuck_dia.
#figure(image(ip("structure2.png")), caption: "Диаграмма компонентов"
) <fuck_dia>
Основное приложение (Kotlin) -- риложения включающее нативные и
общие части для каждой платформы. Нативные будут выполняться только на
определённой платформе. Общие же функции выполняются вне зависимости
от платформы.
API Яндекс Музыка — интерфейс для связи с сервисом Яндекс
Музыка
Локальная база данных Sqlite — база данных, в которой хранится
информация о треках
#fhh("Сведения о связях составными частями программы")
Связь с API Яндекс Музыка осуществляется через протокол HTTPS,
оттуда получаются все треки, рекомендации и настройки пользователя.
Отображение информации происходит через общие функции,
воспроизведение и сохранение данных происходит через нативные функции
приложение.
Сохранение данных происходит через библиотеку SqlDelight с
использованием JDBC в базу данных Sqlite.
#fhh("Сведения о связи с другими программами")
Приложение имеет явную связь с сервисом Яндекс Музыка,
использованием API с данным приложением для получения данных о треках,
пользователе и его рекомендация.
#fh("Настройка программы")
#fhh("Настройка на состав технических средств")
Не требуется.
#fhh("Настройка на состав программных средств")
Не требуется.
#fh("Проверка программы")
Работоспособность программы «Yandex Music 3» проверяется запуском
программы. При запуске откроется окно, представленное на рисунке @fuck_you.
#figure(image(ip("screen.png")), caption: "Окно при запуске") <fuck_you>
#fh("Сообщение системному программисту")
При ошибке «Unsupported Java» при сборке приложения,
представленная на рисунке @fuck_unsupported, установите версию JDK для сборки в
настройках на 20, на рисунке @fuck_idea, показан пример настройки сборки в IntelliJ IDEA.
#figure(image(ip("Unsupported.png")), caption: "Окно при запуске") <fuck_unsupported>
#figure(image(ip("IDEA.png")), caption: "Окно при запуске") <fuck_idea>
Требуется проверить работоспособность тестов до попытки сборки
приложения.
Действия оператора в ходе некорректного выполнения тестов:
- проверить, актуальность версии приложения;
- очистить кэш сборки, командой «gradle clean»;
- проверить, подключение к интернету.
|
|
https://github.com/rabotaem-incorporated/algebra-conspect-1course | https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/03-polynomials/02-deg-props.typ | typst | Other | #import "../../utils/core.typ": *
== Свойства степени
#pr[
$f, g in R[x], space deg f = m, space deg g = n$
+ #[
$deg(f + g) <= max(m, n)$
При этом: $m eq.not n ==> deg(f + g) = max(m, n)$
]
+ $deg(f g) <= m + n$
]
#proof[
+ #[
$f = limits(sum)_(i = 0)^m a_i X^i, space g = limits(sum)_(i = 0)^n b_i X^i, space d = max(m, n)$
$f = limits(sum)_(i = 0)^d a_i X^i, space g = limits(sum)_(i = 0)^d b_i X^i$
$f + g = limits(sum)_(i = 0)^d (a_i + b_i) X^i ==> deg(f + g) <= d$
$m eq.not n ==> display(cases(
a_d = 0,
b_d eq.not 0
))$ или $display(cases(
a_d eq.not 0,
b_d = 0
)) ==> a_d + b_d eq.not 0 ==> deg(f + g) = d$
]
+ $( limits(sum)_(i = 0)^m a_i X^i ) ( limits(sum)_(j = 0)^n b_j X^j ) = a_0 b_0 + (a_0 b_1 + a_1 b_0)X + ... + a_m b_n X^(m + n) ==> deg f g <= m + n$
]
#notice[
$deg f g < m + n$, если $a_m eq.not 0$ или $b_n eq.not 0$ и $a_m b_n = 0$
]
#notice[
Будем считать, что $deg 0 = -oo$
]
#def[
_Область целостности_ (целостное кольцо, область) --- коммутативное ассоциативное кольцо с $1 eq.not 0$ и без делителей нуля (то есть никакие два ненулевых элемента не дают ноль при умножении)
]
#pr[
Пусть $R$ --- область целостности.
+ $forall f,g in R[x]: deg(f g) = deg f + deg g$
+ $R[x]$ --- область целостности
]
#proof[
+ В предыдущем доказательстве $display(cases(
a_m eq.not 0,
b_n eq.not 0
)) ==> a_m b_n eq.not 0 ==> deg(f g) = m + n$
+ $f eq.not 0 ==> deg f >= 0, space g eq.not 0 ==> deg g >= 0 ==> deg(f g) >= 0 ==> f g eq.not 0$
]
#follow[
Пусть $R$ --- область целостности: тогда $R[x]^* = R^*$
]
#proof[\
"$supset$": очевидно $R^* subset R[x]^*$
"$subset$": пусть $f in R[x]^* ==> exists g in R[x]: f dot g = 1$
$deg(f g) = 0 = deg f + deg g ==> deg f = deg g = 0 ==> f in R ==> f in R^*$
]
#examples[
+ $ZZ[x]^* = \{plus.minus 1\}$
+ $RR[x]^* = RR without \{0\}$
+ $(factor(ZZ, 4 ZZ))[x]^*$ --- бесконечное множество
]
#exercise[
$R[[x]]^* = \{ limits(sum)_(i = 0)^(oo) a_i X^i divides a_0 in R^*\}$
]
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/link-08.typ | typst | Other | // Link to page one.
#link((page: 1, x: 10pt, y: 20pt))[Back to the start]
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Multiple%20Integrations.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Multiple Integrations",
authors: (
"<NAME>",
),
date: "30 Octobre, 2023",
)
#set heading(numbering: "1.1.")
= Multiple Integrations
<multiple-integrations>
== Definition
<definition>
Multiple integrals are a way of extending the concept of a single
integral to integrate functions with more than one variable. In other
words, a multiple integral is a mathematical operation that calculates
the integral of a function with multiple variables, such as a function
of two variables (x and y) or a function of three variables (x, y, and
z). These integrals can be used to solve a variety of problems in
mathematics and other fields, such as finding the volume of a
three-dimensional object or calculating the amount of force acting on a
surface. The general form of a multiple integral is:
`∫∫ f(x, y, z) dx dy dz`
where f(x, y, z) is the function being integrated, and dx, dy, and dz
are the differentials of the variables x, y, and z, respectively. The
process of evaluating a multiple integral involves breaking the region
over which the integral is being calculated into many small subregions
and calculating the integral over each subregion. This can be a complex
process, but there are many tools and techniques that can be used to
make it easier.
|
|
https://github.com/julyfun/typst-simple-report | https://raw.githubusercontent.com/julyfun/typst-simple-report/main/main.typ | typst | #import "simplepaper.typ": *
#show strong: set text(weight: 900) // Songti SC 700 不够粗
#show heading: set text(weight: 900)
#set text(
font: ("New Computer Modern", "Songti SC")
)
#show: project.with(
title: "交附闵分信奥暑期集训结果及后续安排",
)
= 信奥暑期集训情况
CCF 非专业能力认证提高组(CSP-S)和全国青少年信息学奥林匹克联赛(NOIP)将在 2024 年 9 月 21 日开始陆续举行,这两场比赛是上海信息学奥赛省队选拔赛的前置比赛,将作为省队选拔最终成绩的一部分,若学生能进入上海省队,则凭借上海今年来的表现,很有可能进入国家集训队;同时,若取得 CSP-S 和 NOIP 的省级一 / 二等奖,可以在高考综合评价中,尤其是专业面试环节获取很大优势,提高综评成绩,并可作为进入大学 ACM 校队的敲门砖;NOIP 的高分选手可参加清华中学生冬令营 THUWC 和北大冬令营 PKUWC,获得大学强基计划优惠政策。
交附闵分信奥校队从 7 月 6 日开始,每周六 14:00 至 16:30 举行腾讯会议室线上集训,讲解 NOIP 提高组算法和 CSP-S 第一轮笔试题,使用 `luogu.com` 作为题库和评测 OJ,训练后提供腾讯会议回放,并布置每周训练题单和作业。执行情况如下:
== 集训名单
#import "@preview/tablem:0.1.0": tablem
#tablem[
| *姓名* |
| ---- |
| 甘旭晨 |
| 杨子琦 |
| 杜含 |
| 汪宇尧 |
| 刘坤烁 |
| 于天越 |
| 胡蕴思 |
| 酆益帆 |
| 张远非 |
]
== 课程表
#tablem[
| *日期* | *时间* | *复赛算法讲解* | *初赛真题讲解* | *出勤率* |
| ---- | ---- | ---- | ---- | ---- |
| 7.6 | 14:00-16:30 | 【数据结构1-1】线性表 | CSP-S 2023 I | 100% |
| 7.13 | 14:00-16:30 | 【数据结构1-2】二叉树 | CSP-S 2023 II | 75% |
| 7.20 | 14:00-16:30 | 【数据结构1-3】集合 Extended | CSP-S 2022 I | 100% |
| 7.27 | 14:00-16:30 | 【数据结构1-4】图论 | CSP-S 2022 II | 100% |
| 8.3 | 14:00-16:30 | 【算法2-2】常见优化算法 | CSP-S 2021 I | 75% |
| 8.17 | 14:00-16:30 | 【算法2-3】分治 Extended 与倍增 | CSP-S 2021 II | 100% |
| 8.24 | 14:00-16:30 | 【算法2-4】字符串 Extended | CSP-S 2023 大题 | |
| 8.31 | 14:00-16:30 | 【动态规划 1】复杂动态规划 | CSP-S 2022 大题 | |
]
= 现有问题
现役信奥队员对学习信奥兴趣高,体会到写 OI 算法攻坚克难的乐趣,每周训练题单和作业完成情况良好(由 `luogu.com` 提供作业评测和完成情况检查),都具备冲击 CSP-S / NOIP 一等奖的实力,部分同学拥有冲击高分和省队选拔的实力。但是接下来的集训安排将会较为紧张,尚存在以下问题:
+ 学生虽然学习了较多算法并刷了大量例题,但缺乏模拟赛和真题训练。
+ 按照目前每周一次的集训安排,复杂动态规划和数论等近年 NOIP 热点知识点将难以排入。
+ 各校信奥校队大多进行线下集训,相比线上可以明显提高效率。学生目前面临较大作业压力,集训和作业的时间安排有困难。
= 后续集训初步计划
== 暑期学校集训
暑期最后一周集训安排在学校机房内密集训练,如有条件最好能安排学生住宿,以进行全天集训。如不能住宿,则安排晚上机房集训。
=== 每日安排:住宿集训版
#tablem[
| 日期 | 上午 8:00 - 12:00 | 下午 | 晚上 18:00 - 21:00 |
| ---- | ---- | ---- | ---- |
| 8.26 周一 | CSP-S 2023 初赛模拟赛 | 自由订正练习,或完成学校作业 | 初赛模拟赛讲解 + 【算法2-5】进阶搜索 |
| 8.27 周二 | CSP-S 2023 复赛自由训练 | 自由订正练习,或完成学校作业 | 复赛模拟赛讲解 + 【图论2-1】树 |
| 8.28 周三 | CSP-S 2022 初赛模拟赛 | 自由订正练习,或完成学校作业 | 初赛模拟赛讲解 + 【图论2-2】最短路 |
| 8.29 周四 | CSP-S 2022 复赛模拟赛 | 自由订正练习,或完成学校作业 | 复赛模拟赛讲解 + 【图论2-3】生成树 |
| 8.30 周五 | CSP-S 2021 初赛模拟赛 | 自由订正练习,或完成学校作业 | 初赛模拟赛讲解 + 【图论2-4】连通性问题 |
]
=== 每日安排:晚上集训版
#tablem[
| 日期 | 时间 | 晚上安排 |
| ---- | ---- | ---- |
| 8.26 周一 | 18:00 - 21:00 | 初赛模拟赛 + 【算法2-5】进阶搜索 |
| 8.27 周二 | 18:00 - 21:00 | 初赛讲解 + CSP-S 2023 真题讲解 + 【图论2-1】树 |
| 8.28 周三 | 18:00 - 21:00 | 初赛模拟赛 + 【图论2-2】最短路 |
| 8.29 周四 | 18:00 - 21:00 | 初赛讲解 + CSP-S 2022 真题讲解 + 【图论2-3】生成树 |
| 8.30 周五 | 18:00 - 21:00 | 初赛模拟赛 + 【图论2-4】连通性问题 |
]
== CSP-S 第一轮前安排
#tablem[
| *日期* | *时间* | *复赛算法讲解* | *初赛真题讲解* |
| ---- | ---- | ---- | ---- |
| 8.31 | 14:00-17:00 | 【动态规划 1】复杂动态规划 | CSP-S 2021 大题 |
| 9.7 | 14:00-17:00 | 【动态规划 2】线性状态动态规划 | CSP-S 2020 大题 |
| 9.14 | 14:00-17:00 | 初赛模拟赛 + 讲解 | |
| 9.20 日(比赛前一天) | 下午晚上自由时间 | 机房初赛靠前辅导 | |
]
== CSP-S 第二轮前安排
第二轮(复赛)将在 10 月中旬到下旬举行,预计为 10月19日或10月26日。
#tablem[
| *日期* | *时间* | *复赛算法讲解* |
| ---- | ---- | ---- |
| 9.28 | 14:00-17:00 | 【动态规划3】区间与环形动态规划 |
| 10.3 | 14:00-17:00 | 【动态规划4】树与图上的动态规划 |
| 10.4 | 14:00-17:00 | CSP-S 2021 复赛模拟赛 |
| 10.5 | 14:00-17:00 | 复赛模拟赛讲解 + 【动态规划5】状态压缩动态规划 |
| 10.12 | 14:00-17:00 | 【数学2-1】进阶数论 |
]
考前周一到周五尽量为学生安排赛前集训,尽可能减免文化课作业的布置,以达到最佳冲刺状态。依据比赛经验,赛前一到两周的集训往往有奇效。
=== 赛前一周集训安排
#tablem[
| *日期* | *下午* | *晚上* |
| ---- | ---- | ---- |
| 周一 | 【数学2-2】组合数学与计数 | NOIP 模拟赛 |
| 周二 | 【数据结构2-1】二叉堆与树状数组 | NOIP 模拟赛讲解 |
| 周三 | 【数据结构2-2】线段树 | NOIP 模拟赛 |
| 周四 |【动态规划6】动态规划的设计与优化 | NOIP 模拟赛讲解 |
| 周五 | 所有提高组模板题 | 赛前辅导 |
]
\
\
- 集训老师:方俊杰 上海交通大学
- 手机: 15356160627
- 微信: hoale85125
|
|
https://github.com/Shuenhoy/modern-zju-thesis | https://raw.githubusercontent.com/Shuenhoy/modern-zju-thesis/master/pages/undergraduate-task.typ | typst | MIT License | #import "../utils/fonts.typ": 字号, 字体
#import "../utils/datetime-display.typ": datetime-display
#import "../utils/twoside.typ": *
#import "./template-individual.typ": template-individual
#let undergraduate-task(info: (:), task, comment: none) = {
template-individual("本科生毕业论文(设计)任务书", outlined: true)[
#set text(size: 字号.小四)
#strong[
一、题目:#info.title.join()<mzt:no-header-footer>\
二、指导教师对毕业论文(设计)的进度安排及任务要求:]
#task
#v(0.8fr)
#strong[起讫日期 20 #h(1.5em) 年 #h(1.5em) 月 #h(1.5em) 日 至 20 #h(1.5em) 年 #h(1.5em) 月 #h(1.5em) 日]
#v(1em)
#strong(
align(right)[
指导教师(签名)#box(width: 5em, stroke: (bottom: 0.5pt)) 职称#box(width: 5em, stroke: (bottom: 0.5pt))],
)
#v(2em)
#strong[#h(-2em)三、系或研究所意见:]
#v(1fr)
#strong(
align(right)[
负责人(签名)#box(width: 5em, stroke: (bottom: 0.5pt))\
年#h(2em)月#h(2em)日
],
)
]
twoside-emptypage
} |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-01.typ | typst | Other | // Test math operators.
// Test plus and minus.
#for v in (1, 3.14, 12pt, 45deg, 90%, 13% + 10pt, 6.3fr) {
// Test plus.
test(+v, v)
// Test minus.
test(-v, -1 * v)
test(--v, v)
// Test combination.
test(-++ --v, -v)
}
#test(-(4 + 2), 6-12)
// Addition.
#test(2 + 4, 6)
#test("a" + "b", "ab")
#test("a" + if false { "b" }, "a")
#test("a" + if true { "b" }, "ab")
#test(13 * "a" + "bbbbbb", "aaaaaaaaaaaaabbbbbb")
#test((1, 2) + (3, 4), (1, 2, 3, 4))
#test((a: 1) + (b: 2, c: 3), (a: 1, b: 2, c: 3))
|
https://github.com/kiwiyou/algorithm-lecture | https://raw.githubusercontent.com/kiwiyou/algorithm-lecture/main/basic/01-orientation.typ | typst | #import "@preview/cetz:0.1.2"
#import "@preview/algorithmic:0.1.0"
#import "../slide.typ"
#show: slide.style
#show link: slide.link
#show footnote.entry: slide.footnote
#let algorithm(..args) = text(font: ("linux libertine", "Pretendard") ,size: 17pt)[#algorithmic.algorithm(..args)]
#align(horizon + center)[
= 알고리즘 기초 세미나
OT: 알고리즘 문제를 푸는 방법
#text(size: 0.8em)[
연세대학교 전우제#super[kiwiyou] \
2023.11.15.r1
]
]
#slide.slide([알고리즘 문제의 의도])[
- 시험자가 얼마나 원하는 기능을 잘 구현할 수 있는지 시험
#align(horizon + center)[
#cetz.canvas({
import cetz.draw: *
set-style(
stroke: (thickness: 2pt),
mark: (size: 0.5, angle: 80deg),
)
content((0, 0), align(center)[기능 \ = 여러분의 코드], name: "code", padding: 1, frame: "rect")
content((rel: (-3, 0), to: "code.left"), [입력], anchor: "right", name: "input")
content((rel: (3, 0), to: "code.right"), [출력], anchor: "left", name: "output")
line((rel: (0.5, 0), to: "input.right"), (rel: (-0.5, 0), to: "code.left"), mark: (end: ">"))
line((rel: (0.5, 0), to: "code.right"), (rel: (-0.5, 0), to: "output.left"), mark: (end: ">"))
})
]
#pagebreak()
- "잘" 구현한다는 것은?
1. 마감 기한 안에 코드를 짤 수 있어야 함
2. 기능이 맡은 일을 정확하게 수행해야 함
3. 기능이 적당한 시간 안에 돌아가야 함
#align(horizon + center)[
#cetz.canvas({
import cetz.draw: *
set-style(
stroke: (thickness: 2pt),
mark: (size: 0.5, angle: 80deg),
)
content((0, 0), [맡은 일], name: "task", anchor: "right", padding: 0.5)
content((4, 1), [알고리즘을 응용하는 사고력 문제], anchor: "left", name: "think", padding: 0.5)
content((4, -1), [알고리즘을 사용하는 실 기능 구현 문제], anchor: "left", name: "impl", padding: 0.5)
line("task.right", "think.left", mark: (end: ">"))
line("task.right", "impl.left", mark: (end: ">"))
content(("task.right", .5, "think.left"), text(size: 0.8em)[대회], angle: "think.left", padding: 0.2, frame: "rect", fill: white, stroke: none)
content(("task.right", .5, "impl.left"), text(size: 0.8em)[코테], angle: "impl.left", padding: 0.2, frame: "rect", fill: white, stroke: none)
})
]
#pagebreak()
- 구현력은 문제를 많이 푸는 경험으로 터득
- #link("https://acmicpc.net/")[백준 온라인 저지]
- #link("https://programmers.co.kr/")[프로그래머스]
- 출제되는 문제의 유형을 파악하고 유형별 문제 해결 방법을 숙지
]
#slide.slide([알고리즘 문제의 접근 방식])[
- 문제 상황을 알기 쉬운 형태로 정리
-> 수식화, 알고 있는 문제로 변형
- 문제에서 어느 정도로 효율적인 풀이를 원하는지 파악
-> 시간복잡도 분석
- 풀이가 비효율적이라면 어느 부분을 개선할 수 있는지 파악
-> 필요없는 계산을 최대한 줄이기
]
#slide.slide([시간복잡도 분석])[
- 현대 상용 컴퓨터는 1초에 수억#super[10#super[8]] 번의 단위 연산#super[unit operation]이 가능#footnote()[인터프리트되는 언어의 경우 단위 연산이 없는 것과 마찬가지이므로 이보다 훨씬 적은 수의 연산을 수행할 수 있다.]
- 코드가 조금만 복잡해져도 단위 연산의 횟수를 정확하게 세는 것이 어려움
- 입력 크기에 따라 단위 연산의 횟수가 얼마나 빠르게 증가하는지만 계산
#pagebreak()
#algorithm({
import algorithmic: *
Function("Max-Sum-Pair", args: ([$A$], ))
Assign[$m$][0]
For(
cond: [$i <- 0$ *until* $"len"(A)$],
For(
cond: [$j <- 0$ *until* $i$],
Assign[$m$][$max(m, A[i] + A[j])$]
)
)
Return[$m$]
})
- 덧셈과 $max$ 연산은 모두 합쳐 $N^2 + N$번 일어나지만 $O(N^2)$으로 표기
- $N = 5000$이라면 $N^2 = 2.5 times 10^7$이므로 $1$초 시간제한 내에 실행될 것
- $N = 10^5$이라면 $N^2 = 10^10$이므로 $1$초 시간제한 내에 실행되지 않을 것
- 정확한 계산이 아니므로 드물게 시간이 안 맞을 수 있음
]
#slide.slide([빠른 입출력])[
- 백준 온라인 저지의 경우 미리 준비된 입력 파일들을 프로그램에 전달하고 프로그램의 출력을 출력 파일들과 비교
- 콘솔 입출력 기능을 사용하면 되지만, 내부 동작 방식으로 인해 문제가 생길 수 있음
]
#slide.slide([과제])[
- #slide.problem("15552", "빠른 A+B")
] |
|
https://github.com/paugarcia32/CV | https://raw.githubusercontent.com/paugarcia32/CV/main/modules_es/education.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Formación")
#cvEntry(
title: [Grado en Ingeniería Telemática],
society: [UPC - EETAC, Castelldefels],
date: [2020 - Actualidad],
location: [ES],
logo: "../src/logos/upc.png",
description: list(
[Tesis: Plataforma IoT abierta para proyectos de ciencia ciudadana: soluciones de conectividad]
)
)
#cvEntry(
title: [Bachillerato Tecnológico],
society: [Col·legi Montserrat, Barcelona],
date: [2018 - 2020],
location: [ES],
logo: "../src/logos/cole montse.png",
description: list(
[Tesis: Análisis y hackeo de tarjetas NFC]
)
)
|
https://github.com/flavio20002/typst-presentation-minimal-template | https://raw.githubusercontent.com/flavio20002/typst-presentation-minimal-template/main/lib.typ | typst | MIT No Attribution | #let script-size = 15pt
#let normal-size = 20pt
#let large-size = 30pt
#let very-large-size = 38pt
#let huge-size = 58pt
#let logo-light-image = state("logo-light-image", none)
#let section-page = state("section-page", false)
#let columns-content(..args) = {
let slide-info = args.named()
let bodies = args.pos()
let colwidths = none
let thisgutter = 1cm
if "colwidths" in slide-info{
colwidths = slide-info.colwidths
if colwidths.len() != bodies.len(){
panic("Provided colwidths must be of same length as bodies")
}
}
else{
colwidths = (1fr,) * bodies.len()
}
if "gutter" in slide-info{
thisgutter = slide-info.gutter
}
grid(
columns: colwidths,
gutter: thisgutter,
..bodies
)
}
#let project(
title: [Title],
sub-title: [sub-title],
author: none,
date: none,
aspect-ratio: "16-9",
main-color: rgb("#E30512"),
text-color-light: white,
text-color-dark: black,
cover: none,
logo: none,
logo-light: none,
index-title: none,
body
) = {
set document(title: title, author: author)
set text(fill: text-color-dark, size: normal-size, lang: "it")
set underline(offset: 3pt)
set page(
paper: "presentation-" + aspect-ratio,
margin: 0pt,
)
set list(tight:true, indent: 0.27cm ,body-indent: 0.7cm, marker: (place(center, dy: -0.25em, text(size: 1.5em, fill: main-color, "▶")), place(center, dy: -0.2em, text(size: 1.3em, fill: main-color, "■"))))
set enum(numbering: (..args) => text(fill:main-color, numbering("1.", ..args)))
set figure(gap: 20pt)
show figure: it => [
#set text(size: script-size)
#it
]
show raw: set text(size: 12pt)
let page-number-int() = {
let lastpage-number = context{counter(page).final(here()).at(0)}
set align(right)
text(size: script-size)[
#counter(page).display("1 / 1", both: true)
]
}
let page-number() = {
place(bottom + right)[
#pad(bottom: 0.5cm, right: 0.5cm)[
#let lastpage-number = context{counter(page).final(here()).at(0)}
#set align(right)
#text(size: script-size)[
#counter(page).display("1 / 1", both: true)
]
]
]
}
let slide-polygon() = {
place(top+left, polygon(
fill: main-color,
(0cm, 0cm),
(0cm, 3cm),
(0.4cm, 3cm),
(0.4cm, 0cm),
))
}
let slide-logo(theLogo) = {
if theLogo!= none {
place(top + right, dx: -0.5cm, dy: 0.5cm)[
#set image(width: 2.5cm)
#theLogo
]
}
}
// Display the title page.
page(margin: 0pt)[
#set text(fill: text-color-light)
#if (cover != none){
place()[
#set image(width: 100%, height: 100%)
#cover
]
}
#logo-light-image.update(x =>
logo-light
)
#place(block(fill: rgb("000000C2"), width: 100%, height: 100% + 1pt))
#place(
polygon(
fill: main-color,
(100%, 0%),
(55%, 0%),
(80%, 100%),
(100%, 100%),
))
#slide-logo(logo-light)
#pad(left: 1.5cm, right: 10cm, y: 1.5cm)[
#v(1fr)
#block(width: 15cm)[ #par(leading: 1cm)[
#text(size: 62pt, weight: "regular", upper(title))
]]
#v(0.5cm)
#text(size: 30pt, weight: "regular", sub-title)
#v(1fr)
#if author != none {
text(size: normal-size)[#author]
} --
#if date != none {
text(size: normal-size)[#date]
}
]
]
set page(
background: context{
if section-page.at(here()) {
rect(width: 100%, height: 100%, fill: main-color)
place(top,
polygon(
fill: white,
(90%, 20%),
(90% - 1.2cm, 20%),
(90% - 1.2cm, 90%),
(90% - 1.2cm, 20%),
(90% - 1.2cm, 90% - 1.2cm),
(90% - 9cm, 90% - 1.2cm),
(90% - 9cm, 90%),
(90%, 90%),
(90%, 20%)
))
context{
let logo-light = logo-light-image.at(here())
place(top + right, dx: -0.5cm, dy: 0.5cm)[
#set image(width: 2.5cm)
#logo-light
]
}
place(bottom + right)[
#pad(bottom: 0.5cm, right: 0.5cm)[
#let lastpage-number = context{counter(page).final(here()).at(0)}
#set align(right)
#text(fill: white, size: script-size)[
#counter(page).display("1 / 1", both: true)
]
]
]
}
else{
[
#slide-logo(logo)
#slide-polygon()
#page-number()
]
}
},
margin: (top:4cm, bottom: 1cm, left: 1.5cm, right: 1.5cm)
)
set align(horizon)
// Display the summary page.
place(top + left, dy: -4cm, block(height: 3cm, width: if logo!= none {100% - 2.5cm} else {100%}, align(horizon, text(size: very-large-size, weight: "regular", index-title))))
context{
let elems = query(selector(heading.where(level: 1)).after(here()))
enum(tight: false, ..elems.map(elem => {link((page: elem.location().page() + 1, x: 0pt, y: 0pt),elem.body)}))
}
show link: it => [
#set text(fill: main-color)
#underline(it)
]
show heading.where(level: 1): it => [
#section-page.update(x =>
true
)
#pagebreak(weak: true)
#set text(huge-size, fill: white, weight: "bold")
#move(dy: -1.5cm, place(horizon, pad(right:5cm, upper(it.body))))
]
show heading.where(level: 2): it => {
section-page.update(x =>
false
)
pagebreak()
set text(very-large-size, weight: "regular")
place(top + left, dy: -4cm, block(height: 3cm, width: if logo!= none {100% - 2.5cm} else {100%}, align(horizon, it.body)))
}
show heading.where(level: 3): it => {
pagebreak()
context{
let elems = query(selector(heading.where(level: 2)).before(here()))
let heading2 = elems.last().body
place(top + left, dy: -4cm, block(height: 3cm, width: if logo!= none {100% - 2.5cm} else {100%}, align(horizon, [#block(below: 0em, above: 0em, text(heading2, size: very-large-size, weight: "regular")) #block(below: 0em, above: 0.65em, text(it.body, size: normal-size, weight: "regular"))])))
}
}
// Add the body.
body
} |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/list-attach-05.typ | typst | Other | // ... even if forced to.
Hello
#list(tight: false)[A][B]
World
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/components/TypstTemplate/figures.typ | typst | #import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge
#import "@preview/tablem:0.1.0": tablem
#import "@preview/lovelace:0.3.0": pseudocode-list, pseudocode, line-label
#import "@preview/truthfy:0.4.0": truth-table, truth-table-empty
#import "@preview/codly:0.2.0": *
#import "@preview/timeliney:0.1.0": timeline, headerline, group, taskgroup, task, milestone
// 插入图片
#let fig(alignment: center, ..args) = align(alignment, image(..args))
// 正则捕捉自动设置数学环境,对表格等使用
#let automath_rule = it => {
show regex("\d+(.\d+)*"): it => $it$
it
}
// 普通表,包含居中
#let tbl(alignment: center, align_content: center + horizon, automath: false, ..args) = {
let fig = align(alignment, table(align: align_content, ..args))
if automath {
show table.cell: automath_rule
fig
} else {fig}
}
// 三线表,包含居中
#let tlt(alignment: center, align_content: center + horizon, automath: false, ..args) = {
let fig = align(alignment, table(
stroke: none,
align: align_content,
table.hline(y: 0),
table.hline(y: 1),
..args,
table.hline(),
))
if automath {
show table.cell: automath_rule
fig
} else {fig}
}
// 类 markdown 表格,使用 tablem 实现
#let tblm(alignment: center, automath: false, ..args) = {
let fig = align(alignment, tablem(..args))
if automath {
show table.cell: automath_rule
fig
} else {fig}
}
// 真值表,使用 truthfy 实现
#let truth-tbl(alignment: center, ..args) = align(alignment, truth-table(..args))
#let truth-tbl-empty(alignment: center, ..args) = align(alignment, truth-table-empty(..args))
// 算法框,使用 lovelace 实现
#let my-lovelace-defaults = (
line-numbering: "1",
booktabs: true,
// stroke: none,
// hooks: 0.5em,
indentation: 1.5em,
booktabs-stroke: 2pt + black,
)
#let pseudocode-list = pseudocode-list.with(..my-lovelace-defaults)
#let algo(title: none, body, ..args) = {
pseudocode-list(
title: title + h(1fr),
body,
..args
)
}
#let comment(body) = {
h(1fr)
text(size: .85em, fill: gray.darken(50%), sym.triangle.stroked.r + sym.space + body)
}
#let no-number = [- #hide([])] // empty line and no number
// 代码块,使用 codly 实现
#let code(body) = [#body]
// icons for codly
#let codly_icon(codepoint) = {
box(
height: 1em,
baseline: 0.1em,
image(codepoint)
)
h(0.2em)
}
#let c_svg = codly_icon("/public/assets/c.svg")
#let cpp_svg = codly_icon("/public/assets/cpp.svg")
#let python_svg = codly_icon("/public/assets/python.svg")
#let rust_svg = codly_icon("/public/assets/rust.svg")
#let java_svg = codly_icon("/public/assets/java.svg")
#let sql_svg = codly_icon("/public/assets/sql.svg")
#let typst_svg = codly_icon("/public/assets/typst.svg")
#let verilog_svg = codly_icon("/public/assets/verilog.svg")
#let diagram(..args) = align(center, fletcher.diagram(
node-stroke: 1pt,
edge-stroke: 1pt,
mark-scale: 70%,
..args
))
#let edge(..args, marks: "-|>") = fletcher.edge(..args, marks: marks)
|
|
https://github.com/xiongyaohua/typst-template-swjtu-thesis | https://raw.githubusercontent.com/xiongyaohua/typst-template-swjtu-thesis/main/modules/common.typ | typst | #let 阶段 = state("阶段", "前文") // 文档当前所处阶段:前文、正文、结论、附录。不同阶段有不同排版格式要求。
#let 正文开始() = {
阶段.update("正文")
}
#let 结论开始() = {
阶段.update("结论")
}
#let 附录开始() = {
阶段.update("附录")
}
#let 字号 = (
初号: 42pt,
小初: 36pt,
一号: 26pt,
小一: 24pt,
二号: 22pt,
小二: 18pt,
三号: 16pt,
小三: 15pt,
四号: 14pt,
中四: 13pt,
小四: 12pt,
五号: 10.5pt,
小五: 9pt,
六号: 7.5pt,
小六: 6.5pt,
七号: 5.5pt,
小七: 5pt,
)
#let 字体 = (
仿宋: ("Times New Roman", "FangSong"),
宋体: ("Times New Roman", "NSimSun"),
黑体: ("Times New Roman", "SimHei"),
楷体: ("Times New Roman", "KaiTi"),
代码: ("New Computer Modern Mono", "Times New Roman", "SimSun"),
)
#let 占位(body) = {
set text(fill: red)
body
}
#let 格式化日期(p_datetime, format) = {
if type(p_datetime) == datetime {
set text(font: 字体.宋体, size: 字号.小四)
p_datetime.display(format)
} else {
set text(font: 字体.宋体, size: 字号.小四, fill: red)
datetime.today().display(format)
}
}
// 全局样式
#let 全局样式(rest) = {
set page(paper:"a4", margin: (
x: 2.6cm, y:2.7cm
))
set text(font: 字体.宋体, size: 字号.小四, lang: "zh")
set par(justify: true, linebreaks: "optimized")
set underline(offset: 2pt, extent: 1pt)
set heading(supplement: none)
show strong: set text(font: 字体.黑体)
show emph: set text(font: 字体.楷体)
show figure.where(kind: table): set figure.caption(position: top)
show figure: set figure.caption(position: bottom)
show figure: it => {
it
par(leading: 0em, hide(text(size: 0pt)[xx])) // 保证下一段提行
}
show heading.where(level: 1): set text(size: 字号.小二)
show heading.where(level: 1): set align(center)
show heading.where(level: 2): set text(size: 字号.小三)
show heading.where(level: 3): set text(size: 字号.四号)
show heading: set text(font: 字体.黑体, size: 字号.小四)
show heading.where(level: 1): it => {
pagebreak()
counter(figure.where(kind: image)).update(0)
counter(figure.where(kind: table)).update(0)
counter(math.equation).update(0)
it
par(leading: 0em, hide(text(size: 0pt)[xx])) // 保证下一段提行
}
show heading: it => {
it
par(leading: 0em, hide(text(size: 0pt)[xx])) // 保证下一段提行
}
show heading.where(level: 1): set block(inset: (top: 1.5em, bottom: 1em))
show heading: set block(inset: (top: 0.5em, bottom: 0.5em))
//show raw: box.with(fill: luma(200), outset: 1pt, inset: 1pt)
show raw.where(block: false): it => {
set text(font: "Noto Sans Mono CJK SC")
box(
fill: luma(200),
outset: 1pt,
inset: 2pt,
radius: 2pt,
baseline: 1pt,
it.text
)
}
show raw.where(block: true): it => {
set text(font: "Noto Sans Mono CJK SC")
set block(fill: luma(230), width: 90%, radius: 3pt, inset:5pt)
set align(center)
it
}
show ref: it => {
let el = it.element
if el != none and el.func() == heading {
it
if el.level == 1 []
else if el.level == 2 [节]
else [小节]
} else if el != none and el.func() == figure {
let fig_counter = el.caption.counter
let supplement = el.caption.supplement
let chapter = counter(heading).at(el.location()).at(0)
let fig_num = fig_counter.at(el.location()).at(0)
let f = if 阶段.at(el.location()) == "附录" { "A" } else { "1"}
link(el.location(), {
supplement
numbering(f, chapter)
[--]
numbering("1", fig_num)
})
} else if el != none and el.func() == math.equation {
let eq_counter = counter(math.equation)
let supplement = el.supplement
let chapter = counter(heading).at(el.location()).at(0)
let eq_num = eq_counter.at(el.location()).at(0)
let f = if 阶段.at(el.location()) == "附录" { "A" } else { "1"}
link(el.location(), {
supplement
[ (#{numbering(f, chapter)}--#{numbering("1", eq_num)})]
})
}
else {
it
}
}
rest
}
|
|
https://github.com/MingLLuo/typst-course-description | https://raw.githubusercontent.com/MingLLuo/typst-course-description/main/main.typ | typst | #import "utils.typ": *
// Default: A4, optional: https://typst.app/docs/reference/layout/page/
// First Page includes:
// 1. School ready to apply
// 2. Major ready to apply
// 3. Your name
// 4. Your School
// 5. Your Major
// School Logo
#set text(font: translate(zh: "SimSun", en: "Arial"))
#FrontPage(
// appliedSchool: translate(
// zh: "奥胡斯大学",
// en: "Aarhus University",
// ),
// appliedMajor: translate(
// zh: "计算机科学",
// en: "Computer Science",
// ),
name: translate(
zh: "史豪",
en: "<NAME>",
),
graduatedFrom: translate(
zh: "华南师范大学",
en: "South China Normal University",
),
graduatedMajor: translate(
zh: "计算机科学与技术",
en: "Computer Science and Technology",
),
term: term("2021", "秋季", "Fall") + " - " + term("2025", "春季", "Spring"),
graduatedLogoLink: "assets/scnu.svg",
date: "2024/12/1",
)
#counter(page).update(1)
#set page(
margin: auto,
header: {
align(end)[
#set text(size: 10pt, weight: "bold")
#translate(zh: [课程描述], en: [Course Descriptions]) --- #translate(zh: [奥胡斯大学], en: [Aarhus University])
]
},
footer: {
align(center)[
#set text(size: 10pt)
#counter(page).display("1/1", both: true)
]
},
)
// Second Page includes:
// Outlines
#show outline.entry.where(level: 1): it => {
v(16pt, weak: true)
strong(it)
}
#outline(title: translate(zh: "目录", en: "Table of Contents"), indent: 1em)
#pagebreak()
// Third Page includes:
// Content of all courses
// In format of: a form
// | - Semester | - Course | - Nature - | - Credit | - Grade - |
// | - 1 | - Calculus | - Compulsory | - 4 | - 90 |
// Optional: ECTS Grade (under construction)
// Read from a JSON file
#let Factor-to-ECTS = 1.5
#let courses = json("courses.json")
#let key_map = (
"semester_zh": "学期",
"semester_en": "Semester",
"course_zh": "课程",
"course_en": "Course",
"nature_zh": "性质",
"nature_en": "Nature",
"credit": translate(zh: "学分", en: "Credit"),
"grade_zh": "成绩",
"grade_en": "Grade",
"description_zh": "描述",
"description_en": "Description",
"ects": translate(zh: "ECTS学分", en: "ECTS"),
)
#let key_trans(key) = {
if key == "credit" {
key
} else if mode == Chinese {
key + "_zh"
} else if mode == English {
key + "_en"
} else {
key
}
}
#let keys_to_valid_index(keys, desc, ects) = {
let new_keys = ()
for key in keys {
if key == "credit" {
new_keys.push(key)
}
if mode == Chinese {
if key.ends-with("_zh") {
new_keys.push(key)
}
}
if mode == English {
if key.ends-with("_en") {
new_keys.push(key)
}
}
}
if not desc {
new_keys = new_keys.filter(key => not key.starts-with("description"))
}
if ects {
new_keys.push("ects")
}
new_keys
}
// change the keys to valid index
// TODO: Add pattern matching
#let course-table-json(data) = {
// let keys = keys_to_valid_index(data.at(0).keys(), false, false)
let keys = (
"semester",
"course",
"nature",
"grade",
"credit",
)
let keys = keys.map(key => key_trans(key))
align(left)[
#set text(size: 12pt, weight: "bold")
= #translate(zh: [修读课程总览], en: [Courses Overview])
]
align(center)[
#set text(size: 11pt, weight: "regular")
#let header = keys.map(key => text(weight: "bold")[#key_map.at(key, default: "[n/a]")])
#table(
columns: keys.len(),
rows: auto,
align: horizon + center,
table.header(..header),
..data.map(row => keys.map(key => row.at(key, default: "[n/a]"))).flatten(),
)
]
pagebreak()
}
#course-table-json(courses)
// Detailed Course Description
// Table with Line between each course
#let course-description-json(data) = {
let keys = keys_to_valid_index(data.at(0).keys(), true, false)
align(left)[
= #translate(zh: [课程详细描述], en: [Course Descriptions])
]
for info in data {
let course = key_trans("course")
let semester = key_trans("semester")
let nature = key_trans("nature")
let credit = "credit"
let grade = key_trans("grade")
let description = key_trans("description")
align(left)[
#set text(size: 10pt, weight: "regular")
#let credit_value = float(info.at(credit, default: "[n/a]"))
#let credit_value_float = credit_value * Factor-to-ECTS
#table(
columns: 9 * (1fr,),
rows: (auto, auto, auto),
align: horizon,
inset: 10pt,
// First Line of the Table
// | - Course - | - Semester -|
table.cell(colspan: 2,text(weight: "bold")[#key_map.at(course, default: "[n/a]")]),
table.cell(colspan: 3, grid(align: horizon)[
== #text(size: 10pt, weight: "medium",[#info.at(course, default: "[n/a]")])
]),
table.cell(colspan: 2,text(weight: "bold")[#key_map.at(semester, default: "[n/a]")]),
table.cell(colspan: 2, info.at(semester, default: "[n/a]")),
// Second Line of the Table
// | - Nature - | - Credit - | - Grade - | - ECTS - |
text(weight: "bold")[#key_map.at(nature, default: "[n/a]")],
table.cell(colspan: 2, info.at(nature, default: "[n/a]")),
text(weight: "bold")[#key_map.at(grade, default: "[n/a]")],
info.at(grade, default: "[n/a]"),
text(weight: "bold")[#key_map.at(credit, default: "[n/a]")],
info.at(credit, default: "[n/a]"),
text(weight: "bold")[#translate(zh: [ECTS 学分], en: [ECTS])],
[#credit_value_float],
// Third Line of the Table
// | - Description - |
table.cell(colspan: 2, text(weight: "bold")[#key_map.at(description, default: "[n/a]")]),
table.cell(colspan: 7, info.at(description, default: "[n/a]")),
)
#pagebreak()
]
}
}
#course-description-json(courses)
// Last page: Appendix, include
// 1. Source of the description
// 2. Signature, date |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/tutor/0.3.0/README.md | markdown | Apache License 2.0 | # tutor
Utilities to write exams and exercises with integrated solutions. Set the variable `#(cfg.sol = true)` to display the solutions of a document.
Currently the following features are supported:
* Automatic total point calculation through the `#points()` and `#totalpoints()` functions.
* Checkboxes that are either blank or show the solution state using eg. `#checkbox(cfg, true)`.
* Display blank lines allowing students to write their answer using eg. `#lines(cfg, 3)`.
* A proposition for a project structure allowing self-contained exercises and a mechanism to show or hide the solutions of an exercise.
## Usage
### Minimal Example
```typst
#import "@local/tutor:0.3.0": points, totalpoints, lines, checkbox, default-config
#let cfg = default-config()
// enable solution mode
#(cfg.sol = true)
// display 3 lines (for hand written answer)
#lines(cfg, 3)
// checkbox for multiple choice (indicates correct state)
#checkbox(cfg, true)
// show achievable points
Max. points: #points(2)
Max. points: #points(3)
// show sum of all total achievable points (will show 5)
Total points: #totalpoints(cfg)
```
### Practical Example
Check [example](https://github.com/rangerjo/tutor/tree/main/example) for a more practical example.
`tutor` is best used with the following directory and file structure:
```
├── main.typ
├── src
│ ├── ex1
│ │ └── ex.typ
│ └── ex2
│ └── ex.typ
└── tutor.toml
```
Every directory in `src` holds one self-contained exercise. The exercises can be imported into `main.typ`:
```typst
#import "@local/tutor:0.3.0": totalpoints, lines, default-config
#import "src/ex1/ex.typ" as ex1
#import "src/ex2/ex.typ" as ex2
#let cfg = default-config()
#ex1.exercise(cfg)
#ex2.exercise(cfg)
```
Supporting self-contained exercises is one of `tutor`s primary design goals. Each exercise lives within a folder and can easily be copied or referenced in a new document.
An exercise is a folder that contains an `ex.typ` file along with any other assets (images, source code aso). The following exercise shows a practical usage of the `#checkbox()` and `#points()` functions.
`src/ex1/ex.typ`
```typst
#import "@local/tutor:0.3.0": points, checkbox
#let exercise(cfg) = [
#heading(level:cfg.lvl, [Abbreviation FHIR (#points(1) point)])
What does FHIR stand for?
#set list(marker: none)
- #checkbox(cfg, false) Finally He Is Real
- #checkbox(cfg, true) Fast Health Interoperability Resources
- #checkbox(cfg, false) First Health Inactivation Restriction
#if cfg.sol {
[ Further explanation: FHIR is the new standard developed by HL7. ]
}
]
```
Finally this second example shows the `#lines()` function.
`src/ex2/ex.typ`
```typst
#import "@local/tutor:0.3.0": points, lines
#let exercise(cfg) = [
#heading(level:cfg.lvl, [FHIR vs HL7v2 (#points(4.5) points)])
List two differences between HL7v2 and FHIR:
+ #if cfg.sol { [ HL7v2 uses a non-standard line format, where as FHIR uses XML or JSON] } else { [ #lines(cfg, 3) ] }
+ #if cfg.sol { [ FHIR specifies various resources that can be queried, where as HL7v2 has a number of fixed fields that are either filled in or not]} else { [ #lines(cfg, 3) ] }
]
```
This would then give the following output in question mode (`#(cfg.sol=false)`)
and in solution mode (`#(cfg.sol=true)`):

## Configuration
`tutor` is designed to create exams and solutions with one single document source. Furthermore, the individual utilities provided by `tutor` can be configured. This can be done in either of two ways:
1. Use the `#default-config()` function and patch your configuration. The following example would configure the solution mode and basic line spacings to 8 millimeters:
```typst
#let cfg = default-config()
#(cfg.sol = false)
#(cfg.utils.lines.spacing = 8mm)
```
2. Use an external file to hold the configurations in your prefered format. See [tutor.toml](https://github.com/rangerjo/tutor/blob/main/example/tutor.toml) for a configuration in TOML. Load the configuration into your main document using
```typst
#let cfg = toml("tutor.toml")
```
|
https://github.com/Isaac-Fate/booxtyp | https://raw.githubusercontent.com/Isaac-Fate/booxtyp/master/src/theorems/new-fancy-template.typ | typst | Apache License 2.0 | #import "../colors.typ": color-schema
#import "../counters.typ": exercise-counter
#let exercise(content) = {
locate(loc => {
// Increament the exercise counter
exercise-counter.step(level: 3)
// Get the current exercise number
let number = numbering("1.1", ..exercise-counter.at(loc))
// Emoji for the exercise
emoji.hand.write
// Render the exercise title
text(fill: color-schema.green.dark)[
*Exercise #number*
]
// Add some space
h(0.5em)
// Exercise content
content
})
} |
https://github.com/xkevio/parcio-typst | https://raw.githubusercontent.com/xkevio/parcio-typst/main/parcio-thesis/template/template.typ | typst | MIT License | #import "@preview/drafting:0.2.0": margin-note, set-page-properties
#import "@preview/subpar:0.1.1"
#import "parcio-bib.typ": is-parcio-bib
#let ovgu-blue = rgb("#0068B4")
#let ovgu-darkgray = rgb("#606060")
#let ovgu-lightgray = rgb("#C0C0C0")
#let ovgu-orange = rgb("#F39100")
#let ovgu-purple = rgb("#7A003F")
#let ovgu-red = rgb("#D13F58")
#let large = 14.4pt
#let Large = 17.28pt
#let LARGE = 20.74pt
#let huge = 24.88pt
// TODO box (default: no inline).
#let todo(inline: false, body) = if inline {
rect(
fill: ovgu-orange,
stroke: black + 0.5pt,
radius: 0.25em,
width: 100%,
body
)
} else {
set rect(fill: ovgu-orange)
margin-note(stroke: ovgu-orange, body)
}
// Like \section* (unnumbered level 2 heading, does not appear in ToC).
#let section = heading.with(level: 2, outlined: false, numbering: none)
// Neat inline-section in smallcaps and sans font.
#let inline-section(title) = smallcaps[*#text(font: "Libertinus Sans", title)*]
// Fully empty page, no page numbering.
#let empty-page = page([], footer: [])
// Subfigures.
#let subfigure = subpar.grid.with(
numbering: (num) => {
numbering("1.1", counter(heading).get().first(), num)
},
numbering-sub-ref: (sup, sub) => {
numbering("1.1a", counter(heading).get().first(), sup, sub)
},
)
// Custom ParCIO table as illustrated in the template.
#let parcio-table(max-rows, ..args) = table(
..args,
row-gutter: (2.5pt, auto),
stroke: (x, y) => (
left: 0.5pt,
right: 0.5pt,
top: if y <= 1 { 0.5pt },
bottom: if y == 0 or y == max-rows - 1 { 0.5pt }
)
)
// ----------------------
// ACTUAL TEMPLATE
// ----------------------
#let project(
title,
author,
abstract,
thesis-type: "Bachelor/Master",
reviewers: (),
date: datetime.today(),
lang: "en",
body
) = {
set document(title: title, author: author.name)
set page("a4", margin: 2.5cm, number-align: right, numbering: "i", footer: [])
set text(font: "Libertinus Serif", 12pt, lang: lang)
set heading(numbering: "1.1.")
set par(justify: true)
set math.equation(numbering: "(1)")
let _translation-file = toml("translations.toml")
let translations = _translation-file.at(
lang,
default: _translation-file.at(_translation-file.default-lang)
)
// Make URLs use monospaced font.
show link: it => {
set text(font: "Inconsolata", 12pt * 0.95) if type(it.dest) == str
it
}
// Enable heading specific figure numbering and increase spacing.
set figure(numbering: n => numbering("1.1", counter(heading).get().first(), n), gap: 1em)
show figure: set block(spacing: 1.5em)
// Add final period after fig-numbering (1.1 -> 1.1.).
// Additionally, left align caption if it spans multiple lines.
show figure.caption: c => {
grid(
columns: 2,
column-gutter: 4pt,
align(top)[#c.supplement #c.counter.display(c.numbering).#c.separator],
align(left, c.body),
)
}
// Create the "Chapter X." heading for every level 1 heading that is numbered.
show heading.where(level: 1): h => {
set text(huge, font: "Libertinus Sans")
if h.numbering != none {
pagebreak(weak: true)
v(2.3cm)
// Reset figure counters:
counter(figure.where(kind: image)).update(0)
counter(figure.where(kind: table)).update(0)
counter(figure.where(kind: raw)).update(0)
if h.body == [Appendix] {
counter(heading).update(1)
[Appendix #counter(heading).display(h.numbering)]
} else {
translations.chapter + " " + counter(heading.where(level: 1)).display()
}
[\ #v(0.2em) #h.body]
} else {
v(2.3cm)
h
}
}
show heading.where(level: 2): h => {
if h.numbering != none {
[#counter(heading).display()~~#h.body]
} else {
h
}
}
// Make @heading automatically say "Chapter XYZ" instead of "Section XYZ",
// unless we want to manually specify it.
set ref(supplement: it => {
if it.func() == heading {
if it.level > 1 {
translations.section
} else {
translations.chapter
}
} else {
it.supplement
}
})
// Redirect bib-citations to the manually inserted ones.
show cite: c => {
if is-parcio-bib.get() and not str(c.key).starts-with("_") {
show regex(".+"): x => link(label("_" + str(c.key)), x)
c
} else {
c
}
}
// Customize ToC to look like template.
set outline(fill: repeat[~~.], indent: none, title: translations.contents)
show outline: o => {
show heading: pad.with(bottom: 1em)
o
}
// Level 2 and deeper.
show outline.entry: it => {
let cc = it.body.children.first().text
box(
grid(
columns: (auto, 1fr, auto),
h(1.5em + ((it.level - 2) * 2.5em)) + link(it.element.location())[#cc#h(1em)#it.element.body],
it.fill,
box(width: 1.5em) + it.page,
),
)
}
// Level 1 chapters get bold and no dots.
show outline.entry.where(level: 1): it => {
set text(font: "Libertinus Sans")
let cc = if it.element.body == [Appendix] {
"A." // hotfix
} else if it.body.has("children") {
it.body.children.first()
} else {
h(-0.5em)
}
v(0.1em)
box(grid(
columns: (auto, 1fr, auto),
strong(link(it.element.location())[#cc #h(0.5em) #it.element.body]),
h(1fr),
strong(it.page),
))
}
show raw: set text(font: "Inconsolata")
show raw.where(block: true): r => {
set par(justify: false)
show raw.line: l => {
box(table(
columns: (-1.25em, 100%),
stroke: 0pt,
inset: 0em,
column-gutter: 1em,
align: (x, y) => if x == 0 { right } else { left },
text(fill: ovgu-darkgray, str(l.number)),
l.body,
))
}
set align(left)
rect(width: 100%, stroke: gray + 0.5pt, inset: 0.75em, r)
}
show heading.where(level: 2): set text(font: "Libertinus Sans", Large)
show heading.where(level: 3): set text(font: "Libertinus Sans", Large)
show heading: it => it + v(0.69em)
set footnote.entry(separator: line(length: 40%, stroke: 0.5pt))
set list(marker: (sym.bullet, "◦"))
let (first-reviewer, second-reviewer, supervisor) = translations.title-page
// -------------- TITLE PAGE -------------- //
// STYLIZING TITLE PAGE AND ABSTRACT BEGINS HERE:
align(center)[
#image(alt: "Blue OVGU logo", width: 66%, "ovgu.svg")
]
v(4.75em)
align(center)[
#text(Large, font: "Libertinus Serif")[*#thesis-type #translations.thesis*]
#v(2.5em)
#text(huge, font: "Libertinus Sans")[
#set par(justify: false)
*#title*
]
#v(1.25em)
#set text(Large)
#show raw: set text(large * 0.95)
#align(center)[
#author.name\
#v(0.75em, weak: true)#link("mailto:" + author.mail)[#raw(author.mail)]
]
#v(0.5em)
#text(Large)[
#show regex("[a-zA-Z]+"): r => translations.date.months.at(date.month() - 1)
#date.display(translations.date.date-format)
]
#v(5.35em)
// first and second reviewer are required, supervisor is optional.
#if reviewers.len() >= 2 {
let first-reviewer-name = reviewers.first()
let second-reviewer-name = reviewers.at(1)
let supervisor-name = reviewers.at(2, default: none)
[
#first-reviewer:\
#first-reviewer-name\ \
#v(-1.5em)
#second-reviewer:\
#second-reviewer-name\ \
#v(-1.5em)
#if supervisor-name != none [
#supervisor:\
#supervisor-name
]
]
}
]
show raw: set text(12pt * 0.95)
pagebreak(to: "odd")
set-page-properties()
v(-8.5em)
align(center + horizon)[
#text(font: "Libertinus Sans", [*Abstract*])\ \
#align(left, abstract)
]
pagebreak()
pagebreak()
body
} |
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/brainstorm-tracking-implementation.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Brainstorm: Position Tracking",
type: "brainstorm",
date: datetime(year: 2023, month: 7, day: 28),
author: "<NAME>",
witness: "<NAME>",
)
Now that we chose our sensor configuration we chose how we wanted to implement
absolute tracking. The most popular method of doing this was first pioneered by
team 5225, the $pi$lons. They wrote a document describing their implementation
process, which can be found here: #link("http://thepilons.ca/wp-content/uploads/2018/10/Tracking.pdf").
Since the release of this document there have been many libraries that have
implemented it, each in their own way.
#grid(
columns: (1fr, 1fr),
gutter: 20pt,
[
== DIY Implementation
#pro-con(pros: [
- Gives us a lot of control
], cons: [
- Requires lots of troubleshooting and development time
])
],
[],
[
== LemLib
#pro-con(pros: [
- Actively maintained
- Supports our current sensor configuration
- Supports many different movement algorithms
], cons: [
- Not in a stable state
])
],
[],
[
== ARMS
#pro-con(pros: [
- Supports our sensor configuration
], cons: [
- Not actively maintained
])
],
[],
[
== OkapiLib
#pro-con(
pros: [
- Provides many useful utilities like filters and asynchronous controllers
- Included in PROS by default
],
cons: [
- Does not support our sensor configuration
- Not actively maintained
],
)
],
[],
)
|
https://github.com/El-Naizin/cv | https://raw.githubusercontent.com/El-Naizin/cv/main/README.md | markdown | Apache License 2.0 | <h1 align="center">
<img src='https://github.com/mintyfrankie/mintyfrankie/assets/77310871/64861d2d-971c-47cd-a5e8-5ad8659f2c2b'>
<br><br>
Brilliant CV
</h1>
<p align="center">
<img alt="Check Status Badge" src="https://github.com/mintyfrankie/brilliant-CV/actions/workflows/compile.yml/badge.svg"/>
<img alt="Typst Version" src="https://img.shields.io/badge/Compatible Typst Version-0.8.0-blue"/>
</p>
> The Brilliant CV project is still under preview, just like Typst is, so use with caution as future updates might break your current production.
>
> Read commits and changelog should you find new patches are not working, and feel free to lock to a working release & submit issues or PRs, I am happy to help!
<br>
**Brilliant CV** is a [**Typst**](https://github.com/typst/typst) template for making **Résume**, **CV** or **Cover Letter** inspired by the famous LaTeX CV template [**Awesome-CV**](https://github.com/posquit0/Awesome-CV).
## Features
- **Separation of style and content**: version control your CV entries in the `modules` folder, without touching the styling and typesetting of your CV / Cover Letter _(hey, I am not talking about **Macrohard Word**, you know)_
- **Quick twitches on the visual**: add company logos, put your shiny company name or your coolest title at the first line globally or per-document needs
- **Multilingual support**: centrally store your multilingual CVs (English + French + German + Chinese + Japanese if you are superb) and change output language in a blink
## Preview
| CV | Cover Letter |
| :------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------: |
|  |  |
| CV (_French, red, no photo_) | Cover Letter (_French, red_) |
| :------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------: |
|  |  |
| CV (_Chinese, green_) | Cover Letter (_Chinese, green_) |
| :------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------: |
|  | |
## Usage
### Installation
You can either directly create a new repository by using this template, or you might want to add the submodule repository and build up your own Typst project.
**Method 1: Jumpstart by clicking `Use this template` and create your own CV repository**
When compiling, use:
```
typst compile ./cv.typ ./output/CV.pdf --font-path ./src/fonts/
```
**Method 2: Add the [submodule repository](https://github.com/mintyfrankie/brilliant-CV-Submodule) to your existing project**
```bash
cd your/CV/project
git submodule add https://github.com/mintyfrankie/brilliant-CV-Submodule brilliant-CV
typst compile cv.typ
```
When you want to get new features from the updated template module:
```bash
git submodule update --remote
```
### Tips
- `metadata.typ` should live in the project root folder, and by changing the variables in it, you can quickly adjust language or display settings of the documents.
- Make sure when you build a multilingual module (`./modules_fr` for example) you are quoting the right language variable in the `metadata.typ` (`fr` in this case).
### Project Structure
```
|
|-- modules/ --> sections of your CV
| |- *.typ
|
|-- modules_* --> multilingual sections of your CV
|
|-- brilliant-CV/
| |- template.typ --> the template file
| |- metadata-demo.typ -> the example metadata file
|
|-- src/
| |- fonts/ --> local font files
| |- logos/ --> logos for your cvEntry
| |- *.png --> images used in the documents
| |- *.bib --> BibTeX file for Publications section
|
|-- cv.typ --> CV file
|-- letter.typ --> Cover Letter file
|-- metadata.typ --> Personal Infos & Settings
```
## Current Issues
> As Typst is still a very young (although very promising and robust to my belief) project, some features are only partially supported on certain platforms. It is hence difficult to predict any anomalies, but you are definitely welcomed to bring a PR, an issue or a discussion!
- **Image cropping**: Typst does not have direct support to crop images using native primitives. Bring your own cropped image for profile photo if needed.
- **Publications Section**: Current version of Typst does not allow full customization on the `#bibliography` function, so the display of publication section might not be optimal. See [this disucssion](https://github.com/mintyfrankie/brilliant-CV/discussions/3).
## Credit
- [**Typst**](https://github.com/typst/typst) is a newborn, open source and simple typesetting engine that offers a better scripting experience than [**LaTeX**](https://www.latex-project.org/).
- [**Awesome-CV**](https://github.com/posquit0/Awesome-CV) is the original LaTeX CV template from which this project is heavily inspired. Thanks [posquit0](https://github.com/posquit0) for your excellent work!
|
https://github.com/Amelia-Mowers/typst-tabut | https://raw.githubusercontent.com/Amelia-Mowers/typst-tabut/main/README.md | markdown | MIT License | <div>
# Tabut
*Powerful, Simple, Concise*
A Typst plugin for turning data into tables.
## Outline
- [Examples](#examples)
- [Input Format and Creation](#input-format-and-creation)
- [Basic Table](#basic-table)
- [Table Styling](#table-styling)
- [Header Formatting](#header-formatting)
- [Remove Headers](#remove-headers)
- [Cell Expressions and Formatting](#cell-expressions-and-formatting)
- [Index](#index)
- [Transpose](#transpose)
- [Alignment](#alignment)
- [Column Width](#column-width)
- [Get Cells Only](#get-cells-only)
- [Use with Tablex](#use-with-tablex)
- [Data Operation Examples](#data-operation-examples)
- [CSV Data](#csv-data)
- [Slice](#slice)
- [Sorting and Reversing](#sorting-and-reversing)
- [Filter](#filter)
- [Aggregation using Map and Sum](#aggregation-using-map-and-sum)
- [Grouping](#grouping)
- [Function Definitions](#function-definitions)
- [`tabut`](#tabut)
- [`tabut-cells`](#tabut-cells)
- [`rows-to-records`](#rows-to-records)
- [`records-from-csv`](#records-from-csv)
- [`group`](#group)
</div>
<div>
# Examples <span id="examples"></span>
</div>
<div>
## Input Format and Creation <span id="input-format-and-creation"></span>
The `tabut` function takes input in “record” format, an array of
dictionaries, with each dictionary representing a single “object” or
“record”.
In the example below, each record is a listing for an office supply
product.
<div>
``` typ
#let supplies = (
(name: "Notebook", price: 3.49, quantity: 5),
(name: "Ballpoint Pens", price: 5.99, quantity: 2),
(name: "Printer Paper", price: 6.99, quantity: 3),
)
```
</div>
</div>
<div>
## Basic Table <span id="basic-table"></span>
Now create a basic table from the data.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "example-data/supplies.typ": supplies
#tabut(
supplies, // the source of the data used to generate the table
( // column definitions
(
header: [Name], // label, takes content.
func: r => r.name // generates the cell content.
),
(header: [Price], func: r => r.price),
(header: [Quantity], func: r => r.quantity),
)
)
```
</div>
<div>
<img src="doc/compiled-snippets/basic.svg"
style="width:2.24804in;height:1.01335in" />
</div>
`funct` takes a function which generates content for a given cell
corrosponding to the defined column for each record. `r` is the record,
so `r => r.name` returns the `name` property of each record in the input
data if it has one.
</div>
<div>
The philosphy of `tabut` is that the display of data should be simple
and clearly defined, therefore each column and it’s content and
formatting should be defined within a single clear column defintion. One
consequence is you can comment out, remove or move, any column easily,
for example:
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "example-data/supplies.typ": supplies
#tabut(
supplies,
(
(header: [Price], func: r => r.price), // This column is moved to the front
(header: [Name], func: r => r.name),
(header: [Name 2], func: r => r.name), // copied
// (header: [Quantity], func: r => r.quantity), // removed via comment
)
)
```
</div>
<div>
<img src="doc/compiled-snippets/rearrange.svg"
style="width:2.58903in;height:1.01335in" />
</div>
</div>
<div>
## Table Styling <span id="table-styling"></span>
Any default Table style options can be tacked on and are passed to the
final table function.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "example-data/supplies.typ": supplies
#tabut(
supplies,
(
(header: [Name], func: r => r.name),
(header: [Price], func: r => r.price),
(header: [Quantity], func: r => r.quantity),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/styling.svg"
style="width:2.24804in;height:1.01335in" />
</div>
</div>
<div>
## Header Formatting <span id="header-formatting"></span>
You can pass any content or expression into the header property.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "example-data/supplies.typ": supplies
#let fmt(it) = {
heading(
outlined: false,
upper(it)
)
}
#tabut(
supplies,
(
(header: fmt([Name]), func: r => r.name ),
(header: fmt([Price]), func: r => r.price),
(header: fmt([Quantity]), func: r => r.quantity),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/title.svg"
style="width:3.14555in;height:1.05075in" />
</div>
</div>
<div>
## Remove Headers <span id="remove-headers"></span>
You can prevent from being generated with the `headers` paramater. This
is useful with the `tabut-cells` function as demonstrated in it’s
section.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "example-data/supplies.typ": supplies
#tabut(
supplies,
(
(header: [*Name*], func: r => r.name),
(header: [*Price*], func: r => r.price),
(header: [*Quantity*], func: r => r.quantity),
),
headers: false, // Prevents Headers from being generated
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none,
)
```
</div>
<div>
<img src="doc/compiled-snippets/no-headers.svg"
style="width:1.69109in;height:0.7739in" />
</div>
</div>
<div>
## Cell Expressions and Formatting <span id="cell-expressions-and-formatting"></span>
Just like the headers, cell contents can be modified and formatted like
any content in Typst.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "usd.typ": usd
#import "example-data/supplies.typ": supplies
#tabut(
supplies,
(
(header: [*Name*], func: r => r.name ),
(header: [*Price*], func: r => usd(r.price)),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/format.svg"
style="width:1.58711in;height:1.01133in" />
</div>
</div>
<div>
You can have the cell content function do calculations on a record
property.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "usd.typ": usd
#import "example-data/supplies.typ": supplies
#tabut(
supplies,
(
(header: [*Name*], func: r => r.name ),
(header: [*Price*], func: r => usd(r.price)),
(header: [*Tax*], func: r => usd(r.price * .2)),
(header: [*Total*], func: r => usd(r.price * 1.2)),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/calculation.svg"
style="width:2.53821in;height:1.01133in" />
</div>
</div>
<div>
Or even combine multiple record properties, go wild.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#let employees = (
(id: 3251, first: "Alice", last: "Smith", middle: "Jane"),
(id: 4872, first: "Carlos", last: "Garcia", middle: "Luis"),
(id: 5639, first: "Evelyn", last: "Chen", middle: "Ming")
);
#tabut(
employees,
(
(header: [*ID*], func: r => r.id ),
(header: [*Full Name*], func: r => [#r.first #r.middle.first(), #r.last] ),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/combine.svg"
style="width:1.6171in;height:1.01133in" />
</div>
</div>
<div>
## Index <span id="index"></span>
`tabut` automatically adds an `_index` property to each record.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "example-data/supplies.typ": supplies
#tabut(
supplies,
(
(header: [*\#*], func: r => r._index),
(header: [*Name*], func: r => r.name ),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/index.svg"
style="width:1.31304in;height:1.01133in" />
</div>
You can also prevent the `index` property being generated by setting it
to `none`, or you can also set an alternate name of the index property
as shown below.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "example-data/supplies.typ": supplies
#tabut(
supplies,
(
(header: [*\#*], func: r => r.index-alt ),
(header: [*Name*], func: r => r.name ),
),
index: "index-alt", // set an aternate name for the automatically generated index property.
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/index-alternate.svg"
style="width:1.31304in;height:1.01133in" />
</div>
</div>
<div>
## Transpose <span id="transpose"></span>
This was annoying to implement, and I don’t know when you’d actually use
this, but here.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "usd.typ": usd
#import "example-data/supplies.typ": supplies
#tabut(
supplies,
(
(header: [*\#*], func: r => r._index),
(header: [*Name*], func: r => r.name),
(header: [*Price*], func: r => usd(r.price)),
(header: [*Quantity*], func: r => r.quantity),
),
transpose: true, // set optional name arg `transpose` to `true`
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/transpose.svg"
style="width:3.57327in;height:1.01335in" />
</div>
</div>
<div>
## Alignment <span id="alignment"></span>
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "usd.typ": usd
#import "example-data/supplies.typ": supplies
#tabut(
supplies,
( // Include `align` as an optional arg to a column def
(header: [*\#*], func: r => r._index),
(header: [*Name*], align: right, func: r => r.name),
(header: [*Price*], align: right, func: r => usd(r.price)),
(header: [*Quantity*], align: right, func: r => r.quantity),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/align.svg"
style="width:2.56141in;height:1.01133in" />
</div>
You can also define Alignment manually as in the the standard Table
Function.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "usd.typ": usd
#import "example-data/supplies.typ": supplies
#tabut(
supplies,
(
(header: [*\#*], func: r => r._index),
(header: [*Name*], func: r => r.name),
(header: [*Price*], func: r => usd(r.price)),
(header: [*Quantity*], func: r => r.quantity),
),
align: (auto, right, right, right), // Alignment defined as in standard table function
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/align-manual.svg"
style="width:2.56141in;height:1.01133in" />
</div>
</div>
<div>
## Column Width <span id="column-width"></span>
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "usd.typ": usd
#import "example-data/supplies.typ": supplies
#box(
width: 300pt,
tabut(
supplies,
( // Include `width` as an optional arg to a column def
(header: [*\#*], func: r => r._index),
(header: [*Name*], width: 1fr, func: r => r.name),
(header: [*Price*], width: 20%, func: r => usd(r.price)),
(header: [*Quantity*], width: 1.5in, func: r => r.quantity),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none,
)
)
```
</div>
<div>
<img src="doc/compiled-snippets/width.svg"
style="width:4.22222in;height:1.01133in" />
</div>
You can also define Columns manually as in the the standard Table
Function.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "usd.typ": usd
#import "example-data/supplies.typ": supplies
#box(
width: 300pt,
tabut(
supplies,
(
(header: [*\#*], func: r => r._index),
(header: [*Name*], func: r => r.name),
(header: [*Price*], func: r => usd(r.price)),
(header: [*Quantity*], func: r => r.quantity),
),
columns: (auto, 1fr, 20%, 1.5in), // Columns defined as in standard table
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none,
)
)
```
</div>
<div>
<img src="doc/compiled-snippets/width-manual.svg"
style="width:4.22222in;height:1.01133in" />
</div>
</div>
<div>
## Get Cells Only <span id="get-cells-only"></span>
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut-cells
#import "usd.typ": usd
#import "example-data/supplies.typ": supplies
#tabut-cells(
supplies,
(
(header: [Name], func: r => r.name),
(header: [Price], func: r => usd(r.price)),
(header: [Quantity], func: r => r.quantity),
)
)
```
</div>
<div>
<img src="doc/compiled-snippets/only-cells.svg"
style="width:3.36683in;height:2.73299in" />
</div>
</div>
<div>
## Use with Tablex <span id="use-with-tablex"></span>
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut-cells
#import "usd.typ": usd
#import "example-data/supplies.typ": supplies
#import "@preview/tablex:0.0.8": tablex, rowspanx, colspanx
#tablex(
auto-vlines: false,
header-rows: 2,
/* --- header --- */
rowspanx(2)[*Name*], colspanx(2)[*Price*], (), rowspanx(2)[*Quantity*],
(), [*Base*], [*W/Tax*], (),
/* -------------- */
..tabut-cells(
supplies,
(
(header: [], func: r => r.name),
(header: [], func: r => usd(r.price)),
(header: [], func: r => usd(r.price * 1.3)),
(header: [], func: r => r.quantity),
),
headers: false
)
)
```
</div>
<div>
<img src="doc/compiled-snippets/tablex.svg"
style="width:2.90837in;height:1.24877in" />
</div>
</div>
<div>
# Data Operation Examples <span id="data-operation-examples"></span>
While technically seperate from table display, the following are
examples of how to perform operations on data before it is displayed
with `tabut`.
Since `tabut` assumes an “array of dictionaries” format, then most data
operations can be performed easily with Typst’s native array functions.
`tabut` also provides several functions to provide additional
functionality.
</div>
<div>
## CSV Data <span id="csv-data"></span>
By default, imported CSV gives a “rows” or “array of arrays” data
format, which can not be directly used by `tabut`. To convert, `tabut`
includes a function `rows-to-records` demonstrated below.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut, rows-to-records
#import "example-data/supplies.typ": supplies
#let titanic = {
let titanic-raw = csv("example-data/titanic.csv");
rows-to-records(
titanic-raw.first(), // The header row
titanic-raw.slice(1, -1), // The rest of the rows
)
}
```
</div>
Imported CSV data are all strings, so it’s usefull to convert them to
`int` or `float` when possible.
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut, rows-to-records
#import "example-data/supplies.typ": supplies
#let auto-type(input) = {
let is-int = (input.match(regex("^-?\d+$")) != none);
if is-int { return int(input); }
let is-float = (input.match(regex("^-?(inf|nan|\d+|\d*(\.\d+))$")) != none);
if is-float { return float(input) }
input
}
#let titanic = {
let titanic-raw = csv("example-data/titanic.csv");
rows-to-records( titanic-raw.first(), titanic-raw.slice(1, -1) )
.map( r => {
let new-record = (:);
for (k, v) in r.pairs() { new-record.insert(k, auto-type(v)); }
new-record
})
}
```
</div>
`tabut` includes a function, `records-from-csv`, to automatically
perform this process.
<div>
``` typ
#import "@preview/tabut:1.0.2": records-from-csv
#let titanic = records-from-csv(csv("example-data/titanic.csv"));
```
</div>
</div>
<div>
## Slice <span id="slice"></span>
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut, records-from-csv
#import "usd.typ": usd
#import "example-data/titanic.typ": titanic
#let classes = (
"N/A",
"First",
"Second",
"Third"
);
#let titanic-head = titanic.slice(0, 5);
#tabut(
titanic-head,
(
(header: [*Name*], func: r => r.Name),
(header: [*Class*], func: r => classes.at(r.Pclass)),
(header: [*Fare*], func: r => usd(r.Fare)),
(header: [*Survived?*], func: r => ("No", "Yes").at(r.Survived)),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/slice.svg"
style="width:5.33036in;height:1.49023in" />
</div>
</div>
<div>
## Sorting and Reversing <span id="sorting-and-reversing"></span>
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "usd.typ": usd
#import "example-data/titanic.typ": titanic, classes
#tabut(
titanic
.sorted(key: r => r.Fare)
.rev()
.slice(0, 5),
(
(header: [*Name*], func: r => r.Name),
(header: [*Class*], func: r => classes.at(r.Pclass)),
(header: [*Fare*], func: r => usd(r.Fare)),
(header: [*Survived?*], func: r => ("No", "Yes").at(r.Survived)),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/sort.svg"
style="width:4.40184in;height:1.49023in" />
</div>
</div>
<div>
## Filter <span id="filter"></span>
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut
#import "usd.typ": usd
#import "example-data/titanic.typ": titanic, classes
#tabut(
titanic
.filter(r => r.Pclass == 1)
.slice(0, 5),
(
(header: [*Name*], func: r => r.Name),
(header: [*Class*], func: r => classes.at(r.Pclass)),
(header: [*Fare*], func: r => usd(r.Fare)),
(header: [*Survived?*], func: r => ("No", "Yes").at(r.Survived)),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/filter.svg"
style="width:5.33036in;height:1.49023in" />
</div>
</div>
<div>
## Aggregation using Map and Sum <span id="aggregation-using-map-and-sum"></span>
<div>
``` typ
#import "usd.typ": usd
#import "example-data/titanic.typ": titanic, classes
#table(
columns: (auto, auto),
[*Fare, Total:*], [#usd(titanic.map(r => r.Fare).sum())],
[*Fare, Avg:*], [#usd(titanic.map(r => r.Fare).sum() / titanic.len())],
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/aggregation.svg"
style="width:1.73668in;height:0.53445in" />
</div>
</div>
<div>
## Grouping <span id="grouping"></span>
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut, group
#import "example-data/titanic.typ": titanic, classes
#tabut(
group(titanic, r => r.Pclass),
(
(header: [*Class*], func: r => classes.at(r.value)),
(header: [*Passengers*], func: r => r.group.len()),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/group.svg"
style="width:1.53415in;height:1.01133in" />
</div>
<div>
``` typ
#import "@preview/tabut:1.0.2": tabut, group
#import "usd.typ": usd
#import "example-data/titanic.typ": titanic, classes
#tabut(
group(titanic, r => r.Pclass),
(
(header: [*Class*], func: r => classes.at(r.value)),
(header: [*Total Fare*], func: r => usd(r.group.map(r => r.Fare).sum())),
(
header: [*Avg Fare*],
func: r => usd(r.group.map(r => r.Fare).sum() / r.group.len())
),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
)
```
</div>
<div>
<img src="doc/compiled-snippets/group-aggregation.svg"
style="width:2.21231in;height:1.01133in" />
</div>
</div>
<div>
# Function Definitions <span id="function-definitions"></span>
</div>
<div>
## `tabut` <span id="tabut"></span>
Takes data and column definitions and outputs a table.
<div>
``` typc
tabut(
data-raw,
colDefs,
columns: auto,
align: auto,
index: "_index",
transpose: false,
headers: true,
..tableArgs
) -> content
```
</div>
### Parameters
`data-raw`
This is the raw data that will be used to generate the table. The data
is expected to be in an array of dictionaries, where each dictionary
represents a single record or object.
`colDefs`
These are the column definitions. An array of dictionaries, each
representing column definition. Must include the properties `header` and
a `func`. `header` expects content, and specifies the label of the
column. `func` expects a function, the function takes a record
dictionary as input and returns the value to be displayed in the cell
corresponding to that record and column. There are also two optional
properties; `align` sets the alignment of the content within the cells
of the column, `width` sets the width of the column.
`columns`
(optional, default: `auto`) Specifies the column widths. If set to
`auto`, the function automatically generates column widths by each
column’s column definition. Otherwise functions exactly the `columns`
paramater of the standard Typst `table` function. Unlike the
`tabut-cells` setting this to `none` will break.
`align`
(optional, default: `auto`) Specifies the column alignment. If set to
`auto`, the function automatically generates column alignment by each
column’s column definition. If set to `none` no `align` property is
added to the output arg. Otherwise functions exactly the `align`
paramater of the standard Typst `table` function.
`index`
(optional, default: `"_index"`) Specifies the property name for the
index of each record. By default, an `_index` property is automatically
added to each record. If set to `none`, no index property is added.
`transpose`
(optional, default: `false`) If set to `true`, transposes the table,
swapping rows and columns.
`headers`
(optional, default: `true`) Determines whether headers should be
included in the output. If set to `false`, headers are not generated.
`tableArgs`
(optional) Any additional arguments are passed to the `table` function,
can be used for styling or anything else.
</div>
<div>
## `tabut-cells` <span id="tabut-cells"></span>
The `tabut-cells` function functions as `tabut`, but returns `arguments`
for use in either the standard `table` function or other tools such as
`tablex`. If you just want the array of cells, use the `pos` function on
the returned value, ex `tabut-cells(...).pos`.
`tabut-cells` is particularly useful when you need to generate only the
cell contents of a table or when these cells need to be passed to
another function for further processing or customization.
### Function Signature
<div>
``` typc
tabut-cells(
data-raw,
colDefs,
columns: auto,
align: auto,
index: "_index",
transpose: false,
headers: true,
) -> arguments
```
</div>
### Parameters
`data-raw`
This is the raw data that will be used to generate the table. The data
is expected to be in an array of dictionaries, where each dictionary
represents a single record or object.
`colDefs`
These are the column definitions. An array of dictionaries, each
representing column definition. Must include the properties `header` and
a `func`. `header` expects content, and specifies the label of the
column. `func` expects a function, the function takes a record
dictionary as input and returns the value to be displayed in the cell
corresponding to that record and column. There are also two optional
properties; `align` sets the alignment of the content within the cells
of the column, `width` sets the width of the column.
`columns`
(optional, default: `auto`) Specifies the column widths. If set to
`auto`, the function automatically generates column widths by each
column’s column definition. If set to `none` no `column` property is
added to the output arg. Otherwise functions exactly the `columns`
paramater of the standard typst `table` function.
`align`
(optional, default: `auto`) Specifies the column alignment. If set to
`auto`, the function automatically generates column alignment by each
column’s column definition. If set to `none` no `align` property is
added to the output arg. Otherwise functions exactly the `align`
paramater of the standard typst `table` function.
`index`
(optional, default: `"_index"`) Specifies the property name for the
index of each record. By default, an `_index` property is automatically
added to each record. If set to `none`, no index property is added.
`transpose`
(optional, default: `false`) If set to `true`, transposes the table,
swapping rows and columns.
`headers`
(optional, default: `true`) Determines whether headers should be
included in the output. If set to `false`, headers are not generated.
</div>
<div>
## `records-from-csv` <span id="records-from-csv"></span>
Automatically converts a CSV data into an array of records.
<div>
``` typc
records-from-csv(
data
) -> array
```
</div>
### Parameters
`data`
The CSV data that needs to be converted, this can be obtained using the
native `csv` function, like `records-from-csv(csv(file-path))`.
This function simplifies the process of converting CSV data into a
format compatible with `tabut`. It reads the CSV data, extracts the
headers, and converts each row into a dictionary, using the headers as
keys.
It also automatically converts data into floats or integers when
possible.
</div>
<div>
## `rows-to-records` <span id="rows-to-records"></span>
Converts rows of data into an array of records based on specified
headers.
This function is useful for converting data in a “rows” format (commonly
found in CSV files) into an array of dictionaries format, which is
required for `tabut` and allows easy data processing using the built in
array functions.
<div>
``` typc
rows-to-records(
headers,
rows,
default: none
) -> array
```
</div>
### Parameters
`headers`
An array representing the headers of the table. Each item in this array
corresponds to a column header.
`rows`
An array of arrays, each representing a row of data. Each sub-array
contains the cell data for a corresponding row.
`default`
(optional, default: `none`) A default value to use when a cell is empty
or there is an error.
</div>
<div>
## `group` <span id="group"></span>
Groups data based on a specified function and returns an array of
grouped records.
<div>
``` typc
group(
data,
function
) -> array
```
</div>
### Parameters
`data`
An array of dictionaries. Each dictionary represents a single record or
object.
`function`
A function that takes a record as input and returns a value based on
which the grouping is to be performed.
This function iterates over each record in the `data`, applies the
`function` to determine the grouping value, and organizes the records
into groups based on this value. Each group record is represented as a
dictionary with two properties: `value` (the result of the grouping
function) and `group` (an array of records belonging to this group).
In the context of `tabut`, the `group` function is particularly useful
for creating summary tables where records need to be categorized and
aggregated based on certain criteria, such as calculating total or
average values for each group.
</div>
|
https://github.com/heiafr-isc/typst-report-template | https://raw.githubusercontent.com/heiafr-isc/typst-report-template/main/lib/heiafr.typ | typst | Apache License 2.0 | // ---------------------------------------------------------------------------
// Copyright © 2024 Haute école d'ingénierie et d'architecture de Fribourg
// SPDX-License-Identifier: Apache-2.0
// ---------------------------------------------------------------------------
// Author : <NAME> <<EMAIL>>
// Date : 23 February 2024
// ---------------------------------------------------------------------------
// Template for student reports at the Haute école d'ingénierie et
// d'architecture de Fribourg
// ---------------------------------------------------------------------------
#import "@preview/tablex:0.0.8": tablex, hlinex, vlinex
#import "french_date.typ": short_date, long_date
#let main_text(..content) = text(font: "Noto Sans", ..content)
#let heading_text(..content) = text(font: "Noto Serif", ..content)
//
// Version Table
//
#let version_table(reverse: true, versions) = {
if reverse {
versions = versions.rev()
}
heading(numbering: none, outlined: false, [Tableau des versions])
set par(justify: false)
tablex(
columns: (5em, 5em, auto, 1fr), // 4 columns
rows: auto, // at least 1 row of auto size
align: (center + top, center + top, top, top),
auto-lines: false,
(),
vlinex(),
vlinex(),
vlinex(),
(),
[*Version*],
[*Date*],
[*Auteur(s)*],
[*Modifications*],
hlinex(),
// [0.1.0], [1.1.2024], [B. Vonlanthen], [Version initiale],
//[0.1.1], [2.1.2024], [B. Vonlanthen], lorem(10),
..(..versions.map(v => {
(v.version, short_date(v.date), v.author, v.changes)
})).flatten(),
)
}
//
// Declaration of Honor
//
#let declaration_of_honor(authors) = {
set heading(numbering: none)
[= Déclaration d'honneur]
for author in authors [
Je, soussigné#if author.gender == "f" [e],
#author.firstname #author.lastname, déclare sur l'honneur que le travail rendu
est le fruit d'un travail personnel. Je certifie ne pas avoir eu recours au
plagiat ou à toute autre forme de fraude. Toutes les sources d'information
utilisées et les citations d'auteur ont été clairement mentionnées.
#v(4cm)
]
}
//
// Report
//
#let report(
title: none,
subtitle: none,
type: none,
year: none,
location: [Fribourg],
versions: (),
profile: none,
authors: (),
supervisors: (),
experts: (),
clients: (),
doc,
) = {
set text(font: "Noto Sans")
set heading(numbering: "1.")
set par(justify: true)
// Heading formating for level 1
show heading.where(level: 1): it => {
if (it.numbering != none) {
block(
fill: rgb(195, 40, 35, 40),
width: 100%,
inset: 20pt,
{
heading_text(
weight: "medium",
size: 22pt,
stack(
dir: ttb,
[#it.supplement #numbering("1", ..counter(heading).at(it.location()))],
v(5mm),
heading_text(weight: "semibold", size: 24pt, it.body),
),
)
},
)
v(20pt)
} else {
heading_text(weight: "semibold", size: 22pt, it)
v(12pt)
}
}
// Heading formating for all levels
show heading: it => {
if it.level <= 1 {
pagebreak(weak: true)
it
} else {
block(inset: (y: 10pt), heading_text(it))
}
}
// Title page : Logo header
block(inset: (top: -30pt), image("img/logo-heiafr.svg"))
v(1fr)
// Document type
set align(center)
block(heading_text(
size: 17pt,
weight: "semibold",
[Filière Informatique et Systèmes de Communication],
))
if profile != none {
block(heading_text(size: 15pt, weight: "semibold", profile))
}
v(1fr)
block(heading_text(size: 17pt, weight: "semibold", type))
block(heading_text(size: 17pt, weight: "semibold", year))
v(1fr)
// Document title and subtitle in a red block
{
set text(fill: white)
block(fill: rgb(195, 40, 35, 255), width: 100%, inset: 10mm, {
heading_text(weight: "black", size: 28pt, title)
if subtitle != none {
parbreak()
heading_text(weight: "semibold", size: 18pt, subtitle)
}
})
}
v(1fr)
// Author
set text(fill: black, size: 16pt)
set align(center)
let count = authors.len()
let ncols = calc.min(count, 3)
grid(columns: (1fr,) * ncols, row-gutter: 24pt, ..authors.map(author => [
#text(
size: 18pt,
weight: "semibold",
heading_text(author.firstname + " " + author.lastname),
) \
#main_text(size: 12pt, author.email)
]))
v(1fr)
// Clients (if dedfined)
if clients.len() > 0 {
parbreak()
grid(
columns: (1fr, 1fr),
row-gutter: 6pt,
align(right, heading_text([_Mandants_ : #h(5mm)])),
align(left, heading_text(clients.join(linebreak()))),
)
}
// Supervisors
parbreak()
grid(
columns: (1fr, 1fr),
row-gutter: 6pt,
align(right, heading_text([_Superviseurs_ : #h(5mm)])),
align(left, heading_text(supervisors.join(linebreak()))),
)
// Experts (if defined)
if experts.len() > 0 {
parbreak()
grid(
columns: (1fr, 1fr),
row-gutter: 6pt,
align(right, heading_text([_Experts_ : #h(5mm)])),
align(left, heading_text(experts.join(linebreak()))),
)
}
v(2fr)
// Title page : Footer
set text(size: 14pt)
tablex(
columns: (9em, 1fr, 9em),
align: (left + horizon, center + horizon, right + horizon),
auto-lines: false,
image("img/logo-isc.svg", width: 22mm),
block(
heading_text(location + [, ] + long_date(versions.last().date)) + linebreak() + heading_text([Version ] + versions.last().version),
),
image("img/logo-hesso.svg", width: 35mm),
)
set align(left)
// Table of version
pagebreak()
set page(numbering: "i")
version_table(versions)
// Table of content
outline()
pagebreak()
// Main content
set page(numbering: "1")
counter(page).update(1)
main_text(size: 11.5pt, doc)
// Declaration of honor
main_text(size: 11.5pt, declaration_of_honor(authors))
} |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/001%20-%20Magic%202013/002_Xathrid%20Gorgon.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"<NAME>",
set_name: "Magic 2013",
story_date: datetime(day: 04, month: 07, year: 2012),
author: "<NAME>",
doc
)
#figure(image("002_Xathrid Gorgon/01.jpg", height: 40%), caption: [], supplement: none, numbering: none)
#emph[East of the border, I am called Sentos the Merciful. West of the border, I am called Sentos the Righteous. In the place where east meets west, I am just a man. A man alone in a monk's cottage in a monastery deep in the borderland mountains. A man twenty-six years old and the veteran of a war that started the year I was born.]
#emph[An hour to the east is An Karras, the city of my birth. It's an ancient city, so old that the dust between the flagstones is the remnants of temples built in its infancy. There, my parents, my wife, and legions of admirers would joyfully welcome my return. They venerate Sentos the Righteous, the soldier who brought glory on all who dwell in Thune.]
#emph[But what of those who cry for Sentos the Merciful, the soldier who ended the war through an act of mercy unparalleled in a war-torn land? What of their eastern city with its ancient temples? They blessed me for sparing their Elder Sun King, a man of unnatural long life and wisdom. Their storytellers called me goddess-born. My mother, who nearly died bearing me, laughed to hear such foolishness.]
#emph[On a cloudless day, I can glimpse the legendary domes of An Karras in the distance, backed by the cerulean ocean. But it's night, cold and misty, and I see only shadows outside my open window. By choice, my world has narrowed to four things: A sleeping pallet. The empty desk at which I sit. The ring upon my finger. And the flask of poison.]
#emph[The ring came to me the day the war ended on Fleet Rock. The day I did not execute a man. The poison I obtained the day An Karras celebrated the scourging of the east. If I drink to righteousness, I end myself in the name of that great city on the western horizon. If I drink to mercy, I end myself for that eastern city now a shamble of charred stone. You could not draw a straight line between my heart and that devastation. But in the borderland, in this place where I am nothing but a man, it's my burden alone.]
#emph[So I'll lift the flask in praise of elder kings, to ancient temples, to tales of men who forsake glory. But I'll drink to oblivion. And rejoice as darkness falls.]
#figure(image("002_Xathrid Gorgon/02.jpg", width: 100%), caption: [War Priest of Thune | Art by Izzy], supplement: none, numbering: none)
The wooden door of the cottage slammed open against a gust of wind, and the crash jerked Sentos out of his dark slumber. The empty flask of poison careened across the desk and shattered against the wall. He whirled around in his chair as the wind gusted again, blowing autumn leaves through the open door. Several black rats scurried over the threshold and hid behind the straw pallet along the wall.
The torch on the far wall still burned, and it was still night. #emph[But is it the same night?] On shaky legs, Sentos tripped toward the door, hoping to shut it against the chill, when something at the edge of the clearing caught his eye. He left the cottage and stumbled toward it. #emph[A statue?] Gleaming white in the moonlight, the statue resembled one of the monks who lived in the keep. But the stonecutter had carved fear into the monk's elderly features. #emph[A strange way to show a holy man] , Sentos thought.
The monk's cottage was isolated from the main keep. There had been no statue before, of that he was certain. How could the monks transport such weight along the winding footpath that led to the cottage? He stumbled back inside, where he wanted to lie down and sleep. #emph[But what of the rats?] #emph[And the broken glass? Has midnight come and gone? ] His thoughts felt too banal for a man who just opted for death over life.
#figure(image("002_Xathrid Gorgon/03.jpg", width: 100%), caption: [Ravenous Rats | Art by Carl Critchlow], supplement: none, numbering: none)
Back in the cottage he realized he was not alone a heartbeat before a cold blade was pressed against his throat.
"Don't move," a woman's voice warned him. She sounded young, like one of the youth who lived in the village below the monastery. "Are you Sentos the Merciful?" She spoke with an accent not of Thune, but not of the east either. Shandalar was vast, and wherever she was from, it was unfamiliar to Sentos.
"No." He could see the woman's shadow on the wall, backlit by the torch near the door. She was only slightly shorter than him, but then, he wasn't a very tall man.
"Then who are you?" she asked.
"Sentos the Not Dead," he said. She jammed the blade into his back, between his shoulder blade and his spine. He barely managed to not scream. Such a foolish assumption that a woman couldn't be deadly.
"Who are you?" she demanded.
"Sentos," he managed to say. The blade was still in his back. He felt momentary panic, like a clawing sensation in his belly. He wanted it out of him. He wanted it in her throat.
"Tell me what happened on Fleet Rock. The day you ended the war."
#figure(image("002_<NAME>/04.jpg", width: 100%), caption: [Public Execution | Art by <NAME>], supplement: none, numbering: none)
"I didn't kill a man," Sentos said through clenched teeth. #emph[Pain is just weakness leaving the body] . She twisted the blade, and he felt a gush of warm blood release from the gap in the skin. #emph[She doesn't understand the mind of warrior. Once she makes me hate her, pain becomes irrelevant.]
"Use more words, Sentos the Not Dead," she hissed.
"They led a silver-haired man to the executioner's block. He looked like a vagrant from the streets of An Karras," Sentos said. "No one told me he was the false king."
"So why spare his life?" she asked.
#emph[Why, indeed? Because of the ring that is now heavy on my hand. Why? He offered me the ring to spare his life. Why? Because a ring for my pretty wife sounded better than a bucket full of blood and another head rolling across the floor.]
"Why torture me for an answer?" She was not an eastern survivor. An easterner would have murdered him for calling the silver-haired man a false king.
She ripped the blade out from the left side of his spine and drove it into the right. But as fury warmed his chest, the pain disappeared. Oblivion could wait until he snapped her neck with his bare hands. He tried to spin around, but her grip was iron. Far stronger than he had expected, she slammed him down on the desk, his face grinding into the broken shards of the poison flask.
"Because you have something I need." She pushed his head down with such force, it felt like the planks would snap under the pressure. "Why did you spare his life?"
"Because it could have been me on that block. Or my son. Or anyone in the midst of that miserable war. I did it out of mercy." It was a lie he'd told many times before, and it flowed easily from his lips. #emph[She'll believe me because she thinks I want to live.]
#figure(image("002_Xathrid Gorgon/05.jpg", width: 100%), caption: [Captain's Call | Art by <NAME>les], supplement: none, numbering: none)
"Was it your secret plan to use their surrender against them?" she asked. "Get them to lay down their weapons, then rip their throats out?"
"No, my superiors saw an advantage where none had been intended." That was not a lie, and the words felt like pebbles on his tongue. #emph[No straight line between my heart and that devastation.]
"So what they say is true. You are a righteous man." Usually, when someone called him that, it was with deference. But he heard no respect or awe in her tone.
"Does that give you peace?" Sentos asked, still hating her, still immune to the blade in his back, still watching her shadow on the wall.
"Peace?" she scoffed. "I am cursed. A demon requires payment. He demands the eyes of a righteous man."
She pushed back her hood, and her silhouette transformed as the writhing strands of her hair unleashed themselves. A gorgon, a monster of Xathrid, with the power to petrify a man with her gaze. Disgusted, he recoiled against her grip. If he glimpsed her face, he would meet the same fate at the monk in the clearing. #emph[Just a kindly man come to check on my fate.]
#figure(image("002_Xathrid Gorgon/06.jpg", width: 100%), caption: [Xathrid Gorgon | Art by Chase Stone], supplement: none, numbering: none)
"Eyes of stone have failed me," she hissed. "Eyes of lesser men are insufficient. Your eyes will be my salvation."
The instant she eased the pressure on his head, Sentos grabbed a shard of glass, whirled around, and plunged into her heart.
Even before he removed the shard, black snakes poured from the wound. He scrabbled away from the flood of vipers, slipping and crashing to the ground. They swarmed over him, their fangs sinking into him and releasing venom into his blood. Desperately, Sentos rolled on his belly and crawled toward the door. Around him, the snakes that caught the gorgon's gaze turned to stone. With their fangs still deep in his skin, they weighed his body down as he inched toward the threshold.
The gorgon's foot slammed into the back of his neck, pinning him down in the nest of petrified snakes.
"How are you not dead? Are you not a man?" She crouched down beside him, yanking up his hand with such force that he heard his shoulder snap. "This ring? Where did you get this?"
#emph[From the False King on Fleet Rock, that man of unnatural long life and wisdom. He offered me the same in exchange for his freedom. I didn't believe his lies. But I gave him his freedom for the trinket anyway.]
#figure(image("002_Xathrid Gorgon/07.jpg", width: 100%), caption: [Ring of Xathrid | Art by Erica Yang], supplement: none, numbering: none)
With her blade, she sliced off his finger, taking the ring for her own.
"A ring that grants ceaseless life," she murmured. "Missing for so long, but here? In Thune?"
Without the ring, the venom seized his heart. The blood flowed freely from his wounds. He struggled to breathe while the door seemed to plunge miles away from his reach. #emph[Escape is senseless] . Instead, Sentos twisted his neck and gazed at the gorgon's face. She howled, slicing the knife down to take his eyes while he was still flesh. But he heard the tip of her blade meet the stone of his face. #emph[And rejoiced as darkness fell.]
#figure(image("002_Xathrid Gorgon/08.jpg", height: 40%), caption: [], supplement: none, numbering: none)
|
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/math/operators.md | markdown | MIT License | # Operators
> See [reference](https://typst.app/docs/reference/math/op/).
There are lots of built-in "text operators" in Typst math. This is a symbol that behaves very close to plain text. Nevertheless, it is different:
```typ
$
lim x_n, "lim" x_n, "lim"x_n
$
```
## Predefined operators
Here are all text operators Typst has built-in:
```typ
$
arccos, arcsin, arctan, arg, cos, cosh, cot, coth, csc,\
csch, ctg, deg, det, dim, exp, gcd, hom, id, im, inf, ker,\
lg, lim, liminf, limsup, ln, log, max, min, mod, Pr, sec,\
sech, sin, sinc, sinh, sup, tan, tanh, tg "and" tr
$
```
## Creating custom operator
Of course, there always will be some text operators you will need that are not in the list.
But don't worry, it is very easy to add your own:
```typ
#let arcsinh = math.op("arcsinh")
$
arcsinh x
$
```
### Limits for operators
When creating operators (upright text with proper spacing), you can set limits for _display mode_ at the same time:
```typ
$
op("liminf")_a, op("liminf", limits: #true)_a
$
```
This is roughly equivalent to
```typ
$
limits(op("liminf"))_a
$
```
Everything can be combined to create new operators:
```typ
#let liminf = math.op(math.underline(math.lim), limits: true)
#let limsup = math.op(math.overline(math.lim), limits: true)
#let integrate = math.op($integral dif x$)
$
liminf_(x->oo)\
limsup_(x->oo)\
integrate x^2
$
```
|
https://github.com/levinion/typst-dlut-templates | https://raw.githubusercontent.com/levinion/typst-dlut-templates/main/templates/thesis/reference.typ | typst | MIT License | #import "../util/style.typ":font_family,font_size
#import "../util/functions.typ":invisible_heading
#import "../util/bib.typ":bilingual-bibliography
#let reference(bib)={
if bib != none {
set align(center)
set text(font: font_family.heiti, size: font_size.xiao_san)
set par(leading: 1.5em)
set block(spacing: 1.5em)
[参 考 文 献]
invisible_heading[参 考 文 献]
set align(left)
set text(font: font_family.songti, size: font_size.wu)
set par(leading: 1em)
set block(spacing: 1em)
let bilingual-bibliography = bilingual-bibliography(bibliography: bib)
bilingual-bibliography
set text()
pagebreak(weak: true)
}
}
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/pattern-relative_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test with relative set to `"self"`
#let pat(..args) = pattern(size: (30pt, 30pt), ..args)[
#place(top + left, line(start: (0%, 0%), end: (100%, 100%), stroke: 1pt))
#place(top + left, line(start: (0%, 100%), end: (100%, 0%), stroke: 1pt))
]
#set page(fill: pat(), width: 100pt, height: 100pt)
#rect(fill: pat(relative: "self"), width: 100%, height: 100%, stroke: 1pt)
|
https://github.com/0xPARC/0xparc-intro-book | https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/src/oram-takeaways.typ | typst | #import "preamble.typ":*
#takeaway[ORAM takeaways][
1. _Oblivious RAM_ is a system to hide memory access patterns from a server.
2. The server stores encrypted data blocks in a binary tree,
and it does not learn which blocks correspond to which memory items.
3. Every time the ORAM client accesses a block, it writes that block back to the root.
4. A randomized eviction procedure moves blocks away from the root,
so individual nodes of the tree don't overflow.
]
|
|
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/visualization/brainstorm.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator, codetastic
#import notebookinator: *
#import themes.radial.components: *
#import codetastic: qrcode
#show: create-body-entry.with(
title: "Brainstorm: Data Visualization",
type: "brainstorm",
date: datetime(year: 2023, month: 11, day: 11),
author: "<NAME>",
witness: "<NAME>",
)
There are a multitude of different options that we could choose from. These
options fall into two categories:
- Graphing on the brain screen
- Graphing on an external computer
Graphing on an external computer is difficult due to the bandwidth limitations.
We would have to have the computer plugged into either the brain or the
controller at all times. Plugging directly into the brain gives us a very high
bandwidth, but it becomes inconvenient if we want to move the robot. We can
still connect wirelessly through the controller, but the bandwidth of that is
incredibly low.
However, we found a workaround that alleviates some of these problems. The brain
is Bluetooth cable. This connect not only doesn't require a physical connection
to either the controller or the brain, it also has a much higher bandwidth than
a traditional wireless connection.
The only downside is that the Bluetooth capabilities of the brain are largely
undocumented, and we would require a fair amount of trial and error to get it
working. Fortunately, a member of the VEX community has already done a large
portion of the work for us, and has published a working example. #footnote(
[
Minimal working Bluetooth script:
#align(
bottom,
qrcode(
"https://gist.github.com/wireboy5/e41444a135d7643c92fc3b83aa69058b/1160ac92c0cd4408e3b309228f77d2957c2cc7db",
size: 2pt,
),
)
],
)
= Options
== Native App
This option would involve writing a native desktop application for data
visualization. This options would allow users to simply download the app, click
connect, and then view data. We're unsure what tools we would use for this
currently but it seems like the easiest option for the user.
#pro-con(pros: [
- Very easy to use
- Requires little setup from the user
], cons: [
- Very difficult to implement
- Would require us to learn a large amount of new tools
- Must be compatible with multiple different operating systems
])
== Grafana Integration
This option involves an integration with the Grafana data visualization tool.
Grafana is a powerful tool designed exactly for our use case. Using it would
mean that we already have a whole host of functionality essentially for free,
without having to implement it ourselves. We would have to write some kind of
integration that can send information to one of the data sources that Grafana
can read from in addition to setting up Bluetooth, but that's about it.
#pro-con(pros: [
- Industry grade software
- Easier to develop
], cons: [
- Setup is very annoying for the user
])
Overall this option seems like the easiest option for us to write, but could
cause some friction with the user. Grafana is tricky to set up, and isn't just a
single one and done download. We'd probably also need additional services to act
as a data source.
== LCD Screen
This solution eliminates the need for a external connection the brain entirely,
and graphs the data directly on the brain's LCD screen. PROS #footnote("See glossary.") already
packages a library called LVGL (Light and Versatile Graphics Library), which
already supports things like graphs.
#pro-con(
pros: [
- No bandwidth problems
- No setup required by the user
],
cons: [
- The LCD screen is extremely small and difficult to see if the robot is moving
- Data is still extremely hard to get off of the brain if we want to save it for
later, or put it into the notebook.
],
)
This solution would be our go to if we didn't have other places that we wanted
to display the data, like the notebook. Its super easy, but as soon as you need
the data somewhere else, our workflow is exactly the same as it was before.
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/suiji/0.2.2/src/lib.typ | typst | Apache License 2.0 | #import "random.typ": gen-rng, integers, random, uniform, normal, discrete-preproc, discrete, shuffle, choice
#import "chinese.typ": rand-sc
|
https://github.com/TGM-HIT/typst-diploma-thesis | https://raw.githubusercontent.com/TGM-HIT/typst-diploma-thesis/main/docs/manual.typ | typst | MIT License | #import "template.typ" as template: *
#import "/src/lib.typ" as tgm-hit-thesis
#let package-meta = toml("/typst.toml").package
#let date = datetime(year: 2024, month: 10, day: 23)
#show: manual(
title: "TGM HIT diploma thesis template",
// subtitle: "...",
authors: package-meta.authors.map(a => a.split("<").at(0).trim()),
abstract: [
A diploma thesis template for students of the HIT department at TGM Wien.
],
url: package-meta.repository,
version: package-meta.version,
date: date,
)
// the scope for evaluating expressions and documentation
#let scope = (tgm-hit-thesis: tgm-hit-thesis)
= Introduction
This template is aimed at students of the information technology department at the TGM technical secondary school in Vienna. It can be used both in the Typst app and using the CLI:
Using the Typst web app, you can create a project by e.g. using this link: #link("https://typst.app/?template=" + package-meta.name + "&version=latest").
To work locally, use the following command:
#raw(
block: true,
lang: "bash",
"typst init @preview/" + package-meta.name
)
If you are getting started writing your thesis, you will likely be better off looking into the thesis document created by the template: it contains instruction and examples on the most important features of this template. If you have not yet initialized the template, a rendered version is linked in the README. If you are new to Typst, also check out the Typst documentation: https://typst.app/docs/.
The rest of this manual documents the individual functions offered by this package. This is useful if you want to know what customization options are available, or you're not sure what parts of the template package do.
As a school-specific template, this package does not offer enough configurability to be used at different institutions. However, if you like this template, feel free to adapt the code (MIT-licensed) to your needs, or open a Github issue if you think the template could be adapted to work for your requirements.
= Module reference
== `tgm-hit-thesis`
The template's main module. All functions that need to be called are directly exported from this module.
#module(
read("/src/lib.typ"),
name: "tgm-hit-thesis",
label-prefix: none,
scope: scope,
show-module-name: false,
)
== `tgm-hit-thesis.utils`
Utilities, mostly internal. The #ref-fn("chapter-end()") function is re-exported from the main module.
#module(
read("/src/utils.typ"),
name: "tgm-hit-thesis.utils",
label-prefix: none,
scope: scope,
show-module-name: false,
)
== `tgm-hit-thesis.glossary`
Wrappers for #link("https://typst.app/universe/package/glossarium")[Glossarium] functionality. The #ref-fn("glossary-entry()") function and Glossarium's ```typc gls()``` and ```typc glspl()``` are re-exported from the main module.
#module(
read("/src/glossary.typ"),
name: "tgm-hit-thesis.glossary",
label-prefix: none,
scope: scope,
show-module-name: false,
)
== `tgm-hit-thesis.l10n`
Contains contextual constants that display localized strings. This is a thin wrapper around #link("https://typst.app/universe/package/linguify")[linguify] that improves autocomplete and avoids typos in Typst code. Have a look at the source code to see what definitions are available.
#module(
read("/src/l10n.typ"),
name: "tgm-hit-thesis.l10n",
label-prefix: none,
scope: scope,
show-module-name: false,
)
== `tgm-hit-thesis.assets`
Contains images used in the template.
#module(
read("/src/assets/mod.typ"),
name: "tgm-hit-thesis.assets",
label-prefix: none,
scope: scope,
show-module-name: false,
)
|
https://github.com/JunzheShen/SJTU-Resume-Template-in-Typst | https://raw.githubusercontent.com/JunzheShen/SJTU-Resume-Template-in-Typst/main/template.typ | typst | // 字体
#let font = (
main: "IBM Plex Serif",
mono: "IBM Plex Mono",
cjk: "Microsoft YaHei",
)
// 图标
#let icon(path) = box(
baseline: 0.125em,
height: 1.0em,
width: 1.25em,
image("./icons/" + path)
)
#let faAngleRight = icon("fa-angle-right.svg")
// 主体
#let resume(
size: 10pt,
themeColor: rgb(38, 38, 125),
info:none,
photo_path:none,
body
) = {
// 页边距设定
set page(margin: 20pt, background: place(top + right, image("简历背景(无个人信息).jpg")))
// 基础字体设定
set text(font: (font.main, font.cjk), size: size, lang: "zh")
// 标题及小标题样式
show heading: set text(themeColor, 1.1em)
// 二级标题下加一条横线
show heading.where(level: 2): it => stack(
v(0.3em),
it,
v(0.6em),
line(length: 100%, stroke: 0.05em + themeColor),
v(0.1em),
)
// 更改 bullet list 的图标
// set list(indent: 1em, body-indent: 0.8em, marker: faAngleRight)
// 上面的语句无法精确控制图标位置, 因此改用了下列方法重写 list
show list: it => stack(spacing: 0.4em, ..it.children.map(item => {
grid(
columns: (2em, 1fr),
gutter: (0em),
box({
h(0.75em)
faAngleRight
}),
pad(top: 0.15em, item.body)
)
}))
// 链接颜色
show link: set text(fill: themeColor)
// 主体设定
set par(justify: true)
show par: set block(spacing: 0.65em)
// 空出个人信息的位置
box(height: 150pt)
//个人信息
place(top+right,
dx: 12pt,
dy: 81pt,
box(
width: 440pt,height: 60pt,
)[
#set text(fill: white, font: font.cjk, size: size+1pt, weight: 550)
#set par(leading:13pt)
#set align(left)
#grid(columns: 2, column-gutter: 25pt, row-gutter: 5pt)[
姓名:#info.name\
院校:#info.school\
专业:#info.major
][
电话:#info.phone\
邮箱:#info.email\
微信:#info.wechat
]
]//box
)
//照片
place(top+left,
dx: 0pt,
dy: 0pt,
box(
height: 40mm,
)[
#if photo_path != none [
#image(photo_path)
]else[
#box(fill: white,width: 30mm,height: 40mm)
// #rect[111]
]
]//box
)
body
}
// 带竖线的侧边栏
#let sidebar(side, content, withLine: true, sideWidth: 12%) = style(styles => {
let sideSize = measure(side, styles)
let contentSize = measure(content, styles)
let height = calc.max(sideSize.height, contentSize.height) + 0.5em
grid(
columns: (auto, 0%, 1fr),
gutter: (0.75em),
{
set align(right)
v(0.25em)
side
v(0.25em)
},
if (withLine) {line(end: (0em, height), stroke: 0.05em)},
{
v(0.25em)
content
v(0.25em)
},
)
})
// 日期: 颜色变灰
#let date(body) = text(
fill: rgb(128, 128, 128),
size: 0.9em,
body
)
// 项目
#let item(
title,
desc,
endnote,
color: rgb(23, 95, 139),
) = {
set text(fill: color)
v(0.25em)
grid(
columns: (30%, 1fr, auto),
gutter: (0em),
title, desc, endnote
)
}
|
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/04-opentype/fonttools-ttx.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/components.typ": note
#import "/lib/glossary.typ": tr
#show: web-page-template
// ## FontTools and ttx
== FontTools 和 `ttx` 工具
// To crack open that OTF file and look at the tables inside, we're going to use a set of Python programs called `fonttools`. `fonttools` was originally written by <NAME>, but is now maintained by <NAME> and a cast of hundreds. If you don't have `fonttools` already installed, you can get hold of it by issuing the following commands at a command prompt:
为了能拆开 OTF 文件并且直接看看这些数据表,我们需要一套被称为`fontTools`的Python程序。`fontTools`最初由Just van Rossum编写,现在则由 <NAME> 和数百位贡献者一起维护。如果你还未安装 `fontTools`,可以使用如下命令来安装它:
#note[
// > If you're a Mac user and you're not familiar with using a terminal emulator, pick up a copy of *Learning Unix for OS X* by <NAME>. If you're a Windows user, I'm afraid you're on your own; Windows has never made it particularly easy to operate the computer through the command prompt, and it's too painful to explain it here. If you're on Linux, you already know what you're doing.
如果你是Mac用户,且不熟悉终端和命令行操作,可以看看Dave Taylor写的《Learn Unix for OS X》一书。如果你是Windows用户,你可能需要自行研究了。Windows的命令行功能不太易用,使用它进行系统交互会比较痛苦,我在这就不过多解释了。如果你是Linux用户的话,我相信你已经很熟悉下面的操作了。
]
```bash
easy_install pip
pip install fonttools
```
// If you have the Homebrew package manager installed, which is highly recommended for developing on Mac computers, you can get `fonttools` through Homebrew:
如果你安装了在Mac上做开发工作时推荐使用的Homebrew包管理器的话,也可以用它来获取 `fontTools`:
```bash
brew install fonttools
```
#note[
// > Homebrew is a system which allows you to easily install and manage a number of useful free software packages on Mac OS X. You can get it from http://brew.sh/
Homebrew 是 Mac OS X 系统上的一个用于轻松安装和管理自由软件包的工具。你可以在其官网获取它:#link("http://brew.sh/")。
]
// The core of the `fonttools` package is a library, some code which helps Python programmers to write programs for manipulating font files. But `fonttools` includes a number of programs already written using the library, and one of these is called `ttx`.
`fontTools`的核心是一个帮助Python开发者编写字体处理功能的程序库。但它同时也包含了几个用这个库编写而成的可以直接使用的程序。`ttx` 工具就是其中之一。
// As we mentioned above, an OpenType font file is a database. The database, with its various tables, is stored in a file using a format called SFNT, which stands for "spline font" or "scalable font". OpenType, TrueType, PostScript and a few other font types all use the SFNT representation to lay out their tables into a binary file. But because the SFNT representation is *binary* - that is to say, not human readable - it's not very easy for us either to investigate what's going on in the font or to make changes to it. The `ttx` utility helps us with that. It is used to turn an SFNT database into a textual representation, XML, and back again. The XML format is still designed primarily to be read by computers rather than humans, but it at least allows us to peek inside the contents of an OpenType font which would otherwise be totally opaque to us.
上面已经介绍过,OpenType字体文件其实是一个包含多个数据表的数据库。这些数据表使用 SFNT 格式储存在文件中。SFNT代表#tr[spline]字体(spline font)或可缩放字体(scalable font)。OpenType、TrueType、PostScript等字体格式都会使用SFNT来储存数据表。但SFNT是一种人类无法直接阅读的二进制格式,想了解字体内部的构造或者修改它就比较困难。`ttx`工具就是来帮我们处理这个难题的。它可以将SFNT数据库转换为XML格式的文本形式,同时支持反向转换。XML其实也是一种偏向于给计算机看的格式,但至少比之前那种人类完全不可理解要好的多了。借助它,我们可以略微窥探一下OpenType字体中的实际内容。
|
https://github.com/Marmare314/typst-presentation | https://raw.githubusercontent.com/Marmare314/typst-presentation/main/README.md | markdown | MIT License | # typst-presentation
An easy to use presentation template.
|
https://github.com/dismint/docmint | https://raw.githubusercontent.com/dismint/docmint/main/multicore/study.typ | typst | #import "template.typ": *
#show: template.with(
title: "6.5081 Study Guide",
subtitle: "Spring 2024"
)
= Chapter 1
#define(
title: "Mutual Exclusion"
)[
The property that no two processes are in their critical section at the same time.
]
/ Deadlock Free: At least one thread will make progress.
/ Starvation Free: If a thread wants to enter the critical section, it will eventually do so.
/ Liveness Property: A property that states that something good will eventually happen.
/ Safety Property: A property that states that something bad will never happen.
#define(
title: "Amdahl's Law"
)[
$ 1 - p + p / n $
]
= Chapter 2
When we show something satisfies mutual exclusion, we want to show that assuming it doesn't, we can derive a contradiction.
```java
class LockOne implements Lock {
private boolean[] flag = new boolean[2];
public void lock() {
int i = ThreadID.get();
int j = 1 - i;
flag[i] = true;
while (flag[j]) {};
}
public void unlock() {
int i = ThreadID.get();
flag[i] = false;
}
}
```
In this case, we know the following two precedence chains are true, assume they happened in the order listed WLOG:
- `write_a(flag[A] = true) -> read_a(flag[B] = false -> CS_a`
- `write_b(flag[B] = true) -> read_b(flag[A] = false -> CS_b`
Therefore it must also be the case that:
- `read_a(flag[B] = false) -> write_b(flag[B] = true) -> CS_a`
Then from this we can derive the precedence chain:
- `write_a(flag[A] = true) -> read_a(flag[B] = false) -> write_b(flag[B] = true) -> read_b(flag[A] = false)`
Which is a contradiction, since thread B could not possibly have read A as false.
/ Execution: A timeline of function calls and returns as ranges.
/ Quiescence: A state where no thread is in the critical section, a pause state.
Method calls should be linearizable, and should appear in their real time order of they are separated by a period of quiescence.
#define(
title: "Quiescent Consistency"
)[
Any time an object becomes quiescent, it should appear as if all operations have been executed in some sequential order, which have happened prior to that quiescence.
]
= Chapter 3
#define(
title: "Libearizability"
)[
Each method call should appear to take effect instantaneously at some moment between its invocation and return.
]
History calls are written as: `<x.m(a*) A>`, where `x` is the object, `m` is the method, `a*` is the arguments, and `A` is the thread. History returns are written as `<x:t(r*) A>`, where `x` is the object, `t` is the return value of `ok` or `error`, `r*` is the return values, and `A` is the thread.
A *method call* in a history is a pair of a call and a return, where the call is before the return, and the return is for the call. The notation `complete(H)` is a history where we should throw out all pending method calls. We can also look at a `thread subhistory` or an `object subhistory`.
Two histories are *equivalent* if for every thread `A`, the `thread subhistorie`s are the same.
A method call in a history precedes another if the call finishes before the other starts.
A history *`H`* is *linearizable* if there is an extension *`H'`*, and there exists a sequential history `*S*` such that `complete(H')` is equivalent to `S` and if a method call precedes another in the original history, it also precedes it in the sequential history.
An overall history is linearizable if and only if each object in the history is linearizable.
/ Wait-Free: Every call finishes its execution in a finite number of steps. It becomes *bounded* wait-free if there is a bound on the number of steps a method call takes. This bound could be dependent on the number of threads. If it is not dependent on the number of threads, it is `population-oblivious`.
/ Lock-Free: At least one thread makes progress in a finite number of steps, infinitely often.
= Chapter 4
/ Atomic Register: A register that can be read and written atomically.
/ Safe Register: A `read()` that does not overlap with a `write()`, returns the value written by the most recent `write()` and if it does overlap, then the `read()` can return any valid value for the register.
/ Regular Register: A `read()` that does not overlap with a `write()`, returns the value written by the most recent `write()` and if it does overlap, then the `read()` can return either of the two values, either new or old.
A register is an `M`-valued register if it can store values from `0` to `M - 1`.
= Chapter 5
#define(
title: "Consensus Numbers"
)[
A consensus object provides a method `decide(v)` that each thread calls with a value at most once. The result must be:
/ Consistent: All threads that call `decide(v)` get the same value `v`.
/ Valid: The value `v` must be one of the values that was passed to `decide(v)`.
You can only make an object with equal or lower consensus number from objects with a consensus number of `n`.
]
There is a special type of register called a `Common2` register, and any set of functions belongs to `Common2` if for two functions $f_1$ and $f_2$, either:
- $f_1$ and $f_2$ commute: $f_1(f_2(x)) = f_2(f_1(x))$
- One function overwrites another: $f_1(f_2(x)) = f_1(x)$ or $f_2(f_1(x)) = f_2(x)$
The consensus number of `Common2` is `2`.
= Chapter 6
Universal objects are those that given sufficiently many of them, we can construct a wait-free linearizable implementation of any concurrent object. These objects must have consensus number `n` for `n` threads.
We can make any sequential object into a lock-free linearizable concurrent object by wrapping it in a queue of nodes, where you add your method to the head, and then walk from tail to head, executing it for your own local copy. Each node keeps a copy of the last thread that it used.
How exactly the consensus algorithm works is a bit questionable, and is one of the hard parts of implementation in a practical setting.
In order to make this construction wait-free, we need to add a new `announce` array, where you store it into this array during the `apply` function. During the main loop, try help another announced object, indexed based on the current sequence number of the head. The particular reason that the algorithm does not add a given node twice now is due to the specific ordering of the operations.
= Chapter 7
Locking stuff, maybe study later?
= Chapter 9
/ Coarse-Grained Synchronization: Locking the entire data structure.
/ Fine-Grained Synchronization: Lock only the parts of the data structure that are being accessed.
/ Optimistic Synchronization: Assume that there are no conflicts, and then check for conflicts later, locking after you unsure you have what you expect.
/ Lazy Synchronization: Delay synchronization until it is absolutely necessary, allowing `contains` and such to be wait-free.
We can see an example of this with the `LinkedList` and the `marked` construct.
We can finally extend this idea into non-blocking synchronization, where we can use `compareAndSet` to atomically update a value if it is what we expect.
= Chapter 10
#define(
title: "Pool"
)[
A `Pool` is an object that is similar to a set, but does not provide the `contains` method to test membership, and allows items to appear more than once.
]
`Pool` methods can be:
/ Total: Any method call immediately returns without waiting for something to happen.
/ Partial: May wait for certain conditions to hold.
/ Synchronous: The method call returns only after another method directly overlaps it.
A queue is an example of a `Pool`.
#define(
title: "ABA Problem"
)[
Suppose we implement the memory recycling with the local pools of freed nodes. The following sequence could happen:
+ Thread A attempts to deq, but freezes right before the compare and set of `B <- A`
+ Threads B and C deq `A` and `B` respectively.
+ Then Thread A wakes up and compares `A` to `B`, and sees that they are the same, and then proceeds to set the head equal to `B`, a recycled node.
This is why it is called ABA, because it flops between those three values. To fix this problem, we could use a stamp, that increments the object every time it is modified.
]
= Chapter 11
Now we take a look at stacks, which are another type of `Pool`
#define(
title: "Exponential Backoff"
)[
The idea with exponential backoff is that if you fail to get a lock, you wait for a random amount of time, and then try again. If you fail again, you wait for a longer amount of time, and so on. This is a way to avoid the thundering herd problem. Generally the base amount of waiting is multiplied by two up to a certain maximum cap.
]
#define(
title: "Elimination"
)[
The idea with elimination in a stack is to get rid of the serial bottleneck of using the `compareAndSet` method. The idea is to have a `push` and `pop` method that can be used to exchange values between threads, eliminating the other.
In order to ensure that there is not more that one match, we must use a coordination structure called an *exchanger* to ensure that exactly two threads and no more can exchange values.
]
= Chapter 12
#define(
title: "Combining Trees"
)[
The idea behind combining trees is that we have a tree with at most two threads per leaf, and we traverse the tree upward, and if two threads meet each other, only one of them will continue upward to update the value. This will minimize contention on the lock. There are some bad cases, for example after a node gets locked, a lot of other guys arrive late There are some bad cases, for example after a node gets locked, a lot of other guys arrive late.
]
- Tree width, length (why this could be better), construction
#define(
title: "Diffracting Tree"
)[
Uses a branching log depth algorithm and uses a `Prism` to eliminate things.
]
You can also use these things to sort.
= Chapter 13
Bucket threshold versus global threshold, don't always want to resize locks.
#define(
title: "Lock Striping"
)[
The number of locks is fixed, and we coarse grain based on the mod.
]
= Chapter 16
Work, Critical Path, and Parallelism analysis and using the master theorem.
/*
= there are a couple things here
Consensus numbers
0 valent means that that is point where it will decide 0
fetch negate and add with a, b, c and c, b, a example 0 0 1 1, a b c, then d can't tell the difference between a and c
for 3 => 222, , fna of 1, 10, 100
-212 if 10 goes first
213 if 1 then goes
113, but it doesn't ge tthis
if somethig has a consensus number of n, then you can only use it to make consensus number of n
skip lists
learn about universal construction
counting networks - balancers, mergers, step property
linearization when something happens
*/
hierarchical spin locks short / long critical shared no shared
wf linear qobj 2 deq r/w reg
volatile
linea rseq consistency
parallelism
aba
wakeup
regiers
work
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/036%20-%20Guilds%20of%20Ravnica/008_The%20Gathering%20Storm%3A%20Chapter%202.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Gathering Storm: Chapter 2",
set_name: "Guilds of Ravnica",
story_date: datetime(day: 12, month: 06, year: 2019),
author: "<NAME>",
doc
)
The rot gardens of the Devkarin were legendary.
Any fool could build a midden, or grow mushrooms from offal. But the shadow elves approached the flora of decomposition with the same attention a surface-world gardener might lavish on roses or orchids. It was putrescence raised to high art, practiced by long-lived masters in a realm that never saw the sun.
The personal chambers of Jarad, guildmaster of the Golgari Swarm, were a particularly fine example. A broad, circular courtyard was covered by a vaulted ceiling, crusted with long stalactites. The only light came from bio-luminescent fungi, which grew from wooden globes that hung down at irregular intervals. The planters were arranged to divide the space into many small, intimate meeting spots and corridors, and couches covered in soft moss were provided for guests who wished to recline.
Each planter was a corpse, or sometimes several corpses, carefully propped, cut, and arranged to promote the growth of some particular species of fungus. The rot gardeners’ shamanic magic hedged out the common agents of decay, keeping the bodies relatively intact. Here a man sat with his legs crossed, head tipped back, vast yellow-white stalk growing out of his eyes; beside him a woman arched her back, her chest sectioned and peeled back to allow delicate blue fronds to reach up from her heart. Some of the fungi were so large and solid they grew around their hosts, leaving faces and limbs to jut out of quivering masses of gray-white flesh. Others were the smallest, most delicate things, that would dissolve under a stray breath. A few of them, if ingested, would kill a human in seconds. Many more would do strange things to the eater’s brain.
Jarad sat on his fungus throne, long strands of soft-fringed moss falling all around him. Around him wait the Cilia, the most powerful and influential of the Devkarin, slim elven bodies glad in spidersilk, faces painted in insect patterns.
The silent servants that moved among them, bearing trays of food and a variety of intoxicants, were elegant as well. Though dead, they walked with the grace of nobility, and their clothes were intricate, ancient things, the burial finery of centuries past. These were the Erstwhile, raised from the vault of Umerilek by Mazirek, the kraul death priest. Jarad adored them. So much more graceful that the shambling rot zombies the shamans raised, with a poise and intelligence common undead couldn’t match. They’d become quite the fashion in the Golgari court, and it was a poor shadow elf these days who wasn’t served by nobles of an ancient age.
There was a sound of splintering wood from the front of the room. Jarad looked up and frowned.
"I ordered that sealed," he said.
"You did." Storrev stood at Jarad’s side. She was an Erstwhile lich, possessed of all the intelligence she’d had in life. Dressed all in black, with a long veil shrouding her dried, ruined face, she was almost invisible until she spoke, voice haughty with the accent of a long-dead court. "I believe someone is trying to get in."
"What?" Jarad got to his feet. "Who dares?"
Across the corpse-planters, through the delicate fungi, he saw the front door flex inward. It was a massive thing, root-wood banded with cold iron, but its timbers groaned and cracked. Another instant, and it shattered, sending splinters tearing through the delicate rot-sculptures. Fungal blooms that had taken decades to grow collapsed into pools of slime.
In the doorway was a hulking figure, a troll larger than any Jarad had ever laid eyes on. There were more creatures behind it, but his eyes were fixed on the humanoid shape who stepped forward. A woman, dressed in fighting leathers, a cutlass at her hip. Humanoid, but not human, and certainly not elven. Where her hair should have been was a mass of curling black tentacles, writhing like a basket full of snakes.
There were several gorgons in the service of the Golgari swarm, but only one who would dare such an insult. Jarad’s lip curled.
"Vraska."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Vraska stepped into the rot garden. She’d always hated the place. The air was thick with the sick-sweet scent of decay, and the hundred little corners were made for the backstabbing, bickering conspiracies on which the Devkarin court had always thrived.
#emph[That] , she thought, #emph[ends tonight.] #emph[] #emph[] Jarga was still picking bits of door out of his fist, but the two kraul followed her, six-legged insects layered in chitinous armor. Mazirek, on her left, was nearly as tall as Vraska, his carapace daubed in spiraling black paint. He was the closest thing the kraul had to a leader, and had been her first ally among the hives.
On her right walked a much smaller kraul, a sickly-looking dead white specimen with drooping, useless wings. Xeddick had been an outcast among his people, for his coloration and his strange abilities, until Vraska had befriended him. Since then, he’d followed her like a puppy.
Jarad, in his spidersilk robe and blue and red face paint, rose from his throne and pointed at her.
"Vraska," he snarled. "I do not recall summoning you. Nor asking you to break down my door."
"And here I am, nevertheless," Vraska said. "Funny, that."
She started toward him, kicking a corpse-planter out of the way in a spray of pink spores. The two kraul followed, armor clicking. Out of the corner of her eye, she could see shadow elves scrambling out of the way, while their Erstwhile servants stood motionless.
"All this decadence," the gorgon mused. "The years have not been kind to you, Jarad."
"What exactly do you think you’re doing?" Jarad, at least, was unafraid to face her. A few courtiers stood with him, and she saw hands straying toward weapons. "You have value to this court, but do not overestimate your importance. I could have your head for this."
"Could you?" Vraska murmured. She pushed another planter out of the way, stopping a dozen feet from the guildmaster. "Let’s see you try to take it, then."
Jarad’s eyes narrowed. "So that’s the way it is."
"That’s the way it is." Vraska rested her hand on her cutlass. "Well? I’m waiting."
"Someone kill her," Jarad drawled.
Two of his courtiers strode forward, a young man with the mantis tattoos of a fourth-grade blademaster and a woman in the flowing robe of a shaman. With a nod, Vraska directed Mazirek toward the woman, and drew the cutlass from her belt.
The blademaster was fast, his sword the thin rapier popular among the Devkarin for their lethal, precise forms. She barely turned his first cut, and he danced back out of range of her riposte, his sword leaving a bloody line across her forearm. Vraska growled in irritation, slammed his next stroke aside with the greater weight of her weapon, and bulled forward until they were face to face. Golden energy gathered in her eyes.
He realized his mistake too late. Before he could look away, power flashed between them. A wave of gray flowed out from his eyes, turning his flesh cold and hard and dead. Stone fingers clenched on the hilt of his sword. Off balance, the statue stood for only a moment before toppling, smashing into pieces with a #emph[crunch] .
The other duel was ending, too. Sheets of fungi rippled across Mazirek’s carapace, but the kraul seemed unperturbed. His forelimbs moved with blinding speed, working a spell, and the elf stumbled backward clutching at her throat. For a moment she stared, eyes bulging, as black lines like necrotic veins spread through her flesh. Then she fell, curling up on her side, shuddering as the flesh rotted from her bones. In a few seconds there was only a skeleton lying in a pool of slime.
#emph[Friend-Vraska. ] The mental touch was Xeddick’s. The kraul was a telepath, a rarity almost unheard of among his race. Vraska half wondered if he was the result of some rogue Simic experiment. #emph[The dead gather.] #emph[] #emph[] She looked over her shoulder. The Erstwhile were assembling by the door, ladies in threadbare court dresses, men in rotten coats and cobwebbed wigs. Four of them stepped from behind Jarad’s throne, wearing the armor of an ancient royal guard, swords at their belts. Storrev stood beside Jarad, face hidden behind her veil.
#emph[I see them] , she thought to Xeddick. She felt his nervousness, and sent a pulse of reassurance. #emph[Everything is under control.] #emph[] #emph[] "How do you expect this to end?" the guildmaster said, apparently uncowed by the demise of his champions. The rest of his court had retreated to a safe distance.
"With you on your knees, begging for mercy." Vraska sheathed her cutlass and rubbed at the wound on her arm. "We can skip straight to that, if you like."
"Suppose you kill me," Jarad said. "You know what will happen? The Devkarin—"
"The Devkarin have been in power too long," Vraska said. "You’ve treated the Golgari as an instrument of your personal pleasure, squandered our strength in decadence. That ends today."
"You don’t have the strength," Jarad sneered. "A few bugs aren’t enough. Start a civil war here, gorgon, and it will end with your head on a spike. And #emph[your] people, Mazirek, will suffer for a hundred generations."
"We have borne your tyranny long enough," Mazirek said. His speech was slurred and clicking, coming through mouthparts not designed for the common tongue. "Vraska offers the kraul respect."
"Respect will do you very little good when you’re rotting in my garden." Jarad grinned, bright and unhinged. "But enough of this! Put aside your grievances, and I will make you—"
Vraka lashed out, a fast punch that caught Jarad on the nose with a solid #emph[crunch] . He staggered backward, blood streaming over his upper lip.
"Storrev!" he shrieked. "Stop her."
#emph[And now] , Vraska thought, #emph[we find out if Bolas was right. ] #emph[] #emph[] The assembled Erstwhile stood, waiting. The four guards around the throne, the servants now standing in ranks around the room. They stood—
—and did nothing.
"Storrev!" Jarad whirled in a spray of blood. "What is the meaning of this?"
"You are the past," the lich said, without inflection. "Vraska is the future."
#emph[Ahhhh. ] Jarad turned back to Vraska, and #emph[now] there was panic in his eyes. She drank it in like nectar. His mouth worked, hands clutching at his robe.
"You still won’t get away with it," he muttered. "Enjoy your little victory. The rest of the elves—"
"Have Erstwhile servants," Vraska said. "Don’t they?"
Jarad’s eyes went wide. "No."
"We’ll spare those who don’t resist." She took another step forward, and he fell to his knees. "But the Golgari are #emph[mine] now." Vraska glanced at Mazirek, who made a deferential gesture with his forelimbs, and Storrev, who inclined her head. "The reign of the shadow elves is over."
"I . . . I can help you," Jarad mumbled. "There are things I know . . . secrets. You need me."
"You know, you’re right?" She motioned to Xeddick, and the little kraul came forward to stand before the guildmaster. #emph[You know what to do] , she thought at him.
#emph[Yes, friend-Vraska. ] Xeddick’s mental touch was unhappy. He didn’t like using his powers this way. #emph[Do not resist, enemy-Jarad. It only makes the pain worse.] #emph[] #emph[] Judging by the way he screamed, Jarad resisted. When it was over, he lay in a whimpering heap at the base of his throne.
#emph[You have what we need?] Vraska thought to Xeddick.
#emph[I believe so, friend-Vraska. Lists of agents in the surface world, passwords, meeting places. ] Xeddick sent a wave of disgust. #emph[His mind tastes of filth.] #emph[] #emph[] #emph[I can imagine. ] #emph[] #emph[] Vraska leaned down and grabbed the guildmaster by the collar, dragging him up to meet her gaze. Golden energy gathered, and Jarad screamed again.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Rain lashed the side of Orzhova, the Cathedral Opulent, great stronghold of the banker-priests of the Orzhov. Kaya was certain it was a beautiful building, all flying buttresses and bas-reliefs, with wide stained-glass windows and gilded fixtures. She just wished it wasn’t such a pain in the ass to climb, especially at night and in the rain.
#emph[This is probably high enough. ] Her hair hung in a sodden mass at the nape of her neck, and she was soaked through to her smallclothes, in spite of a leather raincape. She’d entered the building at ground level, then worked her way up as far as she could manage without raising the alarm before slipping over to the outside to climb the tower. So far, this had allowed her to bypass most of the Orzhov security, though she doubted her luck in that respect would continue. #emph[You don’t get rich enough to build your own cathedral without getting a little paranoid.] #emph[] #emph[] Still, she’d had worse jobs, and in much worse places. The city-plane of Ravnica was positively pleasant when measured against some of the swamps and catacombs where she’d been sent to hunt her incorporeal prey. #emph[The food’s good, as long as you don’t think too hard about where they get it. And when you ask about a hot bath, the innkeepers don’t look at you like you’ve gone mad. Though it would be nice if the rain ] ever#emph[ stopped.] #emph[] #emph[] She found a handhold on an outcropping cornice, beside a carved gargoyle whose open maw spouted a stream of rainwater. Kaya gave the gargoyle a long, suspicious look, but it didn’t seem inclined to suddenly spring to life. Bracing herself against it, she took a deep breath and drew on her power. Violet energy flowed around her, shifting her body from solidity to ghost-like incorporeality, and she stepped in through the solid stone. It was a more difficult trick than it appeared—the hard part was keeping her grip on the #emph[outside] of the wall solid until she’d gotten sufficient footing on the #emph[inside] —but Kaya had been sliding through barriers at odd angles most of her life.
As she’d hoped, her climb up the main tower of the Orzhova had gotten her past the first few lines of defense. She found herself in a sumptuously carpeted hallway, lit by candles burning softly in gilded braziers. Doors at regular intervals bore brass nameplates, and the wood was engraved with the elaborate coats of arms of the knights and syndics who worked here, making the wheels of Orzhov commerce turn. Judging by the height of the ceiling, there were at least three more stories between her and her target.
#emph[Assuming, of course, the information the dragon provided is accurate. ] The first rule of mercenary work was "never trust the client," and that was doubly true in the case of <NAME>. But the payoff was big enough that she’d thought it worth the risk. #emph[If anyone has the power to fix the broken sky, it’s Bolas. ] And her contacts had insisted he was at least reasonably trustworthy. #emph[For a dragon, anyway.] #emph[] #emph[] She padded softly down the hallway, water dripping noiselessly onto the silk carpets. At the end of the hall, there was a stairway up to the next floor, secured by a floor-to-ceiling iron grill. Kaya examined the tiny golden runes inset around the keyhole that locked it in place, found a ward that would raise an alarm if the lock was picked, and grinned. She stepped through in a shimmer of purple, and jogged up the switchback stairs.
The next floor was some kind of records archive, which seemed to go on forever. #emph[No surprise there. Priests like to write things down, and so do bankers, so I’m sure banker-priests are even worse. ] The doors to the storerooms were inscribed with dire magical traps, but the hallway had only a few tripwires, which were so easily disabled it was almost insulting. #emph[If this keeps up, I’m going to have leave them a stern note.] #emph[] #emph[] Another grate blocked off the stairs, and this one was augmented by a pair of guards in plate armor and conical helmets. They had the stolid, bored look of guards everywhere. Observing them from around a corner, Kaya figured she could probably take them both down if she had to—a knife throw to the unarmored throat of the one on the left, then close and take the other one’s legs out from under him before he could get that clumsy sword out. #emph[But that’s hardly elegant. ] Besides, she didn’t want to kill anyone she didn’t have to.
Instead, she worked her way back the corridor to the outer wall and phased back onto the exterior of the tower. This was even harder than going the other way, but she found a convenient handhold on the sculpted bust of some long-dead aristocrat, and swung her legs out in a spray of violet before managing to set her feet against another buttress. From there, she climbed, ascending until she figured she was well past the guards. #emph[Better to stay inside as much as I can, though. They must have ] some #emph[protection against flying thieves.] #emph[] #emph[] She braced again on another convenient gargoyle. It was only when she already had one hand reaching into the stone that it occurred to her that #emph[this] one didn’t have a rain pipe in its mouth and seemed considerably less weathered. By then, it was already moving.
#emph[Ah, hell.] #emph[] #emph[] A very complicated moment followed. Kaya had one hand incorporeal and reaching through a stone wall, and her other arm and one foot shoved against the gargoyle. It shifted away from her, and she was suddenly falling off the wall. At the same time, it opened its beak to shriek a warning, which would undoubtedly bring every guard in the cathedral running.
#emph[Think fast.] #emph[] #emph[] She let her left hand, inside the tower, slip back into corporeality and scrabble blindly. Thankfully, her groping fingers found the stem of a brazier, and she grabbed it, setting her weight against the wall. It took most of her concentration to maintain the narrow band of incorporeality around her wrist, but she had enough left to lash out with her other hand and jam it into the gargoyle’s throat, grabbing its tongue in her fist. The stony creature’s eyes bulged, but it remained silent. For a moment, Kaya hung suspended from her impromptu handholds.
#emph[Now what?] #emph[] #emph[] The gargoyle started closing its beak. It didn’t have the best leverage, but the edges of its beak were razor sharp, and the upper and lower tip dug into Kaya’s arm, cutting through the leather and drawing blood. She gritted her teeth and set her legs against the tower again.
"You know," she told the gargoyle, "I’m willing to live and let live here. Any interest?"
It glared at her malevolently and upped the pressure. Much more, and her arm would snap.
"Fair enough," Kaya muttered.
She let go of the brazier and let her arm phase back outside, leaving her hanging from her grip on the gargoyle. That set her swinging sideways toward it, and she pushed off with her legs to turn the motion into an arc, like a circus acrobat spinning around a trapeze only infinitely more painful. As she neared the end of her swing, she pulled one of the long knives on her hips with her free hand, and used all her momentum to jam it home into the gargoyle’s neck, with a little touch of her power ensuring it slid easily through the creature’s stony hide. The gargoyle gave a strangled squawk and toppled forward, losing its grip on the wall. Kaya let her hand phase through it, then pushed herself up in a standing jump that took her all the way through the outer wall and back inside the tower.
All in all, she felt she’d earned a few moments writhing on the carpet, silently cursing all gargoyles as she clutched the torn skin of her forearm and tried hard not scream. When the pain had subsided a little, she wiggled her fingers just to make sure she still could, extracted a bandage from her pack, and bound the wound.
#emph[I hope the damn thing didn’t land on anyone. ] A random splattered passerby wasn’t what she needed on her conscience.
This level, thankfully, was as empty as the previous. Another switchback stair led upward, with no obvious protections. Kaya took it, cautiously, and found that it led to a very solid-looking door. More runic warding, in fine golden script, was inscribed around the edges. She leaned close to read.
#emph[Pass through the door, summon a dread spirit of vengeance, blah blah blah. ] She flexed her injured hand again, checked her knives, and took a breath. #emph[Here goes.] #emph[] #emph[] Purple flared around her as she passed through the door. She got a brief impression of a large, well-appointed sitting room beyond, but her view was almost immediately obscured by a maelstrom of ghostly energy that coalesced in front of her. A humanoid figure, like a translucent, emaciated corpse, formed out of nothing, red sparks of hate blooming in wide, empty eye sockets. It reached for her throat, and she felt the chill of the grave washing over her.
The thing looked #emph[very] surprised when Kaya’s daggers, glowing with the purple of her incorporeality, slammed into its chest. Ghosts and spirits invariably were shocked to learn that the phasing which made Kaya pass freely through physical world also made her very solid indeed to their kind. Typically, though, they didn’t live—#emph[or continue to exist, or whatever] —long enough to spread the lesson around, since they usually had few defenses against a foot of cold steel in their ghostly hearts.
This one screamed, thinned, and vanished into the thin air from whence it had come. Kaya sheathed her blades with a satisfied smirk. Looking around the room, she found a dark-haired woman standing behind a long wooden table, leaning on a cane, with a bespectacled young man beside her with the air of a clerk.
"<NAME>?" Kaya said, and got a cautious nod. "I’m here to rescue you."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#linebreak A few minutes later, Kaya was sitting at the big, polished table, redoing the bandage on her arm a little more carefully. Teysa and the young man, whose name turned out to be Tomik, sat across from her.
"Let me see if I’ve got this straight," Teysa said, steepling her fingers. Even with her hair mussed from sleeping and wearing only a black silk nightgown, she retained her poise. "You’re on a contract from"—she glanced significantly at Tomik—"our mutual friend."
"Mhmm," Kaya said, wincing as she peeled away blood-crusted cloth.
"Your contract is . . ."
"To help you take control of the Orzhov." Kaya looked up. "I figured getting you out of a cell would be a good start."
"How much do you know about the Orzhov?"
"Almost nothing," Kaya said cheerfully. "Our #emph[friend] said you were locked up by a bunch of ghosts, which I figure is why he came to me in particular."
"Did you have a plan for what happens next?"
"Not really. I figured that was your department, though I’ll certainly take care of your ghost problem for you."
Tomik shook his head, as though he were still half-asleep. Teysa wore a tight expression, and her fingers interlaced.
"It’s not just a ‘ghost problem’," she said. "The #emph[Obzedat] are the spirits of the most powerful of the Orzhov, who have ruled our guild for millennia."
"And you want to get rid of them."
"Yes," Teysa admitted. "But it’s not going to be that easy."
"No?" Kaya tied off the bandage and smiled. "You’ve seen me work."
"It’s not your ability I doubt, it’s the rest of the plan." Teysa sighed. "If you break me out of here #emph[before] you assassinate the Ghost Council, everyone will assume I was involved. The powers of the guild will rally to the enemies of the Karlovs. We’d have a costly civil war on our hands, and no guarantee we’d win."
"Assuming," Tomik added, "the other guilds didn’t take advantage of our weakness."
Kaya looked at the clerk and raised an eyebrow. Teysa pursed her lips.
"Tomik is my personal secretary," she said. "I trust him implicitly."
#emph[Except you don’t want him to know you’re working with Bolas] , Kaya thought. #emph[Interesting. ] She sat back in her chair, hands behind her head.
"Okay," Kaya said. "So you #emph[don’t] want me to break you out of here?"
"It wouldn’t achieve what we want," Teysa said. "Grandfather locked me up—"
"Who?"
"Grandfather," Teysa repeated irritably. "He’s the head of the Ghost Council now."
Kaya, whose family relationships could be best described as "complicated," tried to imagine what it would be like if clan elders persisted indefinitely into undeath. #emph[The mind rebels. ] "All right. Go on."
"He locked me up because I wanted to take the Orzhov in a different direction." Teysa glanced at Tomik. "Less isolation, and more engagement with the other guilds. There are those in the hierarchy who support me, which is why he was afraid of admitting me to the council. But if I ally myself with outside forces, those allies will abandon me."
"So what then?"
"You have to destroy the Obzedat without the appearance of my help. With Grandfather gone, the hierarchs will have no choice but to turn to me."
"<NAME>," Tomik said. "You know how dangerous that is. If she were to fail, and admit the plan to your grandfather—"
"Have a little faith in me," Kaya said.
"It’s a valid point," Teysa said. "If you #emph[were] caught, Grandfather would have your living spirit ripped from your body, and then his necromancers would get whatever answers he wanted before condemning you to utter oblivion."
"Let’s not kill me off #emph[just] yet." Kaya scratched her nose thoughtfully. "The ghosts meet in the basement, right?"
Tomik nodded. "In the Catacomb, several floors below the base of the cathedral. No one living has been down there for centuries."
"And I’m sure it’s full of death traps and bound spirits. These places usually are." She pulled a face. "I have to admit, I don’t relish the prospect of trying to cut through all that with every guard in the tower on my ass. I got a look at the wards on my way in, and I’m not going to be able to get in there without sounding the alarm."
"We need allies," Teysa said. She glanced at Tomik speculatively, but before she could say anything more there was the sound of booted feet and jingling metal from the hallway.
"Ah, hell," Kaya said, jumping up. "Someone must have noticed what happened to your doorkeeper."
"Go," Teysa said urgently. "I’ll tell them it was an attempt to kill me, they’ll believe that. Find the Twisted Stem Inn, Tomik will get a message to you there."
"This job is getting more complicated by the minute," Kaya muttered. But she had to admit it sounded like the best option at present. #emph[Certainly better than fighting a tower full of guards. ] She nodded curtly to the pair of them and hurried to the window.
"You can’t get out that way!" Teysa said. "The windows are—"
Kaya phased through, in a burst of purple light, and was gone.
"—sealed," she finished, thoughtfully. The door banged open, and she turned to face the guards, putting on her best smile.
|
|
https://github.com/daskol/mpl-typst | https://raw.githubusercontent.com/daskol/mpl-typst/main/gallery/main.typ | typst | MIT License | /**
* main.typ
*
* This is an example paper which demonstrates how to use typ-files rendered
* with custom `matplotlib` backend based on Typst.
*/
#set document(title: [#smallcaps[Typst] #smallcaps[Matplotlib] Backend Demo])
#set page(
paper: "a4",
margin: (left: 0.75in, right: 8.5in - (0.75in + 6.75in), top: 1.0in),
)
#set par(justify: true, leading: 0.58em)
#set text(font: "Times", size: 10pt)
#show: it => columns(2, gutter: 0.25in, it)
#lorem(50)
#lorem(50)
#lorem(50)
#lorem(50)
#lorem(50)
#lorem(50)
#lorem(50)
// NOTE The point is to include typ-file and adjust figure kind
// correspondently.
#figure(
include "line-plot-simple.typ",
kind: image,
caption: [Simple line plot],
placement: top,
) <line-plot-simple>
#lorem(50)
#lorem(50)
|
https://github.com/Functional-Bus-Description-Language/Specification | https://raw.githubusercontent.com/Functional-Bus-Description-Language/Specification/master/src/functionalities/mask.typ | typst | == Mask
The mask functionality represents a bit mask.
The mask is data that is automatically read by the provider from its registers.
By default, a mask can be written and read by the requester. The mask is very similar to the config.
The difference is that the config is value-oriented, whereas the mask is bit-oriented.
From the provider’s perspective the mask and the config are the same.
From the requester’s perspective the code generated for interacting with the mask and the config is different.
The mask functionality has following properties:
*`atomic`*` bool (true) {definitive}`
#pad(left: 1em)[
The atomic property defines whether an access to the mask must be atomic.
If atomic is true, then the provider must guarantee that any change of the mask value, triggered by the requester write, is seen as an atomic change by the other modules of the provider.
This is especially important when the mask spans more than single register, as in case of single register write the change is always atomic.
]
*`init-value`*` bit string (uninitialized) {definitive}`
#pad(left: 1em)[
The init-value property defines the initial value of the mask.
]
*`read-value`*` bit string (None) {definitive}`
#pad(left: 1em)[
The read-value property defines the value returned by the provider on the mask read.
If the read-value is not set, then the provider must return the actual value of the mask.
]
*`reset-value`*` bit string (None) {definitive}`
#pad(left: 1em)[
The reset-value property defines the value of the mask after the reset.
If the reset-value is set, but a bus or block containing the mask is not resettable (`reset = None`), then the compiler shall report an error.
]
*`width`*` integer (bus width) {definitive}`
#pad(left: 1em)[
The width property defines the bit width of the mask.
]
The code generated for the requester must provide means for setting, clearing and updating particular bits of the mask.
The updating includes setting, clearing and toggling.
The set differs from the update set.
The set sets particular bits and simultaneously clears all remaining bits.
The update set sets particular bits and keeps the value of the remaining bits.
The clear differs from the update clear in an analogous way.
The toggle always works on provided bits leaving the remaining bits untouched.
|
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/互联网原理与技术/作业/理论6.typ | typst | The Unlicense | #import "../../template.typ": *
#import "@preview/tablem:0.1.0": tablem
#show: project.with(
title: "理论 6",
authors: (
"absolutex",
)
)
// P3、P5、 P14、P15、 P21、P31
= 理论作业6
== P3 假设某分组的信息部分(图6.3中的D)包含10字节,它由字符 “Internet” 的8比特无符号二进制ASCII表示组成。对该数据计算因特网检验和。
```python
#! /usr/bin/env python3
s = sum(map(ord, "Internet")) # =841
s = int(s / (1 << 8)) + s % (1 << 8) # 进位 =76, 01001100
s = ~s # 补码 =-77, 10110100
```
`checksum = 10110100`
== P5 考虑5比特生成多项式,G=10011,并且假设D的值为101010101010。R的值是什么?
```python
#! /usr/bin/env python3
G=0b10011
D=0b101010101010
r=5
(D << r )% G
# = 17
```
== P14.如图6-33所示,考虑通过两台路由器互联的3个局域网。
=== a.对所有的接口分配IP地址。对子网1使用形式为192.168.1.xxx的地址,对子网2使用形式为192.168.2.xxx 的地址,对子网3使用形式为192.168.3.xxx的地址。
#tablem[
|主机|ip|
|---|---|
|A|192.168.1.2|
|B|192.168.1.3|
|C|192.168.2.2|
|D|192.168.2.3|
|E|192.168.3.2|
|F|192.168.3.3|
|左路由左侧接口|192.168.1.1|
|左路由右侧接口|192.168.2.1|
|右路由左侧接口|192.168.2.4|
|右路由右侧接口|192.168.3.1|
]
#linebreak()
=== b.为所有的适配器分配 MAC 地址。
由于所有设备的MAC均不同且没有限制,因此直接使用
*`MAC-A`...`MAC-F`, MAC-R1-左,MAC-R1-右,MAC-R2-左,MAC-R2-右*
来指代适配器 MAC 地址。
=== c.考虑从主机E向主机B发送一个IP数据报。假设所有的ARP 表都是最新的。就像在6.4.1节中对单路由器例子所做的那样,列举出所有步骤。
1. 主机E发送IP数据报,其中MAC地址指示了 MAC-R2-右。
2. 路由器R2收到IP数据报,查表发现子网地址在子网1内,需要通过接口 MAC-R1-右。
3. 路由器R2将IP数据报发给R1(MAC-R1-左)。
4. R1收到IP数据报,查表查到了 MAC-B,通过接口 MAC-R1-左 发出。
=== d.重复(c),现在假设在发送主机中的ARP 表为空(并且其他表都是最新的)。
1. 主机E发送IP数据报,其中MAC地址指示了 MAC-R2-右。
2. 路由器R2收到IP数据报,没发现MAC-B地址,因此广播ARP请求。
3. R1 收到ARP请求,发现自己有MAC-B,于是回应请求。
3. 路由器R2收到回应,将MAC-R1-右写入ARP表,并交出数据报。
4. R1收到IP数据报,查表查到了 MAC-B,通过接口 MAC-R1-左 发出。
== P15 考虑图6-33。现在我们用一台交换机S1代替子网1和子网2之间的路由器,并且将子网2和子网3之间的路由器标记为R1。
=== a.考虑从主机E向主机F发送一个IP 数据报。
+ 主机E将请求路由器R1帮助转发该数据报吗?为什么?
不用。因为在一个子网中。
+ 在包含 IP数据报的以太网帧中,源和目的IP和MAC地址分别是什么?
- 源IP:192.168.3.2
- 目的IP:192.168.3.3
- 源MAC:MAC-E
- 目的MAC:MAC-F
=== b.假定E希望向B发送一个 IP 数据报,假设E的ARP缓存中不包含B的MAC地址。
+ E将执行ARP 查询来发现B的MAC 地址吗?为什么?
会。因为不在同一子网且ARP缓存中没有B的MAC地址。
+ 在交付给路由器R1的以太网帧(包含发向B的IP数据报)中,源和目的IP和MAC地址分别是什么?
- 源IP:192.168.3.2
- 目的IP:192.168.1.3
- 源MAC:MAC-E
- 目的MAC:MAC-R2-右
=== c.假定主机A希望向主机B发送一个IP数据报,A的ARP缓存不包含B的MAC地址,B的ARP缓存也不包含A的MAC地址。进一步假定交换机S1的转发表仅包含主机B 和路由器R1的表项。因此,A将广播一个ARP请求报文。
+ 一旦交换机S1收到ARP请求报文将执行什么操作?
- 在表中存储主机A的MAC地址、该帧到达的接口
+ 路由器R1也会收到这个ARP 请求报文吗?
- 不会。因为交换机S1已经存储了主机A的MAC地址。
+ 如果收到的话,R1将向子网3转发该报文吗?
+ 一旦主机B收到这个ARP请求报文,它将向主机A回发一个ARP响应报文。但是它将发送一个ARP查询报文来请求A的MAC地址吗?为什么?
+ 一旦交换机S1收到来自主机B的一个ARP 响应报文,它将做什么?
== P21 现在考虑习题P14中的图6-33。对主机A、两台路由器和主机F的各个接口提供MAC地址和IP地址。假定主机A向主机F发送一个数据报。当在下列场合传输该帧时,给出在封装该IP数据报的帧中的源和目的MAC 地址:
=== (i)从A到左边的路由器;
src: 192.168.1.2, MAC-A
dst: 192.168.1.1, MAC-R1-左
=== (ii)从左边的路由器到右边的路由器;
src: 192.168.2.1, MAC-R1-右
dst: 192.168.2.4, MAC-R2-左
=== (iii)从右边的路由器到F。还要给出到达每个点时封装在该顿中的IP数据报中的源和目的IP地址。
src: 192.168.3.1, MAC-R2-右
dst: 192.168.3.3, MAC-F
== P31.在这个习题中,你将把已经学习过的因特网协议的许多东西拼装在一起。假设你走进房间,与以太网连接,并下载一个Web页面。从打开PC电源到得到Weeb网页,发生的所有协议步骤是什么?假设当你给PC加电时,在DNS 或浏览器缓存中什么也没有。(提示:步骤包括使用以太网、DHCP、ARP、 DNS、 TCP 利 HTTP 协议。)明确指出在这些步骤中你如何获得网关路由器的IP和MAC地址。
1. 打开PC电源时,网卡初始化并通过DHCP协议,PC向网络中的DHCP服务器请求IP地址、子网掩码、网关和DNS服务器的信息。
2. 获得本地IP地址后,PC需要确定网关路由器的MAC地址,以便正确发送数据帧。PC通过ARP协议广播请求,询问局域网中与网关IP地址相对应的MAC地址。
3. 网关路由器收到ARP请求后,会回复包含自己MAC地址的ARP响应。PC收到ARP响应后,获得了网关路由器的MAC地址。
4. PC通过DHCP获取了DNS服务器的IP地址,并使用DNS协议向DNS服务器查询目标Web页面的域名对应的IP地址。
5. 建立TCP连接:使用目标Web服务器的IP地址,PC通过TCP协议与Web服务器建立可靠的双向通信通道。
6. HTTP请求:通过TCP连接,PC向Web服务器发送HTTP请求,请求特定页面。
7. Web服务器接收到HTTP请求后,处理请求并准备发送相应的Web页面。
8. Web服务器通过TCP连接向PC发送HTTP响应,其中包含请求的Web页面的数据。
9. PC接收到Web服务器的HTTP响应后,浏览器解析响应,渲染并显示Web页面。
|
https://github.com/rabotaem-incorporated/algebra-conspect-1course | https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/03-polynomials/05-euclidian-rings.typ | typst | Other | #import "../../utils/core.typ": *
== Евклидовы области
#def[
_Евклидовой областью целостности_ (_евклидовой областью_, _евклидовым кольцом_) называется область целостности $R$,
для которой существует функция $nu: R without \{0\} -> ZZ_(>= 0)$, называемая _евклидовой нормой_, такая что:
+ Если $d divides a$, то $nu(d) <= nu(a)$, причем $nu(d) = nu(a) <==> d sim a$.
+ Для любых $a, b in R, space b eq.not 0$: существует представление $a = b q + r$, где $r = 0$ или $nu(r) < nu(b)$.
_Замечание_: свойство один можно убрать, но доказательства будут сложнее.
]
#examples[
+ $R = K[x]$, ($K$ --- поле), где $nu(P) = deg P$
+ $R = ZZ$, где $nu(a) = abs(a)$
+ $R = ZZ[i] = \{ a + b i divides a,b in ZZ \}$, где $nu(a + b i) = a^2 + b^2$
(подробнее в книжке Аейрленд, Роузен - "Классическое введение в современную теорию чисел")
+ #[
$R = K[[x]]$, ($K$ --- поле)
$R^* = \{ a_0 + a_1 x + a_2 x + ... divides a_0 eq.not 0 \}$
$ord f = min \{ j divides a_j eq.not 0 \}$
$f = x^(ord f) dot (a_j + a_(j + 1)x + ...) sim x^(ord f)$
Докажите, что это евклидова область.
]
+ #[
$R = ZZ_((5)) = \{ (a)/(b) divides a, b in ZZ, space 5 divides.not b \}$
Докажите, что это евклидова область.
]
]
#lemma[
Пусть $R$ --- область целостности, $a, b in R$. Тогда $a sim b <==> a = epsilon b, space epsilon in R^*$
]
#proof[
"$arrow.l.double$":
Пусть $a = epsilon b ==> b$. Так как $epsilon$ --- обратим, $b = epsilon^(-1) a$.
$
cases(
a = epsilon b ==> a divides b,
b = epsilon^(-1) a ==> b divides a
) <==> a sim b
$
"$arrow.r.double$":
$
a sim b ==> display(cases(
a divides b,
b divides a
)) ==> display(cases(
b = epsilon a,
a = epsilon' b
)) ==> b = epsilon epsilon' b ==> (epsilon epsilon' - 1) b = 0 ==> epsilon #[--- обратим].
$
]
#def[
$R$ --- коммутативное кольцо, $I subset R$ называется _идеалом_ в $R$, если:
+ $I eq.not empty$
+ $forall a, b in I: a + b in I$
+ $forall a in I space forall b in R: a b in I$
]
#examples[
+ $R = ZZ, space I = 2ZZ$
+ $R = K[X], space I = \{ f in R divides f(0) = 0 \}$
+ $R = C[0, 1]$\ (непрерывные функции на отрезке [0, 1]), $ space I = \{ f in R divides f(0) = 0 \}$
]
#def[
Пусть $R$ --- коммутативное кольцо, $r in R$.
Из свойств кольца очевидно, что $angle.l r angle.r harpoons.rtlb (r) harpoons.rtlb \{ r s divides s in R \}$ --- идеал в $R$.
Тогда $(r)$ называется _главным идеалом_ порожденным элементом $r$.
]
#notice[
$(r) = (r') <==> r sim r'$
]
#example[
Пример неглавного идеала:
$
R = ZZ[X], space I = \{ f : 2 divides f(0) \}
$
Это множество всех многочленов, у которых свободный член четный.
]
#pr[
В евклидовой области все идеалы главные.
]
#proof[
Пусть $I$ --- идеал в евклидовой области $R$.
Случай $I = \{0\}$ --- тривиален, тогда $I = (0)$. Пусть $I eq.not \{0\}$.
Зафиксируем норму $nu$ и рассмотрим $c in I$ с минимальной нормой. Докажем, что $I = (c)$.
"$supset$":
Так как для любого $b in R$ должно быть выполнено $c b in I$, то $I supset (c)$.
"$subset$":
Предположим, $exists a in I without (c)$. Представим евклидову норму в виде $a = c q + r$, $q, r in R$.
Если $r = 0$, то $a in (c)$ по определению главного идеала. Но иначе $nu(r) < nu(c)$.
Выразим $r$:
$
r = a - c q = a + c(-q).
$
Так как $c in I$ и $a in I$, то и $c(-q) in I$, следовательно $r in I$.
Но $nu(r) < nu(c)$, что противоречит минимальности нормы $nu(c)$
]
#def[
Область целостности, в которых все идеалы главные, называется _областью главных идеалов (ОГИ)_.
]
#pr[
Пусть $R$ --- область главных идеалов. Тогда:
+ $a, b in R ==>$ у $a$ и $b$ существует наибольший общий делитель
+ Если $d$ --- наибольший общий делитель $a$ и $b$, то $d = a m + b n, space m, n in R$
]
#proof[
Можно считать $a eq.not 0$ или $b eq.not 0$, если $a = b = 0$, то $d = 0$ подходит, $d eq.not 0$ не подходит.
+ #[
Рассмотрим множество $I = \{ a m + b n divides m, n in R \}$ --- идеал в $R$. Тогда можно записать $I = (d)$, так как $I$ --- область главных идеалов.
Заметим, что $d$ --- общий делитель $a$ и $b$.
$
display(cases(
a = a dot 1 + b dot 0 in I = (d),
b = a dot 0 + b dot 1 in I = (d)
)) ==> display(cases(
d divides a,
d divides b
))
$
Покажем, что $d$ --- наибольший общий делитель $a$ и $b$.
То есть, что
$
display(cases(
d' divides a,
d' divides b
)) limits(==>)^((!)) d' divides d
$
Так как $d in I$, $d = a m_0 + b n_0, space m_0, n_0 in R$.
$
display(cases(
d' divides a,
d' divides b
)) ==> display(cases(
d' divides a m_0,
d' divides b n_0
)) ==> d' divides d.
$
Что и требовалось доказать.
]
+ #[
Если $d'$ --- наибольший общий делитель $a$ и $b$, то:
$
d' sim d in I ==> d' in I ==> d' = a m + b n, space m, n in R.
$
]
]
#notice[
Наибольший общий делитель в ОГИ обозначают $(a, b)$.
]
#def[
Элементы ОГИ $a$ и $b$ называют _взаимно простыми_, если $(a, b) = 1$.
]
#pr[
$(a, b) = 1 <==> m, n in R: a m + b n = 1$
]
#proof[
"$arrow.r.double$": Из предыдущего предложения
"$arrow.l.double$": $exists m,n in R: a m + b n = 1$
Пусть $d = (a, b) ==> d divides a, d divides b ==> d divides (a m + b n) ==> d divides 1 ==> d sim 1 ==> (a, b) = 1$
]
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/root_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test large bodies
$ sqrt([|x|]^2 + [|y|]^2) < [|z|] $
$ v = sqrt((1/2) / (4/5))
= root(3, (1/2/3) / (4/5/6))
= root(4, ((1/2) / (3/4)) / ((1/2) / (3/4))) $
|
https://github.com/HiiGHoVuTi/requin | https://raw.githubusercontent.com/HiiGHoVuTi/requin/main/lang/inclusions.typ | typst | #import "../lib.typ": *
#show heading: heading_fct
Soit $Sigma$ un alphabet. Pour $w in Sigma^*$ un mot et $alpha in Sigma$ une lettre, on note $|w|_alpha$ le nombre d’occurrence de $alpha$ dans $w$. Pour $L$ un langage sur $Sigma$, on pose $sigma(L) = {w in Sigma^* | exists u in L, forall alpha in Sigma, |u|_alpha = |w|_alpha}$ la _permutation_ de $L$.
On dira que $L$ est strictement hors-contexte si $L$ est hors-contexte et n'est pas régulier.
#question(2)[Montrer que $L_1 = {a^n b^n : n in NN}$ n'est pas régulier mais qu'il est hors-contexte. Que vaux $sigma(L_1)$ ?]
#question(2)[Donner un langage $L$ tel que $L$ soit strictement hors contexte mais $sigma(L)$ régulier.]
#question(2)[Donner un langage $L'$ tel que $L'$ soit régulier mais $sigma(L')$ strictement hors-contexte.]
#question(3)[Montrer que si $L$ est tel que $L_1 subset.eq L subset.eq sigma(L_1)$, alors $L$ n'est pas régulier.]
#question(3)[Est-ce qu'il existe $L'$ un langage strictement hors-contexte tel que $sigma(L')$ est strictement hors-contexte et tel qu'il existe $L$ régulier tel que $L' subset.eq L subset.eq sigma(L')$ ?]
|
|
https://github.com/Chwiggy/thesis_bachelor | https://raw.githubusercontent.com/Chwiggy/thesis_bachelor/main/src/chapters/01_introduction.typ | typst | #import "../preamble.typ": *
= Introduction
In recent years, but for decades by now, the demand for a paradigm shift in transportation infrastructure and service has become louder and louder.
While calls for a shift away from car centric mobility are nothing new and were a well established part of German academic discourse in the 1990s already @frank_hat_1993, it has become part of a widespread political discourse around the so called _Verkehrswende_ @holzapfel_urbanismus_2020.
With increased awareness and concrete experiences of climate change this discourse has reached states of heated debate.
Taunted benefits of a modal shift away from individual motorised transit towards public transit include a more efficient transport system both in terms of traffic throughput as well as in terms of energy usage, decreased local pollution @teufel_autoverkehr_1993, and a lessened dependency on cars favouring more healthy modes of transit and more livable environments for humans @rissel_physical_2012 @stevenson_health_2016 @holzapfel_urbanismus_2020.
However appealing these pleas for an improved mobility regime may be, there is a distinct lack of easily accessible tools to measure how well a public transit system is serving its users, and the people who for some reason or another have decided that they will not use it.
Public Transit Data beyond planned schedules is often hard to come by, and the often quite complex thoughts and models that go into service planning remain behind the closed doors of local transit agencies in a lot of cases @pieper_kreislauf_2021 @karner_assessing_2018.
One option of addressing this gap is the use of reach data over larger areas to assess the coverage public transit provides for reaching different points of interest hopefully relevant to daily life of potential users e.g. @verduzco_torres_public_2024.
These studies are based in schedule data and as in this example several assumptions about public transit usage.
One of these assumptions is usually a time of day for travel time calculations, usually something like morning rush hour on an average workday @verduzco_torres_public_2024.
This however ignores the changing nature of transit accessibility over the course of the day.
As general traffic volumes change over the course of the day, so do public transit schedules and quite dramatically at that @levinson_towards_2020.
Unlike with car traffic, it is not uncommon to see public transport schedules with considerable gaps: be they a few hours at night in which there is basically no service, or in some instances even entire days like Sundays that see no service at all, or very reduced service patterns.
This temporal variability in transit accessibility is so far not generally addressed well in the literature and in available data sets @verduzco_torres_public_2024.
There is, of course, also a smaller kind of temporal variation.
With schedule based transit the exact departure time can have distinct consequences on actual travel times.
Any hour of the day travel times from a specific location may look very different: Arriving at a stop at 10:34 you might exactly make the bus out of your village, but at 10:35 you might have missed it and would need to wait for the next bus in what might be anything from a few minutes to hours @levinson_towards_2020.
This variation necessitates more or less planning effort on the side of public transport users depending on their departure location, destination, and again the time of day as transit schedules change over the course of the day.
With these two temporal variations in mind, this thesis will try to establish indicators to visualise and illuminate transit accessibility issues and their temporal dimension with the example of Heidelberg, Germany as a playing ground.
== Motivation
There are a plenty of indicators already out there trying to capture the characteristics of transit networks.
This spans from network centrality measures applied in almost simplistic network models to thorough analyses of various aspects of transit access @tu_centrality_2013 @liu_spatial_2020 @conway_evidencetransit @karner_assessing_2018.
Within transit there is hardly such a thing as a neutral descriptive dataset, indicator or study.
Baked in are almost always assumptions and political ideas on how our transit system should look, assumptions about the costs of transit to society and the individual, and last but not least assumptions about the need for mobility and the kind of destinations deemed worthwhile to reach.
All of these assumptions of course are inherently also linked to larger societal ideas of how our lives should be structured and lived.
None of these assumptions are inevitable or ever lasting and should be aknowledged then as at least in part tainted by normative ideas about how transit should work and about how transit should be used.
And not least, this means, that this thesis won't be free of these implicit or explicit value judgements either.
Transit is an inherently political topic.
As an exteriority to daily life, transport systems are hard to influence by an individual according to their own needs.
With the strong link between transportation and the necessary built infrastructure, transit systems within their geographic location have a strong amount of inertia @holzapfel_urbanismus_2020.
Historical decisions about the transport network therefor still have an outsized influence on the transit opportunities of modern people.
And since these decisions underlie the general rules for societal decision making processes, they also mirror general social power structures.
Historically then transport planning also was a domain built for men by men.
The daily itineraries of women however tend to be much less focused on the singular destinations of a commute, but tend to move through space more freely based on the needs of other people in need of care work @heier_alle_2024 @holzapfel_urbanismus_2020.
In German transport planning around the middle of the last century this has resulted in a tendency to make cities favourable to the usage of cars as transportation from A to B in terms of a regular commute @heier_alle_2024.
But not only in Germany was this idea of how transit and cities should work en vogue. Functional cities, as in cities characterised by a separation of functions like living, work and relaxation, became the modern ideaal of a city. This trend not least helped by the publishing of the highly influential Athens Charta, however again centers the needs of men on their daily commutes @holzapfel_urbanismus_2020.
This way of looking at urban environments coupled with ideas of unlimited growth had far reaching ramifications then for the lived environment we still move in today. Urban and transit planning of course has undergone several trends in various distances to the ideals laid out in the Athens Charta since then. Among these changes, participation has gained a lot of importance in planning processes. However, from my own experience, participation is often easier used as buzzword than done. It takes deliberate and long processes to gain meaningful insights from these processes @heier_alle_2024 @amt_fur_stadtentwicklung_und_statistik_heidelberg_integriertes_2023.
Capturing all these various aspects of a transit network and all the needs of various users at once however runs the danger of reducing all these complexities to the absurd.
Transit planning and identifying demand in public transit networks then is a complicated process, that takes into account a plethora of data that's hard to access or acquire @pieper_kreislauf_2021. And often to this day neglects the needs of some populations, often based on paternalistic assumptions @heier_alle_2024. To this day a lot of research and planning have focused on the commute as the itinerary of interest @owen_modeling_2015. In part this may be due to the easy nature of these itineraries. Measuring transit demand otherwise takes the careful building of model itineraries that capture the different lived realities of all kinds of people @conway_evidencetransit.
This almost precludes the idea of an easy spatial measure of transit access based on individual experiences. However, with an idea focused on opportunities for social connection and social services, which generally tend to be spread more evenly across cities, and a focus on a singular urban space, it might be possible to characterise the nature of a transit system and its capacity to move people without an intense focus on individual points of interest. To this end, I employed statistical routing data based on conveyal engine @conway_evidencetransit.
== Research Questions <hypo>
Guiding this research, are a few research questions then, that I tried to answer with two indices one for average travel times and one trying to capture the need to plan journeys out before starting on an itinerary. For each research question there are a handful of hypotheses to test. Ideally this thesis can falsify some of these hypotheses.
First of all, I will focus on the spatial pattern of mean travel times, to answer the question if the proposed indices can capture observable patterns in the traffic flow of the city. There are two hypothesis associated with this question:
+ Mean Travel Times cannot capture transit service patterns at a given point in time
+ Outlying areas have generally worse accessibility across all times of the day than geographically central locations. For Heidelberg this would mean that Hauptbahnhof and Bismarckplatz always have a lower mean travel time than areas farther out.
Second, focussing on the travel planning indicator, I will try to answer if the planning indicator can be a useful measure of transit service in a given area.
#set enum(start: 3)
+ The planning indicator aligns with accissibility indicator, as in the most central parts of the city will also have the least need to plan journeys
+ The planning indicator will preserve it's characteristics across the course of a day. Areas that neccessitate a lot of journey planning will allways neccessitate a lot of planning.
<end_of_chapter>
#locate(loc => bib_state.at(query(<end_of_chapter>, loc).first().location())) |
|
https://github.com/An-314/Notes_of_Electrodynamics | https://raw.githubusercontent.com/An-314/Notes_of_Electrodynamics/master/chap5.typ | typst | #import"@preview/physica:0.9.2":*
#import "template.typ": *
= 静电学中的边值问题:圆边界 Boundary-Value Problems in Electrostatics
== Laplace Equation in Spherical Coordinates 球坐标系下的Laplace方程
=== Laplace Equation in Spherical Coordinates
$
laplacian Phi = 1/r pdv(,r,2)(r Phi) + 1/(r^2 sin theta) pdv(,theta)(sin theta pdv(Phi,theta)) + 1/(r^2 sin^2 theta) pdv(Phi,phi,2)= 0
$
分离变量
$
Phi(R,theta,phi) = U(r)/r P(theta) Q(phi)
$
代入方程得到
$
P Q dv(U,r,2) + (U Q)/(r^2 sin theta) dv(,theta)(sin theta dv(P,theta)) + (U P)/(r^2 sin^2 theta) dv(Q,phi,2) = 0
$
即
$
r^2 sin^2 theta (1/U dv(U,r,2) + 1/(P r^2 sin theta) dv(,theta)(sin theta dv(P,theta))) + 1/(Q) dv(Q,phi,2) = 0
$
有
$
1/(Q) dv(Q,phi,2) = -m^2 => Q = e^(plus.minus i m phi),m in ZZ
$
以及
$
(P r^2)/U dv(U,r,2) + 1/(sin theta) dv(,theta)(sin theta dv(P,theta)) = (m^2 P)/(sin^2 theta)
$
分离,得到
$
1/(sin theta) dv(,theta)(sin theta dv(P,theta)) + (l(l+1) - (m^2)/(sin^2 theta))P = 0\
dv(U,r,2) - (l(l+1) U)/(r^2) = 0 => U = A r^(l+1) + B r^(-l)
$
== Legendre Equation and Legendre Polynomials Legendre方程和Legendre多项式
=== Generalized Legendre Equation 连带 Legendre 方程
$
1/(sin theta) dv(,theta)(sin theta dv(P,theta)) + (l(l+1) - (m^2)/(sin^2 theta))P = 0
$
令
$
x = cos theta, -1<= x <= 1
$
则
$
dv(,x)((1-x^2) dv(P,x)) + (l(l+1) - m^2/(1-x^2))P = 0
$
是Generalized Legendre equation 连带 Legendre 方程,其解为连带 Legendre 函数。
=== Ordinary Legendre Equation 普通 Legendre 方程
连带 Legendre 方程中 $m=0$即为普通 Legendre 方程,其解为普通 Legendre 函数。
$
dv(,x)((1-x^2) dv(P,x)) + l(l+1)P = 0
$
=== Legendre Polynomials
$
P(x) = x^alpha sum_(j = 0)^oo a_j x^j
$
代入化简得到
$
sum_(j = 0)^oo (alpha + j)(alpha + j - 1) a_j x^(alpha + j - 2) - sum_(j = 0)^oo ((alpha+j)(alpha+j-1) - l(l+1)) a_j x^(alpha+j) = 0
$
可以得到
$
a_(j+2) = ((alpha + j)(alpha + j + 1) - l(l+1))/((alpha + j + 1)(alpha + j + 2)) a_j
$
#figure(
image("pic/2024-10-18-11-38-51.png", width: 80%),
numbering: none,
)
=== Termination of the Series 级数截断
- 当$x^2<1$时,无论$l$的值是多少,级数都会收敛
- 数列在$x=±1$处发散,除非截断
考虑到$α$和$j$为正整数或零,如果$l$为零或正整数,递推关系将终止:
$
a_(j+2) = ((alpha + j)(alpha + j + 1) - l(l+1))/((alpha + j + 1)(alpha + j + 2)) a_j
$
对$a_0!=0,a_1=0$有
$
a_(j+2) = cases(
(j(j+1) - l(l+1))/((j+1)(j+2)) a_j & alpha=0 & P(x) = a_0 + a_2 x^2 + a_4 x^4 + ...,
((j+1)(j+2) - l(l+1))/((j+2)(j+3)) a_j & alpha=1 & P(x) = a_0 x + a_2 x^3 + a_4 x^5 + ...,
)
$
$alpha=0$使得$l$在奇数处截断,$alpha=1$使得$l$在偶数处截断。
=== First few Legendre polynomials
$
P_0 (x) &= 1\
P_1 (x) &= x\
P_2 (x) &= (3x^2 - 1)/2\
P_3 (x) &= (5x^3 - 3x)/2\
P_4 (x) &= (35x^4 - 30x^2 + 3)/8\
P_5 (x) &= (63x^5 - 70x^3 + 15x)/8\
$
有性质
$
P_l (-x) = (-1)^l P_l (x)
$
*Rodrigues' formula*
$
P_l (x) = 1/(2^l l!) dv(,x,l) (x^2 - 1)^l
$
=== Complete Orthogonal
Legendre 多项式是 $[-1,1]$上的完备正交函数系,即
$
integral_(-1)^1 P_l (x) P_k (x) dd(x) = 2/(2l + 1) delta_(l k)
$
#figure(
image("pic/2024-10-18-11-55-04.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-10-18-11-57-07.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-10-18-11-57-23.png", width: 80%),
numbering: none,
)
Any function $f(x)$ on the interval $[-1,1]$ can be expanded in terms of the Legendre polynomials.
=== Recurrence relations(递归关系) among Legendre polynomials
$
dv(P_(l+1),x)- dv(P_(l-1),x) = (2l+1) P_l
$
#figure(
image("pic/2024-10-18-11-59-10.png", width: 80%),
numbering: none,
)
$
dv(P_(l+1),x) - x dv(P_l,x) = (l+1) P_l
$
#problem[
Use the recurrence formulas to evaluate the integral:
$
I = integral_(-1)^1 x P_l (x) P_l' (x) dd(x)
$
]
#solution[
#figure(
image("pic/2024-10-18-12-44-02.png", width: 80%),
numbering: none,
)
]
== Boundary-Value Problems with Azimuthal Symmetry 具有方位对称性的边值问题
=== Laplace Problem with Azimuthal Symmetry
$
Phi(r, theta) = sum_(l=0)^oo (A_l r^l + B_l r^(-l-1)) P_l (cos theta)
$
#problem[
Consider the potential inside one sphere of radius $a$,with the surface potential of $V(θ)$.
]
#figure(
image("pic/2024-10-18-14-29-38.png", width: 40%),
numbering: none,
)
#solution[
由于$0$在求解范围内,可以将$B_l$项去掉,得到
$
Phi(r, theta) = sum_(l=0)^oo A_l r^l P_l (cos theta)
$
#figure(
image("pic/2024-10-18-14-38-48.png", width: 80%),
numbering: none,
)
和@shpere 的结果相符
#figure(
image("pic/2024-10-18-14-43-30.png", width: 80%),
numbering: none,
)
]
#problem[
Potential at $x$ due to a unit point charge at $x'$.
]
#figure(
image("pic/2024-10-18-14-47-07.png", width: 30%),
numbering: none,
)
#solution[
旋转坐标系,使$x'$位于$z$轴上。
$
1/abs(vb(x)-vb(x')) = sum_(l=0)^oo (A_l r^l + B_l r^(-l-1)) P_l (cos theta)
$
如果$x$也在$z$轴上,有
$
1/abs(vb(x)-vb(x')) = 1/r_> sum_(l=0)^oo ((r_<)/(r_>))^l
$
所以对于任意的$x$,有
$
1/abs(vb(x)-vb(x')) = 1/r_> sum_(l=0)^oo ((r_<)/(r_>))^l P_l (cos theta)
$
]
#problem[
Potential at $x$ due to a total charge $q$ uniformly distributed around a circular ring of radius $a$.
]
#solution[
#figure(
image("pic/2024-10-18-15-41-35.png", width: 80%),
numbering: none,
)
]
== Behavior of Fields in a Conical Hole or Near a Sharp Point 锥形孔或尖点附近的场行为
=== Legendre Function of the First Kind and Order $ν$
General solution for boundary-value problems with azimuthal symmetry ($m=0$) and $θ$ is unlimited:
$
Phi(r, theta) = sum_(l=0)^oo (A_l r^l + B_l r^(-l-1)) P_l (cos theta)
$
本节将讨论具有方位对称性的球面坐标中的同一问题,但只涉及有限的 $θ$ 范围。
对于 Legendre 函数
$
dv(,x)((1-x^2) dv(P,x)) + l(l+1)P = 0
$
做代换
$
xi = (1-x)/2, nu = l
$
得到
$
dv(,xi)(xi(1-xi) dv(P,xi)) + nu(nu+1) P = 0
$
对于
$
P(xi) = xi^alpha sum_(j = 0)^oo a_j xi^j
$
有
$
a_(j+1)/a_j = ((j-nu)(j+nu+1))/((j+1)^2)
$
得到$v$阶第一类 Legendre 函数
$
P_nu (xi) = 1 + ((-nu)(nu + 1))/(1!1!) xi + ((-nu)(-nu+1)(nu+1)(nu+2))/(2!2!) xi^2 + ...
$
其中$nu$不必是整数,当整数时,$P_nu$是 Legendre 多项式,产生截断。
=== Fields in a Conical Hole or Near a Sharp Point
#problem[
Solve the field inside the conical hole which has a limited range of $θ (0≤θ≤ β)$. The potential on the conducting surface is at zero.
]
#solution[
#figure(
image("pic/2024-10-18-16-00-37.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-10-18-16-01-05.png", width: 80%),
numbering: none,
)
]
== Associated Legendre Functions and the Spherical Harmonics 连带 Legendre 函数和球谐函数
本节讨论方位角不对称($m≠0$)但$θ$和$ϕ$不受限制的球面坐标问题。
=== Associated Legendre Function
连带 Legendre 方程
$
dv(,x)((1-x^2) dv(P,x)) + (l(l+1) - m^2/(1-x^2))P = 0\
dv(U,r,2) - (l(l+1) U)/(r^2) = 0\
1/Q dv(Q,phi,2) = -m^2
$
方程在$-1≤x≤1$上有有限解:$l$必须为零或一个正整数
$
P_l^m (x) = (-1)^m (1-x^2)^(m/2) dv(,x,m) P_l (x) (m>=0)
$
$
P_l^m (x) = (-1)^m/(2^l l!) (1-x^2)^(m/2) dv(,x,l+m) (x^2-1)^l (m = -l, -l+1, ..., l)
$
当$m=0$时,$P_l^0 (x) = P_l (x)$
=== Spherical Harmonics 球谐函数
Orthogonal set:
- $P_l^m (cos theta)$是正交完备的
$
integral_(-1)^1 P_l'^m (x) P_l^m (x) dd(x) = 2/(2l + 1) (l+m)!/(l-m)! delta_(l' l)
$
- 以及$phi$的维度
$
integral_0^(2pi) e^(i(m-m')phi) dd(phi) = 2pi delta_(m m')
$
在单位球面上以$l,m$两种指数构成一个完整的正交集合:
$
Y_(l m) (theta, phi) = sqrt((2l+1)/(4pi) (l-m)!/(l+m)!) P_l^m (cos theta) e^(i m phi)
$
有正交归一关系
$
integral_0^(2pi) integral_(-1)^1 Y^*_(l' m') (theta, phi) Y_(l m) (theta, phi) sin theta dd(theta) dd(phi) = delta_(l' l) delta_(m' m)
$
以及完备性条件
$
sum_(l=0)^oo sum_(m=-l)^l Y^*_(l m) (theta', phi') Y_(l m) (theta, phi) = delta(cos theta- cos theta') delta(phi-phi')
$
#figure(
image("pic/2024-10-18-16-28-31.png", width: 80%),
numbering: none,
)
任意函数$g(theta, phi)$可以由球谐函数展开:
$
g(theta, phi) = sum_(l=0)^oo sum_(m=-l)^l A_(l m) Y_(l m) (theta, phi)
$
其中
$
A_(l m) = integral_0^(2pi) integral_(-1)^1 g(theta, phi) Y^*_(l m) (theta, phi) sin theta dd(theta) dd(phi)
$
=== General Solution in Spherical Coordinates
$
Phi(r, theta, phi)=U(r)/r P(theta) Q(phi)\
Phi(r, theta, phi)=sum_(l=0)^oo sum_(m=-l)^l (A_(l m) r^l + B_(l m) r^(-l-1)) Y_(l m) (theta, phi)
$
== Addition Theorem for Spherical Harmonics 球谐函数的加法定理
=== Addition Theorem for Spherical Harmonics
$
P_l (cos gamma) = (4pi)/(2l+1) sum_(m=-l)^l Y^*_(l m) (theta', phi')Y_(l m) (theta, phi)
$
#figure(
image("pic/2024-10-18-16-34-40.png", width: 40%),
numbering: none,
)
$
1/abs(vb(x) - vb(x')) &= sum_(l=0)^oo r_<^l/r_>^(l+1) P_l (cos gamma)\
&= 4pi sum_(l=0)^oo sum_(m=-l)^l 1/(2l+1) r_<^l/r_>^(l+1) Y^*_(l m) (theta', phi')Y_(l m) (theta, phi)
$
#figure(
image("pic/2024-10-18-16-41-56.png", width: 100%),
numbering: none,
)
== Laplace Equation in Cylindrical Coordinates and Bessel Function 柱坐标系下的Laplace方程和Bessel函数
=== Laplace Equation in Cylindrical Coordinates
$
laplacian Phi = pdv(Phi,r,2) + 1/rho pdv(,rho)(rho pdv(Phi,rho)) + 1/rho^2 pdv(Phi,phi,2) + pdv(Phi,z,2) = 0
$
分离变量
$
Phi(rho, phi, z) = R(rho) P(phi) Z(z)
$
代入方程得到
$
(rho^2/R dv(R,rho,2) + rho/R dv(P,rho)) + 1/Q dv(Q,phi,2) + rho^2/Z dv(Z,z,2) = 0
$
则有
$
dv(Q,phi,2) + nu^2 Q = 0 => Q = e^(plus.minus i nu phi),nu in ZZ
$
$
dv(Z,z,2) - k^2 Z = 0 => Z = e^(plus.minus k z),k in RR
$
$
dv(R,rho,2) + 1/rho dv(R,rho) + (k^2 - nu^2/rho^2) R = 0
$
第三个式子中,令
$
x = k rho
$
则有 $nu$ 阶 Bessel 方程
$
dv(R,x,2) + 1/x dv(R,x) + (1 - nu^2/x^2)R = 0
$
=== Bessel Function
对 $nu$ 阶 Bessel 方程
$
dv(R,x,2) + 1/x dv(R,x) + (1 - nu^2/x^2)R = 0
$
取
$
R(x) = x^alpha sum_(j = 0)^oo a_j x^j
$
代入比较有
$
alpha = plus.minus nu\
a_1 = 0\
a_(j-2) = a_j (nu^2 - (j+alpha)^2)
$
从而
$
a_(2j) = (-1)^j Gamma(alpha+1)/(2^(2j)j! Gamma(j+alpha+1)) a_0
$
选择
$
a_0 = 1/(2^alpha Gamma(alpha+1))
$
得到 Bessel 函数
$
J_nu (x) = (x/2)^nu sum_(j = 0)^oo (-1)^j / (j! Gamma(j+nu+1))(x/2)^(2j)\
J_(-nu) (x) = (x/2)^(-nu) sum_(j = 0)^oo (-1)^j / (j! Gamma(j-nu+1))(x/2)^(2j)
$
如果$𝜈$不是整数,这两个解$J_(±𝜈) (x)$就构成了 Bessel 方程的线性无关解。
当$ν$为整数时$J_ν$和$J_(-ν)$是线性相关的:
$
J_nu = (-1)^nu J_(-nu)
$
由于$J_ν$和$J_(-ν)$是线性相关的,我们可以由此构造出第二个线性无关解:
- Neumann 函数(第二类 Bessel 函数)
$
N_nu (x) = (J_nu (x) cos nu pi - J_(-nu) (x))/(sin nu pi)
$
这样$J_ν$和$N_ν$就是线性无关的解。
- Hankel 函数(第三类 Bessel 函数)
$
H_nu^((1)) (x) = J_nu (x) + i N_nu (x)\
H_nu^((2)) (x) = J_nu (x) - i N_nu (x)
$
$H_nu^((1))$和$H_nu^((2))$是线性无关的解。
Bessel 函数的递推关系:
$
Omega_(nu-1) (x) + Omega_(nu+1) (x) = (2nu)/x Omega_nu (x)\
Omega_(nu-1) (x) - Omega_(nu-1) (x) = 2 dv(Omega_nu (x),x)
$
#figure(
image("pic/2024-10-18-23-45-18.png", width: 100%),
numbering: none,
)
=== Modified Bessel functions 虚宗量 Bessel 函数
对方程
$
dv(R,rho,2) + 1/rho dv(R,rho) + (k^2 - nu^2/rho^2) R = 0\
dv(Z,z,2) - k^2 Z = 0
$
将$k^2->-k^2$得到
$
dv(R,rho,2) + 1/rho dv(R,rho) - (k^2 + nu^2/rho^2) R = 0\
dv(Z,z,2) + k^2 Z = 0
$
代换$x = k rho$得到
$
dv(R,x,2) + 1/x dv(R,x) - (1 + nu^2/x^2) R = 0
$
这个方程的解是虚宗量 Bessel 函数,解为
$
I_nu (x) = i^(-nu) J_nu (i x)\
K_nu (x) = pi/(2) i^(nu+1) H_nu^((1)) (i x)
$
#figure(
image("pic/2024-10-18-23-57-16.png", width: 30%),
numbering: none,
)
- Bessel functions - Cylindrical coordinate(柱坐标系)
- Legendre functions - Spherical coordinate(球坐标系)
- Trigonometric functions - Cartesian coordinate(直角坐标系)
=== 正交完备性
Bessel函数是$rho in [0,a]$上的正交完备函数系:
$
J_nu ((x_(nu n)rho)/a)
$
其中$x_(nu n)$是$J_nu$的第$n$个零点。
有权重函数$rho$,正交性为
$
integral_0^a rho J_nu ((x_(nu n')rho)/a) J_nu ((x_(nu n)rho)/a) dd(rho) = a^2/2 (J_(nu+1) (x_(nu n)))^2 delta_(n n')
$
#figure(
image("pic/2024-10-19-00-07-28.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-10-19-00-09-24.png", width: 80%),
numbering: none,
)
区间$0≤ρ≤a$上的任意函数$f(ρ)$可以展开为Bessel函数的级数:
$
f(ρ) = sum_(n=0)^oo A_(nu n) J_nu ((x_(nu n)ρ)/a)
$
== Boundary-Value Problems in Cylindrical Coordinates 柱坐标系下的边值问题
#problem[
What is the potential inside the cylinder which has a radius of a and a height of $L$? The potential on the side and the bottom of the cylinder is zero, while the top has a potential of $Φ=V(ρ,ϕ)$.
]
#solution[
#figure(
image("pic/2024-10-19-00-35-09.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-10-19-00-41-24.png", width: 80%),
numbering: none,
)
]
== Expansion of Green Functions in Spherical Coordinates 球坐标系下的Green函数展开
问题:
1. 如何给出以$r=a$和$r=b$为边界的球壳的格林函数?
2. 为什么我们使用格林函数作为与坐标相适应的函数的一系列乘积?
1. 处理涉及电荷分布和边界值的问题;
2. 满足在某些可分离坐标系的表面上规定的适当边界条件;
3. 处理用对称电荷法难以获得的问题。
=== Expansion of Green Function in Spherical Coordinates
- No boundary
$
G(vb(x),vb(x')) = 1/abs(vb(x) - vb(x')) = 4 pi sum_(l=0)^oo sum_(m=-l)^l 1/(2l+1) r_<^l/r_>^(l+1) Y^*_(l m) (theta', phi') Y_(l m) (theta, phi)
$
- 球形边界$r=a$的外部
$
G(vb(x),vb(x')) = 1/abs(vb(x) - vb(x')) - a/(x'abs(vb(x) - a^2/x'^2 vb(x')))
$
而其中
$
- a/(x'abs(vb(x) - a^2/x'^2 vb(x'))) &= - a/r' 1/abs(vb(x) - a^2/x'^2 vb(x'))\
&= - a/r' 4 pi sum_(l=0)^oo sum_(m=-l)^l 1/(2l+1) 1/r^(l+1) (a^2/r')^l Y_(l m)^* (theta', phi') Y_(l m) (theta, phi)
$
这是把上式中
$
r_> = r, r_< = a^2/r'
$
代入得到的。
从而最终的Green函数为
$
G(vb(x),vb(x')) = 4 pi sum_(l=0)^oo sum_(m=-l)^l 1/(2l+1) (r_<^l/r_>^(l+1) - 1/a (a^2/(r r'))^(l+1)) Y_(l m)^* (theta', phi') Y_(l m) (theta, phi)
$
其中
$
r_<^l/r_>^(l+1) - 1/a (a^2/(r r'))^(l+1) = cases(
1/r'^(l+1) (r^l - a^(2l+1)/r^(l+1)) & r > a\
1/r^(l+1) (r'^l - a^(2l+1)/r'^(l+1)) & r < a
)
$
1. 当$r$或$r'$等于$a$时,径向因子消失
2. $r->oo$或$r'->oo$时,径向因子趋于零
3. $r$和$r'$对称
=== General expansion in separable coordinates
$
G(vb(x),vb(x')) = 4 pi sum_(l=0)^oo sum_(m=-l)^l 1/(2l+1) (r_<^l/r_>^(l+1) - 1/a (a^2/(r r'))^(l+1)) Y_(l m)^* (theta', phi') Y_(l m) (theta, phi)
$
$
G(vb(x),vb(x')) = sum_(l=0)^oo sum_(m=-l)^l A_(l m) (r | r', theta', phi') Y_(l m) (theta, phi)
$
利用
$
laplacian_x G(vb(x),vb(x')) = -4 pi delta(vb(x)-vb(x'))\
delta(vb(x)-vb(x')) = 1/r^2 delta(r-r') delta(phi-phi') delta(cos theta - cos theta')= 1/r^2 delta(r-r')sum_(l=0)^oo sum_(m=-l)^l Y_(l m) (theta, phi) Y_(l m)^* (theta', phi')
$
令
$
A_(l m) (r | r', theta', phi') = g_l (r, r') Y^*_(l m) (theta', phi')
$
$
1/r dv(,r,2) (r g_l (r,r')) - (l(l+1))/r^2 g_l (r,r') = -4 pi delta(r-r')
$
$g_l$是Radial Green function
#figure(
image("pic/2024-10-19-01-25-35.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-10-19-01-26-12.png", width: 80%),
numbering: none,
)
=== Expansion with boundary surfaces at $r=a$ and $r=b$
$
g_l (r,r') = cases(
A r^l + B r^(-l-1) & r < r'\
A' r^l + B' r^(-l-1) & r > r'
)
$
有边界条件
$
g_l (r=a, r')=0, g_l (r=b, r')=0
$
得到
$
g_l (r,r') = cases(
A(r^l - (a^(2l+1))/r^(l+1)) & r < r'\
B'(1/r^(l+1) - r^l/b^(2l+1)) & r > r'
)
$
由$r$和$r'$的对称性,有
$
g_l (r,r') &= C (r_<^l - a^(2l+1)/r_<^(l+1))(1/r_>^(l+1) - r_>^l/b^(2l+1))\
&= cases(
C (r^l - a^(2l+1)/r^(l+1))(1/r'^(l+1) - r'^l/b^(2l+1)) & r < r'\
C (r'^l - a^(2l+1)/r'^(l+1))(1/r^(l+1) - r^l/b^(2l+1)) & r > r'
)
$
对$g_l$的式子multiply both sides by $r$, and integrate over $r'-𝜖$ and $r'+𝜖$,可以得到$C$
$
C = (4pi)/((2l+1)(1-(a/b)^(2l+1)))
$
#figure(
image("pic/2024-10-19-01-43-40.png", width: 80%),
numbering: none,
)
最终得到Green函数
$
G(vb(x),vb(x')) = 4 pi sum_(l=0)^oo sum_(m=-l)^l ( Y_(l m)^* (theta', phi') Y_(l m) (theta, phi))/((2l+1)(1-(a/b)^(2l+1))) (r_<^l - a^(2l+1)/r_<^(l+1))(1/r_>^(l+1) - r_>^l/b^(2l+1))
$
- $a->0,b->oo$得到自由空间的Green函数
$
G(vb(x),vb(x')) = 1/abs(vb(x) - vb(x')) = 4 pi sum_(l=0)^oo sum_(m=-l)^l 1/(2l+1) r_<^l/r_>^(l+1) Y^*_(l m) (theta', phi') Y_(l m) (theta, phi)
$
- $b->oo$得到球壳的Green函数
$
G(vb(x),vb(x')) = 4 pi sum_(l=0)^oo sum_(m=-l)^l 1/(2l+1) (r_<^l/r_>^(l+1) - 1/a (a^2/(r r'))^(l+1)) Y_(l m)^* (theta', phi') Y_(l m) (theta, phi)
$
- 对于内部问题$a->0$
== Solution of Potential Problems with the Spherical Green Function Expansion 用球形Green函数展开解决电势问题
=== General Solution to the Poisson Equation with Dirichlet Boundary Conditions
根据 @DbGreen
$
Phi(vb(x)) = 1/(4 pi epsilon_0) integral_V G_D(vb(x),vb(x')) rho(vb(x')) dd(vb(x'), 3) - 1/(4 pi) integral.cont_S Phi(vb(x')) partialderivative(G_D,n') dd(vb(a)')
$
再结合刚推导出来的Green函数
$
G(vb(x),vb(x')) = 4 pi sum_(l=0)^oo sum_(m=-l)^l ( Y_(l m)^* (theta', phi') Y_(l m) (theta, phi))/((2l+1)(1-(a/b)^(2l+1))) (r_<^l - a^(2l+1)/r_<^(l+1))(1/r_>^(l+1) - r_>^l/b^(2l+1))
$
#problem[
What is the potential inside a sphere of radius $b$? On the surface of $r=b, Φ=V(θ,ϕ)$. There is no charge inside the sphere.
]
#figure(
image("pic/2024-10-19-14-50-17.png", width: 30%),
numbering: none,
)
#solution[
#figure(
image("pic/2024-10-19-14-40-58.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-10-19-14-42-48.png", width: 80%),
numbering: none,
)
得到电势
$
Phi(vb(x)) = sum_(l=0)^oo sum_(m=-l)^l (integral V(theta', phi') Y_(l m)^*(theta', phi')dd(Omega')) (r/b)^l Y_(l m) (theta, phi)
$
事实上在前面我们说$Phi$可以被展开为球谐函数
$
Phi(r, theta, phi) = sum_(l=0)^oo sum_(m=-l)^l (A_(l m) r^l + B_(l m) r^(-l-1)) Y_(l m) (theta, phi)
$
另外,我们也有镜像电荷法的 Green 函数推出了
$
Phi(vb(x)) = 1/(4 pi epsilon_0) integral Phi(a, phi', theta') (a(x^2 - a^2))/(x^2 + a^2 - 2a x cos gamma)^(3/2) dd(Omega')
$
二者形式符合。
]
#problem[
Solve the potential inside a hollow grounded *sphere* of radius $b$, with a concentric *ring* of charge of radius $a$ and total charge $Q$.
]
#figure(
image("pic/2024-10-19-14-55-14.png", width: 30%),
numbering: none,
)
#solution[
#figure(
image("pic/2024-10-19-14-56-08.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-10-19-14-57-17.png", width: 80%),
numbering: none,
)
]
#problem[
Solve the potential inside a hollow grounded sphere of radius $b$, with a uniform line charge of total charge $Q$ located on the $z$ axis between the north and south poles of the sphere.
]
#figure(
image("pic/2024-10-19-15-10-36.png", width: 40%),
numbering: none,
)
#solution[
#figure(
image("pic/2024-10-19-15-13-05.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-10-19-15-14-27.png", width: 80%),
numbering: none,
)
]
== Expansion of Green Functions in Cylindrical Coordinates 柱坐标系下的Green函数展开
=== Expansion of Green Function in Cylindrical Coordinates
#figure(
image("pic/2024-10-19-15-18-53.png", width: 80%),
numbering: none,
)
#figure(
image("pic/2024-10-19-15-20-34.png", width: 80%),
numbering: none,
)
得到结果
$
1/abs(vb(x) - vb(x')) = 1/pi sum_(m=-oo)^oo integral_(-oo)^oo dd(k) e^(i m (phi -phi'))e^(i k(z-z'))I_m (k rho_<) K_m (k rho_>)
$
其中$I_m$和$K_m$是修正 Bessel 函数(虚宗量 Bessel 函数)。
== Eigenfunction Expansions for Green Functions Green函数的特征函数展开
=== Eigenfunctions and Eigenvalues
Elliptic differential equation 椭圆微分方程
$
laplacian Psi(vb(x)) + (f(vb(x))+lambda)Psi(vb(x)) = 0
$
如果要求$Ψ(x)$满足所关心的体积$V$的表面$S$上的同质边界条件,那么椭圆微分方程就不会有良好的(例如有限连续的)解,除了$λ$的某些值。
$
laplacian Psi_n (vb(x)) + (f(vb(x))+lambda_n)Psi_n (vb(x)) = 0
$
特征函数是正交的:
$
integral_V Psi_n^* (vb(x)) Psi_m (vb(x)) dd(vb(x)) = delta_(n m)
$
特征函数构成一个正交完备集。假设 Green 函数的边界条件与特征函数相同,并满足方程:
$
laplacian_x G(vb(x),vb(x')) + (f(vb(x))+lambda)G(vb(x),vb(x')) = -4 pi delta(vb(x)-vb(x'))
$
=== Eigenfunction Expansions for Green Functions
$
G(vb(x),vb(x')) = sum_n a_n (vb(x')) Psi_n (vb(x))
$
结合
$
laplacian Psi_n (vb(x)) + (f(vb(x))+lambda_n)Psi_n (vb(x)) = 0\
laplacian_x G(vb(x),vb(x')) + (f(vb(x))+lambda)G(vb(x),vb(x')) = -4 pi delta(vb(x)-vb(x'))
$
得到
$
sum_n a_n (vb(x')) (lambda-lambda_n) Psi_n (vb(x)) = -4 pi delta(vb(x)-vb(x'))
$
两边乘以$Psi_m^* (vb(x))$并积分,得到
$
a_m (vb(x')) = -4 pi (Psi_m^* (vb(x')))/(lambda_m-lambda)
$
从而 Green 函数的展开为
$
G(vb(x),vb(x')) = -4 pi sum_n (Psi_n^* (vb(x')) Psi_n (vb(x)))/(lambda_n-lambda)
$
#problem[
3D Fourier Integral representation of $1/abs(x-x')$.
]
#solution[
$
laplacian Psi_n (vb(x)) + (f(vb(x))+lambda_n)Psi_n (vb(x)) = 0
$
中$f=0,lambda_n=k^2$是连续的特征值
$
(laplacian + k^2) Psi_vb(k) (vb(x)) = 0
$
$
Psi_vb(k) (vb(x)) = 1/(2pi)^(3/2) e^(i vb(k) dot vb(x))
$
根据Green函数的展开
$
1/abs(vb(x)-vb(x')) = 1/(2pi^2) integral e^(i vb(k) dot (vb(x)-vb(x'))) dd(vb(k))
$
]
#problem[
Find the Green function for a Dirichlet problem inside a rectangular box defined by the six planes, $x=0, y=0, z=0, x=a, y=b, z=c$.
]
#solution[
#figure(
image("pic/2024-10-19-15-39-17.png", width: 80%),
numbering: none,
)
] |
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/dialogues/dialogue-layout.typ | typst | #import "@local/typkit:0.1.0": *
#let dialogue-layout(items, body-width: auto, row-gutter: 15pt, spacing: 0.8em) = {
set block(breakable: false)
show par: set block(spacing: spacing )
let even(item) = {
block(breakable: false, width: body-width, {
item
})
}
let items = map-even-odd(items, even, bold)
table(
column-gutter: 10pt,
columns: (auto, body-width),
stroke: none,
row-gutter: row-gutter,
..items,
)
}
|
|
https://github.com/monaqa/typst-easytable | https://raw.githubusercontent.com/monaqa/typst-easytable/master/src/lib.typ | typst | MIT License | #import "@preview/tablex:0.0.8": cellx, gridx, hlinex, vlinex
#import "./elem.typ"
#let _easytable_processor(n_columns, columns, operations, tablex_extra_args: (:)) = {
let data = ()
let row_idx = 0
let layout_func = ((c) => c,) * n_columns
for op in operations {
if op._kind == "easytable.push_row" {
// validation
if op.data.len() != n_columns {
panic(
"# of columns does not match. expected " + str(n_columns) + ", got " + str(op.data.len()),
)
}
for (col_idx, z) in op.data.zip(layout_func).enumerate() {
let _trans = op.at("cell_trans", default: none)
let _style = op.at("cell_style", default: none)
let (c, layout_f) = z
c = layout_f(c)
if _trans != none {
c = _trans(x: col_idx, y: row_idx, c)
}
let cell_args = if _style == none { () } else {
_style(x: col_idx, y: row_idx)
}
data.push(cellx(c, ..cell_args))
}
row_idx += 1
}
if op._kind == "easytable.set_layout" {
if op.layout.len() != n_columns {
panic(
"# of columns does not match. expected " + str(n_columns) + ", got " + str(op.layout.len()),
)
}
layout_func = op.layout
}
if op._kind == "easytable.push_hline" {
data.push(hlinex(..op.at("args", default: ())))
}
if op._kind == "easytable.push_vline" {
data.push(vlinex(..op.at("args", default: ())))
}
}
gridx(columns: columns, ..tablex_extra_args, ..data)
}
#let hline_tb(operations, stroke: 0.8pt) = {
(
(_kind: "easytable.push_hline", args: (stroke: stroke)),
..operations,
(_kind: "easytable.push_hline", args: (stroke: stroke)),
)
}
#let rectbox(operations, stroke: 1.0pt) = {
(
(_kind: "easytable.push_hline", args: (stroke: stroke)),
(_kind: "easytable.push_vline", args: (stroke: stroke)),
..operations,
(_kind: "easytable.push_hline", args: (stroke: stroke)),
(_kind: "easytable.push_vline", args: (stroke: stroke)),
)
}
/// テーブルを作成する。
///
/// - tablex_extra_args (dict, (:)): tablex 生成時に `tablex` にわたすキーワード引数。
/// - body (array, (:)): テーブルのデータやレイアウト設定など。
#let easytable(decoration: hline_tb, tablex_extra_args: (:), body) = {
let n_column_detector = body.find(
(c)=> ("easytable.set_layout", "easytable.push_row", "easytable.set_column").contains(c._kind),
)
if n_column_detector == none {
panic("empty table, # of n_column_detector cannot be determined.")
}
let n_columns = n_column_detector.length
let columns = {
let op_set_column = body.find(c => c._kind == "easytable.set_column")
if op_set_column == none {
n_columns
} else {
op_set_column.value
}
}
body = decoration(body)
_easytable_processor(n_columns, columns, body, tablex_extra_args: tablex_extra_args)
}
|
https://github.com/herbhuang/utdallas-thesis-template-typst | https://raw.githubusercontent.com/herbhuang/utdallas-thesis-template-typst/main/content/related_work.typ | typst | MIT License | #import "/utils/todo.typ": TODO
= Related Work
#TODO[
Describe related work regarding your topic and emphasize your (scientific) contribution in contrast to existing approaches / concepts / workflows. Related work is usually current research by others and you defend yourself against the statement: “Why is your thesis relevant? The problem was al- ready solved by XYZ.” If you have multiple related works, use subsections to separate them.
] |
https://github.com/An-314/Notes-of-DSA | https://raw.githubusercontent.com/An-314/Notes-of-DSA/main/sort.typ | typst | = 排序
== 快速排序Quick Sort
选择一个轴点,将小于轴点的元素放在轴点左边,大于轴点的元素放在轴点右边,然后递归地对左右两个子序列进行快速排序。$"sorted"(S) = "sorted"(S_L) + "pivot" + "sorted"(S_R)$
pivot: $max["lo", "mi") <= "pivot" < min("mi", "hi")$
排好的轴点就是排序之后的位置,此后不会再动。快速排序就是将所有元素逐个转换为轴点的过程。
```cpp
template <typename T> void Vector<T>::quickSort( Rank lo, Rank hi ) {
if ( hi - lo < 2 ) return;
Rank mi = partition( lo, hi ); //能否足够高效?
quickSort( lo, mi );
quickSort( mi + 1, hi );
}
```
=== `partition`——LUG版
每次选取一个轴点的候选,从前缀和后缀交替扫描,将小于轴点的元素交换到前缀,大于轴点的元素交换到后缀,直至交换至前缀与后缀的交界处。
#figure(
image("fig\排序\1.png",width: 80%),
caption: "LUG版partition"
)
交替的方法是:从前缀开始,如果当前元素小于候选者,则继续向后扫描;如果当前元素大于候选者,则从后缀开始,向前扫描,直至找到一个小于轴点的元素,将其交换至前缀,然后继续向后扫描。
```cpp
template <typename T> Rank Vector<T>::partition( Rank lo, Rank hi ) { //[lo, hi)
swap( _elem[lo], _elem[lo + rand() % (hi-lo)] ); //随机交换
T pivot = _elem[lo]; //经以上交换,等效于随机选取候选轴点
while ( lo < hi ) { //从两端交替地向中间扫描,彼此靠拢
do hi--; while ( (lo < hi) && (pivot <= _elem[hi]) ); //向左拓展G
if (lo < hi) _elem[lo] = _elem[hi]; //凡 小于 轴点者,皆归入L
do lo++; while ( (lo < hi) && (_elem[lo] <= pivot) ); //向右拓展L
if (lo < hi) _elem[hi] = _elem[lo]; //凡 大于 轴点者,皆归入G
} //assert: lo == hi or hi+1
_elem[hi] = pivot; return hi; //候选轴点归位;返回其秩
}
```
==== 时间复杂度
最好的情况下,每次都几乎均匀地划分成两个子序列,递归树的深度为$O(log n)$,每层的时间复杂度为$O(n)$,总的时间复杂度为$O(n log n)$。
最坏的情况下,每次都只能划分成一个子序列,递归树的深度为$O(n)$,每层的时间复杂度为$O(n)$,总的时间复杂度为$O(n^2)$。
采用*随机选取(Randomization)、 三者(low,high,mid)取中(Sampling)*之类的策略,降低最坏情况的概率,而无法杜绝。但是数据是非理想随机的,所以这些策略可能有效。
==== 空间复杂度
空间复杂度即是递归栈的深度,最好情况下,递归栈的深度为$O(log n)$,空间复杂度为$O(log n)$。
模拟进栈过程:
```cpp
#define Put( K, s, t ) { if ( 1 < (t) - (s) ) { K.push(s); K.push(t); } }
#define Get( K, s, t ) { t = K.pop(); s = K.pop(); }
template <typename T> void Vector<T>::quickSort( Rank lo, Rank hi ) {
Stack<Rank> Task; Put( Task, lo, hi ); //类似于对递归树的先序遍历
while ( !Task.empty() ) {
Get( Task, lo, hi ); Rank mi = partition( lo, hi );
if ( mi-lo < hi-mi ) { Put( Task, mi+1, hi ); Put( Task, lo, mi ); }
else { Put( Task, lo, mi ); Put( Task, mi+1, hi ); }
} //大|小任务优先入|出栈,可保证(辅助栈) 空间不过O(logn)
}
```
小任务优先出栈,大任务优先入栈,可保证辅助栈空间不过$O(log n)$。
===== 递归深度分析
下面我们证明:最坏情况递归$Omega (n)$层,概率极低;平均情况递归$O(log n)$层,概率极高。
对于一个区间,我们定义好的轴点为居中占比为$lambda$的部分的轴点。事实上对于除非过于侧偏的pivot,都会有效地缩短递归深度。
```
|<--(1-lambda)/2-->|<--lambda-->|<--(1-lambda)/2-->|
|<-----坏轴点----->||<--好轴点-->||<-----坏轴点----->|
```
于是,在任何一条递归路径上, 好轴点决不会多于
$
d(n, lambda) = log_(2/(n+1)) n
$
这是因为之后递归的所有好节点会出现在当前区间的中间占比为$lambda + (1-lambda)/2$的部分。
以$lambda = 0.5$为例,$d(n, 0.5) = log_(4/3) n approx 2.41 log n $。这意味着同时,深入$1/lambda d(n, lambda)$层后,即可期望出现$d(n, lambda)$个好轴点——从而在此之前终止递归。
下面证明任何一条递归路径的长度,只有极小的概率超过
$
D(n, lambda) = 2/lambda d(n, lambda)
$
事实上此概率
$
&<= sum_(k=0)^(D(n, lambda)) (1-lambda)^k lambda^(D-k) \
&= 2^(-D(n, lambda)) sum_(k=0)^(D(n, lambda)) (2 lambda)^k \
&<= 2^(-4D) (e D/d)^d
= 16^(-d)(4e)^d \
&approx n^(-1.343)
$
当$n=10^6$时,递归深度不超过$D$的概率$>=1-n^(-0.343)approx 99.12%$。从而可以说复杂度为$O(log n)$是极高概率发生(occurring w.h.p)的。
===== 比较次数分析
记期望的比较次数为$T(n)$,是一个期望值,下面分析$T(n)$的递归表达式。
+ 递推分析
设$T(n)$为$n$个元素的序列的期望比较次数,是`partition`与递归任务的期望之和,$T(0) = T(1) = 0$,
$ T(n) &= n-1 + 1/n sum_(k=0)^(n-1) (T(i) + T(n-i-1)) \
&= n-1 + 2/n sum_(k=0)^(n-1) T(i) \
&approx 2 n ln n $
+ 后向分析
设经排序后得到的输出序列为:${a_1, a_2, ...,a_i,...,a_j,..., a_n}$。
这一输出与具体使用何种算法无关,故可使用Backward Analysis。
比较操作的期望次数应为
$
T(n) = sum_(i=0)^(n-2) sum_(j=i+1)^(n-1) P(i,j)
$
亦即,每一对$<a_i,a_j>$在排序过程中接受比较之概率的总和。
`quickSort`的过程及结果,可理解为:按某种次序,将各元素逐个确认为`pivot`。
若$k in [0,i) union (j,n)$,则$a_k$早于或晚于$a_i$和$a_j$被确认,均与$P(i,j)$无关。实际上,$<a_i,a_j>$接受比较,当且仅当在${a_i,...,a_j}$中,$a_i$或$a_j$率先被确认。
从而
$
T(n) &= sum_(i=0)^(n-2) sum_(j=i+1)^(n-1) P(i,j)\
&= sum_(j=0)^(n-1) sum_(i=0)^(k-1) P(i,j) \
&= sum_(j=0)^(n-1) sum_(i=0)^(k-1) 2/(j-i+1) \
&approx sum_(j=0)^(n-1)2 (ln(j) - 1) \
&<= 2 n ln n
$
#figure(
image("fig\排序\2.png",width: 80%),
caption: "排序算法的对比"
)
=== `partition`——DUP版
有大量元素与轴点雷同时
- 切分点将接近于lo
- 划分极度失衡
- 递归深度接近于$O(n)$
- 运行时间接近于$O(n^2)$
移动`lo`和`hi`的过程中,同时比较相邻元素,若属于相邻的重复元素,则不再深入递归。但一般情况下,如此计算量反而增加,得不偿失。
DUP的想法就是在LUG `partition`的比较上,将两头指针移动的判定条件的判定条件由`<=`改为`<`,从而使相邻元素不再重复比较。
```cpp
template <typename T> Rank Vector<T>::partition( Rank lo, Rank hi ) { //[lo, hi)
swap( _elem[lo], _elem[lo + rand() % (hi-lo)] ); //随机交换
T pivot = _elem[lo]; //经以上交换,等效于随机选取候选轴点
while ( lo < hi ) { //从两端交替地向中间扫描,彼此靠拢
/* 与LUG版仅改变符号 */
do hi--; while ( (lo < hi) && (pivot < _elem[hi]) ); //向左拓展G
if (lo < hi) _elem[lo] = _elem[hi]; //凡不大于轴点者,皆归入L
do lo++; while ( (lo < hi) && (_elem[lo] < pivot) ); //向右拓展L
if (lo < hi) _elem[hi] = _elem[lo]; //凡不小于轴点者,皆归入G
} //assert: lo == hi or hi+1
_elem[hi] = pivot; return hi; //候选轴点归位;返回其秩
}
```
- 可以正确地处理一般情况同时复杂度并未实质增高;
- 遇到连续的重复元素时
- `lo`和`hi`会交替移动
- 切分点接近于`(lo+hi)/2`
- 由LUG版的勤于拓展、懒于交换,转为懒于拓展、勤于交换
=== `partition`—— LGU版
在形式上将`partition`化简,全部用swap实现。呈现形式是Piovt + L + G + U 。用这样的方式,可以大大化简代码。
#figure(
image("fig\排序\3.png",width: 65%),
caption: "LGU版partition"
)
采用`swap`实现滚动拓展,而非平移拓展
```cpp
template <typename T> Rank Vector<T>::partition( Rank lo, Rank hi ) { //[lo, hi)
swap( _elem[ lo ], _elem[ lo + rand() % ( hi – lo ) ] ); //随机交换
T pivot = _elem[ lo ]; Rank mi = lo;
for ( Rank k = lo + 1; k < hi; k++ ) //自左向右考查每个[k]
if ( _elem[ k ] < pivot ) //若[k]小于轴点,则将其
swap( _elem[ ++mi ], _elem[ k ]); //与[mi]交换, L向右扩展
swap( _elem[ lo ], _elem[ mi ] ); //候选轴点归位(从而名副其实)
return mi; //返回轴点的秩
}
```
== k-selection
k-selection:在任意一组可比较大小的元素中,由小到大,找到次序为$k$者。亦即,在这组元素的非降排序序列$S$中,找出$S[k]$。
median:长度为$n$的有序序列$S$中,元素$S[floor(n/2)]$称作中位数。
=== 众数Majority
无序向量中,若有一半以上元素同为$m$,则称之为众数。
==== 充分条件
如果获取了中位数,只需要验证该数是否为众数即可,若不是,则无众数。
```cpp
template <typename T> bool majority( Vector<T> A, T & maj )
{ return majEleCheck( A, maj = median( A ) ); }
```
mode:众数若存在,则亦必频繁数。
```cpp
template <typename T> bool majority( Vector<T> A, T & maj )
{ return majEleCheck( A, maj = mode( A ) ); }
```
同样地:`mode()`算法难以兼顾时间、空间的高效。
==== 减而治之——丢掉前缀
若在向量A的前缀$P$($|P|$为偶数)中,元素 $x$ 出现的次数恰占半数,则$A$有众数,仅当对应的后缀 $A - P$ 有众数$m$,且$m$就是 $A$ 的众数。
证:
1. 若$x = m$,则在排除前缀 $P$ 之后, $m$与其它元素在数量上的差距保持不变
2. 若$x != m$,则在排除前缀 $P$ 之后, $m$与其它元素在数量上的差距不致缩小
从而可以按照这样的方法,不断地剪掉前缀、保存候选者,进行扫描。
```cpp
template <typename T> T majCandidate( Vector<T> A ) {
T maj;
for ( Rank c = 0, i = 0; i < A.size(); i++ )
if ( 0 == c ) {
maj = A[i]; c = 1;
} else
maj == A[i] ? c++ : c--;
return maj;
}
```
最后验证候选者是否为众数。
```cpp
template <typename T> bool majority( Vector<T> A, T & maj )
{ return majEleCheck( A, maj = majEleCandiate( A ) ); }
```
=== QuickSelect
下图是对`k-selection`的尝试,采用了不同的方法。
#figure(
image("fig\排序\4.png",width: 90%),
caption: "尝试"
)
希望能找到$O(n)$的算法。
采用快速排序的想法,每次选取一个轴点,将小于轴点的元素放在轴点左边,大于轴点的元素放在轴点右边。直到轴点的秩为$k$。
```cpp
template <typename T> void quickSelect( Vector<T> & A, Rank k ) {
for ( Rank lo = 0, hi = A.size(); lo < hi; ) {
Rank i = lo, j = hi; T pivot = A[lo]; //大胆猜测
while ( i < j ) { //小心求证: O(hi - lo + 1) = O(n)
do j--; while ( (i < j) && (pivot <= A[j]) ); if (i < j) A[i] = A[j];
do i++; while ( (i < j) && (A[i] <= pivot) ); if (i < j) A[j] = A[i];
} //assert: quit with i == j or j+1
A[j] = pivot;
if ( k <= j ) hi = j; //suffix trimmed
if ( i <= k ) lo = i; //prefix trimmed
} //A[k] is now a pivot
}
```
在期望上讲,复杂度为$O(n)$,但是最坏情况下,复杂度为$O(n^2)$。
可以用递推的方式证明:
$
T(n) &= (n-1) + 1/n sum_(k=0)^(n-1) max{T(k) , T(n-k-1)} \
&= (n-1) + 1/n sum_(k=0)^(n-1) T(max{k, n-k-1}) \
&<= (n - 1) + 2/n sum_(k=n/2)^(n-1) T(k) \
$
其中
$
T(1) = 0, T(2) = 1
$
可以归纳
$
T(n) < 4n
$
从而,该算法在期望上讲,复杂度为$O(n)$。
=== LinearSelect
`LinearSelect`是`QuickSelect`的改进版,采用了*中位数的中位数*的思想。
先找局部中位数,取这些中位数的中位数,得到较好的猜测位置。由这个中位数进行分割,递归地进行查找。
```cpp
def linearSelect( A, n, k ):
Let Q be a small constant
1. if ( n = |A| < Q ) return trivialSelect( A, n, k )
2. else divide A evenly into n/Q subsequences (each of size Q)
3. Sort each subsequence and determine n/Q medians //e.g. by insertionsort
4. Call linearSelect() to find M, median of the medians //by recursion
5. Let L/E/G = { x </=/> M | x in A }
6. if (k < |L|) return linearSelect(A, |L|, k)
if (k < |L|+|E|) return M
return linearSelect(A+|L|+|E|, |G|, k-|L|-|E|)
```
#figure(
image("fig\排序\5.png",width: 50%),
caption: "LinearSelect"
)
将`linearSelect()`算法的运行时间记作`T(n)`
- 第0步: $O(1) = O(Q log Q)$ ,递归基:序列长度$|A| <= Q$
- 第1步: $O(n)$ ,子序列划分
- 第2步: $O(n) = Q^2 times n/Q$ ,/子序列各自排序,并找到中位数
- 第3步: $T(n/Q)$ ,从$n/Q$个中位数中,递归地找到全局中位数
- 第4步: $O(n)$ ,划分子集`L/E/G`,并分别计数 —— 一趟扫描足矣
- 第5步: $T((3n)/4)$,如下图,至少有$1/4$被排除
#figure(
image("fig\排序\6.png",width: 60%),
caption: "LinearSelect——复杂度"
)
从而总复杂度是线性的,并且选取$Q=5$。
由于常系数过大($~ >$40),理论价值比应用价值高。
== Shell Sort
注意到每交换一个逆序对,总逆序对数量一定严格减少。
Shell排列考虑将线性序列理解成矩阵,按列进行排序。
*递减增量*(diminishing increment)
- 由粗到细:重排矩阵,使其更窄, 再次逐列排序(h-sorting/h-sorted)
- 逐步求精:如此往复,直至矩阵变成一列(1-sorting/1-sorted)
#figure(
image("fig\排序\7.png",width: 90%),
caption: "Shell Sort"
)
```cpp
template <typename T> void Vector<T>::shellSort( Rank lo, Rank hi ) {
for ( Rank d = 0x7FFFFFFF; 0 < d; d >>= 1 ) //PS Sequence: 1, 3, 7, 15, 31, ...
for ( Rank j = lo + d; j < hi; j++ ) { //for each j in [lo+d, hi)
T x = _elem[j]; Rank i = j; //within the prefix of the subsequence of [j]
while ( (lo + d <= i) && (x < _elem[i-d]) ) //find the appropriate
_elem[i] = _elem[i-d]; i -= d; //predecessor [i]
_elem[i] = x; //where to insert [j]
}
} //0 <= lo < hi <= size <= 2^31
```
对每一列进行插入排序。事实上,Shell排序很适合并行化。
对于Shell排序,选择合适的增量序列是很重要的。
=== Shell序列
Shell给出的是${2^k}$的序列,但是这样的序列并不是最优的。最坏情况要达到$O(n^2)$。
反例是:考查由子序列 `A = unsort[0, 2N−1)` 和 `B = unsort[2N−1, 2N)` 交错而成的序列。在做2-sorting时, A、 B各成一列;故此后必然各自有序。最后一次1-sorting仍需$O(n^2)$。
根源在于,$H_"shell"$中各项并不互素,甚至相邻项也非互素。
这里不加证明的给出几个引理:
*LEM L*:
如下图,设有向量`X[0, m + r)`和 `Y[0, r + n)`,且满足:对任何`0 <= j < r`,都有`Y[j] <= X[m + j]`。在`X`和`Y`分别(按非降次序)排序幵转换为 `X'`和` Y'`后,对任何`0 <= j < r`,依然有`Y'[j] <= X'[m + j]`成立。
#figure(
image("fig\排序\8.png",width: 60%),
caption: "LEM L"
)
*THM K*(Knuth):
A g-ordered sequence REMAINS g-ordered after being h-sorted.
证明用到了LEM L。其中h-ordered是指,当排列成长为h的矩阵时,每一列都是有序的,即$S[i] <= S[i + h]$。
由此可以得到,经过一次h-sorting和g-sorting的的序列可以保持h-ordered和g-ordered。
#figure(
image("fig\排序\9.png",width: 80%),
caption: "Inversion"
)
*线性组合*:对于任意$m、n ∈ N$,既是h-sorting又是g-ordered的序列称为(g,h)-ordered的,它是(mg+nh)-ordered的序列。
由数论的小性质可知(一些Bezout定理的应用),对于互素的$g,h$,对于任意$k > g h -g -h$,$k$-ordered的序列必然是$(g,h)$-ordered的。
这就意味着
$
i-j> g h - g - h => S[i] >= S[j]
$
所以除了左侧的$g h - g - h$个元素,元素都要比$S[i]$大。所以逆序对的数量不超过$n dot (g h - g - h)$。
=== PS序列
Papernov & Stasevic给出序列:
$
H_"PS" = {2^k - 1} = H_"shell" - 1
$
需要
- $O(log n)$次外部迭代
- $O(n^(3/2))$的复杂度
=== Pratt序列
Pratt给出序列:
$
H_"Pratt" = {2^i 3^j| i,j in N}
$
复杂度是$O(n log^2 n)$。
=== Sedgewick序列
Sedgewick给出序列:
$
H_"Sedgewick" = {9 times 4^i - 9 times 2^i + 1, 4^i - 3 times 2^i + 1}
$
最坏复杂度是$O(n^(4/3))$,平均是$O(n^(7/6))$。是实践中最好的序列。 |
|
https://github.com/tfachada/thesist | https://raw.githubusercontent.com/tfachada/thesist/main/template/Beginning/Keywords-en.typ | typst | MIT License | // Don't add a title. It's already included in the template.
Lorem, Ipsum, Dolor, Sit, Amet
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/gradient-text_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Ref: false
// // Make sure they don't work when `relative: "self"`.
//
// // Hint: 17-61 make sure to set `relative: auto` on your text fill
// // Error: 17-61 gradients and patterns on text must be relative to the parent
// #set text(fill: gradient.linear(red, blue, relative: "self")) |
https://github.com/Nrosa01/TFG-2023-2024-UCM | https://raw.githubusercontent.com/Nrosa01/TFG-2023-2024-UCM/main/Memoria%20Typst/capitulos/0.Abstract.typ | typst | #linebreak()
Sand simulators, a subgenre of cellular automata, have experienced a resurgence in popularity in recent years.However, we have identified a significant barrier that hinders its broader adoption among both users and developers, and this is the scarcity of background or available examples. Therefore, the aim of this project is to investigate various implementations of these simulators, evaluating their advantages and disadvantages, as well as their ability to be extended by any user, in order to increase the visibility and understanding of this subgenre.
To achieve this goal, the project will examine several implementations, both in terms of their execution on the CPU and a version that runs the logic on the GPU. Additionally, a study will be conducted with real users to identify potential issues with the implementations and assess the overall interest in the project. The results of these analyses will be used to draw conclusions and propose possible improvements for the project. |
|
https://github.com/Mouwrice/thesis-typst | https://raw.githubusercontent.com/Mouwrice/thesis-typst/main/measurements/measurements.typ | typst | #import "../lib.typ": *
= Measuring accuracy and deviation <measuring-accuracy-and-deviation>
The following chapter discusses the accuracy and deviation of a body pose estimation tool. More specifically, the outputs of the MediaPipe Pose landmark detection solution are compared to that of a traditional optical tracking system.
All base measurements are taken from a Qualisys Oqus MRI #footnote()[The Oqus MRI is one of Qualisys' traditional optical motion capture cameras, requiring physical trackers on the body that reflect incoming infrared light from the camera. #link("https://www.qualisys.com/cameras/oqus-mri/")[https://www.qualisys.com/cameras/oqus-mri/ #link-icon]] system setup at the Art and Science Interaction Lab at De Krook in Ghent, provided by IDLab-Media #footnote()[The Art and Science Lab is a _" highly modular research infrastructure aimed at interaction research"_, provided by IDLab-Media, one of the research teams within the research group IDLab from Ghent University and imec. #link("https://media.idlab.ugent.be/about/")[https://media.idlab.ugent.be/about/ #link-icon]]. An important section is the discussion of the metrics, @metrics. It is crucial to understand what the measurement metrics are and how they are calculated to be able to interpret the results correctly.
#include("measurement_methods.typ")
#include("measurement_results.typ")
|
|
https://github.com/Joelius300/hslu-typst-template | https://raw.githubusercontent.com/Joelius300/hslu-typst-template/main/main.typ | typst | MIT License | #import "template.typ": *
#import "@preview/i-figured:0.2.4"
#show: project.with(
title: "Bachelorarbeit",
subtitle: "Dies ist der Titel der Bachelorarbeit",
abstract: include "chapters/00_abstract.typ",
logo: "img/HSLU-AICH.png",
student: "<NAME>.",
coach: todo("Coach eintragen", inline: true),
expert: todo("Experte eintragen", inline: true),
departement: [Hochschule Luzern -- Informatik],
degree: "BSc Artificial Intelligence and Machine Learning",
date: "16. Februar 2024",
client: todo("Auftraggeber eintragen", inline: true),
confidential: true,
disable_figure_hypenation: false,
)
#include "glossary.typ"
#include "chapters/01_introduction.typ"
#include "chapters/02_state-of-research.typ"
#include "chapters/03_concept.typ"
#include "chapters/04_methodology.typ"
#include "chapters/05_realization.typ"
#include "chapters/06_evaluation.typ"
#include "chapters/07_reflection-and-outlook.typ"
#fence()
= Bibliografie
#{
set heading(outlined: false) // workaround to avoid duplicate entry
bibliography("references.bib", title: v(-1.3em))
}
#pagebreak(weak: true)
// Restart heading numberings at I.i
#set heading(numbering: "I.i")
#counter(heading).update(0)
#include "additional-outlines.typ"
#pagebreak(weak: true)
// Restart heading numberings at A.i
#set heading(numbering: "A.i", supplement: "Appendix")
#counter(heading).update(0)
#include "chapters/99_appendix.typ"
|
https://github.com/xsro/xsro.github.io | https://raw.githubusercontent.com/xsro/xsro.github.io/zola/typst/Control-for-Integrator-Systems/1linear.typ | typst | #import "@preview/cetz:0.2.0"
#import "lib/lib.typ": ode45,get_signal,op
#let plot_fun(func,y-tick-step:none,domain: (-2, 2),y-label:$dot(x)$,x-label:$x$)={
cetz.canvas({
import cetz.plot
import cetz.draw: *
plot.plot(
size: (2,1),
axis-style: "school-book",
x-tick-step: 1, y-tick-step: y-tick-step,
{
plot.add(domain: domain, func,style: (stroke: red))
},
y-label:y-label,
x-label:x-label
)
})
}
#let ode_plot(func,tfinal,x0,step)={
let (xout,dxout)=ode45((t,x)=>(value:func(t,x.value)),tfinal,(value:x0),step)
cetz.canvas({
import cetz.plot
import cetz.draw: *
plot.plot(
size: (4,1),
axis-style: "school-book",
x-tick-step: 1, y-tick-step: none,
{
// plot.add(xout)
plot.add(get_signal(xout,"value"),label:$x$)
},
y-label:$x$,
x-label:$t$,
)
})
}
= Linear feedback for single integrator and variants
== Stabiliztion of Integrator Systems via linear feedback
From the linear control theory, we know the integrator system $x^((n))=u$ can be stabilized with linear feedback $u=-k_n x -k_(n-1) dot(x)+ dots -k_1 x^((n-1))$.
then the closed loop system expressed in differential equation is
$
x^((n))+k_1 x^((n-1))+k_2 x^((n-2))+dots +k_(n-1)dot(x)+k_n x=0.
$
With Laplace transformation, the system can be expressed with
$
p(s)=s^(n)+k_1 s^(n-1)+k_2 s^(n-2)+dots +k_(n-1)s+k_n =0.
$
To make sure the system is stable,
- all roots of $p(s)=0$ must have negative real parts.
- the polynomial $p(s)$ must be a *Hurwitz* polynomial.
- The system must satisfy *Routh–Hurwitz stability criterion*
- The system matrix $A$ associated with $k_i$ must be a *Hurwitz matrix*: $"Re"["eig"(A)]<0$
*Note*: $k_i>0$ is a necessary condition for the system to be stable.
First, we analyse the single integrator system:
$
dot(x)=u
$
which can be stabilized with linear feedback $u=-k x$.
Under linear feedback, the exponential stability will be observed.
#pagebreak()
== Stabiliztion of Single Integrator Systems via $-|x|^v "sign"(x)$
From @polyakov_generalized_2020, we can find solutions of the system
$dot(x)=-x^(v)$ has some good properties.
Due to the definition of power function, usually we extend the function's
definition to the whole rational field $RR$ as $dot(x)=- "sign"(x) |x|^v, v>=0$.
In some books like @polyakov_generalized_2020, a condition on $v$ is used.
#footnote([
I haven't figure out this condition yet.
The condition write $v$ as $v=p/q$ and says
$p$ should be an odd integer and $q$ is an even natual number.
I think both $p$ and $q$ should be odd natural number and $q!=0$.
])
The general solution to this system is
$
x(t)=(x(0)^(-v+1)+(v-1)t)^(1/(-v+1)) "sign"(x(0))
=x(0)/(1+(v-1)t|x(0)|^(v-1))^(1/(v-1)) "if" v!=1.
$
#figure(
table(
columns:(auto,auto,auto,auto,auto),
[system],
[$x-dot(x)$ curve],
[numerical solution $x=x(t)$],
[analytical solution],
[stability],
//
$dot(x)=-x^(0)=-"sign"(x)$,
plot_fun(x=>-op.sig(x,0)),
ode_plot((t,x)=>-op.sig(x,0),10,1,0.1),
[
when $x(0)>0$\
$x(t)=cases(
x(0)-t quad t in (0,x(0)),
0 quad t>=x(0))$
],
[Finite time\ if $v<1$],
//
$dot(x)=-x^(1/3)$,
plot_fun(x=>-op.sig(x,1/3)),
ode_plot((t,x)=>-op.sig(x,1/3),10,1,0.1),
[
when $x(0)>0$\
$x(t)=cases(
(|x(0)|^(2/3)-2/3 t)^(3/2) quad t in (0,(2/3)|x(0)|^(3/2)),
0 quad t>=x(0))$
],
[Finite time\ if $v<1$],
//
$dot(x)=-x^(1)=-x$,
plot_fun(x=>-op.sig(x,1)),
ode_plot((t,x)=>-op.sig(x,1),10,1,0.1),
$x=x(0)e^(-t)$,
[Exponential\ if $=1$],
//
$dot(x)=-x^(3)$,
plot_fun(x=>-op.sig(x,3)),
ode_plot((t,x)=>-op.sig(x,3),10,1,0.1),
$x(t)=(x(0)^(-2)+2t)^(-1/2)$,
[(practical)\ Fixed time\ if $v>1$ #footnote("converges to a neighborhood of the origin in a fixed time independent of the initial condition.")],
),
caption: [fractional power feedback $dot(x)=-"sign"(x)|x|^v, v>=0$]
)
#let main2sat=4
#let sat_fractional_power(x,v)={
op.sat(op.sig(x,v),main2sat)
}
#pagebreak()
== Discussion: negative power feedback
Faster covergence will be found if we use negative power.
However, this will need infinite gain (infinite energy).
So, it is impossible for physical implementation.
Simulations are carried out with a satutated power function
for the infinite gain is not possible to simulate.
#figure(
table(
columns:(auto,auto,auto,auto,auto),
[system],
[$x-dot(x)$ curve],
[numerical solution $x=x(t)$],
[step],
[stability],
//
$dot(x)=-"sat"(x^(-1/3))$,
plot_fun(x=>-sat_fractional_power(x,-1/3)),
ode_plot((t,x)=>-sat_fractional_power(x,-1/3),2,1,0.0012),
[0.0012],
[Finite time],
//
$dot(x)=-"sat"(x^(-1))=-"sat"(1/x)$,
plot_fun(x=>-sat_fractional_power(x,-1)),
ode_plot((t,x)=>-sat_fractional_power(x,-1),2,1,0.01),
[0.01],
[Finite Time],
//
$dot(x)=-"sat"(x^(-3))$,
plot_fun(x=>-sat_fractional_power(x,-3)),
ode_plot((t,x)=>-sat_fractional_power(x,-3),2,1,0.01),
[0.01],
[Finite Time],
//
$dot(x)=-10*"sign"(x)$,
plot_fun(x=>-10*sat_fractional_power(x,0)),
ode_plot((t,x)=>-10*sat_fractional_power(x,0),2,1,0.1),
[0.1],
[Finite time],
)
)
#pagebreak() |
|
https://github.com/noahjutz/AD | https://raw.githubusercontent.com/noahjutz/AD/main/uebungen/3/mts_2d.typ | typst | #import "/config.typ": theme
#import "@preview/cetz:0.2.2"
#let n = 5
#let i1 = 0
#let i2 = 2
#let j1 = 1
#let j2 = 4
#cetz.canvas(length: 100%, {
import cetz.draw: *
group(name: "matrix", {
set-viewport((32pt, -32pt), (1, -1))
rect((0, 0), (1, 1), stroke: none)
grid((0, 0), (1-1/n, 1-1/n), step: 1 / n)
rect(
(j1/n, i1/n),
(j2/n, i2/n),
fill: theme.primary_trans
)
})
line(
"matrix.north-west",
"matrix.south-west",
stroke: none,
name: "ledge"
)
line(
"matrix.north-west",
"matrix.north-east",
stroke: none,
name: "tedge"
)
group({
let frac(index) = 100% * (index/n) + 100% * (1/(n*2))
for (label, index) in (
($i_1$, i1),
($i_2$, i2)
) {
content(
((0, 0), "|-", (name: "ledge", anchor: frac(index))),
anchor: "west",
padding: (right: 4pt),
name: "label",
label
)
line(
"label.east",
("label.east", "-|", "matrix.west"),
mark: (end: "straight")
)
}
for (label, index) in (
($j_1$, j1),
($j_2$, j2)
) {
content(
((0, 0), "-|", (name: "tedge", anchor: frac(index))),
anchor: "north",
padding: (bottom: 4pt),
name: "label",
label
)
line(
"label.south",
("label.south", "|-", "matrix.north"),
mark: (end: "straight")
)
}
})
}) |
|
https://github.com/Fr4nk1inCs/typreset | https://raw.githubusercontent.com/Fr4nk1inCs/typreset/master/src/lib.typ | typst | MIT License | #let version = "0.1.0"
#import "bundles/homework.typ"
#import "bundles/font.typ"
#import "bundles/report.typ"
|
https://github.com/TomVer99/FHICT-typst-template | https://raw.githubusercontent.com/TomVer99/FHICT-typst-template/main/examples/starter/starter.typ | typst | MIT License | // CHANGE THIS TO THE CORRECT PATH
#import "./../../template/fhict-template.typ": *
#import "./terms.typ": term-list
#show: fhict-doc.with(
title: "",
subtitle: "",
// subtitle-lines: 1,
authors: (
(
name: "",
),
),
version-history: (
(
version: "",
date: "",
author: [],
changes: "",
),
),
pre-toc: [#include "./pre-toc.typ"],
// table-of-figures: false,
// table-of-listings: false,
appendix: [#include "./appendix.typ"],
bibliography-file: bibliography("my-sources.bib"),
// citation-style: "ieee",
glossary-terms: term-list,
// glossary-front: false,
// toc-depth: 3,
// disable-toc: false,
// disable-chapter-numbering: false,
// watermark: none,
// censored: 0,
// print-extra-white-page: false,
// secondary-organisation-color: none,
// secondary-organisation-logo: none,
// secondary-organisation-logo-height: 6%,
// enable-index: false,
// index-columns: 2,
)
|
https://github.com/DawnEver/typst-academic-cv | https://raw.githubusercontent.com/DawnEver/typst-academic-cv/main/README.md | markdown | # Typst Template for Academic CV
## What is Typst
Typst is a new markup-based typesetting system that is designed to be as powerful as LaTeX while being much easier to learn and use.
- [Typst Github](https://github.com/typst/typst)
- [Typst Homepage](https://typst.app)
## Preview
- preview main_en.pdf in [docs.google.com](https://docs.google.com/viewer?url=https://github.com/DawnEver/typst-academic-cv/raw/main/main_en.pdf&embedded=true)
- 预览 main_zh.pdf in [docs.google.com](https://docs.google.com/viewer?url=https://github.com/DawnEver/typst-academic-cv/raw/main/main_zh.pdf&embedded=true)
## Structure
- ./img/ # default image folder
- ./template_en.typ # template file
- ./main_en.typ # main body of the thesis
- ./[main_en.pdf](main_en.pdf) # default output pdf
- ./main_zh.typ # main body of the thesis
- ./[main_zh.pdf](main_en.pdf) # default output pdf
## Usage
Run `typst compile main_en.typ` to obtain main_en.pdf
## Version
Typst>=0.9.0 is recommanded.
## Contribute
Welcome to PRs. |
|
https://github.com/donabe8898/typst-slide | https://raw.githubusercontent.com/donabe8898/typst-slide/main/opc/並行prog/01/syakyo02.typ | typst | MIT License | #show link: set text(blue)
#set text(font: "Noto Sans CJK JP",size:11pt)
#show heading: set text(font: "Noto Sans CJK JP")
#show raw: set text(font: "0xProto Nerd Font")
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt
)
#align(center)[
```go
// =====================================
// 関数かけっこ
// fnAとfnBのどちらが先に終了するか
// =====================================
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Println("関数かけっこ")
// チャネルの作成
chA := make(chan string)
chB := make(chan string)
// ゴルーチン実行
go fnA(chA)
go fnB(chB)
// どちらが先にチャネルを受け取るか
select {
case msg := <-chA:
// 受け取ったメッセージの表示
fmt.Printf("%v\n", msg)
fmt.Println("Aの勝ち!")
case msg := <-chB:
// 受け取ったメッセージの表示
fmt.Printf("%v\n", msg)
fmt.Println("Bの勝ち!")
}
}
// 処理A
func fnA(ch chan string) {
r := rand.Intn(5000) // 1~5000までの乱数を生成
time.Sleep(time.Millisecond * time.Duration(r)) // 処理をrミリ秒停止させる
ch <- "function A is done" // 再開したらチャネルを送信
}
// 処理B
func fnB(ch chan string) {
r := rand.Intn(5000) // 1~5000までの乱数を生成
time.Sleep(time.Millisecond * time.Duration(r)) // 処理をrミリ秒停止させる
ch <- "function B is done" // 再開したらチャネルを送信
}
```
]
|
https://github.com/sysu/better-thesis | https://raw.githubusercontent.com/sysu/better-thesis/main/others/bachelor-proposal.typ | typst | MIT License | #import "style.typ": 字体, 字号
#let table-stroke = 0.5pt
#set page(numbering: "1")
#align(center, text(
font: 字体.黑体,
size: 字号.三号,
weight: "bold",
"南京大学本科毕业论文(设计)开题报告"
))
#set text(font: 字体.宋体, size: 字号.五号)
#set underline(offset: 0.1em)
#align(center)[
填表人签名#underline(" ")填表时间:#underline(" ")年#underline(" ")月#underline(" ")日
]
#v(-0.7em)
#{
set text(size: 字号.小四)
table(
columns: (100pt, 1fr, 100pt, 1fr),
stroke: table-stroke,
align: center + horizon,
[学生姓名], [], [学号], [],
[院系专业], [], [手机号], [],
[指导教师姓名一 \ (必填)], [], [职称], [],
[导师所在院系], [], [是否校内], [],
[指导教师姓名二 \ (选填)], [], [职称], [],
[导师所在院系], [], [是否校内], [],
[毕设类型], table.cell(colspan: 3)[#sym.ballot.x 毕业论文 #h(1fr) #sym.ballot 毕业设计(含毕业作品) #h(1fr)],
[论文题目], table.cell(colspan: 3)[],
)
}
#v(-1.37em)
#table(
columns: 1fr,
stroke: table-stroke,
inset: 10pt,
)[
*一、研究背景及意义*(附参考文献)
#v(45em)
][
*二、国内外研究现状*(文献综述,附参考文献,不少于800字)
#v(45em)
][
*三、主要研究或解决的问题和拟采用的方法*
#v(45em)
][
*四、工作进度计划*(每两周为一个单位)
#v(20em)
][
*指导教师意见*(不少于50个字)
#v(20em)
#set align(right)
*签名:* #h(6em)
#v(1em)
#strong(" 年 月 日")
][
*院系意见:*
*(自动写同意)*
#v(1fr)
#set align(right)
*院系负责人签名:* #h(6em)
#v(1em)
#strong(" 年 月 日")
] |
https://github.com/catg-umag/inach-workshop-2024 | https://raw.githubusercontent.com/catg-umag/inach-workshop-2024/main/document/sections/2_basecalling.typ | typst | #import "../catgconf.typ": github-pill, cmd
= Basecalling
Basecalling es el proceso por el cual se convierte la señal eléctrica captada por los dispositivos de Oxford Nanopore en secuencias de nucleótidos. Esta conversión requiere de algoritmos computacionales avanzados, como las redes neuronales LSTM y los transformers utilizados por las opciones de basecalling actuales. Este proceso es crucial porque define la calidad de los datos, lo que afectará directamente los análisis posteriores.
Oxford Nanopore ha desarrollado múltiples basecallers haciendo uso de diversos avances tecnológicos. El basecaller actual es #link("https://github.com/nanoporetech/dorado")[Dorado], el cual se puede utilizar mediante línea de comandos, o a través de MinKNOW.
== Precisión del basecalling
Dorado cuenta con múltiples modelos de basecalling, cada uno con diferentes equilibrios entre precisión y requerimientos computacionales: `fast`, `hac`, y `sup`. Estos modelos se actualizan continuamente con nuevas versiones.
#align(
center,
table(
columns: 3,
align: (left, center, left),
table.header([Modelo], [Precisión simplex], [Requerimientos computacionales]),
[fast (`fast`)], [95.50%], [],
[high accuracy (`hac`)], [99.25%], [7.5 veces lo requerido por #cmd(`fast`)],
[super accuracy (`sup`)], [99.75%], [8.5 veces lo requerido por #cmd(`hac`)],
),
)
#figure(
image("../images/raw_accuracy.png", width: 80%),
caption: [
Precisión actual de los modelos de basecalling de Oxford Nanopore, con el Kit V14 y celdas R10.4.1 de PromethION en secuenciación de genoma humano. _Fuente: #link("https://nanoporetech.com/es/platform/accuracy")_.
],
)
El modelo #cmd(`sup`) ofrece la máxima precisión, pero sus altos requisitos computacionales lo hacen impráctico de utilizar sin hardware especializado (GPU de gama alta).
== Uso de Dorado
#github-pill("nanoporetech/dorado")
Dorado posee múltiples subcomandos con distintas funcionalidades, que incluyen basecalling, demultiplexación y descarga de modelos, entre otras.
=== Basecalling
Para basecalling, se utiliza el subcomando #cmd(`dorado basecaller`). Par ejecutar este comando se requiere como mínimo el modelo a utilizar y el directorio con los archivos POD5. Por ejemplo, si tenemos el directorio `pod5/` y queremos utilizar el modelo `sup` en su versión 5.0.0, debemos utilizar el siguiente comando:
```sh
dorado basecaller [email protected] pod5/ > reads.ubam
```
Existen múltiples opciones adicionales que se pueden visualizar en la ayuda del comando.
=== Demultiplexación
Para demultiplexar los datos, se utiliza el subcomando #cmd(`dorado demux`). Este comando requiere el archivo UBAM con los reads generado en el basecalling y el kit de barcoding. Por ejemplo, si tenemos el archivo el `reads.ubam` y el kit SQK-NBD114-24:
```sh
dorado demux --output-dir basecalled_reads --kit-name SQK-NBD114-24 --emit-fastq reads.ubam
```
En este ejemplo, #cmd(`--output-dir`) indica el directorio donde se guardarán los archivos demultiplexados, y #cmd(`--emit-fastq`) se utiliza para que los archivos generados estén en formato FASTQ (por defecto, se generan en BAM). |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/cookery/direction/responsive.typ | typst | Apache License 2.0 | #import "mod.typ": *
#show: book-page.with(title: "Static, Responsive rendering")
#include "claim.typ"
Example Application: #link("https://github.com/Myriad-Dreamin/typst.ts/blob/main/packages/typst.ts/index.html")[single-file], #link("https://github.com/Myriad-Dreamin/shiroa")[shiroa] and #link("https://github.com/Myriad-Dreamin/typst.ts/tree/main/projects/hexo-renderer-typst")[hexo-renderer-typst]
== How does Resonspive Rendering Work?
You must prepare a artifact for each document, containing compressed data for different theme and screen settings. The bundle size of artifacts is optimized for typst documents.
Since preparation is offline, it is suitable for static sites and blogs.
After that, we provide a renderer to extract and render artifact in browser. Obviously, it doesn't have capabilities to compile typst code.
Besides static display effect like PDF, by rendering document to canvas, The renderer also overlays SVG for responsive effect by CSS anominations, and HTML layer for semantics embedding and user interactions. If you would like to hack, the HTML elements can be also #link("https://myriad-dreamin.github.io/shiroa/format/supports/multimedia.html")[placed] in Typst document.
== Is it Really Static?
You may doubt that if a renderer is used, it is not static. Though we provide absolutely static renderer that exports typst to browser-directed SVG, official typst also provides PNG, SVG, and PDF export. They are not responsive.
For responsive rendering, it is worth to note that some metadata can be also embedded in HTML. For example, you can embed title, description meta in head to allow page previewing
in social media. Though it is not implemented, HTML elements is considered for rendered statically to help SEO.
== Prepare Artifacts: Precompiler Part
As an example, #link("https://github.com/Myriad-Dreamin/typst.ts/blob/main/projects/hexo-renderer-typst/lib/compiler.cjs")[hexo-renderer-typst] utilizes #cross-link("/guide/all-in-one-node.typ")[All-in-one Library for Node.js] to build its functions. First, it creates a dyn layout compiler for precompiling docuemnts:
```js
this.dyn = DynLayoutCompiler.fromBoxed(NodeCompiler.create(compileArgs).intoBoxed());
```
Then, it simply invokes ```js vector()``` method to compile the document:
```js
return this.dyn.vector({ mainFilePath: path });
```
== Prepare Artifacts: Typst Scripting Part
=== `x-page-width` (stable)
Retreiving the sys arguments specified by the dynamic layout compiler:
```typ
/// It is in default A4 paper size (21cm)
#let page-width = sys.inputs.at("x-page-width", default: 21cm)
```
Templating Example:
```typ
#set page(
width: page-width,
height: auto, // Also, for a website, we don't need pagination.
) if is-web-target;
```
=== `x-target` (unstable)
*Note: If you find `x-target` is not overridden for export web artifacts, the SSG tool you are using may not follow this convention.*
*Note: Official typst may introduce their owned method to specify target, therefore this feature may move to the native approach in future.*
Retreiving the sys arguments specified by SSG Tools:
```typ
/// The default target is _pdf_.
/// `typst.ts` will set it to _web_ when rendering a dynamic layout.
#let target = sys.inputs.at("x-target", default: "pdf")
```
Example:
```typ
#let is-web-target() = target.starts-with("web")
#let is-pdf-target() = target.starts-with("pdf")
```
== Build Tools for SSGs (Static Site Generators)
The interface to develop a tools is explored. But there are already easy-touse tools that could be used for your SSG Framework or learned for a new one:
- #link("https://github.com/Myriad-Dreamin/shiroa")[shiroa] for self-hosted simple book (documentation) site.
- #link("https://github.com/Myriad-Dreamin/typst.ts/tree/main/projects/hexo-renderer-typst")[hexo-renderer-typst] for Hexo.
- #link("https://github.com/dark-flames/apollo-typst")[apollo-typst] for Apollo.
|
https://github.com/miliog/typst-penreport | https://raw.githubusercontent.com/miliog/typst-penreport/master/typst-penreport/helper/severity.typ | typst | MIT No Attribution | #let Severity = (
Informational: 0,
Low: 1,
Medium: 2,
High: 3,
Critical: 4,
Undetermined: 5,
)
#let getSeverityInfo(severity) = [
#if severity == Severity.Informational {
return (
text: "Informational",
bg: rgb("#00B0F0"),
)
} else if severity == Severity.Low {
return (
text: "Low",
bg: green,
)
} else if severity == Severity.Medium {
return (
text: "Medium",
bg: orange,
)
} else if severity == Severity.High {
return (
text: "High",
bg: red,
)
} else if severity == Severity.Critical {
return (
text: "Critical",
bg: rgb("#221E1F"),
)
} else if severity == Severity.Undetermined {
return (
text: "Undetermined",
bg: gray.darken(30%),
)
} else {
assert(severity in Severity, message: "Severity not found!")
}
] |
https://github.com/zjutjh/zjut-report-typst | https://raw.githubusercontent.com/zjutjh/zjut-report-typst/main/example.typ | typst | #import "template/template.typ": *
#show: project.with(
title: "xxx课程实验报告",
name:"xxx实验",
id: "202110001000",
class: "计科2100",
authors: "作者",
department: "计算机学院",
date: (2023, 5, 15),
cover_style: "zjut_report",
)
#toc()
#pagebreak()
= 大标题测试
== 小标题测试
=== 三级标题测试
大学之道,在明明德,在亲民,在止于至善。
知止而后有定;
定而后能静;静而后能安;
安而后能虑;虑而后能得。
物有本末,事有终始。知所先后,则近道矣。
古之欲明明德于天下者,先治其国;
欲治其国者,先齐其家;
欲齐其家者,先修其身;
欲修其身者,先正其心;
欲正其心者,先诚其意;
欲诚其意者,先致其知;
致知在格物。
物格而后知至;知至而后意诚;
意诚而后心正;心正而后身修;
身修而后家齐;家齐而后国治;
国治而后天下平。
自天子以至于庶人,壹是皆以修身为本。
其本乱而末治者,否矣。
其所厚者薄,而其所薄者厚,未之有也。
此谓知本,此谓知之至也。
== 小标题测试2
测试测试
= 大标题测试2
#img(
image("./template/asserts/校名.png"),
caption: "测试图片, 浙江工业大学",
) <img:test>
#equation(
$a^2 + b^2 = c^2$,
caption: "勾股定理",
) <equation:test>
公式测试引用@equation:test
#tbl(
table(
columns: (auto, auto),
[姓名], [性别],
[张三], [男],
[李四], [女],
),
caption: "测试表格",
) <table:test>
表格测试引用@table:test
#code(
```cpp
#include <iostream>
int main() {
std::cout << "Hello World!\n";
return 0;
}
```,
caption: "测试代码",
) <code:test>
#code(
```python
print("Hello World!")
```,
caption: "测试代码2",
) <code:test2>
代码测试引用@code:test,
代码测试引用@code:test2
测试参考文献引用@test
图片测试引用@img:test
#bibliography("bib.yaml", style:"gb-7714-2015-numeric")
|
|
https://github.com/typst-community/mantodea | https://raw.githubusercontent.com/typst-community/mantodea/main/tests/style/test.typ | typst | MIT License | #import "/src/style.typ"
#show: style.default()
= First Part
#lorem(100)
= Second Part
#lorem(50)
== Section
== Another Section
#lorem(250)
=== Subsection
#lorem(100)
= Third Part
#lorem(250)
|
https://github.com/Skimmeroni/Appunti | https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Metodi%20Algebrici/Interi/Quadrati.typ | typst | Creative Commons Zero v1.0 Universal | #import "../Metodi_defs.typ": *
Calcolare $a^(m) mod n$ "a mano" puó richiedere molto tempo, specialmente
se i numeri in questione sono molto grandi. É peró possibile velocizzare
il procedimento impiegando il *metodo dei quadrati ripetuti*, di seguito
discusso.
Si scriva l'esponente $m$ in base due, ottenendo $m = sum_(i = 0)^(k - 1)
d_(i) 2^(i)$, dove ciascun $d_(i)$ é la $i$-esima cifra della rappresentazione.
Si costruisca poi una tabella come quella seguente:
$ mat(
space, c_(0) & = 1;
d_(k - 1), c_(1) & equiv c_(0)^(2) dot a^(d_(k - 1)) mod n;
d_(k - 2), c_(2) & equiv c_(1)^(2) dot a^(d_(k - 2)) mod n;
dots.v, & dots.v ;
d_(1), c_(k - 1) & equiv c_(k - 2)^(2) dot a^(d_(1)) mod n;
d_(0), c_(k) & equiv c_(k - 1)^(2) dot a^(d_(0)) mod n;
delim: "[",
augment: #1
) $
Risulta $a^(m) equiv c_(k) mod n$.
#example[
Si voglia calcolare $3^(90) mod 91$. Si ha $90_(10) = 1011010_(2)$. Si ha:
$ mat(
space, c_(0) & = 1;
1, c_(1) & equiv 1^(2) dot 3^(1) = 3 mod 91;
0, c_(2) & equiv 3^(2) dot 3^(0) = 9 mod 91;
1, c_(3) & equiv 9^(2) dot 3^(1) = 273 equiv -30 mod 91;
1, c_(4) & equiv (-30)^(2) dot 3^(1) = 2700 equiv -30 mod 91;
0, c_(5) & equiv (-30)^(2) dot 3^(0) = 900 equiv -10 mod 91;
1, c_(6) & equiv (-10)^(2) dot 3^(1) = 300 equiv 27 mod 91;
0, c_(7) & equiv (27)^(2) dot 3^(0) = 729 equiv 1 mod 91;
delim: "[",
augment: #1
) $
Risulta $3^(90) equiv 1 mod 91$
]
|
https://github.com/felsenhower/kbs-typst | https://raw.githubusercontent.com/felsenhower/kbs-typst/master/examples/18.typ | typst | MIT License | #set text(font: "Comic Sans MS")
#show heading: it => block[
#set text(fuchsia)
〜#it.body〜 UwU
]
= Einfühwung
Mein ewstew Text mit Typst!
#lorem(20)
|
https://github.com/RaphGL/ElectronicsFromBasics | https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap2/2_analogy_for_ohms_law.typ | typst | Other | === An analogy for Ohm's Law
Ohm's Law also makes intuitive sense if you apply it to the water-and-pipe analogy. If we have a water pump that exerts pressure (voltage) to push water around a "circuit" (current) through a restriction (resistance), we can model how the three variables interrelate. If the resistance to water flow stays the same and the pump pressure increases, the flow rate must also increase.
#table(
stroke: none,
columns: (auto, auto),
align: left,
[*Pressure* = increase], [*Voltage* = increase],
[*Flow rate* = increase], [*Current* = increase],
[*Resistance* = same], [*Resistance* = same],
)
$ E^arrow.t = I^arrow.t R $
If the pressure stays the same and the resistance increases (making it more difficult for the water to flow), then the flow rate must decrease:
#table(
stroke: none,
columns: (auto, auto),
align: left,
[*Pressure* = same], [*Voltage* = same],
[*Flow rate* = decrease], [*Current* = decrease],
[*Resistance* = decrease], [*Resistance* = increase],
)
If the flow rate were to stay the same while the resistance to flow decreased, the required pressure from the pump would necessarily decrease:
#table(
stroke: none,
columns: (auto, auto),
align: left,
[*Pressure* = decrease], [*Voltage* = decrease],
[*Flow rate* = same], [*Current* = same],
[*Resistance* = decrease], [*Resistance* = increase],
)
$ E_arrow.b = I R_arrow.b $
As odd as it may seem, the actual mathematical relationship between pressure, flow, and resistance is actually more complex for fluids like water than it is for electrons. If you pursue further studies in physics, you will discover this for yourself. Thankfully for the electronics student, the mathematics of Ohm's Law is very straightforward and simple.
- With resistance steady, current follows voltage (an increase in voltage means an increase in current, and vice versa).
- With voltage steady, changes in current and resistance are opposite (an increase in current means a decrease in resistance, and vice versa).
- With current steady, voltage follows resistance (an increase in resistance means an increase in voltage).
|
https://github.com/zenor0/FZU-report-typst-template | https://raw.githubusercontent.com/zenor0/FZU-report-typst-template/main/fzu-report/pages/cover-report-fn.typ | typst | MIT License | #import "../utils/packages.typ": fakebold
#import "../utils/fonts.typ": 字体, 字号, chineseunderline, justify-words
#let report-cover-conf(
studentID: "10210xxxx",
author: "zenor0",
school: "计算机与大数据学院",
major: "信息安全",
advisor: "你的老师",
thesisname: "title",
major-title: "实验报告",
date: (year: 2021, month: 9, day: 1),
) = page(paper: "a4", margin: (top: 2cm+0.7cm, bottom: 1cm, left: 2cm + 0.5cm, right: 2cm))[
#set text(lang: "zh")
#set align(center)
//#hide[#heading(outlined: false, bookmarked: true)[封面]]
#image("../assets/logos/fzu_logo.svg", width: 5cm)
#image("../assets/logos/fzu-text-logo.svg", width: 10cm)
#v(40pt)
#block(height: 2cm, {
text(font: 字体.黑体, size: 40pt, fakebold[#major-title])
})
#v(20pt)
#{
set text(font: 字体.宋体, size: 字号.小二, weight: "regular")
grid(
columns: (3.44cm-1em, 1em, 10cm),
rows: 1.4cm,
justify-words("实验名称", width: 4em), ":", chineseunderline(thesisname),
justify-words("学号", width: 4em), ":", chineseunderline(studentID),
justify-words("姓名", width: 4em), ":", chineseunderline(author),
justify-words("学院", width: 4em), ":", chineseunderline(school),
justify-words("专业", width: 4em), ":", chineseunderline(major),
justify-words("指导教师", width: 4em), ":", chineseunderline(advisor),
// justify-words("起止日期", width: 4em), ":", chineseunderline(date),
)
}
// #date.display()
#set text(font: 字体.宋体, size: 字号.小三)
#date.display("[year]年[month padding:space]月[day padding:space]日")
]
// 测试部分
#report-cover-conf(
date: datetime(year: 2024, month: 9, day: 1),
) |
https://github.com/jens-hj/ds-exam-notes | https://raw.githubusercontent.com/jens-hj/ds-exam-notes/main/lectures/7.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]
}
}
}
}
=== Exact Repair & Regenerating Codes
- Introduction to this from last week
*Functional repair vs exact repair*
==== What
*Exact:* You get exactly what you lost \
- Reed Solomon
- `RAID` systems
*Functional:* Can be used for the same purpose, but aren't exactly the same values (like multiplcations of data?) \
- Regenerating codes (RLNC)
==== How to do Exact Repair with RLNC
_MBR and MSR points are predicated on *functional repair*_ \
RLNC can still be exact repair, but that restricts it in many ways, making it less efficient.
- Fx. E-MBR
- Duplicate each native block. Native and duplicate blocks are in different disks
#image("../img/7/reg-embr.png", width: 30%)
*If* $D_2$ had was lost, it can be rapaired easily #sym.arrow.t
- Fx. Exact repair with known storage structure (kinda MSR)
#image("../img/7/reg-emsr.png", width: 60%)
=== Local Repairability
- XORBAS
- Locality in terms of within same coding?
- Placement is important
#image("../img/7/lr-theorems.png", width: 45%)
==== Example
We want to have locality
#image("../img/7/lr-ex.png", width: 70%)
- If you keep all involved in one code, $x_1,y_1,S_1$ on the same node, then you will lose that data entirely.
- Sparse combinations and its parents _have_ to be stored on different nodes
- With simple clever placement, you can avoid this issue
- Can sustain 2 full node losses, without losing data
- Due to sparse extra combinations
#report-block[
Require better intuition about MDS codes
]
*How to repair* \
#image("../img/7/lr-ex2.png", width: 70%)
- Achieves the optimal performance from theorem 1 & 2 above #sym.arrow.t
#report-block[
He likes the problem from the Facebook setup. \
#ra The _big picture_ view
#image("../img/facebook.png")
_Motivation #sym.arrow.t _ #ra Make sure that network traffic doesn't exceed a certain level
]
==== How Good
- *Reed Solomon 10:4:* 3x storage #ra 2.865x storage = 5% improvement
- *XORBAS 10:6:* 3x storage #ra 2.65x storage = 13% improvement (25% erasure coded)
- Still paying a hefty cost in traffic
#image("../img/7/lr-graph.png", width: 100%)
==== Hybrid Replication & Coding
- Not good from an erasure coding perspective
- Quite restricted
- Lost 8, 9, 10 #ra doomed
- Not nearly as flexible as RS and MDS
- Compromising structure
- _Not_ erasure coded
#gridx(
columns: 2,
image("../img/7/lr-hybrid.png"),
image("../img/7/lr-hybrid-2.png"),
image("../img/7/lr-hybrid-3.png"),
image("../img/7/lr-hybrid-graph.png"),
) |
|
https://github.com/stuxf/basic-typst-resume-template | https://raw.githubusercontent.com/stuxf/basic-typst-resume-template/main/CHANGELOG.md | markdown | The Unlicense | # Basic Resume Changelog
## [v0.1.3](hhttps://github.com/stuxf/basic-typst-resume-template/releases/tags/v0.1.2)
Allow for changing of fonts via initial configuration
## [v0.1.2](hhttps://github.com/stuxf/basic-typst-resume-template/releases/tags/v0.1.2)
Version bump because I'm stupid🐛
## [v0.1.1](hhttps://github.com/stuxf/basic-typst-resume-template/releases/tags/v0.1.1)
Make resume fields optional
## [v0.1.0](hhttps://github.com/stuxf/basic-typst-resume-template/releases/tags/v0.1.0)
Initial Release
|
https://github.com/pncnmnp/typst-poster | https://raw.githubusercontent.com/pncnmnp/typst-poster/master/examples/example_36_48.typ | typst | MIT License | #import "../poster.typ": *
#show: poster.with(
size: "36x48",
title: "A typesetting system to untangle the scientific writing process",
authors: "<NAME>, <NAME>, <NAME>, <NAME>",
departments: "Department of Computer Science",
univ_logo: "./images/ncstate.png",
footer_text: "Conference on Typesetting Systems, 2000",
footer_url: "https://www.example.com/",
footer_email_ids: "<EMAIL>",
footer_color: "ebcfb2",
)
= #lorem(3)
#lorem(100)
#figure(
image("../images/Women_operating_typesetting_machines.png",
width: 50%),
caption: [#lorem(10)]
)
#lorem(60)
= #lorem(2)
#lorem(30)
+ #lorem(10)
+ #lorem(10)
+ #lorem(10)
#lorem(50)
#set align(center)
#table(
columns:(auto, auto, auto),
inset:(10pt),
[#lorem(4)], [#lorem(2)], [#lorem(2)],
[#lorem(3)], [#lorem(2)], [$alpha$],
[#lorem(2)], [#lorem(1)], [$beta$],
[#lorem(1)], [#lorem(1)], [$gamma$],
[#lorem(2)], [#lorem(3)], [$theta$],
)
#set align(left)
#lorem(80)
$ mat(
1, 2, ..., 8, 9, 10;
2, 2, ..., 8, 9, 10;
dots.v, dots.v, dots.down, dots.v, dots.v, dots.v;
10, 10, ..., 10, 10, 10;
) $
== #lorem(5)
#lorem(65)
#figure(
image("../images/Standard_lettering.png",
width: 100%),
caption: [#lorem(8)]
)
= #lorem(3)
#block(
fill: luma(230),
inset: 8pt,
radius: 4pt,
[
#lorem(80),
- #lorem(10),
- #lorem(10),
- #lorem(10),
]
)
#lorem(75)
```rust
fn factorial(i: u64) -> u64 {
if i == 0 {
1
} else {
i * factorial(i - 1)
}
}
```
= #lorem(5)
#lorem(100)
- #lorem(10)
- #lorem(5)
- #lorem(8)
- #lorem(15)
- #lorem(9)
- #lorem(7)
$ sum_(k=1)^n k = (n(n+1)) / 2 = (n^2 + n) / 2 $
#block(
fill: luma(230),
inset: 8pt,
radius: 4pt,
[
#lorem(30),
]
)
#figure(
image("../images/Rosetta_stone.png",
width: 110%),
caption: [#lorem(30)]
)
= #lorem(6)
#lorem(200)
// With content.
#circle[
#set align(center + horizon)
== #lorem(3)
#lorem(100)
$ A = pi r^2 $
$ "area" = pi dot.op "radius"^2 $
$ cal(A) :=
{ x in RR | x "is natural" } $
$ x < y => x gt.eq.not y $
#lorem(50)
]
= #lorem(8)
#lorem(100)
+ #lorem(50)
+ #lorem(60)
+ #lorem(70)
+ #lorem(80)
+ #lorem(90)
#lorem(100)
#figure(
image("../images/CodexRunicus.jpeg",
width: 100%),
caption: [#lorem(10)]
)
#lorem(200)
#set align(center)
== #lorem(4)
#table(
columns:(auto, auto),
inset:(10pt),
[#lorem(4)], [#lorem(2)],
[#lorem(3)], [$theta$],
[#lorem(2)], [$delta$],
[#lorem(1)], [$tau$],
[#lorem(2)], [$ohm$],
)
#set align(left)
= #lorem(5)
#lorem(100)
$ f(x, y) := cases(
1 "if" (x dot.op y)/2 <= 0,
2 "if" x "is even",
3 "if" x in NN,
4 "else",
) $
#lorem(200)
```go
package main
import (
"fmt"
"time"
)
func readword(ch chan string) {
fmt.Println("Type a word, then hit Enter.")
var word string
fmt.Scanf("%s", &word)
ch <- word
}
func timeout(t chan bool) {
time.Sleep(5 * time.Second)
t <- false
}
func main() {
t := make(chan bool)
go timeout(t)
ch := make(chan string)
go readword(ch)
select {
case word := <-ch:
fmt.Println("Received", word)
case <-t:
fmt.Println("Timeout.")
}
}
```
#lorem(100) |
https://github.com/touying-typ/touying | https://raw.githubusercontent.com/touying-typ/touying/main/examples/metropolis.typ | typst | MIT License | #import "../lib.typ": *
#import themes.metropolis: *
#import "@preview/numbly:0.1.0": numbly
#show: metropolis-theme.with(
aspect-ratio: "16-9",
footer: self => self.info.institution,
config-info(
title: [Title],
subtitle: [Subtitle],
author: [Authors],
date: datetime.today(),
institution: [Institution],
logo: emoji.city,
),
)
#set heading(numbering: numbly("{1}.", default: "1.1"))
#title-slide()
= Outline <touying:hidden>
#outline(title: none, indent: 1em, depth: 1)
= First Section
---
A slide without a title but with some *important* information.
== A long long long long long long long long long long long long long long long long long long long long long long long long Title
=== sdfsdf
A slide with equation:
$ x_(n+1) = (x_n + a/x_n) / 2 $
#lorem(200)
= Second Section
#focus-slide[
Wake up!
]
== Simple Animation
We can use `#pause` to #pause display something later.
#meanwhile
Meanwhile, #pause we can also use `#meanwhile` to display other content synchronously.
#speaker-note[
+ This is a speaker note.
+ You won't see it unless you use `config-common(show-notes-on-second-screen: right)`
]
#show: appendix
= Appendix
---
Please pay attention to the current slide number. |
https://github.com/monlie/WeeklyRCBI | https://raw.githubusercontent.com/monlie/WeeklyRCBI/main/weekly.typ | typst | MIT License | #import "@preview/tablex:0.0.6": *
#import "style.typ": 字体, 字号
#let table-stroke = 0.5pt
#let table-inset = (left: 0.4em, right: 0.8em, y: 0.65em)
#let weekly(
doc,
author: "无名氏",
plan: "继续实验",
problem: "无",
writting-date: none,
day-offset: 0,
) = {
let one-week = duration(weeks: 1)
let date-display-format = "[year]年[month]月[day]日"
let writting-date = if writting-date == none {
datetime.today() + duration(days: day-offset)
} else {
writting-date
}
set page(
paper: "a4",
margin: (x: 2.17cm, top: 2.54cm, bottom: 2.4cm)
)
v(1.2em)
set par(justify: true, leading: 1em)
align(center, text(
font: 字体.宋体,
size: 字号.三号,
weight: "semibold",
"西安交通大学类脑智能研究中心\n工作周报"
))
set text(font: 字体.仿宋, size: 字号.小四, weight: "regular")
set underline(offset: 0.1em)
v(-0.8em)
{
set text(size: 字号.小四)
tablex(
columns: (3.42cm, 1fr),
auto-hlines: false,
stroke: table-stroke,
align: left + horizon,
inset: table-inset,
hlinex(),
[填写日期],
[#writting-date.display(date-display-format)],
hlinex(),
[工作时间],
[#(writting-date - one-week).display(date-display-format)------#writting-date.display(date-display-format)],
hlinex(),
[汇报人],
[#author],
)
}
v(-1.2em)
table(
columns: 1fr,
stroke: table-stroke,
inset: table-inset
)[#doc][一周工作计划:#plan][可能存在问题:#problem]
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.