repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/infolektuell/gradle-typst | https://raw.githubusercontent.com/infolektuell/gradle-typst/main/README.md | markdown | MIT License | # Gradle Typst Plugin
[](https://plugins.gradle.org/plugin/de.infolektuell.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.
A Typst document can be compiled from a single _.typ_ file, but a complex project can also contain many files, including data, images, and fonts.
The Typst compiler needs the correct file paths to find everything and compile such projects successfully.
This Gradle plugin offers a way to maintain such projects:
## Features
- [x] Compile multiple documents in parallel for faster builds
- [x] Generate all output formats supported by Typst (PDF, PNG, and SVG)
- [x] Incremental build: Edit files and rebuild only affected documents
- [x] Typst can either be automatically downloaded from GitHub releases, or use a local installation
- [x] Define multiple source sets in one project to produce variants of your content, e.g., versions for printing and web publishing
- [x] Track changes in locally installed Typst packages
- [x] Convert unsupported image formats to format supported by Typst (ImageMagick required)
- [x] Merge generated PDF files into one file using [PDFBox]
- [x] Works well with Gradle's [Configuration Cache] and [Build cache]
## Requirements
The plugin expects these tools being installed locally:
- [ImageMagick] for image conversion (Optional)
## Usage
### Plugin setup
After creating a new Gradle project with `gradle init`, the plugin needs to be configured in _build.gradle.kts_:
```gradle kotlin dsl
plugins {
// Good practice to have some standard tasks like clean, assemble, build
id("base")
// Apply the Typst plugin
id("de.infolektuell.typst") version "0.4.0"
}
// The release tag for the Typst version to be used, defaults to latest stable release on GitHub
typst.version = "v0.12.0"
```
### Adding sources
A source set is a directory in your project under _src_ that may contain subfolders for Typst files, data, images, and fonts.
The Typst files that should be treated as input documents to be compiled must explicitly be configured.
There can be one or as many of them as needed.
Having multiple source sets can be useful if multiple variants of similar content should be produced, especially for data-driven documents.
Otherwise, a single source set is sufficient.
So let's add two of them in _build.gradle.kts_:
```gradle kotlin dsl
// The source sets container
typst.sourceSets {
// Sources for documents intended for web publishing in src/web folder
val web by registering {
// The files to compile (without .typ extension)
documents = listOf("frontmatter", "main", "appendix", "backmatter")
// Values set in this map are passed to Typst as --input options
inputs.put("version", version.toString())
}
// Sources for documents intended for printing in src/printing folder
val printing by registering {
documents = listOf("frontmatter", "main", "poster", "appendix", "backmatter")
}
}
```
In a source set folder, these subfolders are watched for changes:
- _data_: Files in YAML, TOML or JSON format
- _fonts_: Additional font files for your documents
- _images_: Image files included in your documents
- _typst_: Typst files, can be documents or contain declarations for importing
Running `gradlew build` now will compile all documents into _build/typst/<source set>/_.
### Shared sources
If multiple source sets have many files in common, they could go into their own source set without documents.
The source sets using these files can depend on this new shared source set.
```gradle kotlin dsl
typst.sourceSets {
// Sources used by other source sets in src/shared
val shared by registering
val printing by registering {
// Shared sources are also watched when printing documents are compiled
addSourceSet(shared)
}
}
```
### Output formats
Currently, Typst can output a document as PDF or as a series of images in PNG or SVG format.
The desired output options can be configured per source set, e.g., PDF for printing and PNG for web publishing.
```gradle kotlin dsl
typst.sourceSets {
val web by registering {
documents = listOf("frontmatter", "main", "appendix", "backmatter")
format {
// The PNG format is right
png {
enabled = true
// Customized resolution (144 by default)
ppi = 72
}
// Disable the PDF format which is active by default
pdf.enabled = false
}
}
val printing by registering {
documents = listOf("frontmatter", "main", "poster", "appendix", "backmatter")
format {
// Setting this creates a merged PDF file from the documents list
pdf.merged = "thesis-$version"
}
}
}
```
### Images
Image files in _src/<source set>/images_ are copied to _build/generated/typst/images_.
If the format ist not supported by Typst, they are converted to png before copying.
Typst runs after image processing, so the images can be referenced by their path in Typst files.
Typst receives the project directory as root (not the root project), so absolute import paths start with _/src/_.
### Fonts
A document receives the fonts subfolders of their source set and added shared source sets as font paths.
Since version 0.2.0 of this plugin, system fonts are ignored by default for higher reproducibility.
If a Typst version below 0.12.0 is in use or if system fonts should be considered, this must be turned off per configuration:
```gradle kotlin dsl
import de.infolektuell.gradle.typst.tasks.TypstCompileTask
// Configure all typst tasks
tasks.withType(TypstCompileTask::class) {
// Override the convention (false by default)
useSystemFonts = true
}
```
### Creation date
For better build reproducibility, Typst accepts a fixed creation date in UNIX timestamp format.
See [SOURCE_DATE_EPOCH specification] for a format description.
If no timestamp is set, it is determined by Typst.
```gradle kotlin dsl
import de.infolektuell.gradle.typst.providers.GitCommitDateValueSource
// Use the included utility to get a timestamp from git commit
val timestamp = providers.of(GitCommitDateValueSource::class) {
parameters {
revision = "main"
}
}
// Configure the Typst extension with this timestamp (eagerly for configuration cache compatibility)
typst.creationTimestamp = timestamp.get()
```
### Local packages
Typst 0.12.0 added a CLI option to pass the path where local packages are stored.
This plugin sets this explicitly to Typst's platform-dependent convention, so both are working with the same files.
To use an older version of Typst, you have to opt-out of this behavior.
```gradle kotlin dsl
import de.infolektuell.gradle.typst.tasks.TypstCompileTask
// Configure all typst tasks
tasks.withType(TypstCompileTask::class) {
// Unset the package path
packagePath.unset()
// Optionally add the local packages folder from the typst extension to the source set to keep change tracking
sourceSets.register("main") {
typst.add(localPackages)
}
}
```
## License
[MIT License](LICENSE.txt)
[typst]: https://typst.app/
[configuration cache]: https://docs.gradle.org/current/userguide/configuration_cache.html
[build cache]: https://docs.gradle.org/current/userguide/build_cache.html
[imagemagick]: https://imagemagick.org/
[pdfbox]: https://pdfbox.apache.org/
[SOURCE_DATE_EPOCH specification]: https://reproducible-builds.org/specs/source-date-epoch/
|
https://github.com/PmaFynn/cv | https://raw.githubusercontent.com/PmaFynn/cv/master/src/content/en/education.typ | typst | The Unlicense | #import "../../template.typ": *
#cvSection("Education")
#cvEntry(
title: [M.Sc in Information Systems],
organisation: [Universität Münster],
//TODO: insert uni muenster logo here
logo: "",
date: [10/2023 - Present],
location: [Münster, Germany],
description: list(
[Pursuing advanced studies in Information Systems Development and Data Science techniques]
),
//tags: ("Information Systems Development", "Data Analytics")
)
#divider()
#cvEntry(
title: [B.Sc in Information Systems],
organisation: [Universität Münster],
//TODO: insert uni muenster logo here
logo: "",
date: [10/2019 - 03/2023],
location: [Münster, Germany],
description: list(
[Practical bachelor thesis: Integration of Frontend Testing into a CI/CD Pipeline; Grade: 1.0],
//[Final grade: 2.0],
),
)
/*
#divider()
#cvEntry(
title: [General University Entrance Qualification],
organisation: [Gymnasium am Moltkeplatz],
//TODO: insert uni muenster logo here
logo: "",
date: [08/2011 - 06/2019],
location: [Krefeld, Germany],
description: list(
[Major Subjects (ger.: Leistungskurse): Mathematics, Physics],
),
)
*/
|
https://github.com/jdpieck/oasis-align | https://raw.githubusercontent.com/jdpieck/oasis-align/main/0.1.0/oasis-align.typ | typst | #let oasis-align(
int-frac: 0.5,
tolerance: 0.001pt,
max-iterations: 50,
int-dir: 1,
debug: false,
item1,
item2,
) = context {
// Debug functions
let error(message) = text(red, weight: "bold", message)
let heads-up(message) = text(orange, weight: "bold", message)
// Check that inputs are valid
if int-frac <= 0 or int-frac >= 1 {return(error("int-frac must be between 0 and 1!"))}
if int-dir != -1 and int-dir != 1 {return(error("Direction must be 1 or -1!"))}
// use layout to measure container
layout(size => {
let container = size.width
let gutter = if grid.column-gutter == () {0pt}
else {grid.column-gutter.at(0)}
let width1 // Bounding width of item1
let width2 // Bounding width of item2
let height1 // Measured height of item1 using width width1
let height2 // Measured height of item2 using width width2
let fraction = int-frac
let upper-bound = 1
let lower-bound = 0
let diff // Difference in heights of item1 and item2
let dir = int-dir
let min-dif = container
let best-fraction
let n = 0
let swap-check = false
// Loop max to prevent infinite loop
while n < max-iterations {
n = n + 1
// Set starting bounds
width1 = fraction*(container - gutter)
width2 = (1 - fraction)*(container - gutter)
// Measure height of content and find difference
height1 = measure(block(width: width1, item1)).height
height2 = measure(block(width: width2, item2)).height
diff = calc.abs(height1 - height2)
// Keep track of the best fraction
if diff < min-dif {
min-dif = diff
best-fraction = fraction
}
// Display current values
if debug [ + Diff: #diff #h(1fr) item1: (#width1, #height1) #h(1fr) item2: (#width2, #height2)]
// Check if within tolerance
if diff < tolerance or n >= max-iterations {
if debug {heads-up("Tolerance reached!")}
grid(columns: (width1, width2), item1, item2)
break
}
// Use bisection method by setting new bounds
else if height1*dir > height2*dir {upper-bound = fraction}
else if height1*dir < height2*dir {lower-bound = fraction}
else {error("Unknown Error")}
// Bisect length between bounds to get new fraction
fraction = (lower-bound+upper-bound)/2
// If there is no solution in the inital direction, change directions and reset the function.
if width1 < 1pt or width2 < 1pt {
// If this is the second time that a solution as not been found, termiate the function.
if swap-check {error([The selected content is not compatible. To learn more, turn on debug mode by adding
#h(.4em) #box(outset: .2em, fill: luma(92%), radius: .2em, ```typst debug: true```) #h(.4em)
to the function]); break}
swap-check = true
dir = dir *-1
fraction = int-frac
upper-bound = 1
lower-bound = 0
n = 0
}
// Change fraction so value with least height difference if tolereance was not achieved
if n >= max-iterations - 1 {fraction = best-fraction}
}
if n >= max-iterations and debug {error("Maximum number of iterations reached!")}
})
}
#let oasis-align-images(image1, image2) = context {
// Find dimentional ratio between images
let block1 = measure(image(image1, width: 1in))
let block2 = measure(image(image2, width: 1in))
let ratio = (block1.width/block1.height)*block2.height/block2.width
layout(size => {
// Measure size of continaner
let container = size.width
let gutter = if grid.column-gutter == () {0pt}
else {grid.column-gutter.at(0)}
// Set widths of images
let calcWidth1 = (container - gutter)/(1/ratio + 1)
let calcWidth2 = (container - gutter)/(ratio + 1)
// Display images in grid
grid(columns: (calcWidth1, calcWidth2), gutter: gutter,
image(image1),
image(image2)
)
})
}
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/bubble/0.1.0/README.md | markdown | Apache License 2.0 | # Bubble
Simple and colorful template for [Typst](https://typst.app). This template uses a main color (default is `#E94845`) applied to list items, links, inline blocks and headings. You can also set a custom table of content title. Every page is numbered and hase the title of the document and the name of the author at the top.
You can see an example PDF [here](https://github.com/hzkonor/bubble-template/blob/main/main.pdf).
## Usage
You can use this template in the Typst web app by clicking "Start from template" on the dashboard and searching for `bubble`.
Alternatively, you can use the CLI to kick this project off using the command
```bash
typst init @preview/bubble
```
Typst will create a new directory with all the files needed to get you started.
## Configuration
This template exports the `bubble` function with the following named arguments:
- `title`: Title of the document
- `subtitle`: Subtitle of the document
- `author`: Name of the author(s)
- `affiliation`: It is supposed to be the name of your university for example
- `year`: The year you're in
- `class`: For which class this document is
- `date`: Date of the document, current date if none is set *default is current date*
- `logo`: Path of the logo displayed at the top right of the title page, must be set like an image : `image("path-to-img")` *default is none*
- `main-color`: Main color used in the document *default is `#E94645`*
- `alpha`: Percentage of transparency for the bubbles on the title page *default is 60%*
This template also exports these functions :
- `blockquote` : Function that highlights quotes with a grey bar at the left
- `primary-color` : to use your main color
- `secondary-color` : to use your secondary color (which is your main color with the alpha transparency set)
If you want to change an existing project to use this template, you can add a show rule like this at the top of your file:
```typ
#import "@preview/bubble:0.1.0": *
#show: bubble.with(
title: "Bubble template",
subtitle: "Simple and colorful template",
author: "hzkonor",
affiliation: "University",
date: datetime.today().display(),
year: "Year",
class: "Class",
logo: image("logo.png")
)
// Your content goes here
``` |
https://github.com/NorthSecond/Auto_Typst_Resume_Template | https://raw.githubusercontent.com/NorthSecond/Auto_Typst_Resume_Template/main/readme.md | markdown | MIT License | # Typst 中文简历模板
## 介绍
一个借助 Github Actions 实现自动部署的 Typst 简历模板。效果如下(也可参考 Release 页面中的 PDF 文件):
| [中文示例](https://github.com/NorthSecond/Auto_Typst_Resume_Template/releases/download/Release-template-1.0.0/default.pdf) | [英文示例](https://github.com/NorthSecond/Auto_Typst_Resume_Template/releases/download/Release-template-1.0.0/Resume.pdf)|
|:---:|:---:|
|  | |
### 字体
中文简历使用的是 **思源宋体** 的谷歌版本,对于在线使用的用户来说,并不需要进行安装操作,对于本地使用的用户,可以参照下一节中的内容进行字体的安装;英文部分使用 Centaur 字体。
### <del>证件照支持</del>(暂无)
> 目前没有解决插入证件照之后的一些小小的设计问题,所以暂时不支持插入证件照,如果将 `init` 函数中的 `pic_path` 设为非空值可能会出现一些小问题。
目前主要遇见的问题是 Typst 的元素没有找到一个像 LaTeX 一样浮动在页面之上指定位置的方法,因此如果插入图片的话可能会导致姓名不能居中等问题,目前在想办法使用指定size溢出的方式来解决这个问题。
### Github Actions
对于本地没有安装 Typst 的使用者,可以通过 Github Actions 实现自动部署。在每一次提交后,Github Actions 会自动运行 Typst 并将生成的 PDF 文件打包提供下载。
## 使用方式
### Typst Web(推荐)
我制作了一个 [typst.app](https://typst.app) 上的在线项目,[链接在此](https://typst.app/project/r4XMUB3ENQUH7zWiuK7_tO)。可以复制该项目到自己的账号中进行使用,即可完成在线编辑和即时预览。
## Github 仓库
1. 在仓库的右上角点击 "Use this template" 按钮,选择新建一个您的仓库;
2. (可选)在 `Github Actions` 控制界面打开本仓库的 Github Action 功能;
3. 修改 `src` 文件夹下的文件为你的简历内容。
### 本地编译
#### 字体安装
对于本地没有安装谷歌版思源宋体 (`Noto Serif CJK SC`)的用户,需要下载改字体才能正常编译中文版简历,可选只在本仓库使用或者全局安装。下载链接:[Noto Serif CJK SC](https://fonts.google.com/noto/specimen/Noto+Serif+SC),对于访问谷歌受限的用户,可以在国内镜像站如 [清华大学镜像](https://mirrors.tuna.tsinghua.edu.cn/github-release/googlefonts/noto-cjk/Noto%20Serif%20CJK%20Version%202.002%20(OTF,%20OTC,%20Super%20OTC,%20Subset%20OTF,%20Variable%20OTF_TTF)/09_NotoSerifCJKsc.zip) 下载。
对于只在本项目中使用该字体的用户,可以将字体文件放在项目根目录下,`Makefile` 中已经制定了编译的字体路径。
对于全局安装的用户,Windows 用户可以右键字体文件选择 “安装” 或者 “为所有用户安装”。 Linux 用户可以检查自己的发行版包管理器是否有 `fonts-noto-cjk` 或者 `fonts-noto-cjk-extra` 这两个包,如果有的话可以直接安装。安装后请使用 `fc-cache -fv` 命令刷新字体缓存。
#### 编译
在有 Typst 和 GNU Make 的本地环境中,可以通过 Typst 命令行工具进行编译。
项目提供的 Makefile 中包含了以下几个定义目标:
- `make all`:清理文件夹中的所有 .pdf 文件,然后编译中文和英文版本的简历文件;
- `make clean`:清理文件夹中的所有 .pdf 文件;
- `make zh`:编译中文版本的简历文件;
- `make en`:编译英文版本的简历文件;
### Github Actions
项目配置了自动部署的 Github Actions,可以在每次提交后自动运行 Typst (执行的命令是 `make all`)并将生成的 PDF 文件打包提供下载。可以在 `Actions` 标签页查看运行结果,并在对应运行时的 `Summary` 页面的 `Artifacts` 部分下载生成的 PDF 文件压缩包。

### Github Release
项目配置了 Github Release,对于正式版本的发布,使用 `git tag` 功能打上版本号标签,Github Actions 会自动将生成的 PDF 文件发布到 Github Release 页面。
> 请注意,使用 `git tag` 功能时,需要在本地使用 `git push --tags` 命令将标签推送到远程仓库。
## TBD
- [x] 英文版示例与字体
- [ ] 证件照插入的解决方案
|
https://github.com/ralphmb/typst-template-stats-dissertation | https://raw.githubusercontent.com/ralphmb/typst-template-stats-dissertation/main/writeup/sections/appendix.typ | typst | Apache License 2.0 | #let c = counter("appendix")
#let appendix(it) = block[
#c.step()
#heading([Appendix #c.display("1"): #it], numbering: none, outlined:false)
]
// The above function automatically numbers the appendices
//
#appendix([My Code])
A Python implementation of fizzbuzz. \
#raw(read("../assets/code/fizzbuzz.py"),lang:"Python")
#appendix([Other Stuff])
#lorem(100) |
https://github.com/txtxj/Formal-Methods-Typst | https://raw.githubusercontent.com/txtxj/Formal-Methods-Typst/main/formal_method_template.typ | typst | #let proof_line(formula, theory, x0, predicate_flag) = {
if predicate_flag {
columns(3)[
#x0
#colbreak()
#formula
#colbreak()
#{ if theory == [p] {
[premise]
} else if theory == [a]{
[assumption]
} else {
theory
}}
]
} else {
columns(2)[
#formula
#colbreak()
#{ if theory == [p] {
[premise]
} else if theory == [a]{
[assumption]
} else {
theory
}}
]
}
}
#let inner_proof(start_index, start_line_num, end_line_num, predicate_flag, lines) = {
let index = 0
let line_num = start_line_num
let pre_line = none
let x_0_line = none
let assuption_flag = false
block(width: 100%)[
#{
let value_type = 0
for (index, value) in lines.pos().enumerate() {
if index < start_index {
continue
}
if line_num < start_line_num and value != [+] and value != [x] {
line_num += 0.5
continue
}
else if line_num < start_line_num and (value == [+] or value == [x]) {
line_num -= 0.5
continue
}
if line_num >= end_line_num {
return
}
if assuption_flag {
assuption_flag = false
rect(width: 100%, inset: (top: 0pt, bottom: 0pt, left: 10pt, right: 10pt), outset: (top: 5pt, bottom: 5pt))[#inner_proof(index + 1, line_num, line_num + value, predicate_flag, lines)]
start_line_num = line_num + value
} else if value_type == 1 {
value_type = 0
if value == [x] {
x_0_line = pre_line
} else {
line_num += 1
proof_line(pre_line, value, x_0_line, predicate_flag)
x_0_line = none
}
} else if value != [+]{
value_type = 1
pre_line = value;
} else {
assuption_flag = true
}
}
}
]
}
#let gen_line_code(row_num) = {
block(width: 100%)[
#{
for i in range(row_num) {
columns(1)[
#{$#(i+1).$}
]
}
}
]
}
#let proof(..lines) = {
let row_num = 0
let predicate_flag = false
for value in lines.pos() {
if value == [x] {
row_num -= 0.5
predicate_flag = true
} else if value == [+] {
row_num -= 0.5
} else {
row_num += 0.5
}
}
grid(columns: (0.1fr, 0.9fr), gen_line_code(int(row_num)), inner_proof(0, 0, 9999, predicate_flag, lines))
} |
|
https://github.com/dyc3/ssw-555-agile-methods | https://raw.githubusercontent.com/dyc3/ssw-555-agile-methods/main/lib/glossary.typ | typst | // copied from: https://github.com/typst/typst/issues/755#issuecomment-1542595624
// modified to taste
#import "@preview/in-dexter:0.0.5": *
// Generate a regex that matches all the words in glossary named filename
#let glossaryWords(filename) = {
let pipeList = "(?i:" // Match case insensitively
for word in yaml("../" + filename).keys() {
pipeList += "\b" + word + "\b|" // Stop at word boundaries to not match inside other words
}
return regex(pipeList.slice(0, pipeList.len()-1) + ")") // Remove trailing pipe & close parenthesis
}
// Return the position of the word word in the glossary filename as dictionaries don't implement find-like methods
#let glossaryPosition(filename, word) = {
let count = 0
for key in yaml("../" + filename).keys() {
count += 1
if lower(key) == lower(word) {return count} // Search case-insensitively by lowering everything
}
assert(false, message: word + " not found in glossary but matched in regex") // Debug
}
// For a given word and glossary file, return the word augmented with a link to the glossary
#let glossaryShow(filename, word) = {
word = repr(word)
word = word.trim(regex("\s|\[|\]")) // Trim brackets generated by repr() and whitespaces
return {
show link: set underline(stroke: 0pt)
// Insert an invisible char into the word to prevent show from looping on itself
let printableWord = word.first() + "" + word.slice(1)
link(label("glossary"), printableWord)
index(lower(printableWord))
}
}
// Display the words of the glossary with their definition & their eventual web links
#let glossary(filename, title: "Glossary") = {
let data = yaml("../" + filename)
if data.len() > 0 [
#heading(title, numbering: none) #label("glossary")
]
for (word, info) in data {
[/ #word: #info.definition\ → #if "link" in info {link(info.link)}]
}
} |
|
https://github.com/xdoardo/co-thesis | https://raw.githubusercontent.com/xdoardo/co-thesis/master/thesis/chapters/recursive/co-induction.typ | typst | #import "/includes.typ": *
== Induction<section-recursive-induction>
The easiest and most intuitive inductive datatype is that of natural numbers. In
Agda, one may represent them as shown in @code-nat.
#code(label: <code-nat>)[
```hs
data Nat : Set where
zero : Nat
succ : Nat -> Nat
```
]
A useful interpretation of inductive datatypes is to imagine concrete instances
as trees reflecting the structure of the constructors, as shown in
@fig-nat-tree; of course, this interpretation is not limited to _degenerate_
trees and it can be used to represent any kind of inductive structure such as
lists (which shall be binary trees), trees themselves and so on.
#figure(canvas({
import draw: *
tree.tree(
([zero], ([succ zero], ([succ succ zero], [...]))),
spread: 2.5,
grow: 1.5,
draw-node: (node, _) => {
circle((), radius: .45, stroke: none)
content((), node.content)
},
draw-edge: (from, to, _) => {
line(
(a: from, number: .6, abs: true, b: to),
(a: to, number: .6, abs: true, b: from),
mark: (end: ">"),
)
},
title: "tree",
)
}), caption: "Structure of a natural number as tree of constructors")
<fig-nat-tree>
Our interest is not limited to the definition of inductive datatypes, we also
want to prove their properties: the correct mathematical tool to do so is the
_principle of induction_, which has been implicitly used, in history, since the
medieval times of the Islamic golden age, even if some works, such as
@acerbi-plato, claim that Plato's Parmenide contained implicit inductive proofs
already. Its modern version, paired with an explicit formal meaning, goes back
to the foundational works of Boole, De Morgan and Peano in the 19th century.
Suppose we want to prove a property $P$ of natural numbers. This property can
be, for example, @thm-powers[Theorem].
#theorem(label: <thm-powers>)[
For all natural numbers $n$, the sum of the first $n$ powers of $2$ is $2^n -1$,
or
#align(center, $forall n , sum_(i = 0)^(n-1) 2^i eq.triple 2^n - 1$)
]
For the sake of the explaination, we give a proof of @thm-powers in a
discursive manner, so that we are able to delve into each step.
A proof by induction begins by proving a base case (typically $0$ or $1$, but
it is not necessarily always the case); we choose to prove it for $n = 0$: the
sum of the first $0$ powers of $2$ is $0$, and $2^0 -1 = 1 -1 = 0$, therefore
the case base is proved.
The power of the induction principle shows up here. The prover now assumes that
the principle holds for every number up to $n$ (this is called the _inductive
hypothesis_) and using this fact, which in this case is that $sum_(i = 0)^(n-1)
2^i = 2^n$, the prover shows that the statement holds for $n+1$ as well:
#align(center, $sum_(i = 0)^n 2^i = sum_(i = 0)^(n-1) 2^i + 2^n = 2^n + 2^n - 1 = 2^(n+1) - 1$)
#linebreak()
The principle of induction is not limited to natural numbers. Every recursive
type has an _elimination principle_ which prescribes how to use terms of such
type that entails a *structural recursive definition* and a *principle of
structural induction*. This, in turn, implies that there exists a well-founded
relation inducing a well-order on the terms of the type: a well-founded
relation assures that, given a concrete instance of an inductive term,
analysing its constructor tree we will eventually reach a base case (`zero` in
the case of natural numbers, `nil` in the case of lists, the root node in case
of trees). Such a relation implies that a proof that examines a term in a
descending manner will eventually terminate.
There are many cases in which, however, we might want to express theorems about
structures that are not well-founded. A simple example of this is the following:
consider the infinite sequence of natural numbers
#align(center, [$s eq.def 0, 1, 2, 3, 4, ...$])
#linebreak()
The sequence $s$ certainly is a mathematical object that we can show theorems
about: for example, we might want to show that there is no element that is
greater than any other, but how are we to define such an object using
induction? An idea might be that of using lists as defined in @code-list.
#code(label: <code-list>)[
//typstfmt::off
```hs
data List (A : Set) : Set where
[] : List A
_::_ : A -> List A -> List A
```
//typstfmt::on
]
However, concrete terms which we can actually build up cannot be infinite;
instead, they must be a finite sequence of applications of constructors. In
other words, the tree of constructors of a concrete list we can come up with is
necessarily of bounded (finite) height.
We could try to trick Agda to define a potentially infinite sequence such as
$s$ as shown in @code-infinite-list. Then, we could represent $s$ as
`infinite-list 0`.
#code(label: <code-infinite-list>)[
//typstfmt::off
```hs
infinite-list : Nat -> List Nat
infinite-list n = n ∷ (infinite-list (n + 1))
-- Termination checking failed for the following functions:
-- infinite-list
-- Problematic calls:
-- infinite-list (n + 1)
-- (at /home/ecmm/t.agda:28,25-38)
```
//typstfmt::on
]
It turns out, however, that such a definition is not acceptable for Agda's
termination checker. One may argue that this is Agda's fault and that, for
example, Haskell may be completely fine with such a definition (and it is
indeed, as it employs a completely different strategy with regard to
termination checking). In the end, such a definition is indeed _recursive_.
== Coinduction<section-recursive-coinduction>
However, we must notice that a "fully constructed" infinite list such as $s$
does not have a base case and a possible inductive definition cannot be
well-founded. It turns out, then, that it is induction itself that can be
inadequate to reason about some infinite structures. It is important to remark,
however, that in general it is not problematic to reason about infinite
structures, and it is not infinity per sé that makes induction an inadequate
tool.
What induction does is build potentially infinite objects starting from
constructors. *Coinduction*, on the other hand, allows us to reason about
potentially infinite objects by describing how to observe (or destruct) them, as
opposed to how to build them. Following the previous analogy where inductive
datatypes were seen as constructor trees of finite height and functions or
inductive proofs operated on the nodes of this tree, we can see coinduction as a
means to operate on a tree of potentially infinite height by defining how to
extract data from each level of the tree.
While induction has an intuitive meaning and can be explained easily,
coinduction is arguably less intuitive and requires more background to grok
and, as anticipated in the introduction of this chapter, formal explainations
draw inspiration from various and etherogeneous fields of mathematics and
computer science.
In this work we do not have the objective to give a formal and thorough
explaination of coinduction (which can be found, for example, in works such as
@sangiorgi-coinduction and @sangiorgi-advanced-coinduction); instead, we will
give a contained description of the relation between induction and coinduction,
then move to a more formal description using fixed points, with the only
objective of providing an intuition of what is the theoretical background
of coinduction.
Take again the example of lists as prescribed in @code-list. We can express
such a definition using inference rules as shown in @list-rules.
#figure(
tablex(columns: (auto, auto, auto, auto, auto),
align: horizon,
auto-lines: false,
prooftrees.tree(
prooftrees.axi(pad(bottom: 5pt, [$A : "Type"$])),
prooftrees.uni[$"nil" : "List" A$],
),
[_nil_],
h(20pt),
prooftrees.tree(
prooftrees.axi(pad(bottom: 5pt, [$A : "Type"$])),
prooftrees.axi(pad(bottom: 5pt, [$x s : "List" A$])),
prooftrees.axi(pad(bottom: 5pt, [$x : A$])),
prooftrees.nary(3)[$"cons" x space x s : "List" A$],
),
[_cons_],
),
supplement: "Table",
caption: "Inference rules for the polymorphic List type"
)<list-rules>
This inference rules are _satisfied_ by some set of values. Suppose that the type
$A$, interpreted as a _set_, is $A := {x, y, z}$; an example of a set satisfying
the rules in @list-rules is
#linebreak()
#align(center, $S = {"nil", "cons" x "nil", "cons" y "nil", "cons" z "nil", "cons" x space ("cons" x "nil"), "cons" y space ("cons" x "nil"), ...}$)
#linebreak()
The set $S$ is exactly the inductive interpretation of the inference rules: in
$S$ there are those elements that follow the rules and those elements only.
Among all the sets that satisfy the rules, $S$ is the *smallest* one; however,
it is not the only possibility. We could take, for example, the *biggest* set
that follows that prescription and has every possible element of the universe
in it: of course, such a set, say $B$, also follows the inference rules in
@list-rules. The set $B$ is the coinductive interpretation of the inference
rules above.
Consider now dropping the rule _nil_ from @list-rules. The set $S$, the
inductive interpretation, would be the empty set, as no base case is satisfied
and there is no "starting point" to build new lists. On the other hand the set
$B$ would still contain lots of lists, in particular infinite lists.
=== Induction and coinduction as fixed points<subsection-fixed-points>
The mathematical explaination is largely inspired by @pous-coinduction,
@pierce-types and @leroy-coinductive-bigstep and follows a "bottom-up" style of
exposition: we start with concepts that have no apparent connection with
(co-)induction, and reveal near the end how a specific interpretation of the
matter exposed can give an intuition of what coinduction is (as well as a
formal definition in a specific field of mathematics).
Let $U$ be a set such that there exists a binary relation $<= subset.eq U times
U$ that is reflexive, antisymmetric and transitive; we call $< U , <= >$ a
partially ordered set. Note that we concede the possibility for two elements of
$U$ to be incomparable without being the same. Formally:
#definition(
name: "Partially ordered set",
label: <def-poset>
)[
Let $U$ be a set. $U$ is called a partially ordered set if there exists a
relation $<= subset.eq U times U$
such that for any $a, b, c in U$ $<=$ is
1. *reflexive*: $a <= a$
2. *antisymmetric*: $a <= b and b <= a => a = b$
3. *transitive*: $a <= b and b <= c => a <= c$
We call the pair $<U, <= >$ a partial order.
]
An example of a partially ordered set is the power set $2^X$ of any set $X$
with $<=$ being the usual notion of inclusion, as shown in @fig-poset-powerset.
This partially ordered set is in fact a *lattice* as it has a least element
(the empty set $emptyset$) and a greatest element (the entire set $U = {a, b,
c}$). Furthermore, the absence of paths between the sets ${a, b}$ and ${a, c}$
is an exemplification of the fact that two elements of $U$ may be incomparable.
#figure(
render(width: 35%, "
digraph mygraph {
\"{a, b}\" -> \"{a, b, c}\"
\"{a, c}\" -> \"{a, b, c}\"
\"{b, c}\" -> \"{a, b, c}\"
\"{b}\" -> \"{a, b}\"
\"{a}\" -> \"{a, b}\"
\"{a}\" -> \"{a, c}\"
\"{c}\" -> \"{a, c}\"
\"{b}\" -> \"{b, c}\"
\"{c}\" -> \"{b, c}\"
\"∅\" -> \"{a}\"
\"∅\" -> \"{b}\"
\"∅\" -> \"{c}\"
}"),
caption: [Hasse diagram for the partially ordered set created by the inclusion relation
(represented by the arrows) on a set $U = {a, b, c}$],
)<fig-poset-powerset>
#definition(
name: "Lattice",
label: <def-lattice>
)[
A lattice is a partial order $< U, <= >$ for which every pair of elements has a
greatest lower bound and least upper bound, that is
#align(
center,
$forall a in U, forall b in U, space exists s in U, exists i in U, space sup({a, b}) = s and inf({a, b}) = i$,
)
We also give a specific infix notation for the $"sup"$ and $"inf"$ when applied
to binary sets:
#align(
center,
[$a and b space eq.def space sup({a, b}) space $ and $space a or b space eq.def space inf({a,b})$],
)
which we name $"meet"$ and $"join"$, respectively.
]
Lattices are defined _complete_ if for every subset $L subset.eq U$ there are two
elements $"sup"(L)$ and $"inf"(L)$ such that the first is the smallest element
greater than or equal to all elements in $L$, while the second is the greatest
element less than or equal to all elements in $L$. Formally:
#definition(
name: "Complete lattice",
label: <def-complete-lattice>
)[
A complete lattice is a lattice for which every subset of the carrier set has a
greatest lower bound and least upper bound, that is
#align(
center,
$forall L subset.eq U, space exists s in U, exists i in U, space sup(L) = s and inf(L) = i$,
)
Complete lattices always have a bottom element
#align(center, $bot eq.def inf(emptyset)$)
and a top element
#align(center, $top eq.def sup(U)$)
]
We also give a characterization of a specific kind of functions on $U$ in @def-monotone-on-lattice.
#definition(
name: "Monotone function on complete lattices",
label: <def-monotone-on-lattice>
)[
Let $<U, <= >$ be a complete lattice. A function $f : U -> U$ is monotone if it
preserves the partial order:
#align(center, $forall a in U, forall b in U, space a <= b => f(a) <= f(b)$)
We write $[U -> U]$ to denote the set of all monotone functions on $<U, <= >$.
]
#definition[
Let $<U , <= >$ be a complete lattice; let $X$ be a subset of $U$ and let
$f in [U -> U]$. Then we say that
1. $X$ is $bold(f"-closed")$ if $f(X) subset.eq X$, that is, the output set is
included in the input set;
2. $X$ is $bold(f"-consistent")$ if $X subset.eq f(X)$, that is, the input set is
included in the output set; and
3. $X$ is a _fixed point_ of $f$ if $f(X) = X$.
]
For example (taken from @pierce-types), consider the following function on $U = {a, b, c}$:
#align(center, tablex(
columns: 2,
gutter: 4pt,
align: center,
auto-vlines: false,
auto-hlines: false,
[$e_1(emptyset) = {c}$],
[$e_1({a,b}) = {c}$],
[$e_1({a}) = {c}$],
[$e_1({a,c}) = {b, c}$],
[$e_1({b}) = {c}$],
[$e_1({b,c}) = {a, b, c}$],
[$e_1({c}) = {b, c}$],
[$e_1({a, b, c}) = {a, b, c}$],
))
There is only one $e_1"-closed"$ set, ${a, b, c}$, and four $e_1"-consistent"$
sets, $emptyset, {c}, {b,c}, {a,b,c}$.
#theorem(
name: "Knaster-Tarski",
label: <thm-knaster-tarski>
)[
Let $U$ be a complete lattice and let $f in [U -> U]$. The set of fixed points
of $f$, which we define $"fix"(f)$, is a complete lattice itself. In particular
1. the least fixed point of $f$ (noted $mu F$), which is the bottom element of $"fix"(f)$,
is the intersection of all $f"-closed"$ sets.
2. the greatest fixed point of $f$ (noted $nu F$), which is the top element of $"fix"(f)$,
is the union of all $f"-consistent"$ sets.
]
#proof[ Omitted.#h(100%)]
From the example above, we have that $mu e_1 = nu e_1 = {a, b, c}$.
#corollary(label: <cor-ind-coind>)[
1. *Principle of induction*: if $X$ is $f"-closed"$, then $mu f subset.eq X$;
2. *Principle of coinduction*: if $X$ is $f"-consistent"$, then $X subset.eq nu f$.
#h(100%)
]
Now that all the mathematical framework is in place, we can make a concrete
example.
#figure(
tablex(columns: (auto, auto, auto, auto, auto),
align: horizon,
auto-lines: false,
prooftrees.tree(
prooftrees.axi([]),
prooftrees.uni[$epsilon$],
),
[_nil_],
h(20pt),
prooftrees.tree(
prooftrees.axi(pad(bottom: 5pt, [$l$])),
prooftrees.uni[$x :: l$],
),
[_cons_],
),
supplement: "Table",
caption: "Inference rules for the untyped List type"
)<list-untyped-rules>
Consider the rules in @list-untyped-rules, a semplifications of rules in
@list-rules: we drop the polymorphism and leave implicit the part of the "is a
list" part of the judgment; we also consider $x$ in the cons rule to be any
element in the universe. We will show that we can build a complete lattice from
the rules in @list-untyped-rules and then show that the sets $S$ and $B$ that
we defined above are respectively the least fixed point and greatest fixed
point of a specific function $f$ on the complete lattice. We can interpret each
rule in @list-untyped-rules as an _inference system_ over a set $U$ of
judgements. In this case, we have
#linebreak()
#align(center, $ U eq.def {j_1, j_2, j_3}$)
#linebreak()
where, for ease of exposure, we set $j_1 eq.def epsilon$, $j_2 eq.def l$ and $j_3 eq.def x :: l$.
The pair $<2^U, subset.eq>$ is a complete lattice, and has the structure
in @fig-lattice-U.
#figure(
render(width: 35%, "
digraph mygraph {
\"{j₁, j₂}\" -> \"{j₁, j₂, j₃}\"
\"{j₁, j₃}\" -> \"{j₁, j₂, j₃}\"
\"{j₂, j₃}\" -> \"{j₁, j₂, j₃}\"
\"{j₂}\" -> \"{j₁, j₂}\"
\"{j₁}\" -> \"{j₁, j₂}\"
\"{j₁}\" -> \"{j₁, j₃}\"
\"{j₃}\" -> \"{j₁, j₃}\"
\"{j₂}\" -> \"{j₂, j₃}\"
\"{j₃}\" -> \"{j₂, j₃}\"
\"∅\" -> \"{j₁}\"
\"∅\" -> \"{j₂}\"
\"∅\" -> \"{j₃}\"
}"),
caption: [Hasse diagram for the partially ordered set created by the inclusion relation
(represented by the arrows) on the set $U = {j_1, j_2, j_3}$],
)<fig-lattice-U>
We now define another binary relation, $phi : 2^U times U$, that embodies the rules themselves:
#linebreak()
#align(center, $ phi eq.def {(emptyset, j_1), (j_2, j_3)}$)
#linebreak()
Intuitively, if we have a rule $A/c$, then $(A , c) in phi$. We now define a
function $f : 2^U -> 2^U$ that represent a single step of derivation starting
from a set $S$ of premises using the rules in $phi$:
#linebreak()
#align(center, $ f(L) eq.def {j_1} union {c in U | exists A subset.eq L, (A, c) in phi}$)
#linebreak()
Going back to the expanded notation for rules#footnote[We do this as we
technically do not have $({j_1}, {j_3}) in phi$, although it is clearly
something expressed in the rules.] and adding a special notation for $x ::
epsilon eq.def [x]$, we have, for example,
#align(center, $f(emptyset) = {epsilon}$)
#align(center, $f({epsilon}) = {epsilon, [x]}$)
#align(center, $f({[x]}) = {epsilon, x :: [x]}$)
#align(center, $f({epsilon, [x]}) = {epsilon, [x], x :: [x]}$)
These sets are all $f$-consistents, as we always have $L subset.eq f(L)$.
Furthermore, the function $f$ is clearly monotone: $L subset.eq L'$ implies
that from $L'$ we will be able to derive at least the same conclusions that we
can derive from $L$, thus $f(L) subset.eq f(L')$.
From @thm-knaster-tarski, we know that $f$ has a least fixed point and a
greatest fixed point, that is
#align(center, $mu f = sect.big {L | f(L) subset.eq L}$)
#align(center, $nu f = union.big {L | L subset.eq f(L)}$)
The first set, the smallest $f$-closed is the set of terms that can be inductively generated from the rules,
while the second set, the largest $f$-consistent is the set of terms that can be coinductively generated from the rules.
|
|
https://github.com/mem-courses/linear-algebra | https://raw.githubusercontent.com/mem-courses/linear-algebra/main/note/9.二次型.typ | typst | #import "../template.typ": *
#show: project.with(
title: "Linear Algebra #9",
authors: (
(name: "<NAME>", email: "<EMAIL>", phone: "3230104585"),
),
date: "December 29, 2023",
)
#let xi = math.bold(math.xi)
#let theta = math.bold(math.theta)
#let AA = math.bold(math.italic("A"))
#let BB = math.bold(math.italic("B"))
#let XX = math.bold(math.italic("X"))
#let YY = math.bold(math.italic("Y"))
#let EE = math.bold(math.italic("E"))
#let OO = math.bold(math.italic("O"))
#let TT = math.upright("T")
#let x1 = math.attach(math.italic("x"), br: math.upright("1"))
#let x2 = math.attach(math.italic("x"), br: math.upright("2"))
#let x3 = math.attach(math.italic("x"), br: math.upright("3"))
#let alpha = math.bold(math.alpha)
#let beta = math.bold(math.beta)
#let Lambda = math.bold(math.Lambda)
#let diag = math.upright("diag")
#let ssim = math.attach(sp + math.upright("~") + sp, tl: "", tr:"", t: math.upright("S"))
= 二次型
#def[定义1]一个系数取自数域 $PP$,含有 $n$ 个变量 $seqn(x,n)$ 的二次齐次多项式,
$
f(seqn(x,n)) = sum_(i=1)^n sum_(j=1)^n a_(i j) x_i x_j = XX^TT AA XX
$
称为数域 $PP$ 上的一个 *二次型*.当且仅当 $AA = AA^TT$ 时,将其称为 *二次型矩阵*(若不施加约束则有多种可能).
#def[性质1]二次型与一个对称矩阵一一对应.
#def[定义2]只含平方项的二次型称为 *标准形*.
#def[定义3]设有两组变量 (I) $seqn(x,n)$ (II) $seqn(y,n)$,则系数 $C = (c_(i j))_(n times n) in PP^(n times n)$中的一组关系 $XX = bold(C) YY$ 称为从变量 (I) 到 (II) 的 *线性替换*.若 $|bold(C)| != 0$,称为 *非退化线性替换*.特别地,若 $bold(C)^TT bold(C) = EE$(即 $bold(C)$ 的 $n$ 个列向量构成一组标准正交基),则称 $XX = bold(C) YY$ 为 *正交线性替换*.
#def[性质2]正交线性替换向量长度不变.进一步地,对坐标应用正交替换,空间几何体保持形状不变.
#prof[
#def[证明]
1. 证明长度不变:$display(
||XX||^2 = XX^TT XX = (bold(C) YY)^TT bold(C) YY = YY^TT (bold(C)^TT bold(C)) YY = YY^TT YY = ||YY||^2
)$.
2. 证明角度不变:$display(
(alpha,beta) = XX_1^TT XX_2 = (bold(U) YY_1)^TT (bold(U) YY_2) = YY_1^TT (bold(U)^TT bold(U)) YY_2 = YY_1^TT YY_2
)$.
]
#note[
#def[应用]可用来求二次曲面(线)的标准方程.
]
== 化二次型为标准形
=== 配方法
#def[例1]$f(x1,x2,x3) = x1^2 + 2 x1 x2 + 2 x1 x3 + x2^2 - 2 x2 x3 - x3^2$.(含有 $x_i^2$)
#prof[
$
f(x1,x2,x3)
&= (x1^2+2x1 x2+2x1 x3) + x2^2 - 2x2 x3 - x3^2\
&= (x1 + x2 + x3)^2 - 4 x2 x3 - 2 x3^2\
&= (x1+x2+x3)^2 - 2 (x2+x3)^2 + 2x2^2
$
]
#def[例2]$f(x1,x2,x3) = 2x1 x2 + 2x1 x3 - 6 x2 x3$(不含有 $x_i^2$)
#prof[
令 $display(cases(x1=y_1+y_2,x2=y_1-y_2,x_3=y_3))$,$XX=bold(C) YY$ 非退化,此时:$f(x1,x2,x3) = 2 y_1^2 - y_2 ^2 - 4 y_1 y_2 + 8 y_2 y_3$,化为第一种情形.
]
#def[定理]任意一个二次型都可以经过非退化的线性替换化成一个标准形.
=== 利用实对称矩阵的性质
根据实对称矩阵的性质,一定存在可逆矩阵 $bold(C) in PP^(n times n)$ 使 $bold(C)^(-1) AA bold(C) = bold(C)^TT AA bold(C) = diag(seqn(lambda,n))$.
设 $f(seqn(x,n)) = XX^TT AA XX$,对其应用非退化线性变换 $XX = bold(C) YY$ 得
$
f(seqn(x,n)) = (bold(C) YY)^TT AA (bold(C) YY) = YY^TT (bold(C)^TT AA bold(C)) YY = lambda_1 y_1^2 + lambda_2 y_2^2 + dots.c + lambda_n y_n^2
$
由于 $(bold(C)^TT AA bold(C))^TT = bold(C)^TT AA bold(C)$,由性质1得 $bold(C)^TT AA bold(C)$ 即所求的标准形.
== 合同
设 $AA,BB in PP^(n times n)$,若有可逆矩阵 $bold(C) in PP^(n times n)$,使得 $bold(C)^TT AA bold(C) = BB$,则称 $AA,BB$ 在数域 $PP$ 上合同.
#def[性质1]合同具有自反性、对称性、传递性.
#def[性质2]两个合同的矩阵有三个不变:
#deft[性质2]1. 保持秩不变:$r(BB) = r(bold(P)^TT AA bold(P)) = r(AA)$.
#deft[性质2]2. 保持对称性不变:$BB^TT = (bold(P)^TT AA bold(P))^TT = bold(P)^TT AA^TT bold(P)$.
#deft[性质2]3. 保持正定性不变.
== 规范形
=== 二次型的秩
二次型经过非退化线性变换化成标准型后,非平方项的项数相同,将其称为 *二次型的秩*.
#def[定理1]二次型 $f(seqn(x,n)) = display(sum_(i=1)^n sum_(j=i)^n a_(i j) x_i x_j) = XX^TT AA XX$,则二次型的秩等于 $AA$ 的秩.(可将 $AA$ 化为对角矩阵证明)
=== 复数域上的规范形
设复数域上二次型 $f(seqn(x,n))$ 的秩为 $r$,设 $bold(C)^TT AA bold(C) = diag(seqn(d,r),0,dots.c,0)$,进行线性变换 $YY = bold(C) XX$ 得:
$
f(seqn(x,n))
&= d_1 y_1^2 + d_2 y_2^2 + dots.c + d_r y_r^2 + 0 dot y_(r+1)^2 + dots.c + 0 dot y_n^2\
&= (sqrt(d_1) y_1)^2 + (sqrt(d_2) y_2)^2 + dots.c + (sqrt(d_r) y_r)^2\
&= z_1^2 + z_2^2 + dots.c + z_r^2
$
这里进行了非退化线性变换为 $bold(Z) = diag(sqrt(d_1),sqrt(d_2),dots.c,sqrt(d_r),1,dots.c,1) bold(Y)$,将得到的结果称为 *二次型在复数域上的规范形*.
#def[定理2]1. 二次型语言:任意一个复二次型一定可以经过非退化线性变化化为规范形,规范形由二次型的秩唯一确定.
#deft[定理2]2. 矩阵语言:设 $AA = AA^TT in CC^(n times n)$,设 $r(AA) = r$,则 $AA$ 必与 $display(mat(EE_r,;,OO_(n-r)))_(n times n)$ 合同.
#def[推论]对称矩阵 $AA,BB$ 在复数域上合同 $<=>$ $r(AA) = r(BB)$.
=== 实数域上的二次型
$
f(seqn(x,n))
&= d_1 y_1^2 + d_2 y_2^2 + dots.c + d_p y_p^2 + -d_(p+1) y_(p+1)^2 - dots.c - d_r y_r^2 + 0 dot y_(r+1)^2 + dots.c + 0 dot y_n^2\
&= (sqrt(d_1) y_1)^2 + (sqrt(d_2) y_2)^2 + dots.c + (sqrt(d_p) y_p)^2 -(sqrt(d_(p+1)) y_(p+1))^2 - dots.c - (sqrt(d_r) y_r)^2\
&= z_1^2 + z_2^2 + dots.c + z_p^2 - z_(p+1)^2 - dots.c - z_r^2
$
这里同样进行了非退化线性变换 $ZZ = diag(sqrt(d_1),sqrt(d_2),dots.c,sqrt(d_r),1,dots.c,1) bold(CC) XX$,得到的结果称为 *二次型在实数域上的规范形*.
- 正平方项的项数 $p$ 称为 *二次型的正惯性指数*;
- 负平方项的项数 $r-p$ 称为 *二次型的负惯性指数*;
- $p-(r-p) = 2p-r$ 称为 *二次型的符号差*.
该二次型的正(负)惯性指数、符号差也称为实对称矩阵 $AA$ 的正(负)惯性指数、符号差.
#def[定理](惯性定律)
#deft[定理]1. 二次型语言:任意一个实二次型一定可以经过非退化线性变换化为规范形,规范形是唯一的,由二次型的秩和正(负)惯性指数决定.
#deft[定理]2. 矩阵语言:$n$ 阶实对称矩阵 $AA$ 与对角矩阵 $diag(d_1,d_2,dots.c,d_n)$ 合同时,$d_i$ 中不等于零的个数(即 $r(AA)$)和大(小)于零的个数($AA$ 的正(负)惯性指数)都是唯一的.即设实对称矩阵 $AA_(n times n)$ 的秩为 $r$,正惯性指数为 $p$,则 $AA$ 与矩阵 $display(mat(EE_p,,;,-EE_(r-p),;,,OO_(n-r)))$ 合同.
特别地,对于实对称矩阵,一定存在正交矩阵 $bold(U)$ 使得 $bold(U)^(-1) AA bold(U) = bold(U)^TT AA bold(U) = diag(seqn(lambda,n))$,即 $AA$ 与对角矩阵既相似又合同.
== 二次型的正定性
设 $AA$ 为 $n$ 阶实对称矩阵,若
$
XX^TT AA XX >= 0 sp (<=0) ,quad forall XX != OO, XX in RR^n
$
则称实二次型 $XX^TT AA XX$ 和矩阵 $AA$ 是 *半正定*(*半负定*)的,若不等号严格成立,则称其是 *正定*(*负定*)的.
=== 正定矩阵的性质
#def[定理1]设 $AA$ 为 $n$ 阶实对称矩阵,则如下结论等价(成立一个则其余全部成立):
1. 实二次型 $f(seqn(x,n)) = XX^TT AA XX$ 正定(或者说 $AA$ 正定).
2. $f(seqn(x,n))$ 的正惯性系数等于 $n$.
3. $AA$ 的所有特征值恒正.
4. $AA$ 与单位矩阵合同.
5. 存在 $n$ 阶可逆实矩阵 $BB$,使得 $AA = BB^TT BB$.
#def[定理2]正定(负定)矩阵的判定:
1. $n$ 阶实对称矩阵 $AA$ 正定 $<==>$ $AA$ 的所有 $k$ 阶($1<=k<=n$)顺序主子式恒正.
2. $n$ 阶实对称矩阵 $AA$ 负定 $<==>$ $AA$ 的所有 $k$ 阶($1<=k<=n$)顺序主子式与 $(-1)^k$ 的符号相同.
=== 半正定矩阵的性质
#def[定理3]设 $AA$ 为 $n$ 阶实对称矩阵且 $r=r(AA)$,则如下结论等价:
1. 实二次型 $f(seqn(x,n)) = XX^TT AA XX$ 半正定(或者说 $AA$ 半正定).
2. $f(seqn(x,n))$ 的负惯性系数等于 $0$(或者说正惯性系数等于 $r$).
3. $AA$ 的所有特征值非负.
4. $AA$ 与其相抵标准形合同.
5. 存在 $n$ 阶实矩阵 $BB$,使得 $AA = BB^TT BB$.
#def[定理4]半正定(半负定)矩阵的判定:
1. $n$ 阶实对称矩阵 $AA$ 半正定 $<==>$ $AA$ 的所有 $k$ 阶($1<=k<=n$)顺序主子式恒非负.
2. $n$ 阶实对称矩阵 $AA$ 半负定 $<==>$ $AA$ 的所有 $k$ 阶($1<=k<=n$)顺序主子式为零或与 $(-1)^k$ 的符号相同. |
|
https://github.com/explicit-refinement/ert-icfp | https://raw.githubusercontent.com/explicit-refinement/ert-icfp/main/ert.typ | typst | BSD Zero Clause License | #import "@preview/polylux:0.3.1": *
#import themes.simple: *
#show: simple-theme
#let ert = $λ_sans("ert")$;
#let stlc = $λ_sans("stlc")$;
#title-slide[
= Explicit Refinement Types
#v(2em)
<NAME> #h(1em)
<NAME>
University of Cambridge
September 7
ICFP'23 -- Seattle
]
#slide[
#one-by-one[
#only("4-")[
```haskell
-- the output length is the sum of the input lengths
```
]
#only("-6")[
```haskell
append :: [a] -> [a] -> [a]
```
]
#only("7-")[
```haskell
append :: l:[a] -> r:[a] -> {v: [a] | len v == len l + len r}
```
]
][
```haskell
append [] ys = ys
```
][
```haskell
append (x:xs) ys = x:(append xs ys)
```
]
#only(5)[
#align(center + horizon)[
#grid(columns: 3, column-gutter: 1em,
image("liquid-haskell.png", height: 30%),
$∨$,
image("agda.svg", height: 30%)
)
]
]
#only(8, align(center + horizon, text(green,
```
**** LIQUID: SAFE (2 constraints checked) ****
```
)))
#align(bottom + right, [
#only("-5", image("haskell.svg", height: 20%))
#only("6-", image("liquid-haskell.png", height: 30%))
])
]
#slide[
#only("2-")[
#align(center + horizon)[
#align(left)[
```haskell
data Vec (A : Set) : ℕ → Set where
```
#uncover("3-")[
```
[] : Vec A 0
```
]
#uncover("4-")[
```
_∷_ : ∀ (x : A) (xs : Vec A n) → Vec A (s n)
```
]
]
]
]
#align(bottom + right, image("agda.svg", height: 30%))
]
#slide[
```haskell
-- the output length is the sum of the input lengths
```
`append : `
#only("1", text(red, `(m n : ℕ)`))
#only("2-", `(m n : ℕ)`)
` -> Vec A m -> Vec A n -> Vec A `
#only("-4")[`(m + n)`]
#only("5", text(red, `(n + m)`))
#only("6-", `(n + m)`)
#only("2-6")[
```haskell
append 0 n [] ys = ys
```
]
#only("3-6")[
```haskell
append (s m) n (x ∷ xs) ys = x ∷ (append xs ys)
```
]
#only("8-")[
```haskell
append 0 n [] ys = subst (Vec _) (sym (+-identityʳ _)) ys
```
```haskell
append (s m) n (x ∷ xs) ys = subst (λ t → t)
(cong (Vec _) (sym (+-suc _ _)))
(x ∷ (append xs ys))
```
//TODO: fill in underscores
]
#align(center + horizon)[
#only("4", text(blue, $sans("*All Done*")$))
#only("6", text(red,
```
n != n + 0 of type ℕ
when checking that the expression ys has type Vec A (n + 0)
```
))
#only("7",
```
0 + n = 0
s m + n = s (m + n)
```
)
]
#align(bottom + right, image("agda.svg", height: 30%))
]
#slide[
```haskell
-- the output length is the sum of the input lengths
append :: l:[a] -> r:[a] -> {v: [a] | len v == len r + len l}
```
```haskell
append [] ys = ys
```
```haskell
append (x:xs) ys = x:(append xs ys)
```
#only(2, align(center + horizon, text(green,
```
**** LIQUID: SAFE (2 constraints checked) ****
```
)))
#align(bottom + right, image("liquid-haskell.png", height: 30%))
]
#focus-slide[
= Why _not_ refinement types?
]
#slide[
#one-by-one[][
= Quantifiers
$
∀x, y. x ≤ y ==> f(x) ≤ f(y) "(Monotonicity)"
$][$
∀x, y, z. R(x, y) ∧ R(y, z) ==> R(x, z) "(Transitivity)"
$][
= Multiplication
$
3x dot 5y = 2y dot 5x + 4x dot y + x dot y
$]
]
#slide[
= Reliability
#align(center, box(align(left, one-by-one[
][
```
(assert (forall ((a Int))
(exists ((b Int))
(= (* 2 b) a))))
```
][
```
(check-sat)
```
][
#text(olive, `sat`)
])))
#align(bottom)[
#cite(<fuzz>, style: "chicago-fullnotes")
]
]
#slide[
= Folklore
#v(0.5em)
#let pro(txt) = align(left, [#text(olive, "✓") #txt])
#let con(txt) = align(left, [#text(red, "✗") #txt])
#align(center, grid(
columns: 2,
column-gutter: 6em,
row-gutter: 1em,
[*Refinement Types*],
[*Dependent Types*],
only("2-", pro[High automation]),
only("3-", con[Low automation]),
only("4-", con[Low expressivity]),
only("5-", pro[High expressivity]),
only("6-", con[Big TCB]),
only("7-", pro[Small TCB])
))
#only("8-", align(bottom,
cite(<ftrs>, style: "chicago-fullnotes")))
]
#slide[
#align(horizon + center)[
$
∀x, y. R(x, y) <==> R(y, x)
$
#uncover("2-")[
$
x^2 + y^2 ≥ x y z
$
]
#uncover("3-")[
#grid(columns: 2,
image(width: 70%, "lean.svg"),
image(width: 40%, "isabelle.svg")
)
]
]
]
#let gst(x) = text(gray.darken(30%), x)
#slide[
#only("1-")[
```
append : ∀m n: ℕ -> Array A m -> Array A n -> Array A (m + n)
```
]
#only("3-")[
`append `#gst(`0 n {`)`[]`#gst(`, p} {`)`ys`#gst(`, q}`)` = `#gst(`{`)`ys`#gst({
only("3", [`, `
` ... : len ys = 0 + n}`]
)
only("4", [`, `
` trans[len ys =(q) n =(?) 0 + n]}`]
)
only("5-", [`, `
` trans[len ys =(q) n =(β) 0 + n]}`]
)
})
]
#only("6-")[
`append `#gst(`(s m) n {`)`(x:xs)`#gst(`, p} {`)`ys`#gst(`, q}`)` = `
]
#only("7-")[
` let `#gst(`{`)`zs`#gst(`, r}`)` = append `
#gst(`n m {`)`xs`#gst(`, ... : len xs = n} {`)`ys`#gst(`, q}`)
]
#only("8-")[
` in `#gst(`{`)`x:zs`#gst(`, ... : len(x:zs) = (s m) + n}`)
]
#align(bottom)[
#only("2-")[
#v(1em)
```haskell
Array A n := { l : List A | len l = n }
```
]
]
]
// going to write a signature and implementation which superficially resembles our Agda program
// I have a type that says ∀m n, it says what it says
// At this point, want to then give def and can mention that the gray stuff will be explained soon
#slide[
```
|append| : 1 -> 1 -> List |A| -> List |A| -> List |A|
```
```
append () () [] ys = ys
append () () (x:xs) ys =
let zs = append xs ys
in x:zs
```
]
#slide[
```
append : ∀m n: ℕ -> Array A m -> Array A n -> Array A (m + n)
```
`append `#gst(`0 n {`)`[]`#gst(`, p} {`)`ys`#gst(`, q}`)` = `#gst(`{`)`ys`#gst([`, `
` trans[len ys =(q) n =(β) 0 + n]`]
)
`append `#gst(`(s m) n {`)`(x:xs)`#gst(`, p} {`)`ys`#gst(`, q}`)` = `
`append `#gst(`(s m) n {`)`(x:xs)`#gst(`, p} {`)`ys`#gst(`, q}`)` = `
` let `#gst(`{`)`zs`#gst(`, r}`)` = append `
#gst(`n m {`)`xs`#gst(`, ... : len xs = n} {`)`ys`#gst(`, q}`)
` in `#gst(`{`)`x:zs`#gst(`, ... : len(x:zs) = (s m) + n}`)
]
#slide[
`append : ∀m n: ℕ -> Array A m -> Array A n -> Array A `#text(red, `(n + m)`)
`append `#gst(`0 n {`)`[]`#gst(`, p} {`)`ys`#gst(`, q}`)` = `#gst(`{`)`ys`#gst([`, `
` ... : len ys = n + 0]`]
)
`append `#gst(`(s m) n {`)`(x:xs)`#gst(`, p} {`)`ys`#gst(`, q}`)` = `
` let `#gst(`{`)`zs`#gst(`, r}`)` = append `
#gst(`n m {`)`xs`#gst(`, ... : len xs = n} {`)`ys`#gst(`, q}`)
` in `#gst(`{`)`x:zs`#gst(`, ... : len(x:zs) = n + (s m)}`)
]
#slide[
`append `#gst(`0 n {`)`[]`#gst(`, p} {`)`ys`#gst(`, q}`)` = `#gst(`{`)`ys`#gst[`, `
#only("1")[` ... : len ys = n + 0]`]
#only("2-5")[` trans[len ys =(q) n =(?) n + 0`]
#only("6-")[` trans[len ys =(q) n =(zero-right-id n) n + 0`]
]
#gst(align(bottom)[
#uncover("3-")[
#v(1em)
```
zero-right-id : ∀n: ℕ -> n + 0 = n
```
]
#uncover("4-")[
```
zero-right-id 0 = β
```
]
#uncover("5-")[
```
zero-right-id (s n) = trans [
(s n) + 0 =(β) s (n + 0) =(zero-right-id n) (s n)
]
```
]
])
]
#slide[
`append : ∀m n: ℕ -> Array A m -> Array A n -> Array A (n + m)`
`append `#gst(`0 n {`)`[]`#gst(`, p} {`)`ys`#gst(`, q}`)` = `#gst(`{`)`ys`#gst([`, `
` trans[len ys =(q) n =(zero-right-id n) n + 0]`]
)
`append `#gst(`(s m) n {`)`(x:xs)`#gst(`, p} {`)`ys`#gst(`, q}`)` = `
` let `#gst(`{`)`zs`#gst(`, r}`)` = append `
#gst(`n m {`)`xs`#gst(`, ... : len xs = n} {`)`ys`#gst(`, q}`)
` in `#gst(`{`)`x:zs`#gst(`, ... : len(x:zs) = n + (s m)}`)
#gst(align(bottom)[
```
zero-right-id : ∀n: ℕ -> n + 0 = n
```
])
]
#slide[
```
|append| : 1 -> 1 -> List |A| -> List |A| -> List |A|
```
```
append () () [] ys = ys
append () () (x:xs) ys =
let zs = append xs ys
in x:zs
```
]
#slide(gst[
```
mul-comm: ∀{m n: ℕ} -> m * n = n * m
```
#only("2-")[
```
mul-comm 0 n = trans[0 * n
=(β) 0 =(mul-zero-right n) n * 0]
```
]
#only("4-")[
```
mul-comm (s m) n = trans[(s m) * n =(β) (m * n) + n
=(mul-comm m (s n)) (n * m) + n
=(mul-succ (s n) m) n * (s m)]
```
]
#align(bottom)[
#uncover("3-")[
```
mul-zero-right : ∀n: ℕ -> n * 0 = 0
```
]
#uncover("5-")[
```
mul-succ : ∀m n: ℕ -> m * (s n) = m * n + m
```
]
]
])
#let sep = $med | med$
#let dnt(tm) = $[|tm|]$
#let tstlc = $scripts(⊢)_λ$
#slide[]
#slide[
#align(center + horizon)[
$#uncover("2-", $|$)sans("Array") med A med n#uncover("2-", $|$) #uncover("3-", $quad = quad sans("List") med |A|$)$
#uncover("4-")[
$
sans("len") v < n
$
]
#uncover("5-")[
$
∀n ∈ ℕ, #uncover("6-", $∃m ∈ ℕ,$) #uncover("7-", $m ≥ n ∧ m sans("prime")$)
$
]
]
]
#polylux-slide(max-repetitions: 20)[
#grid(
row-gutter: 1em,
column-gutter: 0.5em,
columns: 6,
$X, Y :=$,
uncover("2-", $bold(1)$),
uncover("2-", $| ℕ$),
uncover("3-", $| X + Y$),
uncover("4-", $| X × Y$),
uncover("5-", $| X -> Y$),
uncover("6-", $A, B :=$),
uncover("7-", $bold(1)$),
uncover("7-", $| ℕ$),
uncover("8-", $| A + B$),
uncover("9-", $| (a: A) × B$),
uncover("10-", $| (a: A) → B$),
$$, $$, $$, $$,
uncover("11-", $| ∃a: A, B$),
uncover("12-", $| ∀a: A, B$),
$$, $$, $$, $$,
uncover("13-", $| {a: A | φ}$),
uncover("14-", $| (p: φ) => A$),
uncover("15-", $φ, ψ :=$),
uncover("16-", $⊤$),
uncover("16-", $| ⊥$),
uncover("17-", $| φ ∨ ψ$),
uncover("17-", $| (p: φ) ∧ ψ$),
uncover("18-", $| (p: φ) => ψ$),
$$, $$, $$, uncover("20-", $| a scripts(=)_A b$),
uncover("19-", $| ∃a: A, φ$),
uncover("19-", $| ∀a: A, φ$),
)
#only("7-14")[
#align(center + horizon, rect(inset: 0.5em)[
#only(7, $|bold(1)| = bold(1), quad |ℕ| = ℕ$)
#only(8, $|A + B| = |X| + |Y|$)
#only(9, $|(a: A) × B| = |A| × |B|$)
#only(10, $|(a: A) → B| = |A| → |B|$)
#only(11, $|∃a: A, B| = |B|$)
#only(12, $|∀a: A, B| = bold(1) -> |B|$)
#only(13, $|{a: A | φ}| = |A|$)
#only(14, $|(p: φ) => A| = bold(1) -> |A|$)
])
]
]
#slide[]
#polylux-slide(max-repetitions: 11)[
#align(center + horizon)[
#uncover("2-", $Γ ⊢ a: A$)
#uncover("7-", $quad ==> quad $)
#alternatives-match((
"1-6": $Δ tstlc t: X$,
"7-": $|Γ| tstlc |a|: |A|$
))
#uncover("8-")[
$
Γ ⊢ p: φ
$
]
#grid(columns: 3,
column-gutter: 2em,
uncover("9-")[$Γ ⊢ A sans("ty")$],
uncover("10-")[$Γ ⊢ φ sans("pr")$],
uncover("11-")[$Γ sans("ok")$]
)
]
#uncover("3-6")[
#align(bottom)[
#uncover("3-")[
$Γ := quad dot
#only("4-", $sep Γ, x: A$)
#only("5-", $sep Γ, p: φ$)
#only("6-", $sep Γ, ||x: A||$)$
]
#uncover("4-6")[
#align(center, rect(inset: 0.5em)[
#alternatives-match((
"-4": $|Γ, x: A| = |Γ|, x: |A|$,
"5": $|Γ, p: φ| = |Γ|, p: bold(1)$,
"6-": $|Γ, ||x: A||| = |Γ|, x: bold(1)$
))
])
]
]
]
// #only("24-")[
// $Γ := quad dot
// #only("24-", $sep Γ, x: A$)
// #only("25-", $sep Γ, p: φ$)
// #only("26-", $sep Γ, ||x: A||$)
// quad quad
// #only("24-26")[
// #rect(inset: 0.5em)[
// #only("24", $|Γ, x: A| = |Γ|, x: |A|$)
// #only("25", $|Γ, p: φ| = |Γ|, p: bold(1)$)
// #only("26", $|Γ, ||x: A||| = |Γ|, x: bold(1)$)
// ]
// ]
// $
// ]
]
#slide[
$
#rect(inset: 0.5em, $
dnt(X): sans("Set")
$)
$
$
#uncover("2-", $dnt(bold(1)) = {()},$)
quad #uncover("3-", $dnt(ℕ) = ℕ,$)
quad #uncover("4-", $dnt(X + Y) = dnt(X) ⊔ dnt(Y),$)
$
$
#uncover("5-", $dnt(X × Y) = dnt(X) × dnt(Y),$)
quad #uncover("6-", $dnt(X → Y) = dnt(X) →
#alternatives(start: 7, repeat-last: true,
text(red, $sans("Error")$),
$sans("Error")$,
)dnt(Y)$)
$
#only("8-")[
$
#rect(inset: 0.5em, $
dnt(Δ): sans("Set")
$)
$
$
dnt(dot) = {()}, quad
dnt(#$Δ, x: X$) = dnt(Δ) × sans("Error")dnt(X)
$
]
]
#polylux-slide(max-repetitions: 25)[
#only("-3")[
$
#rect(inset: 0.5em, $dnt(X): sans("Set")$) quad
#rect(inset: 0.5em, $dnt(Δ): sans("Set")$)
#only("4-", $
quad #rect(inset: 0.5em,
$dnt(Δ tstlc t: X): dnt(Δ) -> sans("Error")dnt(X)$)
$)
$
#only("2-3")[
$
#rect(inset: 0.5em,
$dnt(Δ tstlc t: X): dnt(Δ) -> sans("Error")dnt(X)$)
$
]
]
#only("3-")[
$
#rect(inset: 0.5em, $dnt(Γ ⊢ A sans("ty")) med γ ⊆ dnt(|A|)$)
$
]
#align(center+horizon)[
#only("4-7")[
$
dnt(#$Γ ⊢ (x: A) -> B sans("ty")$) med γ
& = #uncover("5-", ${f: dnt(|A|) -> sans(M)dnt(|B|)$)
\ & #uncover("6-", $#h(2em) | ∀ a ∈ dnt(Γ ⊢ A sans("ty")) med γ,$)
\ & #uncover("7-", $#h(3em) f med a ∈ cal(E)dnt(#$Γ, x: A ⊢ B sans("ty")$)(γ, sans("ret") x) }$)
$
]
#only("8")[
$
dnt(#$Γ ⊢ #text(red, $∀x: A,$) B sans("ty")$) med γ
& = {f: #text(red, $bold(1)$) -> sans(M)dnt(|B|)
\ & #h(2em) | ∀ a ∈ dnt(Γ ⊢ A sans("ty")) med γ,
\ & #h(3em) f med #text(red, $()$) ∈ cal(E)dnt(#$Γ, x: A ⊢ B sans("ty")$)(γ, sans("ret") x)
}
$
]
#only("9")[
$
dnt(#$Γ ⊢ ∀x: A, B sans("ty")$) med γ
& = {f: bold(1) -> sans(M)dnt(|B|)
\ & #h(2em) | ∀ a ∈ dnt(Γ ⊢ A sans("ty")) med γ,
\ & #h(3em) f med () ∈ cal(E)dnt(#$Γ, x: A ⊢ B sans("ty")$)(γ, #text(red, $sans("ret") x$))
}
$
]
#only("10-14")[
$
γ &∈ dnt(|Γ^↑|) \
#uncover("11-", $dot^↑ &= dot$) \
#uncover("12-", $(Γ, x: A)^↑ &= Γ^↑, x: A$) \
#uncover("13-", $(Γ, p: φ)^↑ &= Γ^↑, p: φ$) \
#uncover("14-", $(Γ, ||x: A||)^↑ &= Γ^↑, x: A$) \
$
]
#only("15-17")[
#uncover("15-")[
$
dnt(||n: ℕ|| ⊢ {x: ℕ | x < n} sans("ty"))
$
]
#uncover("16-")[
$
dnt(⊢ {x: ℕ | x < 3} sans("ty")) med () = {0, 1, 2}
$
]
#uncover("17-")[
$
dnt(⊢ {x: ℕ | x < 5} sans("ty")) med () = {0, 1, 2, 3, 4}
$
]
]
#only("18")[
$
dnt(#$Γ ⊢ {x: A | φ} sans("ty")$) med γ &
= {x ∈ dnt(Γ ⊢ A sans("ty")) med γ
\ & #h(2em) | dnt(#$Γ, x: A ⊢ φ: sans("pr")$) med (γ, sans("ret") x)}
$
]
]
]
#slide[
$
#rect(inset: 0.5em, $dnt(Γ ⊢ A sans("ty")) med γ ⊆ dnt(|A|)$) quad
#rect(inset: 0.5em,
$dnt(Γ tstlc φ sans("pr")): dnt(|Γ^↑|) -> sans("Prop")$)
$
#align(center + horizon)[
#only("2")[
$
dnt(Γ ⊢ ⊤ sans("pr")) med γ = ⊤ quad
dnt(Γ ⊢ ⊥ sans("pr")) med γ = ⊥
$
]
#only("3")[
$
dnt(Γ ⊢ a scripts(=)_A b sans("pr")) γ
= [dnt(|Γ^↑ ⊢ a: A|) med γ = dnt(|Γ^↑ ⊢ b: A|) med γ]
$
]
#only("4-5")[
$
dnt(#$Γ ⊢ ∃x: A, φ sans("pr")$) γ
& = ∃x ∈ dnt(Γ ⊢ A sans("ty")) med γ,
\ & #h(4em) dnt(#$Γ, x: A ⊢ φ sans("pr")$ (γ, sans("ret") x))
$
]
#only("5")[
$
dnt(#$Γ ⊢ ∀x: A, φ sans("pr")$) γ
& = ∀x ∈ dnt(Γ ⊢ A sans("ty")) med γ,
\ & #h(4em) dnt(#$Γ, x: A ⊢ φ sans("pr")$ (γ, sans("ret") x))
$
]
]
]
#slide[
$
#rect(inset: 0.5em, $dnt(Γ ⊢ A sans("ty")) med γ ⊆ dnt(|A|)$) quad
#rect(inset: 0.5em,
$dnt(Γ tstlc φ sans("pr")): dnt(|Γ^↑|) -> sans("Prop")$)
$
$
#rect(inset: 0.5em,
$dnt(Γ sans("ok")): dnt(|Γ^↑|) -> sans("Prop")$)
$
#align(center + horizon)[
$
#uncover("2-", $dnt(dot sans("ok")) med γ
&= ⊤$) \
#uncover("3-", $dnt(#$Γ, p: φ sans("ok")$) med γ
&= dnt(Γ sans("ok")) med γ ∩ dnt(Γ ⊢ φ: sans("pr")) med γ$) \
#uncover("4-", $dnt(#$Γ, x: A$) med (γ, sans("ret") x)
&= dnt(#$Γ, ||x: A||$) med (γ, sans("ret") x) \
&= dnt(Γ sans("ok")) med γ ∧ x ∈ dnt(Γ ⊢ A sans("ty")) med γ$)
$
]
]
#slide[
= Semantic Regularity
#align(center + horizon, [
#uncover("2-")[
$
Γ ⊢ a: A ==> & \
& #uncover("3-", $∀γ ∈ dnt(|Γ^↑|),$)
#uncover("4-", $dnt(Γ sans("ok")) γ ==>$) \
& #h(2em) #uncover("5-", $dnt(|Γ| tstlc |a|: |A|) med γ^↓$)
#uncover("6-", $∈ dnt(Γ ⊢ A sans("ty")) med γ$)
$
]
#v(2em)
#uncover("7-")[
$
dnt(Γ ⊢ ⊥ sans("pr")) med γ = ⊥
$
]
])
]
#slide[
= Recap
#line-by-line[
- We introduce the language #ert:
- We take a simply typed, effectful lambda calculus #stlc and add refinements
- We support a rich logic of properties:
- Full first-order quantifiers
- Ghost variables/arguments
- We support explicit proofs of all properties
- We give everything a denotational semantics, and prove it sound
- Everything is mechanized in ∼15,000 lines of Lean 4
]
#align(center)[
#uncover("7-")[
Contact: #text(olive, link("mailto:<EMAIL>"))
]
]
]
#bibliography("references.bib") |
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/cpp/lectures/2024-09-27.typ | typst | #import "/utils/math.typ": *
= Полиморфизм
#def[
#defitem[Полиморфизм] --- возможность написания кода, которым можно
использовать для разных типов ("форм").
]
В C++ есть два полиморфизма:
- Времени компиляции (шаблоны)
- Времени исполнения (с помощью наследования и виртуальных функций)
== Наследование
#def[
#defitem[Наследование] --- иерархическое отношение между классами.
Механизм повторного использования и расширения класса без модификации его
кода.
]
Обычно отражает отношение "общее--частное".
Как без наследования:
```cpp
struct A {
void f();
};
struct B {
A a;
void something_new();
};
B obj;
obj.something_new();
obj.a.f();
// ^^^
```
С наследованием:
```cpp
struct A {
void f();
};
struct B : public A {
void something_new();
};
B obj;
obj.something_new();
obj.f();
// ^
```
=== Наследование и права доступа
- ```cpp class D : public B { ... }```
- `public -> public`
- `protected -> protected`
- ```cpp class D : private B { ... }```
- `public, protected -> private`
- ```cpp class D : protected B { ... }```
- `public, protected -> protected`
Изменить права доступа при наследовании:
```cpp
struct B { void f(); };
class D : public B {
private:
using B::f; // делаем f приватным
}
D obj;
obj.f(); // ошибка
```
== Полиморфные функции
Функцию `pmf` можно вызвать для объекта класса `D`, несмотря на то, что она была
объявлена раньше самого класса:
```cpp
struct B {
void f() {
std::cout << "B::f()\n";
}
};
void pmf(B& br) {
br.f();
}
class D : public B {};
// Можем вызывать функцию pmf для класса
// объявленного после неё самой
D obj;
pmf(obj);
```
При вызове `pmf` объект `cast`-уется к типу `B`, вызывается изначальная функция
(из `B`), а не переопределение (из `D`):
```cpp
struct B {
void f() {
std::cout << "B::f()\n";
}
};
void pmf(B& br) {
br.f();
}
class D : public B {
void f() {
std::cout << "D::f()\n";
}
};
B b;
D d;
pmf(b); // -> "B::f()"
pmf(d); // -> "B::f()"
```
=== Виртуальные функции
Если сделать функцию `virtual`, то будет вызваться переопределенная функция, а
не изначальная.
```cpp
struct B {
virtual void f() {
std::cout << "B::f()\n";
}
};
void pmf(B& br) {
br.f();
}
class D : public B {
void f() override {
std::cout << "D::f()\n";
}
};
B b;
D d;
pmf(b); // -> "B::f()"
pmf(d); // -> "D::f()"
```
== Перегрузка, переопределение, сокрытие
- Перегрузка (overload): несколько функций с одним именем в одной области
видимости
- Переопределение (override) виртуальной функции: объявление в дочернем
классе функции с той же сигнатурой
- Сокрытие: объявление функции с тем же именем во вложенной области (в
подклассе/ дочернем классе)
```cpp
struct B {
virtual void f(int) { ... }
virtual void f(double) { ... }
virtual void g(int i = 20) { ... }
};
struct D : public B {
void f(complex<double>);
void g(int i = 20);
}
B b;
D d;
B* pb = new D;
b.f(1.0); // B::f(double)
d.f(1.0); // D::f(complex<double>) неявно кастуемся к double
pb->f(1.0); // B::f(double) нет более специальной реализации для double
b.g(); // B::g(int) 10
d.g(); // D::g(int) 20
pb->g(); // D::g(int) 10 <-- так не надо
```
`override` --- ключевое слово, которое проверяет, что данная функция, и правда,
является переопределением. Иначе выкидывает compile error. Его хорошо писать
везде, где оно подходит.
Если есть хотя бы одна виртуальная функция, то деструктор тоже должен быть
виртуальным.
== Интерфейсы и чистые виртуальные функции
Пример (как делать не надо):
Для добавления каждого нового logger-а приходится много и тривиально менять
метод logger:
```cpp
struct ConsoleLogger {
void log_tx(long from, long to, double amount) { ... }
};
struct DBLogger {
void log_tx(long from, long to, double amount) { ... }
DBLogger(...) {...}
~DBLogger() { ... }
};
struct Processor {
void transfer(long from, long to, double amount) {
// ...
switch (logger_type) {
// ...
}
// ...
}
};
```
Пример (как делать надо):
Сделать интерфейс `Logger`:
```cpp
struct Logger {
virtual void log_tx(long from, long to, double amount) = 0;
// ^^^^
// делает виртуальную функцию чистой
};
class Processor {
public:
Processor(Logger* logger) { ... }
void transfer() { ... }
private:
Logger* logger_;
};
```
#def[
#defitem[Абстрактные классы (интерфейсы)] --- классы с чистыми виртуальными функциями.
]
Абстрактный класс нельзя создать, можно только унаследовать.
== Принципы проектирования
- Минимизация зависимостей между частями системы (классами)
- DRY (Don't repeat yourself) -- не WET (write everything twice/ we enjoy typing)
- KISS (Keep it simple, stupid)
- YAGNI (You aren't gonna need it)
- SOLID
- класс должен отвечать за одну конкретную сущность
- разделение интерфейсов
- открытость к расширению
- принцип подстановки: класс ведет себя, как базовый
|
|
https://github.com/typst-doc-cn/tutorial | https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/basic/reference-math-symbols.typ | typst | Apache License 2.0 | #import "mod.typ": *
#show: book.page.with(title: [参考:常用数学符号])
#set table(
stroke: none,
align: horizon + left,
row-gutter: 0.45em,
)
推荐阅读:
+ #link("https://github.com/johanvx/typst-undergradmath/releases/download/v1.2.0/undergradmath.pdf")[本科生Typst数学英文版,适用于Typst 0.10.0]
+ #link("https://github.com/brynne8/typst-undergradmath-zh/blob/6a1028bc13c525f29f6445e92fc6af3246b3c3cb/undergradmath.pdf")[本科生Typst数学中文版,适用于Typst 0.9.0]
以下表格列出了*数学模式*中的常用符号。
#figure(
table(
columns: 8,
[$hat(a)$], [`hat(a)`], [$caron(a)$], [`caron(a)`], [$tilde(a)$], [`tilde(a)`], [$grave(a)$], [`grave(a)`],
[$dot(a)$],
[`dot(a)`],
[$dot.double(a)$],
[dot.double(a)],
[$macron(a)$],
[`macron(a)`],
[$arrow(a)$],
[`arrow(a)`],
[$acute(a)$], [`acute(a)`], [$breve(a)$], [`breve(a)`],
),
caption: [数学模式重音符号],
)
#figure(
table(
columns: 8,
[$alpha$], [`alpha`], [$theta$], [`theta`], [$o$], [`o`], [$upsilon$], [`upsilon`],
[$beta$], [`beta`], [$theta.alt$], [`theta.alt`], [$pi$], [`pi`], [$phi$], [`phi`],
[$gamma$], [`gamma`], [$iota$], [`iota`], [$pi.alt$], [`pi.alt`], [$phi$], [`phi`],
[$delta$], [`delta`], [$kappa$], [`kappa`], [$rho$], [`rho`], [$chi$], [`chi`],
[$epsilon.alt$], [`epsilon.alt`], [$lambda$], [`lambda`], [$rho.alt$], [`rho.alt`], [$psi$], [`psi`],
[$epsilon$], [`epsilon`], [$mu$], [`mu`], [$sigma$], [`sigma`], [$omega$], [`omega`],
[$zeta$], [`zeta`], [$nu$], [`nu`], [$sigma.alt$], [`sigma.alt`], [$$], [``],
[$eta$], [`eta`], [$xi$], [`xi`], [$tau$], [`tau`], [$$], [``],
[$Gamma$], [`Gamma`], [$Lambda$], [`Lambda`], [$Sigma$], [`Sigma`], [$Psi$], [`Psi`],
[$Delta$], [`Delta`], [$Xi$], [`Xi`], [$Upsilon$], [`Upsilon`], [$Omega$], [`Omega`],
[$Theta$], [`Theta`], [$Pi$], [`Pi`], [$Phi$], [`Phi`],
),
caption: [希腊字母],
)
#figure(
table(
columns: 6,
[$<$], [`<, lt`], [$>$], [`>, gt`], [$=$], [`=`],
[$<=$], [`<=, lt.eq`], [$>=$], [`>=, gt.eq`], [$equiv$], [`equiv`],
[$<<$], [`<<, lt.double`], [$>>$], [`>>, gt.double`], [$$], [``],
[$prec$], [`prec`], [$succ$], [`succ`], [$tilde$], [`tilde`],
[$prec.eq$], [`prec.eq`], [$succ.eq$], [`succ.eq`], [$tilde.eq$], [`tilde.eq`],
[$subset$], [`subset`], [$supset$], [`supset`], [$approx$], [`approx`],
[$subset.eq$], [`subset.eq`], [$supset.eq$], [`supset.eq`], [$tilde.equiv$], [`tilde.equiv`],
[$subset.sq$], [`subset.sq`], [$supset.sq$], [`supset.sq`], [$join$], [`join`],
[$subset.eq.sq$], [`subset.eq.sq`], [$supset.eq.sq$], [`supset.eq.sq`], [$$], [``],
[$in$], [`in`], [$in.rev$], [`in.rev`], [$prop$], [`prop`],
[$tack.r$], [`tack.r`], [$tack.l$], [`tack.l`], [$tack.r.double$], [`tack.r.double`],
[$divides$], [`divides`], [$parallel$], [`parallel`], [$tack.t$], [`tack.t`],
[$:$], [`:`], [$in.not$], [`in.not`], [$!=$], [`!=, eq.not`],
),
caption: [二元关系],
)
#figure(
table(
columns: 6,
[$+$], [`+, plus`], [$-$], [`-, minus`], [$$], [``],
[$plus.minus$], [`plus.minus`], [$minus.plus$], [`minus.plus`], [$lt.tri$], [`lt.tri`],
[$dot$], [`dot`], [$div$], [`div`], [$gt.tri$], [`gt.tri`],
[$times$], [`times`], [$without$], [`without`], [$star$], [`star`],
[$union$], [`union`], [$sect$], [`sect`], [$*$], [`*`],
[$union.sq$], [`union.sq`], [$sect.sq$], [`sect.sq`], [$circle.stroked.tiny$], [`circle.stroked.tiny`],
[$or$], [`or`], [$and$], [`and`], [$bullet$], [`bullet`],
[$xor$], [`xor`], [$minus.circle$], [`minus.circle`], [$dot.circle$], [`dot.circle`],
[$union.plus$], [`union.plus`], [$times.circle$], [`times.circle`], [$circle.big$], [`circle.big`],
[$product.co$],
[`product.co`],
[$triangle.stroked.t$],
[`triangle.stroked.t`],
[$triangle.stroked.b$],
[`triangle.stroked.b`],
[$dagger$], [`dagger`], [$lt.tri$], [`lt.tri`], [$gt.tri$], [`gt.tri`],
[$dagger.double$], [`dagger.double`], [$lt.tri.eq$], [`lt.tri.eq`], [$gt.tri.eq$], [`gt.tri.eq`],
[$wreath$], [`wreath`],
),
caption: [二元运算符],
)
#figure(
table(
columns: 6,
[$sum$], [`sum`], [$union.big$], [`union.big`], [$or.big$], [`or.big`],
[$product$], [`product`], [$sect.big$], [`sect.big`], [$and.big$], [`and.big`],
[$product.co$], [`product.co`], [$union.sq.big$], [`union.sq.big`], [$union.plus.big$], [`union.plus.big`],
[$integral$], [`integral`], [$integral.cont$], [`integral.cont`], [$dot.circle.big$], [`dot.circle.big`],
[$plus.circle.big$], [`plus.circle.big`], [$times.circle.big$], [`times.circle.big`],
),
caption: [「大」运算符],
)
#figure(
table(
columns: 4,
[$arrow.l$], [`arrow.l`], [$arrow.l.long$], [`arrow.l.long`],
[$arrow.r$], [`arrow.r`], [$arrow.r.long$], [`arrow.r.long`],
[$arrow.l.r$], [`arrow.l.r`], [$arrow.l.r.long$], [`arrow.l.r.long`],
[$arrow.l.double$], [`arrow.l.double`], [$arrow.l.double.long$], [`arrow.l.double.long`],
[$arrow.r.double$], [`arrow.r.double`], [$arrow.r.double.long$], [`arrow.r.double.long`],
[$arrow.l.r.double$], [`arrow.l.r.double`], [$arrow.l.r.double.long$], [`arrow.l.r.double.long`],
[$arrow.r.bar$], [`arrow.r.bar`], [$arrow.r.long.bar$], [`arrow.r.long.bar`],
[$arrow.l.hook$], [`arrow.l.hook`], [$arrow.r.hook$], [`arrow.r.hook`],
[$harpoon.lt$], [`harpoon.lt`], [$harpoon.rt$], [`harpoon.rt`],
[$harpoon.lb$], [`harpoon.lb`], [$harpoon.rb$], [`harpoon.rb`],
[$harpoons.ltrb$], [`harpoons.ltrb`], [$arrow.t$], [`arrow.t`],
[$arrow.b$], [`arrow.b`], [$arrow.t.b$], [`arrow.t.b`],
[$arrow.t.double$], [`arrow.t.double`], [$arrow.b.double$], [`arrow.b.double`],
[$arrow.t.b.double$], [`arrow.t.b.double`], [$arrow.tr$], [`arrow.tr`],
[$arrow.br$], [`arrow.br`], [$arrow.bl$], [`arrow.bl`],
[$arrow.tl$], [`arrow.tl`], [$arrow.r.squiggly$], [`arrow.r.squiggly`],
),
caption: [箭头],
)
#figure(
table(
columns: 6,
[$dots$], [`dots`], [$dots.c$], [`dots.c`], [$dots.v$], [`dots.v`],
[$dots.down$], [`dots.down`], [$planck.reduce$], [`planck.reduce`], [$dotless.i$], [`dotless.i`],
[$dotless.j$], [`dotless.j`], [$ell$], [`ell`], [$Re$], [`Re`],
[$Im$], [`Im`], [$aleph$], [`aleph`], [$forall$], [`forall`],
[$exists$], [`exists`], [$ohm.inv$], [`ohm.inv`], [$diff$], [`diff`],
[$prime$], [`', prime`], [$emptyset$], [`emptyset`], [$infinity$], [`infinity`],
[$nabla$], [`nabla`], [$triangle.stroked.t$], [`triangle.stroked.t`], [$square.stroked$], [`square.stroked`],
[$diamond.stroked$], [`diamond.stroked`], [$bot$], [`bot`], [$top$], [`top`],
[$angle$], [`angle`], [$suit.club$], [`suit.club`], [$suit.spade$], [`suit.spade`],
[$not$], [`not`],
),
caption: [其他符号],
)
|
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/frontmatter.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/utils.typ"
#import "/packages.typ": notebookinator, codetastic
#import notebookinator: *
#import themes.radial.components: *
#import codetastic: qrcode
#let label(label: "", size: 0.7em) = {
let data = entry-type-metadata.at(label)
let colored-image = utils.change-icon-color(raw-icon: data.icon, fill: white)
box(fill: data.color, outset: 3pt, radius: 1.5pt)[
#set align(center + horizon)
#image.decode(colored-image, height: size)
]
}
#create-frontmatter-entry(
title: "About This Notebook",
)[
This notebook was written with a programming language called Typst. We write
instructions about formatting in Typst, and they they are rendered into a pdf.
Here are some examples of what that looks like:
```typ
Just some ordinary text // Turns into text
#grid( // Creates a grid layout
columns: (1fr, 1fr),
gutter: 20pt,
pro-con(
pros: [ // Turns into a table of pros and cons (appears on the right side)
- good
- better ],
cons: [
- bad
- worse
],
),
[
Some content on the left side *Bold content on the left side*
],
)
```
This would would render into:
Just some ordinary text // Turns into text
#grid( // Creates a grid layout
columns: (1fr, 1fr),
gutter: 20pt,
pro-con(
pros: [ // Turns into a table of pros and cons (appears on the right side)
- good
- better ],
cons: [
- bad
- worse
],
),
[
Some content on the left side
*Bold content on the left side*
],
)
== Source Code
#grid(
columns: (1fr, 1fr),
gutter: 20pt,
[
The source code can be found here: #link("https://github.com/Area-53-Robotics/53E-Notebook").
Alternatively, you can use the QR code to the left.
],
qrcode("https://github.com/Area-53-Robotics/53E-Notebook", size: 5pt),
)
#colbreak()
= Why Digital?
This is our third year using a digital notebook, and we find that it improves
the experience for both the writer and the viewer in several ways:
- Increased neatness
- Better, more modern tooling
- Styling is defined in one location
== Why Typst?
Typst give us a whole host of benefits:
- Management and collaboration with git or the online editor
- Verification of history with git
- Native scripting support
- Native support for rendering math
- Native support for rendering code
This gives us many more capabilities than something like Google Docs/Slides
would.
== How to Read Entries
Entries all have a type, which is displayed in the top left corner, as well as
in the table of contents. Most types correspond with a step in the engineering
design process, but some do not.
Here are the existing types:
#let spacing = 3pt
#stack(
spacing: 10pt,
[#box(baseline: 30%, label(label: "identify", size: 1.7em)) #h(10pt) *Identify the problem*],
[#box(baseline: 30%, label(label: "brainstorm", size: 1.7em)) #h(10pt) *Brainstorm possible solutions*],
[#box(baseline: 30%, label(label: "decide", size: 1.7em)) #h(10pt) *Decide on the optimal solution*],
[#box(baseline: 30%, label(label: "build", size: 1.7em)) #h(10pt) *Build the solution*],
[#box(baseline: 30%, label(label: "program", size: 1.7em)) #h(10pt) *Program the solution*],
[#box(baseline: 30%, label(label: "test", size: 1.7em)) #h(10pt) *Test the solution*],
[#box(baseline: 30%, label(label: "management", size: 1.7em)) #h(10pt) *Team management*],
[#box(baseline: 30%, label(label: "notebook", size: 1.7em)) #h(10pt) *Notebook Metadata*],
)
]
#create-frontmatter-entry(
title: "Our Team",
)[
#team(
(
name: "<NAME>",
picture: image("./assets/mugshots/felix.jpg", width: 90pt, height: 90pt),
about: [
- 12th Grade
- Team Leader
- Tooling Developer
- Notebooker
- Vocalist
],
),
(
name: "<NAME>",
picture: image("./assets/mugshots/alan.jpg", width: 90pt, height: 90pt),
about: [
- 11th Grade
- Designer
- Builder
- Driver
- Guitarist
],
),
(
name: "<NAME>",
picture: image("./assets/mugshots/john.png", width: 90pt, height: 90pt),
about: [
- 10th Grade
- Designer
- Builder
- "Bass Guitarist"
],
),
(
name: "<NAME>",
picture: image("./assets/mugshots/joy.jpg", width: 90pt, height: 90pt),
about: [
- 10th Grade
- Programmer
- Designer
- Builder
- Guitarist
- Vocalist
],
),
(
name: "<NAME>",
picture: image("./assets/mugshots/meghana3.jpg", width: 90pt, height: 90pt),
about: [
- 9th Grade
- Auton Strategist
- Programmer
- Pianist
- Vocalist
],
),
(
name: "<NAME>",
picture: image("./assets/mugshots/violet.jpg", width: 90pt, height: 90pt),
about: [
- 9th Grade
- Design
- Builder
- Drummer
],
),
)
]
#create-frontmatter-entry(title: "Table of Contents")[
#toc()
]
|
https://github.com/Krsnik/typst-nix | https://raw.githubusercontent.com/Krsnik/typst-nix/main/templates/example/src/package1/lib.typ | typst | #let test = [This is a test]
|
|
https://github.com/mangkoran/utm-thesis-typst | https://raw.githubusercontent.com/mangkoran/utm-thesis-typst/main/05_certification.typ | typst | MIT License | #import "@preview/tablex:0.0.7": tablex, colspanx
#let content() = [
#align(center)[
#upper[*Pengesahan Peperiksaan*]
]
#align(horizon)[
#tablex(
auto-lines: false,
columns: (auto, 1fr),
[Tesis ini telah diperiksa dan diakui oleh], [:],
[Nama dan Alamat Peperiksa Luar], [:],
colspanx(2)[], (),
colspanx(2)[], (),
colspanx(2)[], (),
[Nama dan Alamat Peperiksa Luar], [:],
colspanx(2)[], (),
colspanx(2)[], (),
colspanx(2)[], (),
[Nama Penyelia Lain (jika ada)], [:],
colspanx(2)[], (),
colspanx(2)[], (),
colspanx(2)[], (),
[Disahkan oleh Timbalan Pendaftar di Fakulti], [:],
[Tandatangan], [:],
colspanx(2)[], (),
colspanx(2)[], (),
colspanx(2)[], (),
[Nama], [:],
[Date], [: #datetime.today().display()],
)
]
#pagebreak(weak: true)
]
#content()
|
https://github.com/alberto-lazari/cv | https://raw.githubusercontent.com/alberto-lazari/cv/main/modules_en/honors.typ | typst | #import "/common.typ": *
= Honors
#honor(
date: [November 2020],
title: [Scholarship “Mille e una lode”],
issuer: [
University of Padua \
_Merit\-based Scholarship for the best Computer Science students (\~3% of the total)_
],
)
|
|
https://github.com/fabriceHategekimana/master | https://raw.githubusercontent.com/fabriceHategekimana/master/main/3_Theorie/Type_embeding.typ | typst | === Le type embedding
Une notion intéressante que j'ai découvert dans le langage de programmation de Go est l'intégration de (type embedding). C'est un concept qui favorise la composition par rapport à l'héritage.
L'héritage est un concept de la programmation orientée objet où une classe (dite sous-classe) hérite des propriétés et des méthodes d'une autre classe (dite super-classe). Cela permet de réutiliser le code existant et de créer des relations hiérarchiques entre les classes.
Dans le cadre du sous-typage, l'héritage permet à une sous-classe de se comporter comme une super-classe. Cela signifie qu'un objet de la sous-classe peut être utilisé partout où un objet de la super-classe est attendu. Le sous-typage garantit que la sous-classe respecte le contrat de la super-classe, c'est-à-dire qu'elle implémente ou redéfinit ses méthodes de manière compatible.
Bien que très utile pour la réutilisation de code, l'héritage présentes quelques fragilités qui rendent la maintenance du code difficile. L'héritage apporte un fort couplage entre les classes et leur sous-classes et peut "casser" ces dernières si les super-classes subissent des changements.
La composition est plus flexible et permet un faible couplage, augmentant ainsi la maintenabilité du code. En revanche, on perd le gain de temps assuré par la réusabilité du code promu par l'héritage. C'est là où l'intégration de type intervient.
L'intégration de type permet la réusabilité du code en utilisant la composition. On peut "intégrer" un type en faisant une référence sur celui-ci depuis le type d'accueil. À partir de là, le type intégrant "hérite" des méthode de la classe intégrée. En réalité, le type parent prend les méthodes du même nom qui font appel aux méthodes du type intégré.
Malgré tout, cette propriété ne peut pas être représentée par le système de type de mon language puisqu'il relève plus de la métaprogrammation que de l'inférence de type. En effet, comparé à l'héritage, l'inclusion de type ne provoque pas de sous-typage. Dans le langage Go, il faut passer par les interface pour avoir cette notion de substitution. A ma déception, cette fonctionnalité n'a aucune propriétés intéressantes pour le typage. Cependant il va quand même dans l'idéologie de la simplicité qui a fait de Go un langage prisé par les développeur débutants.
Je profiterai de parler plus loin des autres fonctionnalités intéressantes qui rendrait le langage plus convivial et simple d'emploi pour les utilisateurs de R, mais qui ne présentent aussi très peu d'intérêt au niveau du typage
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-FE00.typ | typst | Apache License 2.0 | #let data = (
("VARIATION SELECTOR-1", "Mn", 0),
("VARIATION SELECTOR-2", "Mn", 0),
("VARIATION SELECTOR-3", "Mn", 0),
("VARIATION SELECTOR-4", "Mn", 0),
("VARIATION SELECTOR-5", "Mn", 0),
("VARIATION SELECTOR-6", "Mn", 0),
("VARIATION SELECTOR-7", "Mn", 0),
("VARIATION SELECTOR-8", "Mn", 0),
("VARIATION SELECTOR-9", "Mn", 0),
("VARIATION SELECTOR-10", "Mn", 0),
("VARIATION SELECTOR-11", "Mn", 0),
("VARIATION SELECTOR-12", "Mn", 0),
("VARIATION SELECTOR-13", "Mn", 0),
("VARIATION SELECTOR-14", "Mn", 0),
("VARIATION SELECTOR-15", "Mn", 0),
("VARIATION SELECTOR-16", "Mn", 0),
)
|
https://github.com/SkiFire13/typst-touying-unipd | https://raw.githubusercontent.com/SkiFire13/typst-touying-unipd/master/README.md | markdown | MIT License | # typst-touying-unipd
A theme for [touying](https://github.com/touying-typ/touying) based on the [Latex Beamer Padova](https://www.math.unipd.it/~burattin/other/tema-latex-beamer-padova/) theme.
|
https://github.com/Akida31/anki-typst | https://raw.githubusercontent.com/Akida31/anki-typst/main/typst/src/lib.typ | typst | #import "raw.typ": anki_export
#import "config.typ"
#import config: set_date, is_export
#import "theorems.typ"
/// Setup the document
///
/// This is crucial for displaying everything correctly!
///
/// *Example*:
/// #example(`show: anki.setup.with(enable_theorems: true)`, ratio: 1000, scale-preview: 100%)
///
/// - doc (content): The document to wrap.
/// - export (bool, auto): Whether to enable export mode.
/// If `export` is `auto`, anki-typst will try to read from `sys.inputs`.
/// - enable_theorems (bool): Whether to enable theorem support (via `ctheorems`)
/// - title (str, none): The top-level deck name of all cards.
/// - prefix_deck_names_with_numbers (bool): Whether to prefix all deck names with the corresponding heading number.
/// -> content
#let setup(
doc,
export: auto,
enable_theorems: false,
title: none,
prefix_deck_names_with_numbers: false,
) = {
import "config.typ"
if export == auto {
config.set_export_from_sys()
}
config.anki_config.update(conf => {
conf.title = title
conf.prefix_deck_names_with_numbers = prefix_deck_names_with_numbers
conf
})
let doc = if enable_theorems {
show: theorems.setup
doc
} else {
doc
}
locate(loc => if is_export(loc) {
set page(margin: 0.5cm, height: auto)
doc
} else {
doc
})
}
|
|
https://github.com/sofianedjerbi/ResumeOld | https://raw.githubusercontent.com/sofianedjerbi/ResumeOld/main/modules/references.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("References")
#let lightbold(str) = text(weight: 501, str)
*Par souci de confidentialité, merci de me contacter afin de joindre mes références.*
#grid(
columns: (50%, 50%),
gutter: 2%,
[
- #lightbold("<NAME>"): Manager Ingenico
- #lightbold("<NAME>"): Suivi Mission Ingenico
- #lightbold("<NAME>"): Suivi Mission Ingenico
],
[
- #lightbold("<NAME>"): Client final boutique
- #lightbold("<NAME>"): Client final Elendil & Kaiiju
- #lightbold("<NAME>"): Responsable CEA
]
)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/link_08.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Link to page one.
#link((page: 1, x: 10pt, y: 20pt))[Back to the start]
|
https://github.com/jamesrswift/journal-ensemble | https://raw.githubusercontent.com/jamesrswift/journal-ensemble/main/src/pages/cover.typ | typst | The Unlicense | #import "../ensemble.typ"
#import "../elements.typ"
#let cover-content(
hero: [],
date: datetime.today(),
volume: 1,
issue: 1,
title: none,
) = {
move(
dx: -2.5cm,
block(
width: 100% + 5cm,
grid(
columns: (1fr, 1fr),
rows: (10cm),
column-gutter: 1cm,
elements.fancy-box(hero),
grid.cell(
inset:(y: 1cm),
{
date.display("[month repr:long] [year]"); linebreak()
[Volume #volume\ ]
[Issue #issue\ ]
v(1fr)
text(size: 13pt,title)
}
)
)
)
)
}
#let cover(
hero: [],
date: datetime.today(),
volume: 1,
issue: 1,
title: none,
) = page(
numbering: none,
{
v(1fr)
cover-content(
hero: hero, date: date, volume: volume, issue: issue, title: title
)
v(1fr)
counter(page).update(0)
}
)
|
https://github.com/elpekenin/access_kb | https://raw.githubusercontent.com/elpekenin/access_kb/main/typst/content/parts/hardware/main.typ | typst | === Cableado de las teclas <sec:scanning>
#include "scanning.typ"
=== Pantallas <pantallas>
En los últimos años es cada vez más común ver teclados que incorporan pequeñas pantallas, sin embargo, no son muy útiles ya que en la gran mayoría de casos se trata de SH1106 o SSD1306, que son dispositivos OLED de 2 colores y con una resolución bastante reducida, de 128x32 o 128x64 píxeles, en torno a la pulgada de diagonal. En nuestro teclado vamos a usar pantallas más potentes para poder mostrar información útil en vez de pequeños dibujos en estas pantallas más comunes.
=== Sensor táctil <sensor-táctil>
También es relativamente común encontrar diseños que incluyen diferentes sensores (por ejemplo joysticks analógicos o PMW3360) para mover el sensor por la pantalla del ordenador sin tener que mover la mano hasta el ratón. Tal como podemos ver en el Dactyl[@img:dactyl]
En nuestro caso, puesto que vamos a añadir una pantalla, podemos aprovechar y usar una táctil, de forma que nos sirva para mover el cursor pero tambíen para tener una pequeña interfaz de usuario en el teclado.
|
|
https://github.com/Servostar/dhbw-abb-typst-template | https://raw.githubusercontent.com/Servostar/dhbw-abb-typst-template/main/src/pages/titlepage.typ | typst | MIT License | // .--------------------------------------------------------------------------.
// | Titlepage |
// '--------------------------------------------------------------------------'
// Author: <NAME>
// Edited: 28.06.2024
// License: MIT
#let new_title_page(config) = (
context [
#let thesis = config.thesis
#let author = config.author
#set align(center)
// title
#v(2cm)
#par(justify: false, leading: 1.5em)[
#text(size: 2em, weight: "bold", hyphenate: false, thesis.title)
#linebreak()
// subtitle
#text(size: 2em, weight: "light", thesis.subtitle)
]
#set align(center + horizon)
// type of paper
#text(size: 1.5em, weight: "medium", thesis.kind)
// faculty
#pad()[
#if text.lang == "de" [
Praxisphase des #author.semester Semesters an der Fakultät für #author.faculty
#linebreak()
im Studiengang #author.program
] else if text.lang == "en" [
Practical phase of the #author.semester semester at the Faculty of #author.faculty
#linebreak()
in the degree program #author.program
] else [
#context panic("no translation for language: ", text.lang)
]
]
// university
#pad()[
#if text.lang == "de" [
an der
] else if text.lang == "en" [
at
] else [
#context panic("no translation for language: ", text.lang)
]
#linebreak()
#author.university
]
#set align(bottom + left)
#if text.lang == "de" [
#table(
columns: 2,
column-gutter: 1cm,
align: left,
stroke: none,
[*Verfasser:*], author.name,
[*Bearbeitungszeitraum:*], thesis.timeframe,
[*Matrikelnummer, Kurs:*], str(author.matriculation-number) + ", " + author.course,
[*Ausbildungsbetrieb:*], author.company,
[*Betrieblicher Betreuer:*], author.supervisor,
[*Abgabedatum:*], thesis.submission-date,
)
] else if text.lang == "en" [
#table(
columns: 2,
column-gutter: 1cm,
align: left,
stroke: none,
[*Author:*], author.name,
[*Editing period:*], thesis.timeframe,
[*Matriculation number, course:*], str(author.matriculation-number) + ", " + author.course,
[*Training company:*], author.company,
[*Company supervisor:*], author.supervisor,
[*Submission date:*], thesis.submission-date,
)
] else [
#context panic("no translation for language: ", text.lang)
]
#align(
bottom,
grid(
// set width of columns
// we need two, so make both half the page width
columns: (60%, 40%),
align(left, if text.lang == "de" [
Unterschrift des betrieblichen Betreuers
] else if text.lang == "en" [
Signature of the company supervisor
] else [
#context panic("no translation for language: ", text.lang)
]
),
align(right, {line(length: 6cm)})),
)
#counter(page).update(0)
]
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/thesist/0.1.0/template/Chapters/1-Introduction.typ | typst | Apache License 2.0 | #import "@preview/thesist:0.1.0": flex-caption, subfigure-grid
#import "@preview/glossarium:0.4.1": gls, glspl
= Introduction
// Start writing here...
|
https://github.com/chamik/gympl-skripta | https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-dila/11-rur.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/helper.typ": hrule, dilo, replika
#dilo("R. U. R.", "rur", "<NAME>", "", "Meziválečná lit.", "Francie", "1880", "epika", "povídka")
#columns(2, gutter: 1em)[
*Téma*\
Hrozba nadvlády strojů, varování před rapidním technologickým pokrokem.
*Motivy*\
hodnota lidská práce, kapitalismus, biblické (Adam a Eva)
*Časoprostor*\
bez bližšího časového určení někdy v~budoucnosti, Rossumův ostrov
*Postavy*#footnote[Jména postav jsou symboly samy o sobě; Domin z latiny pán, <NAME>, Trojská Helena, Prim = první...] \
_<NAME>_ -- Hlavní řiditel Rossumových závodů, hraje si na boha \
_Dr. Gall_ -- řiditel výzkumného oddělení (ref. na Bílou nemoc @nemoc[]) \
_Alquist_ -- stavitel robotů, autor své názory vykládá skrz něj \
_<NAME>_ -- symbol ženy, manželka _H. D._, tragická postava \
_Busman_ -- vrchní účetní, žid \
_Nána_ -- služebná, konzervativní \
_Prim_ a _Helena_ -- "probuzení" roboti
*Kompozice* \
chronologická, tři dějství
// *Vypravěč*
*Jazykové prostředky*\
čistě spisovný jazyk (kromě Nány), technobabble#footnote[Často lékařské termíny jako "protoplazma", aby to znělo chytře], zdvojené r "hrrozné", knižní výrazy, nové slovo "robot"
#colbreak()
*Obsah*\
Na Rossumův ostrov přijede _<NAME>_, dcera prezidenta a chce ukázat závod na výrobu robotů. Chce k robotům promluvit, proč se sebou nechají zacházet jako se stroji na práci. Jsou k nerozeznání od lidí, ovšem nemají city. Helena na ostrově zůstane a vezme si za manžela _<NAME>_. Za deset let se roboti používají už i k válkám a _Helenu_ trápí jejich absence citů, tak přemluví _<NAME>_, aby takové roboty vyrobil. Na světě se postupně přestávájí rodit děti a roboti se začínají bouřit. Helena spálí plány na výrobu robotů, ostrov je přepaden a přžívá pouze _Alquist_. Roboti si uvědomí, že vyhynou, tak prosí Alquista, aby znovu vytvořil plány na výrobu. To se mu nepodaří, ovšem najde dva roboty _Prima_ a _Helenu_, kteří mají city a tudíž by se mohli stát počátkem nové civilizace,
*Literárně historický kontext*\
Celosvětově známá hra. Slovo _robot_ vymyslel bratr Josef Čapek#footnote[„Ale já nevím, jak mám ty umělé dělníky nazvat. Řekl bych jim laboři, ale připadá mně to nějak papírové.“ -- „Tak jim řekni roboty,“ mumlal malíř se štětcem v ústech a maloval dál.]. Varování před zneužitím techniky. Chvalba práce. Naprosto nadčasové dílo.
]
#pagebreak()
*Ukázka*
#table(columns: 2, stroke: none,
..replika("Domin", [Pojďte sem k oknu. Co vidíte?]),
..replika("Helena", [Zedníky.]),
..replika("Domin", [To jsou Roboti. Všichni naši dělníci jsou Roboti. A tadydole, vidíte něco?]),
..replika("Helena", [Nějaká kancelář.]),
..replika("Domin", [Účtárna. A v ní --]),
..replika("Helena", [-- plno úředníků.]),
..replika("Domin", [To jsou Roboti. Všichni naši úředníci jsou Roboti. Až uvidíte továrnu --]),
..replika("", [_(Vtom spustí tovární píšťaly a sirény.)_]),
..replika("Domin", [Poledne. Roboti nevědí, kdy přestat v práci. Ve dvě hodiny vám ukážu díže. ]),
)
#hrule()
#table(columns: 2, stroke: none,
..replika("Helena", [Já skočím z okna, Prime. Půjdeš-li tam, skočím z okna!]),
..replika("Primus", [_(zadrží ji)_ Nepustím! _(K Alquistovi:)_ Nikoho, starý, nezabiješ!]),
..replika("Alquist", [Proč?]),
..replika("Primus", [My -- my -- patříme k sobě.]),
..replika("Alquist", [Ty jsi řekl. _(Otevře dveře ve středu.)_ Ticho. Jděte.]),
..replika("Primus", [Kam?]),
..replika("Alquist", [_(šeptem)_ Kam chcete. Heleno, veď ho. _(Strká je ven.)_ Jdi,
Adame. Jdi, Evo; budeš mu ženou. Buď jí mužem, Prime.]),
..replika("", [_(Zavírá za nimi.)_]),
..replika("Alquist", [_(sám)_ Požehnaný dni! _(Jde po špičkách ke stolu a vylévá zkumavky na zem.)_ Svátku dne šestého! [...] “A stvořil Bůh člověka k obrazu svému: k obrazu božímu stvořil ho, muže a ženu stvořil je. [...] Rossume, Fabry, Galle, velicí vynálezci, co jste vynalezli velkého proti té dívce, proti tomu chlapci, proti tomu prvnímu páru, který vynašel lásku, pláč, úsměv milování, lásku muže a ženy? Přírodo, přírodo, život nezahyne! Kamarádi, Heleno, život nezahyne! Zase se začne z lásky, začne se nahý a maličký; ujme se v pustině, a nebude mu k ničemu, co jsme dělali a budovali, k ničemu města a továrny, k ničemu naše umění, k ničemu naše myšlenky, a přece nezahyne! [...] Nezahyne! _(Rozpřáhne ruce.)_ Nezahyne!]),
..replika("", [_Opona_]),
)
#pagebreak() |
https://github.com/mariunaise/HDA-Thesis | https://raw.githubusercontent.com/mariunaise/HDA-Thesis/master/content/BACH.typ | typst | #import "@preview/glossarium:0.4.1": *
#import "@preview/tablex:0.0.8": tablex, rowspanx, colspanx
= Boundary Adaptive Clustering with Helper Data (BACH)
//Instead of generating helper-data to improve the quantization process itself, like in #gls("smhdt"), or using some kind of error correcting code after the quantization process, we can also try to find helper-data before performing the quantization that will optimize our input values before quantizing them to minimize the risk of bit and symbol errors during the reconstruction phase.
We can explore the option of finding helper data before performing the quantization process.
This approach aims to optimize our input values prior to quantization, which may help minimize the risk of bit and symbol errors during the reconstruction phase.
This differs from methods like @smhdt, which generate helper data to improve the quantization process itself, of those that apply error-correcting codes afterward.
Since this #gls("hda") modifies the input values before the quantization takes place, we will consider the input values as zero-mean Gaussian distributed and not use a CDF to transform these values into the tilde-domain.
== Optimizing single-bit sign-based quantization<sect:1-bit-opt>
Before we take a look at the higher order quantization cases, we will start with a very basic method of quantization: a quantizer, that only returns a symbol with a width of $1$ bit and uses the sign of the input value to determine the resulting bit symbol.
#figure(
include("./../graphics/quantizers/bach/sign-based-overlay.typ"),
caption: [1-bit quantizer with the PDF of a normal distribution]
)<fig:1-bit_normal>
If we overlay the PDF of a zero-mean Gaussian distributed variable $X$ with a sign-based quantizer function as shown in @fig:1-bit_normal, we can see that the expected value of the Gaussian distribution overlaps with the decision threshold of the sign-based quantizer.
Considering that the margin of error of the value $x$ is comparable with the one shown in @fig:tmhd_example_enroll, we can conclude that values of $X$ that reside near $0$ are to be considered more unreliable than values that are further away from the x-value 0.
This means that the quantizer used here is very unreliable as is.
Now, to increase the reliability of this quantizer, we can try to move our input values further away from the value $x = 0$.
To do so, we can define a new input value $z$ as a linear combination of two realizations of $X$, $x_1$ and $x_2$ with a set of weights $h_1$ and $h_2$ that we will use as helper data:
$
z = h_1 dot x_1 + h_2 dot x_2 ,
$<eq:lin_combs>
with $h_i in {plus.minus 1}$. Building only the sum of two input values $x_1 + x_2$ is not sufficient here, since the resulting distribution would be a normal distribution with $mu = 0$ as well.
=== Derivation of the resulting distribution
To find a description for the random distribution $Z$ of $z$ we can interpret this process mathematically as a maximisation of a sum.
This can be realized by replacing the values of $x_i$ with their absolute values as this always gives us the maximum value of the sum:
$
z = abs(x_1) + abs(x_2)
$
Taking into account that $x_i$ are realizations of a normal distribution, we can assume without loss of generality that $X$ is i.i.d., /*to have its expected value at $x=0$ and a standard deviation of $sigma = 1$ --*/ defining the overall resulting random distribution $Z$ as:
$
Z = abs(X_1) + abs(X_2).
$<eq:z_distribution>
We will redefine $abs(X)$ as a half-normal distribution $Y$ whose PDF is
$
f_Y(y, sigma) &= frac(sqrt(2), sigma sqrt(pi)) lr(exp(-frac(y^2, 2 sigma^2)) mid(|))_(sigma = 1), y >= 0 \
&= sqrt(frac(2, pi)) exp(- frac(y^2, sigma^2)) .
$<eq:half_normal>
Now, $Z$ simplifies to
$
Z = Y_1 + Y_2.
$
We can assume for now that the realizations of $Y$ are independent of each other.
The PDF of the addition of these two distributions can be described through the convolution of their respective PDFs:
$
f_Z(z) &= integral_0^z f_Y (y) f_Y (z-y) \dy\
&= integral_0^z [sqrt(2/pi) exp(-frac(y^2,2)) sqrt(2/pi) exp(-frac((z-y)^2, 2))] \dy\
&= 2/pi integral_0^z exp(- frac(y^2 + (z-y)^2, 2)) \dy #<eq:z_integral>
$
Evaluating the integral of @eq:z_integral, we can now describe the resulting distribution of this maximisation process analytically:
$
f_Z = 2/sqrt(pi) exp(-frac(z^2, 4)) "erf"(z/2) z >= 0.
$<eq:z_result>
Our derivation of $f_Z$ currently only accounts for the addition of positive values of $x_i$, but two negative $x_i$ values would also return the maximal distance to the coordinate origin.
The derivation for the corresponding PDF is identical, except that the half-normal distribution @eq:half_normal is mirrored around the y-axis.
Because the resulting PDF $f_Z^"neg"$ is a mirrored variant of $f_Z$ and $f_Z$ is arranged symmetrically around the origin, we can define a new PDF $f_Z^*$ as
$
f_Z^* (z) = abs(f_Z (z)),
$
on the entire z-axis.
$f_Z^* (z)$ now describes the final random distribution after the application of our optimization of the input values $x_i$.
#figure(
include("../graphics/plots/z_distribution.typ"),
caption: [Optimized input values $z$ overlaid with sign-based quantizer $cal(Q)$]
)<fig:z_pdf>
@fig:z_pdf shows two key properties of this optimization:
1. Adjusting the input values using the method described above does not require any adjustment of the decision threshold of the sign-based quantizer.
2. The resulting PDF is zero at $z = 0$ leaving no input value for the sign-based quantizer at its decision threshold.
=== Generating helper-data
To find the optimal set of helper-data that will result in the distribution shown in @fig:z_pdf, we can define the vector of all possible linear combinations $bold(z)$ as the vector-matrix multiplication of the input values $x_i$ and the matrix $bold(H)$ of all weight combinations with $h_i in [plus.minus 1]$:
$
bold(z) &= bold(x) dot bold(H)\
$<eq:z_combinations>
We will choose the optimal weights based on the highest absolute value of $bold(z)$, as that value will be the furthest away from $0$.
//We may encounter two entries in $bold(z)$ that both have the same highest absolute value.
//In that case, we will choose the combination of weights randomly out of our possible options.
To not encounter two entries in $bold(z)$ that both have the same highest absolute value, we can set the first helper data bit to be always $h_1 = 1$.
Considering our single-bit quantization case, @eq:z_combinations can be written as:
$
bold(z) = vec(x_1, x_2) dot mat(delim: "[", +1, -1, +1, -1; +1, +1, -1, -1)
$
The vector of optimal weights $bold(h_"opt")$ can now be found through $op("argmax")_h (bold(z))$.
If we take a look at the dimensionality of the matrix of all weight combinations, we notice that we will need to store only $1$ helper-data bit per quantized symbol because $h_1$ is set to $1$.
In fact, we will show later, that the amount of helper-data bits used by this HDA is directly linked to the number of input values used instead of the number of bits we want to extract during quantization.
== Generalization to higher-order bit quantization
We can generalize the idea of @sect:1-bit-opt and apply it for a higher-order bit quantization.
Contrary to @smhdt, we will always use the same step function as quantizer and optimize the input values $x$ to be the furthest away from any decision threshold.
In this higher-order case, this means that we want to optimise our input values as far away as possible from the nearest decision threshold of the quantizer instead of just maximising the absolute value of the linear combination.
For a complete generalization of this method, we will also parametrize the amount of addends $N$ kin the linear combination of $z$.
That means we can define $z$ from now on as:
$
z = sum_(i=1)^(N) x_i dot h_i
$<eq:z_eq>
We can define the condition to test whereas a tested linear combination is optimal as follows:\
The optimal linear combination $z_"opt"$ is found, when the distance to the nearest quantizer decision bound is maximised.
Finding the weights $bold(h)_"opt"$ of the optimal linear combination $z_"opt"$ can be formalized as:
$
bold(h)_"opt" = op("argmax")_h op("min")_j abs(bold(h)^T bold(x) - b_j) "s.t." h_j in {plus.minus 1}
$<eq:optimization>
==== Example with 2-bit quantizer
//Let's consider the following example using a 2-bit quantizer:\
We can define the bounds of the two bit quantizer $bold(b)$ as $[-alpha, 0, alpha]$ omitting the bounds $plus.minus infinity$.
The values of $bold(b)$ are already placed in the real domain to directly quantize normal distributed input values.
A simple way to solve @eq:optimization is to use a brute force method and calculate all distances to every quantization bound $b_j$, because the number of possible combinations is finite.
Furthermore, fining a solution for @eq:optimization analytically poses to be significantly more complex.
The linear combination $z$ for the amount of addends $i = 2$ is defined as
$
z = x_1 dot h_1 plus x_2 dot h_2
$<eq:bach_z_example>
According to @eq:z_combinations, all possible linear combinations for two input values $x_1 "and" x_2$ of @eq:bach_z_example can be collected as the vector $bold(z)$ of length $2^i |_(i=2) =4$:
$
bold(z) = vec(z_1\, z_2\, z_3\, z_4)
$
Calculating the absolute distances to every quantizer bound $b_i$ for all linear combinations $z_i$ gives us the following distance matrix:
$
bold(cal(A)) = mat(
a_(1,1), a_(2,1), a_(3,1), a_(4,1);
a_(1,2), a_(2,2), a_(3,1), a_(4,2);
a_(1,3), a_(2,3), a_(3,1), a_(4,3);
),
$<mat:distance_A>
where $a_"i,j" = abs(z_i - b_j)$.
Now we want to find the bound $b_i$ for every $z_i$ to which it is closest.
This can be achieved by determining the minimum value for each column of the matrix $bold(cal(A))$.
The resulting vector $bold(nu)$ now consists of the distance to the nearest quantizer bound for every linear combination with entries defined as:
$
nu_"j" = min{a_"i,j" | 1 <= j <= 4} "for each" i = 1, 2, 3.
$
The optimal linear combination $z_"opt"$ can now be found as the entry $z_j$ of $bold(z)$ where its corresponding distance $nu_j$ is maximised.
=== Simulation of the bound distance maximisation strategy<sect:instability_sim>
Two important points were anticipated in the preceding example:
1. We cannot define the resulting random distribution $Z$ after performing this operation analytically and thus also not the quantizer bounds $bold(b)$.
A way to account for that is to guess the resulting random distribution and $bold(b)$ initially and repeating the optimization using quantizer bounds found through the @ecdf of the resulting linear combination values.
2. If the optimization described above is repeated multiple times using an @ecdf, the resulting random distribution $Z$ must converge to a stable random distribution. Otherwise we will not be able to carry out a reliable quantization in which the symbols are uniformly distributed.
To check that the strategy for optimizing the linear combination provided in the example above results in a converging random distribution, we will perform a simulation of the optimization as described in the example using $100 space.nobreak 000$ simulated normal distributed values as realizations of the standard normal distribution with the parameters $mu = 0$ and $sigma = 1$.
@fig:bach_instability shows various histograms of the vector $bold(z)_"opt"$ after different iterations.
Even though the overall shape of the distribution comes close to our goal of moving the input values away from the quantizer bounds $bold(b)$, the distribution itself does not converge to one specific, final shape.
It seems that the resulting distributions for each iteration oscillate in some way, since the distributions for iterations $7$ and $25$ have the same shape.
However the distribution seems to be chaotic and thus does not seem suitable for further quantization.
#figure(
grid(
columns: (1fr, 1fr),
rows: (2),
[//#figure(
#image("../graphics/plots/bach/instability/frame_1.png")
#v(-2em)
//)
Iteration 1],
[//#figure(
#image("../graphics/plots/bach/instability/frame_7.png")
#v(-2em)
//)
Iteration 7],
[//#figure(
#image("../graphics/plots/bach/instability/frame_18.png")
#v(-2em)
//)
Iteration 18],
[//#figure(
#image("../graphics/plots/bach/instability/frame_25.png")
#v(-2em)
//)
Iteration 25]
),
caption: [Probability distributions for various iterations]
)<fig:bach_instability>
=== Center Point Approximation
For that reason, we will now propose a different strategy to find the weights for the optimal linear combination $z_"opt"$.
Instead of defining the desired outcome of $z_"opt"$ as the greatest distance to the nearest quantizer decision threshold, we will define a vector $bold(cal(o)) = [cal(o)_1, cal(o)_2 ..., cal(o)_(2^M)]$ containing the optimal values that we want to approximate with $z$.
Considering a M-bit quantizer with $2^M$ steps, we can define the values of $bold(cal(o))$ as the center points of these quantizer steps.
Its cardinality is $2^M$.
It has to be noted, that $bold(cal(o))$ consists of optimal values that we may not be able to exactly approximate using a linear combination based on weights and our given input values.
We can find the optimal linear combination $z_"opt"$ by finding the minimum of all distances to all optimal points defined in $bold(cal(o))$.
The matrix that contains the distances of all linear combinations $bold(z)$ to all optimal points $bold(cal(o))$ is defined as: $bold(cal(A))$ with its entries $a_"ij" = abs(z_"i" - o_"j")$.\
$z_"opt"$ can now be defined as the minimal value in $bold(cal(A))$:
$
z_"opt" = op("min")(bold(cal(A)))
= op("min")(mat(delim: "[", a_("00"), ..., a_("i0"); dots.v, dots.down, " "; a_"0j", " ", a_"ij" )).
$
#figure(
kind: "algorithm",
supplement: [Algorithm],
include("../pseudocode/bach_find_best_appr.typ")
)<alg:best_appr>
@alg:best_appr shows a programmatic approach to find the set of weights for the best approximation. The algorithm returns a tuple consisting of the weight combination $bold(h)$ and the resulting value of the linear combination $z_"opt"$.
Because the superposition of different linear combinations of normal distributions corresponds to a Gaussian Mixture Model, finding the ideal set of points $bold(cal(o))$ analytically is impossible.
Instead, we will first estimate $bold(cal(o))$ based on the normal distribution parameters after performing multiple convolutions with the input distribution $X$.
The parameters of a multiple convoluted normal distribution is defined as:
$
sum_(i=1)^(n) cal(N)(mu_i, sigma_i^2) tilde cal(N)(sum_(i=1)^n mu_i, sum_(i=1)^n sigma_i^2),
$
while $n$ defines the number of convolutions performed @schmutz.
With this definition, we can define the parameters of the probability distribution $Z$ of the linear combinations $z$ based on the parameters of $X$, $mu_X$ and $sigma_X$:
$
Z(mu_Z, sigma_Z^2) = Z(sum_(i=1^n) mu_X, sum_(i=1)^n sigma_X^2)
$<eq:z_dist_def>
The parameters $mu_Z$ and $sigma_Z$ allow us to apply an inverse CDF on a multi-bit quantizer $cal(Q)(2, tilde(x))$ defined in the tilde-domain.
Our initial values for $bold(cal(o))_"first"$ can now be defined as the centers of the steps of the transformed quantizer function $cal(Q)(2, x)$.
These points can be found easily but for the outermost center points whose quantizer steps have a bound $plus.minus infinity$.\
However, we can still find these two remaining center points by artificially defining the outermost bounds of the quantizer as $frac(1, 2^(2 dot M))$ and $frac((2^(2 dot M))-1, 2^(2 dot M))$ in the tilde-domain and also apply the inverse CDF to them.
#scale(x: 90%, y: 90%)[
#figure(
include("../graphics/quantizers/two-bit-enroll-real.typ"),
caption: [Quantizer for the distribution resulting a triple convolution with distribution parameters $mu_X=0$ and $sigma_X=1$ with marked center points of the quantizer steps]
)<fig:two-bit-enroll-find-centers>]
We can now use an iterative algorithm that alternates between optimizing the quantizing bounds of $cal(Q)$ and our vector of optimal points $bold(cal(o))_"first"$.
#figure(
kind: "algorithm",
supplement: [Algorithm],
include("../pseudocode/bach_1.typ")
)<alg:bach_1>
We can see both of these alternating parts in @alg:bach_1_2[Lines] and @alg:bach_1_3[] of @alg:bach_1.
To optimize the quantizing bounds of $cal(Q)$, we will sort the values of all the resulting linear combinations $bold(z)_"opt"$ in ascending order.
Using the inverse @ecdf defined in @eq:ecdf_inverse, we can find new quantizer bounds based on $bold(z)_"opt"$ from the first iteration.
These bounds will then be used to define a new set of optimal points $bold(cal(o))$ used for the next iteration.
During every iteration of @alg:bach_1, we will store all weights $bold(h)$ used to generate the vector for optimal linear combinations $bold(z)_"opt"$.
We can also use a simulation here to check the convergence of the distribution $Z$ using the same input values and quantizer configurations as in @sect:instability_sim.
#figure(
grid(
columns: (2),
[#figure(
image("./../graphics/plots/bach/stability/frame_1.png"),
//caption: [Iteration 1]
)
#v(-2em)
Iteration 1],
[#figure(
image("./../graphics/plots/bach/stability/frame_25.png")
)
#v(-2em)
Iteration 25],
),
caption: [Probability distributions for the first and 25th iteration of the center point approximation method]
)<fig:bach_stability>
Comparing the distributions in @fig:bach_stability, we can see that besides a closer arrangement the overall shape of the probability distribution $Z$ converges to a stable distribution representing the original estimated distribution $Z$ through @eq:z_dist_def through smaller normal distributions.
The output of @alg:bach_1 is the vector of optimal weights $bold(h)_"opt"$.
$bold(h)_"opt"$ can now be used to complete the enrollment phase and quantize the values $bold(z)_"opt"$.
To perform reconstruction, we can calculate the same linear combination used during enrollment with the generated helper-data and the new PUF readout measurements.
We can lower the computational complexity of this approach by using the assumption that $X$ are i.i.d..
The end result of $bold(cal(o))$ can be calculated once for a specific device series and saved in the ROM of.
During enrollment, only the vector $bold(h)_"opt"$ has to be calculated.
=== Helper-data size and amount of addends
The amount of helper data is directly linked to the symbol bit width $M$ and the amount of addends $N$ used in the linear combination.
Because we can set the first helper data bit $h_1$ of a linear combination to $1$ to omit the random choice, the resulting extracted bit to helper data bit ratio $cal(r)$ can be defined as $cal(r) = frac(M, N-1)$, whose equation is similar tot he one we used in the @smhdt analysis.
== Experiments
To test our implementation of @bach using the prior introduced center point approximation we conducted a similar experiment as in @sect:smhd_experiments.
However, we have omitted the analysis over different temperatures for the enrollment and reconstruction phase here, as the behaviour of @bach corresponds to that of @smhdt in this matter.
As in the S-Metric analysis, the resulting dataset consists of the bit error rates of various configurations with quantization symbol widths of up to $4$ bits evaluated with up to $10$ addends for the linear combinations.
== Results & Discussion
We can now compare the #glspl("ber") of different @bach configurations.
/*#figure(
table(
columns: (9),
align: center + horizon,
inset: 7pt,
[*BER*],[N=2],[N=3],[N=4],[N=5], [N=6], [$N=7$], [$N=8$], [$N=9$],
[$M=1$], [$0.09$], [$0.09$], [$0.012$], [$0.018$], [$0.044$], [$0.05$], [$0.06$], [$0.07$],
[$M=2$], [$0.03$], [$0.05$], [$0.02$], [$0.078$], [$0.107$], [$0.114$], [$0.143$], [$0.138$],
[$M=3$], [$0.07$], [$0.114$], [$0.05$], [$0.15$], [$0.2$], [$0.26$], [$0.26$], [$0.31$],
[$M=4$], [$0.13$], [$0.09$], [$0.18$], [$0.22$], [$0.26$], [$0.31$], [$0.32$],[$0.35$]
),
caption: [#glspl("ber") of different @bach configurations]
)<tab:BACH_performance>*/
#figure(
kind: table,
tablex(
columns: 9,
align: center + horizon,
inset: 7pt,
// Color code the table like a heat map
map-cells: cell => {
if cell.x > 0 and cell.y > 0 {
cell.content = {
let value = float(cell.content.text)
let text-color = if value >= 0.3 {
red.lighten(15%)
} else if value >= 0.2 {
red.lighten(30%)
} else if value >= 0.15 {
orange.darken(10%)
} else if value >= 0.1 {
yellow.darken(13%) } else if value >= 0.08 {
yellow
} else if value >= 0.06 {
olive
} else if value >= 0.04 {
green.lighten(10%)
} else if value >= 0.02 {
green
} else {
green.darken(10%)
}
cell.fill = text-color
strong(cell.content)
}
}
cell
},
[*BER*],[N=2],[N=3],[N=4],[N=5], [N=6], [$N=7$], [$N=8$], [$N=9$],
[$M=1$], [0.01], [0.01], [0.012], [0.018], [0.044], [0.05], [0.06], [0.07],
[$M=2$], [0.03], [0.05], [0.02], [0.078], [0.107], [0.114], [0.143], [0.138],
[$M=3$], [0.07], [0.114], [0.05], [0.15], [0.2], [0.26], [0.26], [0.31],
[$M=4$], [0.13], [0.09], [0.18], [0.22], [0.26], [0.31], [0.32],[0.35],
[$M=5$], [0.29], [0.21], [0.37], [0.31], [0.23], [0.23], [0.19], [0.15],
[$M=6$], [0.15], [0.33], [0.15], [0.25], [0.21], [0.23], [0.19], [0.14]
),
caption: [#glspl("ber") of different @bach configurations]
)<tab:BACH_performance>
@tab:BACH_performance shows the #glspl("ber") of @bach configurations with $N$ addends and extracting $M$ bits out of one input value $z$.
The first interesting property we can observe, is the caveat @bach produces for the first three bit combinations $M = 1, 2 "and" 3$ at around $N = 3$ and $N = 4$.
At these points, the @ber experiences a drop followed by a steady rise again for higher numbers of $N$.
//This observation could be explained through the fact that the higher $N$ is chosen, the shorter the resulting key, since $N$ divides out values available for quantization by $N$.
If $M$ is generally chosen higher, @bach seems to return unstable results, halving the @ber as $N$ reaches $9$ for $M=5$ but showing no real improvement for various addends if $M=6$.
We can also compare the performance of @bach using the center point approximation approach with the #glspl("ber") of higher order bit quantizations that don't use any helper data.
#figure(
table(
columns: 7,
[*M*], [$1$], [$2$], [$3$], [$4$], [$5$], [$6$],
[*BER*], [$0.013$], [$0.02$], [$0.04$], [$0.07$], [$0.11$], [$0.16$]
),
caption: [#glspl("ber") for higher order bit quantization without helper data ]
)<tab:no_hd>
Unfortunately, the comparison of #glspl("ber") of @tab:no_hd[Tables] and @tab:BACH_performance[] shows that our current realization of @bach either ties the @ber in @tab:no_hd or is worse.
Let's find out why this happens.
==== Discussion
If we take a step back and look at the performance of the optimized single-bit sign-based quantization process of @sect:1-bit-opt, we can compare the following #glspl("ber"):
#figure(
table(
columns: 2,
[*No helper data*], [$0.013$],
[*With helper data using greatest distance*],[$0.00052$],
[*With helper data using center point approximation*], [$0.01$]
),
caption: [Comparison of #glspl("ber") for the single-bit quantization process with and without helper data]
)<tab:comparison_justification>
As we can see in @tab:comparison_justification, generating the helper data based on the original idea where @eq:optimization is used improves the @ber of the single-bit quantization by approx. $96%$.
The probability distributions $Z$ of the two different realizations of @bach -- namely the distance maximization strategy and the center point approximation -- give an indication of this discrepancy:
#figure(
grid(
columns: (2),
[#figure(
image("../graphics/plots/bach/compare/bad.png")
)
#v(-2em)
Center point approximation],
[#figure(
image("../graphics/plots/bach/compare/good.png")
)
#v(-2em)
Distance maximization],
),
caption: [Comparison of the histograms of the different strategies to obtain the optimal weights for the single-bit case]
)<fig:compar_2_bach>
@fig:compar_2_bach shows the two different probability distributions.
We can observe that using a vector of optimal points $bold(cal(o))$ results in a more narrow distribution for $Z$ than just maximizing the linear combination to be as far away from $x=0$ as possible.
This difference in the shape of both distributions seem to be the main contributor to the fact that the optimization using center point approximation yields no improvement for the quantization process.
Unfortunately, we were not able define an algorithm translating this idea to a higher order bit quantization for which the resulting probability distribution $Z$ converges.
Taking a look at the unstable probability distributions issued by the bound distance maximization strategy in @fig:bach_instability, we can get an idea of what kind of distribution a @bach algorithm should achieve.
While the inner parts of the distributions do not overlap with each other like in the stable iterations shown in @fig:bach_stability, the outermost values of these distributions resemble the shape of what we achieved using the distance maximization for a single-bit optimization.
These two properties could -- if the distribution converges -- result in far better #glspl("ber") for higher order bit quantization, as the comparison in @tab:comparison_justification indicates.
|
|
https://github.com/ralphmb/typst-template-stats-dissertation | https://raw.githubusercontent.com/ralphmb/typst-template-stats-dissertation/main/writeup/sections/bigsection.typ | typst | Apache License 2.0 | == Tables and Plots
Here's a table with some R output.
#table(
columns:4,
[Variable], [Estimate], [Std. Error], [p],
[(Intercept)], [-1.527], [0.698], [0.029],
[Variable 1], [-0.014], [0.008], [0.081],
[Variable 2], [0.033], [0.008], [0.000],
[Variable 3], [-0.087], [0.429], [0.840],
)
And here's a plot I used in my thesis.
#figure(
image("../assets/contourplot_logistic.png"),
caption: [Caption goes here]
) <contourplot>
Here's a snippet of R code
```R
x <- seq(0,1,0.01)
y <- 2*sin()
```
You can reference figures like @contourplot. Bibliography entries can have short citations @premierleague, or long ones (#cite(<premierleague>, form:"prose"))\
You can have inline equations like $sum_(i in NN) 2^(-i) = 1$, or block equations like follows:
$ n! approx sqrt(2 pi n) ((n)/(e))^(n) $
== Next Section
#lorem(400)
|
https://github.com/lluchs/evince-typst | https://raw.githubusercontent.com/lluchs/evince-typst/master/README.md | markdown | Apache License 2.0 | # evince-typst
(Experimental) addon for the [Evince][evince] document viewer to load [Typst][typst] files directly, without creating an intermediate PDF file.
[evince]: https://wiki.gnome.org/Apps/Evince
[typst]: https://typst.app
## Building
Configure:
```sh
meson setup build --buildtype=release
```
Build:
```sh
cargo build --release
ninja -C build
```
Install:
```sh
# Path will vary depending on your distribution
sudo cp -t /usr/lib/evince/4/backends build/evince-backend/{typstdocument.evince-backend,libtypstdocument.so}
sudo mkdir -p /usr/local/share/mime/packages
sudo cp -t /usr/local/share/mime/packages evince-typst.xml
sudo update-mime-database /usr/local/share/mime/
```
## License
Code in `src/` is based on typst-cli and is licensed under Apache-2.0, see LICENSE.
Code in `evince-backend/` is based on evince and is licensed under GPL version 2 or later, see the comments in the respective files.
|
https://github.com/AliothCancer/AppuntiUniversity | https://raw.githubusercontent.com/AliothCancer/AppuntiUniversity/main/capitoli_fisica/aria_umida.typ | typst | = Aria Umida (miscela bicomponente) <aria-umida-miscela-bicomponente>
== Umidità Assoluta <umidità-assoluta>
$ U_A = 0.622 dot.op frac(p_(v a p o r e %), p_(t o t a l e) - p_(v a p o r e %)) = 0.622 dot.op frac(phi dot.op p_S, p_(upright("totale")) - phi dot.op p_S) $
- $U_A$: Umidità assoluta
- $phi$: Umidità relativa
- $p_S$: Pressione di saturazione del vapore alla data T
- $p_(upright("totale"))$: Pressione totale
Formule correlate : $ U_A = m_(H 2 O) / m_(A r i a med S e c c a) $ $ 0.622 = frac(R, M m_(H 2 O)) dot.op frac(M m_(A r i a med S e c c a), R) $
== Umidità Relativa <umidità-relativa>
$
phi = (P_v (T=T_x)) / (P_(s a t) (T=T_x))
$
- $T_x$: Temperatura fissata
- $phi$: Umidità relativa
- $P_V$: Pressione parziale vapore
- $P_(upright("sat"))$: Pressione di saturazione del vapore
== Entalpia <entalpia>
Formula concettuale:
$
h = "aria secca" + "vapore 0°C" + "vapore da 0°C a "T_x + "acqua condensata"
$
- Il contributo del vapore è formato da *entalpia di formazione del vapore* + *vapore a $T>=T_"condensazione"$*
- L'acqua condensata è data dalla quantità di umidità ecceduta rispetto all'umidità di saturazione.
Ci sono due casi:
- *Senza condensa* -- quando l'umidità assoluta finale che si ottiene in seguito ad una climatizzazione *è minore o uguale* della umidità di saturazione
#box(text([#v(0.2cm) #h(0.2cm) Se $U_a <= U_(s a t)$],color.white),fill: rgb("#0a42dcc8"),height: .9cm, width: 3.8cm, radius: .5cm)
$ h = c_(p_(A S)) dot.op T_x med + med U_a dot.op lr((c_(p_v) T_x + Delta h_(0 , v))) $
- *Con condensa* -- quando l'umidità finale è maggiore di quella di saturazione
#box(text([#v(0.2cm) #h(0.2cm) Se $U_a > U_(s a t)$],color.white),fill: rgb("#0a42dcc8"),height: .9cm, width: 3.8cm, radius: .5cm)
$ h = c_(p_(A S)) dot.op T_x med + med U_a dot.op lr((c_(p_v) T_x + Delta h_(0 , v))) + (U_a - U_"sat")$
Dove:
- $c_(p_(A S)) = 1.007 frac(k J, k g)$ : calore specifico aria secca
- $c_(p_v) = 1.86 frac(k J, k g)$ : calore specifico vapore
- $h_(0 , v) = 2506.1 frac(k J, k g)$ : entalpia vapore a 0 C°
- $T$ : temperatura in Celsius
- $U_a$ : umidità assoluta
\
== Temperatura di Rugiada
È la temperatura alla quale il vapore contenuto nell'aria inizia condensarsi.
=== Metodo Analitico
Esempio:
- Umidità relativa = 60%
- Temperatura = 20 C°
Da questi dati si può ricavare qual è la *pressione parziale di vapore*. Cioè quella parte della pressione totale data dalla presenza di vapore, secondo la legge delle pressioni parziali, la pressione totale di un volume contenente gas/vapore è dato dalla somma delle pressioni parziali. Quindi:
$
P_"tot" = P_v + P_"as"
$
- Pv : pressione parziale del vapore
- Pas : pressione parziale dell'Aria Secca
Per calcolare la pressione parziale di vapore si può usare la definizione di umidità relativa:
$
phi = P_v / P_"sat"(T=20 C°) \ \ => \ \
P_v = phi dot P_"sat"(T=20 C°) \
$
Quindi la Pv sarà il 60%($phi$=0.6) della *attuale pressione di saturazione* cioè quella a 20C°, la *$P_"sat"$ dipende solamente dalla temperatura*.
- Come si ricava la $P_"sat"$?\ Ad ogni valore di pressione di saturazione del vapore si ha anche un valore di temperatura corrispondente.\ Quindi basta vedere la pressione associata alla temperatura attuale, in questo caso 20C° sulla tabella di vapore-acqua satura. Da cui 20C° $=>$ 2.337 kPa.
#let p_v = {
0.6 * 2.337
}
$
P_v = 0.6 dot 2.337 space k P a = #str(p_v,).slice(0,6) space k P a
$
Se ora ci mettiamo nel caso in cui la P di saturazione del vapore è proprio 1.4022 kPa possiamo andare a vedere a che temperatura corrisponde questa condizione. Dalla tabella non c'è il valore esatto corrispondente a 1.4022 kPa ma ci sono valori in cui è compreso 1.227kPa (10C°) e 1.7039kPa (15C°), si procede con l'interpolazione lineare:
$
T_r = (T_2 - T_1) / (P_2 - P_1) (P_x - P_1) + T_1 = 11.8368 space C°
$
(non è niente altro che la formula della retta passante per 2 punti)\
#align(center, $y - y_1 = (y_2 - y_1) / (x_2 - x_1) dot (x - x_1) $)
Si potevano usare anche i valori della tabella con i valori di pressione tra 1 e 1.5 kPa, il risultato esce leggermente diverso. Essendo un'interpolazione sono entrambe approssimazioni, con l'assunzione che tra due valori vicini si può approssimare l'andamento lineare (come una retta).
*L'umidità relativa* _dipende_ dalla *temperatura* (che varia la $P_"sat"$) e dalla *quantità di vapore nell'aria* (rappresentata dalla pressione parziale di vapore).
È la relazione che c'è tra temperatura e pressione parziale di vapore.
=== Metodo grafico (diagramma psicrometrico)
Vedere l'altezza del punto di coordinate $(phi , T)$, il punto che si ottiene incrociando la temperatura di bulbo secco con la curva dell'umidità relativa.
Proiettare il punto orizzontalmente a destra sul metro delle temperature di rugiada e leggere il valore. |
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas1/5_Piatok.typ | typst | #let V = (
"HV": (
("", "Prechváľniji múčenicy", "Na kresťí prečísťiji rúci tvojí prostérl jesí Christé, ot tebé daléče bývšyja prizyvája, i blíz tebé ustrojája. Ťímže moľúsja tí: pľinéna mjá bývša strasťmí soberí, i pokajánije mí dáruj, vsjáku skvérnu strastnúju očiščájuščeje."),
("", "", "Dláni prečístyja tvojá Christé, na drévi voznésl, i tvojá pérsty okrovavíl jesí, choťá izbáviti božéstvennych rúk tvojích ďílo, čelovikoľúbče Adáma, prestuplénijem deržíma v cárstvijich smértnych: jehóže vozdvíhl jesí vlástiju tvojéju vsesíľne."),
("", "", "Preterpíl jesí postradáti nás rádi Spáse, íže jestestvóm neprelóžen, i bezstrástnyj Božestvóm, raspináješisja beznačáľne so zloďiji, tý bezhríšne Christé: i sólnce ne terpjá derznovénija pomračísja, i zemľá vsjá trjasášesja, tvorcá ťa míru poznávši."),
("", "Prechváľniji múčenicy", "Ďíva neskvérnaja inohdá na drévi víďašči, jehóže iz bezsímenna rodí čréva, ne terpjášči utróby ujazvlénija, vlasý terzájušči hlahólaše: íže manovénijem soderžáj tvár vsjú, káko na krest vozdvíhlsja jesí jáko osuždén, vsjáko choťá spastí čelovíčestvo?"),
("", "", "Ďíva neskvérnaja inohdá na drévi víďašči, jehóže iz bezsímenna rodí čréva, ne terpjášči utróby ujazvlénija, vlasý terzájušči hlahólaše: íže manovénijem soderžáj tvár vsjú, káko na krest vozdvíhlsja jesí jáko osuždén, vsjáko choťá spastí čelovíčestvo?"),
("", "", "O čádo neizrečénnoje Otcá prebeznačáľna, hlahólaše prečístaja, na kresťí vzirájušči mojé roždénije, káko ne urazumíju, za kája tebí sijá vozdáša bezblahodátniji ľúdije? No vo jéže prišél jesí spastí tvojé sozdánije, vsjá terpíši dolhoterpilívňi, blahoutróbne."),
("Krestobohoródičen", "", "Vkušénije drévneje Adámovo hórkoje, vkusívyj žélči i ócta, usladíl jesí čádo sladčájšeje, voznéssja na drévi: ťímže mjá jáko sudijá právednyj, vračébnoju strástiju tvojéju usladí Vladýko, voskrés jáko vsesílen, Ďíva hlahólaše slezjášči."),
),
"S": (
("", "", "Krest vozdruzísja na lóbňim, i procveté nám bezsmértije ot istóčnika prisnotekúščaho, rebrá Spásova."),
("", "", "Nerazrušéna sťiná nám jésť čéstnýj krest Spásov, na nehó bo naďíjuščesja spasájemsja vsí."),
("Múčeničen", "", "Molítvami Hóspodi vsích svjatých, i Bohoródicy, tvój mír dážď nám, i pomíluj nás jáko jedín ščédr."),
("Krestobohoródičen", "", "Zakolénije tvojé neprávednoje Christé, Ďíva zrjášči, pláčušči vopijáše tí: čádo sladčájšeje, káko bez právdy stráždeši? I káko na drévi vísiši, íže vsjú zémľu povísivyj na vodách? Ne ostávi mené jedínu, blahoďíteľu mnohomílostive, Máter i rabú tvojú, moľúsja.")
),
)
#let P = (
"1": (
("", "", "Hórkija rabóty izbávľsja Izráiľ, neprochodímoje prójde jáko súšu, vrahá zrjá potopľájema, písň jáko blahoďíteľu pojét Bóhu, čudoďíjuščemu mýšceju vysókoju, jáko proslávisja."),
("", "", "Vo otčájaniji oderžím jésm, mnóžestvo pomyšľáju prehrišénij mojích, i sudijí otvít, Vladýčice Bohoródice: no tý mi búdi božéstvennaja chodátaica, premiňájušči jehó milosérdijem tvojím."),
("", "", "Christijánskoje pribížišče, pádajuščich ispravlénije, prečístaja, sohrišájuščich očiščénije, izbávi mjá prí strášnyja, i ohňá nehasímaho, žízň víčnuju podajúšči mí."),
("", "", "Tebé Ďívo jedínu vsí vírniji sťažáchom zastúpnicu tvérdu, tý bo Bóha rodilá jesí. Ťímže chvalámi vsí čístaja ťá ublažájem, ródi vsí zemníji po hlahólu tvojemú."),
("", "", "Na kresťí víďivši čístaja ziždíteľa i Sýna tvojehó vseneporóčnaja, úžasa ispólnšisja hlahólaše: čtó sijé čádo jáko zločestíviji vozdáša tí zlája voz blahája, jáže javíl jesí ím?"),
),
"3": (
("", "", "Préžde vík ot Otcá roždénnomu netľínno Sýnu, i v posľídňaja ot Ďívy voploščénnomu bezsímenno Christú Bóhu vozopijím: voznesýj róh náš, svját jesí Hóspodi."),
("", "", "Vsí prorócy ťá Máter Bóžiju propovídachu óbrazy preslávnymi: mý sbytijé jásno víďašče vírujem, i prósim ulučíti tobóju božéstvennyja tíchosti."),
("", "", "Vladýčice míra, spasénije vírnych i zastuplénije, jáže iz hlubiný sérdca vozdychánija mojá, vospuščájema čístaja, i sléz tóki prijémši, svjázannaho prehrišéniji mnóhimi izbávi i spasí mja."),
("", "", "Imúšči jáko Máti derznovénije čístaja, ko Christú Bóhu, ot ahárjanskich čád izbávitisja nám molí prísno, i ot vsjákaho vréda, i blahodárno sláviti jehó, preneporóčnaja, utverdí."),
("", "", "Na kresťí vozneséna Sýna svojehó zrjášči prečístaja, vosklicáše, i v boľízni sérdca vozhlašáše vopijúšči. Sýne, čtó ti soďíjaša nasýščšijisja tvojích daróv zločestíviji i bezzakónniji?"),
),
"4": (
("", "", "Žézl iz kórene jesséova, i cvít ot nehó Christé ot Ďívy prozjábl jesí, iz horý chváľnyj, priosinénnyja čášči, prišél jesí voplóščsja ot neiskusomúžnyja neveščéstvennyj i Bóže, sláva síľi tvojéj Hóspodi."),
("", "", "Nizloží surovstvó lukávych vráh, i kovárstva jáže prinosímaja na mjá: i oblecý mja tvojéju krípostiju, vseneporóčnaja, nevredíma prísno sobľudájušči, cíla i nepokolebíma, svítlo ťá vospivájuščaho."),
("", "", "Pobeždén zakónom plóti, bezmístnaja ďílaju bezzakónija vsestrástnyj, i vsjáčeski ne smíju vozvestí óko mojé Vladýčice čístaja, k tebí: no tý zakónom milosérdija tvojehó spasí mja okajánnaho, spasí mja."),
("", "", "Jedínu ťá vírniji s Bohom, upovánije nepostýdno i zastuplénije ímamy Vladýčice: tvojími molítvami izbávi nás ot vsjákich vráh: vídimych i nevídimych, vréda i iskušénij, da ťá neprestánno slávim."),
("", "", "Bez símene jehóže rodilá jesí Sýna, zrjášči vseneporóčnaja na kresťí prihvoždéna, vosklicáše máterski, i rydájušči hlahólaše: čtó jéže na tebí Sýne mój, vížu nóvoje i preslávnoje, i nedovídomoje čúdo?"),
),
"5": (
("", "", "Bóh sýj míra, otéc ščedrót, velíkaho sovíta tvojehó ánhela, mír podavájušča poslál jesí nám. Ťím Bohorazúmija k svítu nastávľšesja, ot nóšči útreňujušče slavoslóvim ťá čelovikoľúbče."),
("", "", "Molítvu neusýpnu imúšči, i téploje zastuplénije o rabích tvojích, vo vsjákich napástvujemych žitijá bidách predvarívši Ďívo, ischití, i spasí, da ne pečáliju požérty búdem i istľíjem."),
("", "", "Maríje Bóžije žilíšče, mené žilíšče bývša lukávych duchóv ďíly skvérnymi, i sích ispolňájuščaho vóľu bezúmno, pokajánijem javí Bóhu žilíšče."),
("", "", "Boľáščyja ný ľúťi dušéju vkúpi i ťílom, strasťmí hrichóvnymi, iscilí jáko milosérdaja i Bóha Máti: tý bo velíkaho voístinnu dušám že i ťílom vračá rodilá jesí Christá, neoskúdnyj istóčnik žízni."),
("", "", "Na drévi krestňim zrjášči Sýna, razlivášesja utróboju, i so slezámi vzyváše preneporóčnaja: užasájusja tvojehó dolhoterpínija Sýne mój, nóvoje víďašči čúdo: káko bezhríšen sýj neprávednuju terpíši smérť?"),
),
"6": (
("", "", "Iz utróby Jónu mladédnca izblevá morskíj zvír, jaková priját: v Ďívu že vsélšejesja slóvo, i plóť prijémšeje prójde sochránšeje netľínnu: jehóže bo ne postradá istľínija, róždšuju sochraní nevreždénnu."),
("", "", "Míra mýslennaho prijátelišče bylá jesí, vsjú zémľu oblahouchávšaho Božestvá blahími voňámi, presvjatája Bohonevísto. Ťímže blahouchánijem molítvy tvojejá vsjákoje zlosmrádije potrebí ot duší mojích prehrišénij."),
("", "", "Óhň slastéj ziló opaľájet mjá, i oskorbľájet smirénnoje mojé sérdce, i k bezmístnomu ďílaniju sovokupľájet mjá bezzakónno. Potščísja séj uhasíti, jáže óhň božéstvennyj róždšaja, spasénije mojé Bohonevístnaja."),
("", "", "Izbávi nás Ďívo vsepítaja, ot napástej vráh vídimych i nevídimych, i sobľudí Máti Bóžija pravoslávnoju víroju voístinnu Bohoródicu ťá ispovídajuščich: ímaši bo prísno móšč, jáko róždši sozdávšaho vsjáčeskaja."),
("", "", "Pri kresťí stojášči, i víďašči svojehó Sýna, plótiju vísima preneporóčnaja, raspaláše pečáliju utróbu svojú, i slezámi oblivájušči vzyváše: čádo, voístinnu neizhlahólanno na vsjá čelovíki tvojé blahoutróbije."),
),
"S": (
("", "Hrób tvój Spáse", "Neskvérnaja áhnica, áhnca i pástyrja vísjašča mértva na drévi zrjášči, rydájušči viščáše, Máterski vosklicájušči: káko preterpľú tvojé, jéže páče slóva Sýne mój, snítije i vóľnyja strásti, Bóže prebláhíj?"),
),
"7": (
("", "", "Ótrocy blahočéstiju sovospitáni, zločestívaho veľínija nebréhše, óhnennaho preščénija ne ubojášasja, no posreďí plámene stojášče pojáchu: otcév Bóže blahoslovén jesí."),
("", "", "Ne terpľú bisóvskaho prilóha i molvý, pomračájet bo mí úm plámeň slastéj plotskích: no ne prézri mené, svjatája Bohoródice, upovánije mojé na ťá vozložívšaho."),
("", "", "Beznevístnaja Ďívo, vsesvjatája Bohonevísto Vladýčice, prehrišénij mojích plenícy razriší molítvami tvojími, i sojúz ľubvé Christóvy prisovokupí, dobroďíteľnyja plodý prinestí mi."),
("", "", "Jáže vsím súščym v míri, zastúpnica jesí i sťiná christijánom, i pribížišče nepostýdno čístaja Maríje ťímže víroju ťá čtúšče vopijém Christú: otéc nášich Bóže blahoslovén jesí."),
("", "", "Presvjatája Ďíva zrjášči Sýna svojehó vísima na kresťí, užásno divľášesja, i hlahólaše: káko preterpľú umerščvléna víďašči ťá načáľnika žízni, i žiznodávca."),
),
"8": (
("", "", "Čúda prejestéstvennaho pokazá óbraz, ohnerósnaja péšč drévle: óhň bo ne opalí júnyja ďíti, Christóvo javľája bezsímennoje ot Ďívy božéstvennoje roždestvó. Ťím vospivájušče vospojím: da blahoslovít tvár vsjá Hóspoda, i prevoznósit vo vsjá víki."),
("", "", "Vladýčice míra Bohoródice, vo hlubiňí zól pohíbeli mené pohružénnaho zloúmňi slasťmí plotskími, i pristrástijem veščmí žitijá, vozvedí jedína milosérdijem tvojím. Ne ímam bo nadéždy spasénija otňúd: vés bo jésm, čístaja, vo otčájaniji."),
("", "", "Tý jesí spasénije vsích čelovíkov, jáže Bóha róždši neizrečénnym óbrazom: tý vírnych spasíteľnica Bohoródice, i sľipých nastávnica, i pádajuščich ispravlénije. Ťímže ťá voschvaľájušče Christú zovém: blahoslovíte vsjá ďilá Hóspoda, pójte i prevoznosíte jehó vo víki."),
("", "", "Sťínu pretvérdu ťá sťažávše, spasénija nášeho nadéždu na ťá vozložíchom, Bohomáti. No tý búdi rabóm tvojím pristánišče, i sťiná neoboríma, i ko jéže vopíti neprestánno naprávi: da blahoslovít tvár vsjákaja Hóspoda, i prevoznósit jehó vo víki."),
("", "", "Utróboju máterski rasterzájema, i slezámi mnóhimi ispolňájema, jáže čísto róždšaja ťá zrjášči na kresťí, stenáňmi neuťíšnymi vzyváše: boľízni izbíhši v roždeství tvojém Sýne mój, boľízniju nýňi oderžíma jésm, víďašči zrák tvój bezčésten."),
),
"9": (
("", "", "Neizhlahólannoje Ďívy tájinstvo: Nébo bo sijá, i prestól cheruvímskij, i svetonósnyj čertóh pokazásja, Christá Bóha vsederžíteľa, sijú blahočéstno jáko Bohoródicu veličájem."),
("", "", "Okaľách bezčéstija strasťmí dúšu mojú okajánnyj, vsjú že dušetľínnymi strasťmí oskverních plóť: no jáko čístaja že i neskvérnaja, tý mja očísti mnóžestvom mílosti tvojejá."),
("", "", "Ne sťažách rázvi tebé čístaja pribížišča, ne znáju Vladýčice, íny na zemlí zastúpnicy tvérdyja i pokróva: ťímže k tebí tépľi pritekóch, prosjá tobóju prijáti sohrišénij izbavlénije."),
("", "", "Vsepítaja, tvojá rabý nýňi mílostivno zríši svýše, víroju blahočéstnoju sobľudájušči, i tvojími molítvami vsjáčeskich izbavľájušči nás obstojánij, ístinnuju ťá čtúščich Bohoródicu čístuju."),
("", "", "Jáže bezsímennoje roždénije poznávšaja, ťá čelovikoľúbče na drévi krestňim povíšena jáko víďi, vopijáše: Sýne i Bóže mój vsesíľne, čelovíki spastí choťáj, káko prijál jesí nýňi raspjátije?"),
),
)
#let U = (
"S1": (
("", "", "Raspénšusja tí Christé, pohíbe mučíteľstvo, i poprána býsť síla vrážija: ni ánhel bo, ni čelovík, no tý sám Hóspodi spásl jesí nás, sláva tebí."),
("", "", "Krestá tvojehó drévu poklaňájemsja čelovikoľúbče, jáko na tóm prihvozdílsja jesí životé vsích: ráj otvérzl jesí Spáse, víroju prišédšemu k tebí razbójniku, i píšči spodóbil jesí ispovídujuščaho ťá: pomjaní mja Hóspodi. Prijimí jákože ónaho, i nás vopijúščich tebí: sohrišíchom vsí, milosérdijem tvojím ne prézri nás."),
("Krestobohoródičen", "", "Neskvérnaja áhnica, áhnca i pástyrja povíšena na drévi mértva zrjášči, pláčušči viščáše, máterski vosklicájušči: káko preterpľú tvojé, jéže páče slóva Sýne mój snítije, i vóľnyja strásti, Bóže preblahíj?"),
),
"S2": (
("", "", "Orúžije krestnoje vo braňích javísja inohdá blahočestívomu carjú Konstantínu, nepobidímaja pobída na vrahí, víry rádi, sehó trepéščut soprotívnyja síly, sijé býsť vírnym spasénije, i Pávlu pochvalá."),
("", "", "Íže drévle Adáma ot pérsti sozdávyj, brénnoju rukóju zaušén býv ščédre, i raspjátije preterpíl jesí, poruhánija že i rány. O čudesé! o mnóhaho dolhoterpínija tvojehó! Sláva Hóspodi živonósnym tvojím strastém, ímiže nás spásl jesí."),
("Múčeničen", "", "Stradánija pochvalóju, i vinéčnoju póčestiju, slávniji strastotérpcy, oďíjavšesja tobóju Hóspodi, terpínijem úbo rán bezzakónnych pobidíša, i síloju božéstvennoju ot nebés pobídu prijáša. Ťích molítvami i nás svobodí ot nevídimaho vrahá Spáse, i spasí nás."),
("Krestobohoródičen", "", "Zrjášči ťá Christé, vseneporóčnaja Máti, mértva na kresťí prostérta, vopijáše: Sýne mój sobeznačáľne Otcú i Dúchu, čtó neizrečénnoje tvojé sijé smotrénije, ímže spásl jesí ščédre, prečístuju rukú tvojéju sozdánije?"),
),
"S3": (
("", "", "Na drévi ťá Slóve krestňim, sólnca slávy Iisúse, za milosérdije mílosti, povíšena plótiju vóleju, jáko víďi sólnce, ne terpjášči derznovénija, pomračísja. Ťímže omračénnuju mojú dúšu prosvití neprikosnovénnym svítom tvojím, i spasí mja, moľúsja."),
("", "", "Na kresťí prihvozdílsja jesí vóleju ščédre, obožíl jesí istľívšeje náše suščestvó, i čelovikoubíjcu zmíja umertvíl jesí. No utverdí pravoslávije v míri, i nizloží jeretíčestvujuščich vostánija, čéstným krestóm tvojím."),
("Krestobohoródičen", "", "Íže tvojé zastuplénije sťažávše prečístaja, i tvojími molítvami ot bíd izbavľájemsja: krestóm bo Sýna tvojehó vsehdá chraními vezší, po dólhu ťá vsí blahočéstno veličájem."),
),
"K": (
"P1": (
"1": (
("", "", "Pomóhšemu Bóhu vo Jehípťi Moiséovi, i ťím faraóna so vsevójinstvom pohruzívšemu, pobídnuju písň pojím, jáko proslávisja."),
("", "", "Strásti preterpív nás rádi, íže jestestvóm bezstrásten, i ráspjat býv s razbójnikoma, načalozlóbnaho zmíja umertvíl jesí Slóve, i spásl jesí poklaňájuščyjasja tebí."),
("", "", "Vostók vostókov sýj, k západom otrinovénomu jestestvú nášemu Iisúse prišél jesí: tebé že sólnca zrjá raspinájema, svít svój sokrý."),
("Múčeničen", "", "Smértiju vrémennoju žízň víčnuju preminívše dóbri stradáľcy slávniji, cárstvija nebésnaho spodóbistesja: sehó rádi proslavľájetesja, i blažími jesté."),
("Múčeničen", "", "Íže strástém Christóvym upodóbľšesja dóblestvenňi, strásti isciľivájete zemných, rukoďíjstvijem tájnym, i slóvom prohónite dúchi, svjatíji múčenicy."),
("Bohoródičen", "", "jákože áhnica zrjášči na kresťí Christá vozdvížena, i vzirájušči áhnca vosklicájušči vopijáše: hďí tvojá zájde dobróta, dolhoterpilíve Sýne prebeznačáľne?"),
),
"2": (
("", "", "Písň pobídnuju pojím vsí Bóhu, sotvóršemu dívnaja čudesá mýšceju vysókoju, i spásšemu Izráiľa, jáko proslávisja."),
("", "", "Jáže jedína bezľítnaho Bóha v ľíto róždši voploščénna, vsesvjatája prečístaja, vseľítnyja strásti preokajánnyja mojejá duší iscilí."),
("", "", "Strúpy duší mojejá, i sérdca nedoumínije, pomyšlénij omračénije, i úmnoje pobiždénije potrebí prečístaja, jáko mílostivaja, tvojími molítvami."),
("", "", "Jáže svít róždšaja Izbáviteľa mojehó, ťmý i múk víčnych izbávi mjá prečístaja: jáko da spasájem vospiváju blahoutróbije tvojé."),
("", "", "V pučíňi ľútych, i v molví strastéj potopľájem jésm áz, tvojú prečístaja prizyváju tišinú: spasí mja, pristánišče bo jesí vírnych."),
),
),
"P3": (
"1": (
("", "", "Da utverdítsja sérdce mojé v vóli tvojéj Christé Bóže, íže nad vodámi nébo utverždéj vtoróje, i osnovávyj na vodách zémľu vsesíľne."),
("", "", "Na kresťí dláni rasprostérl jesí, i pérsty božéstvennyja okrovavív, ďílo rukú tvojéju Vladýko, Adáma ubíjstvennyja rukí izbavľája, jáko jedín bláh i čelovikoľúbec."),
("", "", "V rébra probodén býl jesí kopijém Vladýko, ispravľája rébrennoje popolznovénije, na drévo voznéslsja jesí, drévle bidú prijémšaho dréva plodóm, v ráj vvoďá s razbójnikom blahorazúmnym."),
("Múčeničen", "", "Cerkóvnaja utverždénija, blahočéstija prédnija stolpý, potrebíteli vrážija, Hospódni múčeniki, mýsliju čístoju písnenno da ublážím."),
("Múčeničen", "", "Jáko božéstvennoje súšče lózije mýslennaho vinohráda múčenicy, hrózdije iznesóša nám jávi, terpínija izlivájuščeje vinó, i vsích vírnych serdcá veseľáščeje."),
("Bohoródičen", "", "Blahoslovén plód čréva tvojehó Ďívo vsepítaja, istľívšaja plodóm dréva, rádi krestá svojehó, netľínija ustróivyj pričástniki, božéstvennoju blahodátiju ."),
),
"2": (
("", "", "Da utverdítsja sérdce mojé v vóli tvojéj Christé Bóže, íže nad vodámi nébo utverždéj vtoróje, i osnovávyj na vodách zémľu vsesíľne."),
("", "", "Neplódnyja mýsli mojejá bezplódije vsé potrebí, i plodonósnu dobroďítelmi dúšu mojú pokaží, prečístaja Bohoródice, vírnym pomóščnice."),
("", "", "Izbávi mjá vseneporóčnaja, vsjákaho obstojánija, mnóhich soblázn zmijévych, i víčnaho ohňá, i ťmý, jáže svít róždšaja prevíčnyj."),
("", "", "Strášnym sudíščem čístaja, i ohném ónem neuhasímym, i otvítom ľútym vés osuždén jésm: potščísja spastí mja Vladýčice prečístaja, rabá tvojehó."),
("", "", "Da obožít čelovíčestvo, Bóh býsť čelovík iz tebé Ďívo čístaja, páče slóva i smýsla: sehó rádi ťá sohlásno vsí vírniji ublažájem."),
),
),
"P4": (
"1": (
("", "", "Uslýšach Hóspodi slúch tvój, i ubojáchsja: razumích ďilá tvojá, prorók hlahólaše, i proslávich sílu tvojú."),
("", "", "Zakonodávec práveden sýj, so bezzakónniki vminén býl jesí, na drévo voznéslsja jesí blahoďíteľu Hóspodi, vsích opravdáti choťá."),
("", "", "Síly vsjá udivíšasja ánheľskija, na kresťí tebé zrjášči voznosíma sólnce, i ťmý načáľnyja síly pobiždéni býša."),
("Múčeničen", "", "Iscilénij blahodáť ot duchóvnych darovánij počérpše múčenicy, vsím otmyvájut strásti dušetľínnyja Bóžijeju blahodátiju."),
("Múčeničen", "", "Dremánije otrínuvše neraďínija strastotérpcy, bódrostiju božéstvennoju, i víroju zviréj uspíša stremlénija, i rádujuščesja postradáša."),
("Bohoródičen", "", "Uvý mňí čádo, čtó búdu? Káko zrjú ťa na drévo vozdvížena, i bez právdy umerščvľájema živót podajúščaho? Ďíva pláčušči hlahólaše."),
),
"2": (
("", "", "Dúchom províďa proróče Avvakúme slovesé voploščénije, propovídal jesí vopijá: vnehdá priblížitisja ľítom, poznáješisja, vnehdá prijití vrémeni, pokážešisja: sláva síľi tvojéj Hóspodi."),
("", "", "Ďívo Bohoródice, neskvérnaja síne, oskvernéna mjá prehrišéňmi očísti ščedrótami tvojími, čisťíjšimi kropléňmi: dážď mí rúku pómošči, da zovú: sláva tebí čístaja Bohonevísto."),
("", "", "Chrám osvjaščén javílsja jesí Bóhu, v ťá vséľšemusja páče umá: tohó molí, hrichóvnych skvérn nás očístiti, jáko da chrám poznájemsja, i obítelišče duchóvnoje."),
("", "", "Pomíluj mjá Bohoródice, jáže jedína mílostej istóčnik róždšaja, i razriší duší mojejá ľútuju boľízň, i nedoumínije serdéčnoje: sléz strujú i umilénije préžde koncá podážď, i ľútych izbavlénije."),
("", "", "Svjatája Bohoródice, osvjatí nás, presvjatáho róždši plótiju, upodóbitisja choťáščaho čelovíkom, i nebésnomu cárstviju pričástniki vsích pokaží, prečístaja, tvojími molítvami."),
),
),
"P5": (
"1": (
("", "", "Svítlyj nám vozsijáj svít prisnosúščnyj, útreňujuščym o suďbách zápovidej tvojích, Vladýko čelovikoľúbče Christé Bóže náš."),
("", "", "Na kresťí plótiju vozdvizájem, jazýki prizvál jesí nevídujuščyja tebé, k tvojemú poznániju, sudijé vsích, jedíne mílostive Christé Bóže náš."),
("", "", "Tebí na sudíšči stávšu neprávedňim, právedne Hóspodi, opravdásja préžde osuždénnyj Adám, i zovét: sláva raspjátiju tvojemú, dolhoterpilíve Hóspodi."),
("Múčeničen", "", "Jákože ráj Bohonasaždénnyj javístesja múčenicy, strásti čestnýja jáko cvíty blahouchánnyja imúšče, ímiže blahouchájetsja vírnych dušá vsjákaja."),
("Múčeničen", "", "Bláhocvítnaja i blahoplodovítaja drevesá, íže víry bezsmértija plód procvitóša, i zlóby korénija istorhóša, vospojím múčeniki Hospódni."),
("Bohoródičen", "", "Žézl čestnýj, jáže prozjábšij cvít neuvjadájuščij, jáko uzrí na drévo voznosíma tohó, vopijáše: Vladýko, ne bezčádnu javí mja."),
),
"2": (
("", "", "Tvój mír dážď nám Sýne Bóžij, inóho bo rázvi tebé Bóha ne znájem, ímja tvojé imenújem, jáko Bóh živých i mértvych jesí."),
("", "", "Mértva mjá soďíla inohdá vo Jedémi vkušénije lukávoje: no jáže žízň róždšaja prečístaja, drévle drévom uméršaho oživí mja nýňi, i podážď umilénije."),
("", "", "Spasí mja prečístaja, ot bíd ľútych i vozdvíhni mjá ot hnója strastéj, i izbávi mjá pľinénija i ozloblénija lukávych bisóv, tvojehó nepotrébnaho rabá."),
("", "", "Zinicy duší mojejá ozarí čístaja, zríti mí prísno božéstvennuju svítlosť, i tvojú slávu vseneporóčnaja, jáko da polučú mílosť i víčnuju slávu."),
("", "", "Óblak i ráj, i dvér ťá svíta, trapézu, i runó vímy, rúčku vnútr mánnu nosjášču, sládosť míru, čístaja Ďívo Máti."),
),
),
"P6": (
"1": (
("", "", "Proróka spásl jesí ot kíta čelovikoľúbče, i mené iz hlubiný prehrišénij vozvedí, moľúsja."),
("", "", "Íže čésti vsjákija prevýšši, bezčéstije preterpíl jesí Christé, na kresťí vozdvížen, čelovíki počestí choťá."),
("", "", "Podpisúješi mňí ostavlénije, poraboščénnomu ľstívym, tróstiju bijém Christé Bóže náš preblahíj."),
("Múčeničen", "", "Boľízňmi stradánij k neboľíznenňij preidóste svjatíji končíňi, i neizrečénnyja rádosti spodóbľšesja."),
("Múčeničen", "", "Razžehóstesja úhľmi Christóvy ľubvé premúdriji: ťímže vo óhň vmetájemi ne opaľájemi prebýste."),
("Bohoródičen", "", "Po roždeství vseneporóčnaja, jákože i préžde roždestvá prebylá jesí: Bóha bo rodilá jesí drévom čelovíka spásšaho."),
),
"2": (
("", "", "Proróka Jónu podražája vopijú: živót mój bláže svobodí iz tlí, i spasí mja Spáse míra, zovúšča: sláva tebí."),
("", "", "Oskvernéna mjá mnóhimi hrichí, moľúsja tebí jedínoj bláhój, i neskvérňij síni: omýj ot vsjákija skvérny, chodátajstvom tvojím."),
("", "", "Okormíteľnica mí búdi čístaja, vlájemu v pučíňi ľútych, žitéjskimi núždami, i isprávi, k prísnomu pristánišču, i spasí mja."),
("", "", "Trevolnénije pomyšlénij, i strastéj nachoždénija, i hlubiná hrichóvnaja, okajánnuju mojú dúšu oburevájut: pomozí mi svjatája Vladýčice."),
("", "", "Svjaščénnaja síne pokazánnaja, Maríje, oskvernénnuju slasťmí okajánnuju mojú dúšu osvjatí."),
),
),
"P7": (
"1": (
("", "", "Péšč Spáse orošášesja, ótrocy že likújušče pojáchu: otcév Bóže blahoslovén jesí."),
("", "", "Raspinájem tvár pokolebál jesí: umerščvľájem zmíja umertvíl jesí: blahoslovén jesí Christé Bóže otéc nášich."),
("", "", "Napojájetsja žélčiju dolhoterpilívyj, istočája mí sládosť spasíteľnuju, sládostnoju sňídiju lišénnomu rájskija píšči."),
("Múčeničen", "", "Múčenicy nohoťmí strúžemi, mértvosti debeľstvó otložívše, krasotú že božéstvennuju ot Bóha prijáša."),
("Múčeničen", "", "Strásťmí strásti Christóvij prečísťij podóbjaščesja, dóbliji múčenicy, rány vrážija udób preterpíste."),
("Bohoródičen", "", "Raspinájema zrjášči Hóspoda neporóčnaja Bohoródica, hlahólaše: uvý mňí Sýne mój, káko umiráješi, životé i nadéždo vírnych?"),
),
"2": (
("", "", "Súščym v peščí otrokóm tvojím Spáse, ne prikosnúsja, nižé stuží óhň. Tohdá trijé, jáko jedíňimi ustý pojáchu i blahoslovľáchu, hlahóľušče: blahoslovén Bóh otéc nášich."),
("", "", "Oskvérnšujusja strasťmí dúšu mojú osvjatí, prečístaja Bohonevísto, i umá mojehó ľútoje pľinénije, i sérdca nedoumínije, i bisóvskaja ustremlénija vskóri potrebí čístaja."),
("", "", "Umerščvlénnyj strasťmí plotskími, vseneporóčnaja, oživí úm mój, i Bóhu uhódnaja soveršáti ukripí mjá: da veličáju ťá, i slávľu prísno blahoutróbije tvojé."),
("", "", "Ďívo Máti, jáže jedína Bóha róždšaja, umertví plotskíja mojá slásti, i dušévnuju mojú skvérnu otmýj vskóri: i isťazánija bisóv lukávych izbávi, i spasí mja."),
("", "", "Preispeščréna božéstvennymi dobroďítelmi, rodilá jesí Slóvo sobeznačáľno Otcú, čístaja Ďívo, dobroďíteľmi nebesá voístinnu pokrývšaho: jehóže molí prísno uščédriti nás."),
),
),
"P8": (
"1": (
("", "", "Pisnoslóvcy v peščí spásšaho ďíti, i hromoplámennuju prelóžšaho na rósu, Christá Bóha pójte i prevoznosíte vo vsjá víki."),
("", "", "Jehdá na kresťí spáse prihvozdílsja jesí, kolebášesja tvár: sólnce ustávi lučí, i kámenije raspadášesja, i ád skóro obnažášesja, ne terpjá deržávy tvojejá."),
("", "", "Za osuždénije otrinovénnaho osuždénije postradáv, za prijémšaho nahotú, náh na drévi vísel jesí ščédre: vélija tvojá deržáva i dolhoterpínije."),
("Múčeničen", "", "Íže bezplótnym sožítelije, Christóvy vójini, krestóm jáko broňámi obolčéni, k soprotivobórcu opolčíšasja, i tohó krásnymi nohámi popráša."),
("Múčeničen", "", "Stojáchu posreďí sudíšča s zaklépmi dóbliji, na údy razdrobľájemi, i zdánije razorjájušče prélesti, i bisóvskaja trébišča razbivájušče."),
("Bohoródičen", "", "Jáže nebés prevýššaja, vozdvížena na drévi, i nizlahájuščaho vozdvižénija vrážija, zrjášči jedínaho výšňaho, vospiváše tohó velehlásno."),
),
"2": (
("", "", "Jehóže užasájutsja ánheli, i vsjá vójinstva, jáko tvorcá i Hóspoda, pójte svjaščénnicy, proslávite ótrocy, blahoslovíte ľúdije i prevoznosíte vo vsjá víki."),
("", "", "Voploščájetsja bezplótnyj iz tebé Bohoľípno: jehóže molí prečístaja, strásti mojá plotskíja umertvíti, i oživíti dúšu mojú umerščvlénnuju hrichámi."),
("", "", "Isciľájuščaho sokrušénije Adáma pérstnaho, Spása rodilá jesí prečístaja i Bóha: tohó umolí, jázvy duší mojejá iscilíti, jáže neiscíľno boľáščyja."),
("", "", "Vozdvíhni sležášča mjá vo hlubiňí zlých, i nýňi borjúščaho mjá pobidí, čístaja, i ujázvlennuju bezmístnymi slasťmí dúšu mojú prečístaja ne prézri, no uščédri, i spasí mja."),
("", "", "Izbavľájemsja vsjáčeskich iskušénij, prečístaja, tvojími k Bóhu bódrennymi molítvami, tebé Bohoródicu svíduščiji blahoslovénnuju i obrádovannuju."),
),
),
"P9": (
"1": (
("", "", "Ťá, júže víďi Moiséj neopalímuju kupinú, i ľístvicu oduševlénnuju, júže Jákov víďi, i dvér nebésnuju, jéjuže prójde Christós Bóh náš, písňmi Máti čístaja veličájem."),
("", "", "O káko ľúdije nepokoríviji predáša ťá krestú, jedínaho dolhoterpilívaho vóleju obniščávšaho, i strásti prijémšaho, i bezstrástiju chodátaja bývša, vsím ot Adáma popólzšymsja!"),
("", "", "Raspjátije bezčéstnoje priját Christé plótiju, počestí choťá obezčéstvovannaho čelovíka strasťmí bezslovésnymi, i drévňuju dobrótu pohúbľša: sláva páče umá milosérdiju tvojemú."),
("Múčeničen", "", "Sólnce nezachodímoje Christé, útrenevavšyja k tebí, i ťmú stradánij prešédšyja mánijem tí, k svítu nastávil jesí tvojejá neizrečénnyja slávy i svítlosti: prosvití úbo nás ťích molítvami."),
("Múčeničen", "", "Pólk múčenik svjaščénnych, ťmý mýslennych vrahóv pobidí, i ťmám priminísja svjatých síl, i ťmý strastéj dúš nášich, manovénijem vseďíteľnym isciľájut prísno."),
("Bohoródičen", "", "Svítom Ďívo, iz tebé vozsijávšaho svíta plótiju, úm mój, ozarí, i sérdce prosvití, ťmú othoňájušči hrichóvnuju, i unýnija mojehó vsjáku mhlú prohoňájušči."),
),
"2": (
("", "", "Svitonósnyj óblak, vóňže vsích Vladýka, jáko dóžď s nebesé na runó sníde, i voplotísja nás rádi, býv čelovík, beznačáľnyj, veličájem vsí jáko Máter Bóha nášeho čístuju."),
("", "", "Hrichoľubív sýj v ľínosti prebyváju, i sudíšča, čístaja, neumýtnaho trepéšču: v némže mjá sobľudí tvojími svjatými molítvami Bohonevísto, neosuždénna, da jáko predstáteľnicu mojú ublažáju ťá, prečístaja."),
("", "", "Užasájusja sudíšča Ďívo, i nezabvénnaho óka tvojehó Sýna, soďíjav mnóhija hrichí na zemlí, i sehó rádi tebí vopijú: vsemilosérdaja Vladýčice pomozí mi, i tohdášnija bidý izbávi mjá, i spasí, čístaja."),
("", "", "Kóľ strášen déň ispytánija, otrokovíce! Kóľ užásen otvét! Kóľ horká bidá! Któ postojít próčeje prečístaja Vladýčice? Pomíluj strástnuju mojú dúšu, i préžde koncá dážď mí ostavlénije, prečístaja."),
("", "", "Jáže svít róždšaja božéstvennyj, iz Otcá vozsijávšij, omračénnuju mojú dúšu lesťmí žitéjskimi, i bývšuju vrahóv poruhánije vseneporóčnaja uščédri, i svítu pokajánija spasíteľnaho spodóbi, čístaja."),
),
),
),
"ST": (
("", "", "Tebé na dréve prihvóždšahosja plótiju, i živót nám podávšaho, jáko Spása i Vladýku pojím neprestánno."),
("", "", "Tvojím krestóm Christé, jedíno stádo býsť ánhelov i čelovíkov, i vo jedínom sobóri nébo i zemľá veselítsja: Hóspodi sláva tebí."),
("Múčeničen", "", "Strástotérpcy Christóvy prijidíte ľúdije vsí počtím píňmi i písňmi Dúchóvnymi, svetíľniki míra, i propoívédniki víry, istóčniki prisnotekúščija, iz níchže istekájut vírnym iscilénija. Ťích molítvami Christé Bóže náš, mír dáruj míru tvojemú, i dušám nášym véliju mílosť."),
("Krestobohoródičen", "Prechváľniji múčenicy", "Áhnca, áhnica i vseneporóčnaja Vladýčica, na kresťí jáko víďivši zráka ne imúšča, ni dobróty, uvý mňí, pláčušči hlahólaše: hďí dobróta tvojá zájde sladčájšij? Hďí blahoľípije? Hďí blahodáť sijájuščaja, óbraza tvojehó, Sýne mój ľubézňijšij?"),
)
)
#let L = (
"B": (
("", "", "Sňídiju izvedé iz rajá vráh Adáma: krestóm že vvedé Christós vóň razbójnika, pomjaní mja, zovúšča, jehdá priídeši vo cárstviji tvojém."),
("", "", "Raspénsja bezhríšne, hrichí vsích vzjál jesí Christé, i probodén býl jesí v rébra, spasénija potóki istočíl jesí, vodý že i króve, nazidája sokrušénnyja tléju."),
("", "", "Na drévi prihvoždájem vóleju Iisúse Bóže, vsé otjál jesí ščédre Adámovo strástnoje razumínije: jázvami že čestnými bisóvskoje mnóžestvo ujazvíl jesí."),
("Múčeničen", "", "Íže strástém upodóbľšesja, vóleju postradávšemu plótiju, múčenicy slávniji, prísno strásti isciľájete neiscíľnyja, nedúhi že othónite ot čelovík síloju duchóvnoju."),
("", "", "Ravnosíľnuju, jedinočéstnuju Tróicu slávim ťá, Otcá beznačáľnaho Bóha, i Sýna, i Dúcha svjatáho, jedíno trijipostásnoje Bohonačálije, víroju veličájem."),
("", "", "Na kresťí ťa prihvoždéna, jáko uzrí <NAME>, jáže tebé róždšaja plótiju, pláčušči viščáše: čtó ti vozdadé, o Sýne mój, jevréjskij sobór zakonoprestúpnyj?"),
)
) |
|
https://github.com/RolfBremer/in-dexter | https://raw.githubusercontent.com/RolfBremer/in-dexter/main/README.md | markdown | Apache License 2.0 | # in-dexter
Automatically create a handcrafted index in [typst](https://typst.app/).
This typst component allows the automatic creation of an Index page with entries
that have been manually marked in the document by its authors. This, in times
of advanced search functionality, seems somewhat outdated, but a handcrafted index
like this allows the authors to point the reader to just the right location in the
document.
⚠️ Typst is in beta and evolving, and this package evolves with it. As a result, no
backward compatibility is guaranteed yet. Also, the package itself is under development
and fine-tuning.
## Table of Contents
* [Usage](#usage)
* [Importing the Component](#importing-the-component)
* [Remarks for new version](#remarks-for-new-version)
* [Marking Entries](#marking-entries)
* [Generating the index page](#generating-the-index-page)
* [Brief Sample Document](#brief-sample-document)
* [Full Sample Document](#full-sample-document)
* [Changelog](#changelog)
* [v0.6.1](#v061)
* [v0.6.0](#v060)
* [v0.5.3](#v053)
* [v0.5.2](#v052)
* [v0.5.1](#v051)
* [v0.5.0](#v050)
* [v0.4.3](#v043)
* [v0.4.2](#v042)
* [v0.4.1](#v041)
* [v0.4.0](#v040)
* [v0.3.2](#v032)
* [v0.3.1](#v031)
* [v0.3.0](#v030)
* [v0.2.0](#v020)
* [v0.1.0](#v010)
* [v0.0.6](#v006)
* [v0.0.5](#v005)
* [v0.0.4](#v004)
* [v0.0.3](#v003)
* [v0.0.2](#v002)
## Usage
## Importing the Component
To use the index functionality, the component must be available. This
can be achieved by importing the package `in-dexter` into the project:
Add the following code to the head of the document file(s)
that want to use the index:
```typ
#import "@preview/in-dexter:0.6.1": *
```
Alternatively it can be loaded from the file, if you have it copied into your project.
```typ
#import "in-dexter.typ": *
```
## Remarks for new version
In previous versions (before 0.0.6) of in-dexter, it was required to hide the index
entries with a show rule. This is not required anymore.
## Marking Entries
To mark a word to be included in the index, a simple function can be used. In the
following sample code, the word "elit" is marked to be included into the index.
```typ
= Sample Text
Lorem ipsum dolor sit amet, consectetur adipiscing #index[elit], sed do eiusmod tempor
incididunt ut labore et dolore.
```
Nested entries can be created - the following would create an entry `adipiscing` with sub entry
`elit`.
```typ
= Sample Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit#index("adipiscing", "elit"), sed do eiusmod
tempor incididunt ut labore et dolore.
```
The marking, by default, is invisible in the resulting text, while the marked word
will still be visible. With the marking in place, the index component knows about
the word, as well as its location in the document.
## Generating the Index Page
The index page can be generated by the following function:
```typ
= Index
#columns(3)[
#make-index(title: none)
]
```
This sample uses the optional title, outline, and use-page-counter parameters:
```typ
#make-index(title: [Index], outlined: true, use-page-counter: true)
```
The `make-index()` function takes three optional arguments: `title`, `outlined`, and `use-page-counter`.
* `title` adds a title (with `heading`) and
* `outlined` is `false` by default and is passed to the heading function
* `use-page-counter` is `false` by default. If set to `true` it will use `counter(page).display()` for the page
number text in the index instead of the absolute page position (the absolute position is still
used for the actual link target)
If no title is given the heading should never appear in the layout.
Note: The heading is (currently) not numbered.
The first sample emits the index in three columns.
Note: The actual appearance depends on your template or other settings of your document.
You can find a preview image of the resulting page
on [in-dexter´s GitHub repository](https://github.com/RolfBremer/in-dexter).
You may have noticed that some page numbers are displayed as bold. These are index entries
which are marked as "main" entries. Such entries are meant to be the most important for
the given entry. They can be marked as follows:
```typ
#index(fmt: strong, [Willkommen])
```
or you can use the predefined semantically helper function
```typ
#index-main[Willkommen]
```
### Brief Sample Document
This is a very brief sample to demonstrate how in-dexter can be used. The next chapter
contains a more fleshed out sample.
```typ
#import "@preview/in-dexter:0.6.1": *
= My Sample Document with `in-dexter`
In this document the usage of the `in-dexter` package is demonstrated to create
a hand picked #index[Hand Picked] index. This sample #index-main[Sample]
document #index[Document] is quite short, and so is its index.
= Index
This section contains the generated Index.
#make-index()
```
### Full Sample Document
```typ
#import "@preview/in-dexter:0.6.1": *
#let index-main(..args) = index(fmt: strong, ..args)
// Document settings
#set page("a5")
#set text(font: ("Arial", "Trebuchet MS"), size: 12pt)
= My Sample Document with `in-dexter`
In this document #index[Document] the usage of the `in-dexter` package #index[Package]
is demonstrated to create a hand picked index #index-main[Index]. This sample document
is quite short, and so is its index. So to fill this sample with some real text,
let´s elaborate on some aspects of a hand picked #index[Hand Picked] index. So, "hand
picked" means, the entries #index[Entries] in the index are carefully chosen by the
author(s) of the document to point the reader, who is interested in a specific topic
within the documents domain #index[Domain], to the right spot #index[Spot]. Thats, how
it should be; and it is quite different to what is done in this sample text, where the
objective #index-main[Objective] was to put many different index markers
#index[Markers] into a small text, because a sample should be as brief as possible,
while providing enough substance #index[Substance] to demo the subject
#index[Subject]. The resulting index in this demo is somewhat pointless
#index[Pointless], because all entries are pointing to few different pages
#index[Pages], due to the fact that the demo text only has few pages #index[Page].
That is also the reason for what we chose the DIN A5 #index[DIN A5] format, and we
also continue with some remarks #index[Remarks] on the next page.
== Some more demo content without deeper meaning
#lorem(50) #index[Lorem]
#pagebreak()
== Remarks
Here are some more remarks #index-main[Remarks] to have some content on a second page, what
is a precondition #index[Precondition] to demo that Index #index[Index] entries
#index[Entries] may point to multiple pages.
= Index
This section #index[Section] contains the generated Index #index[Index], in a nice
two-column-layout.
#set text(size: 10pt)
#columns(2)[
#make-index()
]
```
The following image shows a generated index page of another document, with additional
formatting for headers applied.

More usage samples are shown in the document `sample-usage.typ` on
[in-dexter´s GitHub](https://github.com/RolfBremer/in-dexter).
A more complex sample PDF is available there as well.
</span>
## Changelog
### v0.6.1
* Configurable range delimiter. Defaults to em-dash now.
### v0.6.0
* Support for Ranges and Continuations (range references, f. ff.).
* Fix: Consolidate multiple references to the same page.
### v0.5.3
* Fix error in typst.toml file.
* Add a sample for raw display.
### v0.5.2
* Fix a bug with bang notation.
* Add compiler version to toml file.
### v0.5.1
* Migrate deprecated locate to context.
### v0.5.0
* Support page numbering formats (i.e. roman), when `use-page-counter` is set to
true. Thanks to @ThePuzzlemaker!
### v0.4.3
* Suppress extra space character emitted by the `index()` function.
* Fix a bug where math formulas are not displayed.
* Introduce `apply-casing` parameter to `index()` to suppress entry-casing for individual
entries.
### v0.4.2
* Improve internal method `as-text` to be more robust.
* tidy up sample-usage.typ.
### v0.4.1
* Bug fixed: Fix a bug where an index entry with same name as a group hides the group.
* Fixed typos in the sample-usage document.
### v0.4.0
* Support for a `display` parameter for entries. This allows the usage of complex
content, like math expressions in the index. (based on suggestions by @lukasjuhrich)
* Also support a tuple value for display and key parameters of the entry.
* Improve internal robustness and fix some errors in the sample document.
### v0.3.2
* Fix initial parsing and returning fist letter (thanks to @lukasjuhrich, #14)
### v0.3.1
* Fix handling of trailing or multiple spaces and crlf in index entries.
### v0.3.0
* Support multiple named indexes. Also allow the generation of
combined index pages.
* Support for LaTeX index group syntax (`#index("Group1!Group2@Entry"`).
* Support for advanced case handling for the entries in the index. Note: The new default
ist to ignore the casing for the sorting of the entries. The behavior can be changed by
providing a `sort-order()` function to the `make-index` function.
* The casing for the index entry can also be altered by providing a `entry-casing()`
function to the `make-index` function. So it is possible that all entries have an
uppercase first letter (which is also the new default!).
### v0.2.0
* Allow index to respect unnumbered physical pages at the start of the
document (Thanks to @jewelpit). See "Skipping physical pages" in the
sample-usage document.
### v0.1.0
* big refactor (by @epsilonhalbe).
* changing "marker classes" to support direct format
function `fmt: content -> content` e.g. `index(fmt: strong, [entry])`.
* Implemented:
* nested entries.
* custom initials + custom sorting.
### v0.0.6
* Change internal index marker to use metadata instead of figures. This
allows a cleaner implementation and does not require a show rule to hide
the marker-figure anymore.
* This version requires Typst 0.8.0 due to the use of metadata().
* Consolidated the `PackageReadme.md` into a single `README.md`.
### v0.0.5
* Address change in `figure.caption` in typst (commit: 976abdf ).
### v0.0.4
* Add title and outline arguments to #make-index() by @sbatial in #4
### v0.0.3
* Breaking: Renamed the main file from `index.typ` to `in-dexter.typ` to match package.
* Added a Changelog to this README.
* Introduced a brief and a full sample code to this README.
* Added support for package manager in Typst.
### v.0.0.2
* Moved version to GitHub.
|
https://github.com/Tran-Thu-Le/tybank | https://raw.githubusercontent.com/Tran-Thu-Le/tybank/main/main.typ | typst | #import "@preview/suiji:0.1.0": *
#import "template.typ": *
#import "utils.typ": *
#import "bank.typ": questions
#let show_answer = true
// #let show_answer = false
// #let show_solution = true
#let show_solution = false
// #let show_tags = true
#let show_tags = false
#let show_options = (
"answer": show_answer,
"solution": show_solution,
"tags": show_tags
)
#let number_of_questions = questions.len()
#let seed = gen-rng(120)
#let permute_choices_bool = true
#let permute_questions_bool = false
#let permuted_choices = permute_choices(seed, number_of_questions, permute_choices_bool)
#let permuted_questions = permute_questions(seed, number_of_questions, permute_questions_bool)
//------------------------------------------------
// Contents
//------------------------------------------------
#show: project.with(
title: "Đề thi thử Toán 10 GHK2",
authors: ("Thời gian: 90p, Số câu: " + str(questions.len())+"TN, Mã đề: 003",),
watermark_content: [*Tran Thu Le*],
footer_left: link("https://www.facebook.com/TTranThuLe/")[#underline(text(blue)[Tran Thu Le])],
footer_right: counter(page).display("1/1",both: true),
)
// = Trắc nghiệm \
#layout_questions(questions, show_options, permuted_questions, permuted_choices)
#if show_answer {
v(2em)
[*Đáp án Mã đề: 003*]
display_list_of_correct_choices(questions, permuted_questions, permuted_choices)
}
|
|
https://github.com/ufodauge/master_thesis | https://raw.githubusercontent.com/ufodauge/master_thesis/main/src/template/utils/date.typ | typst | MIT License | #let toJapaneseCalendar(date) = {
assert(type(date) == "datetime")
let year = str(date.year() - 2018)
let month = str(date.month())
let date = str(date.day())
return "令和" + year + "年" + month + "月" + date + "日"
}
|
https://github.com/pku-typst/meppp | https://raw.githubusercontent.com/pku-typst/meppp/main/table.typ | typst | MIT License | // return the number of rows of the table
#let table-row-counter(cells, columns) = {
let last-row = (0,) * columns
let x = 0
let y = 0
let volume = 0
for cell in cells {
if cell.has("body") {
let colspan = 1
let rowspan = 1
if cell.has("colspan") {
colspan = cell.colspan
}
if cell.has("rowspan") {
rowspan = cell.rowspan
}
volume += colspan * rowspan
let end = x + colspan
while x < end {
last-row.at(x) += rowspan
x += 1
}
let next = last-row.position(ele => {
ele == y
})
if next == none {
y = calc.min(..last-row)
x = last-row.position(ele => {
ele == y
})
} else {
x = next
}
}
}
let rows = calc.max(..last-row)
let volume-empty = columns * rows - volume
assert(volume == last-row.sum())
return (rows, volume-empty)
}
// A three-line-table returned as a figure
#let meppp-tl-table(
caption: none,
supplement: auto,
stroke: 0.5pt,
tbl,
) = {
let align = center + horizon
if tbl.has("align") {
align = tbl.align
}
let columns = 1
let column-count = 1
if tbl.has("columns") {
columns = tbl.columns
if type(tbl.columns) == int {
column-count = tbl.columns
} else if type(tbl.columns) == array {
column-count = columns.len()
}
}
let header = tbl.children.at(0)
assert(
header.has("children"),
message: "Header is needed.",
)
let header-children = header.children
let header-rows = table-row-counter(header-children,column-count).at(0)
let content = tbl.children.slice(1)
let content-trc = table-row-counter(content, column-count)
let content-rows = content-trc.at(0)
let content-empty-cells = content-trc.at(1)
content = content + ([],) * content-empty-cells
let rows = (1.5pt,) + (1.5em,) * (header-rows + content-rows) + (1.5pt,)
let hline = table.hline(stroke: stroke)
let empty-row = table.cell([], colspan: column-count)
return figure(
table(
align: align,
columns: columns,
rows: rows,
stroke: none,
table.header(
hline,
empty-row,
hline,
..header-children,
hline,
),
..content,
table.footer(
hline,
empty-row,
hline,
repeat: false,
)
),
kind: table,
caption: figure.caption(caption, position: top),
supplement: supplement,
)
} |
https://github.com/Ombrelin/adv-java | https://raw.githubusercontent.com/Ombrelin/adv-java/master/Slides/5-prog-parallele.typ | typst | #import "@preview/polylux:0.3.1": *
#import "@preview/sourcerer:0.2.1": code
#import themes.clean: *
#show: clean-theme.with(
logo: image("images/efrei.jpg"),
footer: [<NAME>, EFREI Paris],
short-title: [EFREI LSI L3 ALSI62-CTP : Java Avancé],
color: rgb("#EB6237")
)
#title-slide(
title: [Java Avancé],
subtitle: [Cours 5 : Programmation Parallèle et Asynchrone],
authors: ([<NAME>]),
date: [2 Février 2024],
)
#new-section-slide("Introduction")
#slide(title: "Thread")[
*Thread* : fil d'exécution. Plusieurs en même temps possible.
- Améliorer la vitesse d'un process : attention à l'overhead
- Permettre un cas d'utilisation : ex modèle client-serveur
]
#slide(title: "Thread Java")[
- Classe `Thread`, construit à partir d'un `Runnable`
- Lancer avec la méthode `start()`
#code(
lang: "Java",
```java
var oddThread = new Thread(() -> {
IntStream
.range(0, 100)
.filter(number -> number % 2 != 0)
.forEach(System.out::println);
});
var evenThread = new Thread(() -> {
IntStream
.range(0, 100)
.filter(number -> number % 2 == 0)
.forEach(System.out::println);
});
evenThread.start();
oddThread.start();
Thread.sleep(5000);
```)
]
#new-section-slide("Synchronisation")
#slide(title: "Joindre")[
- Attendre la fin d'un thread
#code(
lang: "Java",
```java
evenThread.join();
oddThread.join();
```)
]
#slide(title: "Ressource partagée et section critique")[
- Section critique : à excéuter atomiquement sinon problème
- `synchronized` : un seul thread à la fois sur la section
- Collections syncrhonisées : `Collections.synchronizedList(new ArrayList<>())`
- Attention au coût
- Section critiques synchronisées : *code thread-safe*
]
#slide(title: "Ressource partagée et section critique")[
#code(
lang: "Java",
```java
public class Hotel {
private final int roomsCount;
private int bookedRoomsCount = 0;
public Hotel(int roomsCount) {
this.roomsCount = roomsCount;
}
public int getAvailableRoomCount(){
return roomsCount - bookedRoomsCount;
}
public void bookRooms(int numberOfBookedRooms){
if(getAvailableRoomCount() - numberOfBookedRooms < 0){
throw new IllegalArgumentException("Not enough rooms available");
}
else {
bookedRoomsCount += numberOfBookedRooms;
}
}
}
var hotel = new Hotel(20);
var reservationThread1 = new Thread(() -> hotel.bookRooms(3));
var reservationThread2 = new Thread(() -> hotel.bookRooms(7));
```)
]
#slide(title: "Ressource partagée et section critique")[
#code(
lang: "Java",
```java
public synchronized void bookRooms(int numberOfBookedRooms){
if(getAvailableRoomCount() - numberOfBookedRooms < 0){
throw new IllegalArgumentException("Not enough rooms available");
}
else {
bookedRoomsCount += numberOfBookedRooms;
}
}
```
)
]
#slide(title: "Coordonner")[
- Coordonner des threads entre eux
- `wait` : attendre un signal
- `notify` : envoyer un signal
- Dans un bloc `synchronized`
]
#slide(title: "Coordonner")[
#code(
lang: "Java",
```java
var token = new Object();
var oddThread = new Thread(() -> {
var oddNumbers = ...
for (var oddNumber : oddNumbers) {
synchronized (token) {
token.wait();
System.out.println(oddNumber);
token.notify();
}
}
});
var evenThread = new Thread(() -> {
var evenNumbers = ...
for (var evenNumber : evenNumbers) {
System.out.println(evenNumber);
synchronized (token) {
token.notify();
token.wait();
}
}
});
```
)
]
#new-section-slide("Programmation Asynchrone")
#slide(title: "Définition")[
- Abstraction au dessus des threads : tâches
- Mutualiser les threads
- Optimiser le temps CPU (I/O non bloquantes)
*Notions : *
- Promesse : tâche qui va être réalisée de façon asynchrone, on aura la résolution dans le futur
- Continuation : s'exécute sur le résultat de la promesse
]
#slide(title: "Notion d'I/O non bloquantes")[
- CPU-bound : calculs, algos
- I/O-bound : attendre (appel réseau, système de fichiers)
_Attente I/O = Temps CPU gaché_
*Objectif* : le CPU fait autre chose quand il attend l'I/O
]
#slide(title: "Asynchrone en Java : ThreadPool")[
Groupe de threads qui vont traiter une série de tâches
#code(
lang: "Java",
```java
ExecutorService threadPool = Executors.newFixedThreadPool(4);
threadPool.submit(() -> {
...
} )
```)
]
#slide(title: "Promesse en Java : CompletableFuture")[
#code(
lang: "Java",
```java
CompletableFuture<String> task = CompletableFuture
.supplyAsync(() -> {
var result = ... opération longue async...
return result;
});
task.thenAccept((String result) -> println(result));
task.exceptionally(exception -> {
exception.printStackTrace();
return "";
});
```
)
] |
|
https://github.com/mkpoli/ipsj-typst-template | https://raw.githubusercontent.com/mkpoli/ipsj-typst-template/master/docs/doc.typ | typst | #import "@preview/tidy:0.2.0"
#import "./custom-style.typ"
#set text(font: "Noto Serif CJK JP", size: 10pt)
#show raw: set text(font: ("Fira Code", "Noto Sans Mono CJK JP"))
#set heading(numbering: "1.1")
#set page(paper: "jis-b5")
#outline(title: "目次")
#let show-module = tidy.show-module.with(
style: custom-style,
)
= テンプレート
#let docs = tidy.parse-module(read("../lib.typ"))
#show-module(docs)
= ライブラリー
== 脚注
#let doc-footnote = tidy.parse-module(read("../lib/footnote.typ"))
#show-module(doc-footnote)
== フォント
#let doc-font = tidy.parse-module(read("../lib/mixed-font.typ"))
#show-module(doc-font)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10F00.typ | typst | Apache License 2.0 | #let data = (
("OLD SOGDIAN LETTER ALEPH", "Lo", 0),
("OLD SOGDIAN LETTER FINAL ALEPH", "Lo", 0),
("OLD SOGDIAN LETTER BETH", "Lo", 0),
("OLD SOGDIAN LETTER FINAL BETH", "Lo", 0),
("OLD SOGDIAN LETTER GIMEL", "Lo", 0),
("OLD SOGDIAN LETTER HE", "Lo", 0),
("OLD SOGDIAN LETTER FINAL HE", "Lo", 0),
("OLD SOGDIAN LETTER WAW", "Lo", 0),
("OLD SOGDIAN LETTER ZAYIN", "Lo", 0),
("OLD SOGDIAN LETTER HETH", "Lo", 0),
("OLD SOGDIAN LETTER YODH", "Lo", 0),
("OLD SOGDIAN LETTER KAPH", "Lo", 0),
("OLD SOGDIAN LETTER LAMEDH", "Lo", 0),
("OLD SOGDIAN LETTER MEM", "Lo", 0),
("OLD SOGDIAN LETTER NUN", "Lo", 0),
("OLD SOGDIAN LETTER FINAL NUN", "Lo", 0),
("OLD SOGDIAN LETTER FINAL NUN WITH VERTICAL TAIL", "Lo", 0),
("OLD SOGDIAN LETTER SAMEKH", "Lo", 0),
("OLD SOGDIAN LETTER AYIN", "Lo", 0),
("OLD SOGDIAN LETTER ALTERNATE AYIN", "Lo", 0),
("OLD SOGDIAN LETTER PE", "Lo", 0),
("OLD SOGDIAN LETTER SADHE", "Lo", 0),
("OLD SOGDIAN LETTER FINAL SADHE", "Lo", 0),
("OLD SOGDIAN LETTER FINAL SADHE WITH VERTICAL TAIL", "Lo", 0),
("OLD SOGDIAN LETTER RESH-AYIN-DALETH", "Lo", 0),
("OLD SOGDIAN LETTER SHIN", "Lo", 0),
("OLD SOGDIAN LETTER TAW", "Lo", 0),
("OLD SOGDIAN LETTER FINAL TAW", "Lo", 0),
("OLD SOGDIAN LETTER FINAL TAW WITH VERTICAL TAIL", "Lo", 0),
("OLD SOGDIAN NUMBER ONE", "No", 0),
("OLD SOGDIAN NUMBER TWO", "No", 0),
("OLD SOGDIAN NUMBER THREE", "No", 0),
("OLD SOGDIAN NUMBER FOUR", "No", 0),
("OLD SOGDIAN NUMBER FIVE", "No", 0),
("OLD SOGDIAN NUMBER TEN", "No", 0),
("OLD SOGDIAN NUMBER TWENTY", "No", 0),
("OLD SOGDIAN NUMBER THIRTY", "No", 0),
("OLD SOGDIAN NUMBER ONE HUNDRED", "No", 0),
("OLD SOGDIAN FRACTION ONE HALF", "No", 0),
("OLD SOGDIAN LIGATURE AYIN-DALETH", "Lo", 0),
)
|
https://github.com/mumblingdrunkard/mscs-thesis | https://raw.githubusercontent.com/mumblingdrunkard/mscs-thesis/master/src/computer-architecture-fundamentals/index.typ | typst | = Computer Architecture Fundamentals <ch:computer-architecture-fundamentals>
By the nature of the genre (master's theses), this text is targeted at those graduating from a programme in computer science or similar.
// Let $A$ be the set of all computer science students, and $B$ be the set of all computer science students that specialise in computer architecture.
// Supposedly, $A != B$.
// That is to say: there are computer science students that do not study computer architecture; or in mathematical terms: $B #math.subset.neq A$ ($B$ is a proper subset of $A$).
The goal of this chapter is to equip the reader with foundational knowledge required to understand the discussions within this thesis and to establish common terminology.
In the first section, we bridge the gap between abstractions and implementations and cover how a processor is created using constructions of transistors.
The next section covers _pipelining_, a design approach that increases the performance of processors by passing work down a pipeline almost like an assembly line where each stage adds a new part.
@sec:scaling-up shows how processor performance can be increased and how a processor can be modified to break the barrier of completing more than one instruction at a time.
Next follows a short coverage of memory and related terminology.
Lastly, we cover how a modern, high-performance processor tackles this complexity by using a different philosophy entirely.
#include "./abstractions-and-implementations.typ"
#include "./anatomy-of-an-in-order-pipelined-processor.typ"
#include "./scaling-up.typ"
#include "./memory-and-caching.typ"
#include "./high-performance-processor-architecture.typ"
#include "./reduced-vs-complex-instruction-set-computers.typ"
|
|
https://github.com/Xe/automuse | https://raw.githubusercontent.com/Xe/automuse/main/paper/automuse_1/template.typ | typst | zlib License | #let conf(
title: none,
authors: (),
abstract: [],
doc,
) = {
set page(
paper: "us-letter",
header: align(
right + horizon,
text(font: "Iosevka Etoile Iaso", size: 9pt)[#title]
),
)
set par(justify: true)
set text(
font: "<NAME>",
size: 9.8pt,
)
set align(center)
text(font: "I<NAME>toile Iaso", size: 17pt)[#title]
let count = authors.len()
let ncols = calc.min(count, 6)
grid(
columns: (1fr,) * ncols,
row-gutter: 24pt,
..authors.map(author => text(font: "<NAME>", size: 9pt)[
#author.name \
#author.affiliation \
#link("mailto:" + author.email)
]),
)
par(justify: false)[
#text(font: "Iosevka Etoile Iaso", size: 11pt)[*Abstract*] \
#abstract
]
set align(left)
columns(2, doc)
}
|
https://github.com/goshakowska/Typstdiff | https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_complex/all_types_working/all_types_working_delete_result.typ | typst | GNU nano 6.2 test1.typ
= Introduction
#strike[In];#strike[ ];#strike[this];#strike[ ];#strike[report,];#strike[
];#strike[we];#strike[ ];#strike[will];#strike[
];#strike[explore];#strike[ ];#strike[the];#strike[
];#strike[various];#strike[ ];#strike[factors];#strike[
];#strike[that];#strike[ ];#strike[influence];#strike[
];#strike[#emph[fluid dynamics];];#strike[ ];#strike[in];#strike[
];#strike[glaciers];#strike[ ];#strike[and];#strike[
];#strike[how];#strike[ ];#strike[they];#strike[
];#strike[contribute];#strike[ ];#strike[to];#strike[
];#strike[the];#strike[ ];#strike[formation];#strike[
];#strike[and];#strike[ ];#strike[behaviour];#strike[
];#strike[of];#strike[ ];#strike[these];#strike[
];#strike[natural];#strike[ ];#strike[structures.]
#strike[The];#strike[ ];#strike[equation];#strike[
];#strike[$Q = rho A v + C$];#strike[ ];#strike[defines];#strike[
];#strike[the];#strike[ ];#strike[glacial];#strike[
];#strike[flow];#strike[ ];#strike[rate.]
#strike[The];#strike[ ];#strike[flow];#strike[ ];#strike[rate];#strike[
];#strike[of];#strike[ ];#strike[a];#strike[ ];#strike[glacier];#strike[
];#strike[is];#strike[ ];#strike[defined];#strike[ ];#strike[by];#strike[
];#strike[the];#strike[ ];#strike[following];#strike[
];#strike[equation:]
#strike[$ Q = rho A v + C $]
#strike[The];#strike[ ];#strike[flow];#strike[ ];#strike[rate];#strike[
];#strike[of];#strike[ ];#strike[a];#strike[ ];#strike[glacier];#strike[
];#strike[is];#strike[ ];#strike[given];#strike[ ];#strike[by];#strike[
];#strike[the];#strike[ ];#strike[following];#strike[
];#strike[equation:]
#strike[$ Q = rho A v + upright(" time offset ") $]
#strike[Total];#strike[ ];#strike[displaced];#strike[
];#strike[soil];#strike[ ];#strike[by];#strike[
];#strike[glacial];#strike[ ];#strike[flow:];#strike[
];#strike[$ 7.32 beta + sum_(i = 0)^nabla frac(Q_i (a_i - epsilon), 2) $]
#strike[$ v colon.eq vec(x_1, x_2, x_3) $]
#strike[$ a arrow.r.squiggly b $]
#strike[Lorem];#strike[ ];#strike[ipsum];#strike[
];#strike[dolor];#strike[ ];#strike[sit];#strike[
];#strike[amet,];#strike[ ];#strike[consectetur];#strike[
];#strike[adipiscing];#strike[ ];#strike[elit,];#strike[
];#strike[sed];#strike[ ];#strike[do]
#strike[Number:];#strike[ ];#strike[3]
#strike[$- x$];#strike[ ];#strike[is];#strike[ ];#strike[the];#strike[
];#strike[opposite];#strike[ ];#strike[of];#strike[ ];#strike[$x$]
#strike[let];#strike[ ];#strike[name];#strike[ ];#strike[\=];#strike[
];#strike[\[];#strike[#strong[Typst!];];#strike[\]]
#strike[#strong[strong];]
#strike[`print(1)`]
#link("https://typst.app/")[#strike[https:\/\/typst.app/];]
<intro>
= #strike[Heading]
#strike[$x^2$]
#strike[‘single”];#strike[ ];#strike[or];#strike[ ];#strike[“double”]
#strike[~,];#strike[ ];#strike[—]
#strike[$x^2$]
#strike[$ x^2 $]
#strike[$x_1$]
#strike[$x^2$]
#strike[$1 + frac(a + b, 5)$]
#strike[$x\
y$]
#strike[$x & = 2\
& = 3$]
#strike[$pi$]
#strike[$arrow.r$];#strike[ \
];#strike[$x y$]
#strike[$arrow.r , eq.not$]
#strike[$a upright(" is natural")$]
#strike[$⌊x⌋$]
#strike[Lorem];#strike[ ];#strike[ipsum];#strike[
];#strike[dolor];#strike[ ];#strike[sit];#strike[
];#strike[amet,];#strike[ ];#strike[consectetur];#strike[
];#strike[adipiscing];#strike[ ];#strike[elit,];#strike[
];#strike[sed];#strike[ ];#strike[do];#strike[ ];#strike[eiusmod];#strike[
];#strike[tempor];#strike[ ];#strike[incididunt];#strike[
];#strike[ut];#strike[ ];#strike[labore];#strike[ ];#strike[et];#strike[
];#strike[dolore];#strike[ ];#strike[magna];#strike[
];#strike[aliqua.];#strike[ ];#strike[Ut];#strike[
];#strike[enim];#strike[ ];#strike[ad];#strike[ ];#strike[minim];#strike[
];#strike[veniam,];#strike[ ];#strike[quis];#strike[
];#strike[nostrud];#strike[ ];#strike[exercitation];#strike[
];#strike[ullamco];#strike[ ];#strike[laboris];#strike[ ];#strike[nisi]
#strike[#emph[Hello];];#strike[ \
];#strike[5]
#strike[hello];#strike[ ];#strike[from];#strike[ ];#strike[the];#strike[
];#strike[#strong[world];]
#strike[This];#strike[ ];#strike[is];#strike[ ];#strike[Typst‘s];#strike[
];#strike[documentation.];#strike[ ];#strike[It];#strike[
];#strike[explains];#strike[ ];#strike[Typst.]
#strike[Sum];#strike[ ];#strike[is];#strike[ ];#strike[5.]
#strike[The];#strike[ ];#strike[coordinates];#strike[
];#strike[are];#strike[ ];#strike[1,];#strike[ ];#strike[2.]
#strike[The];#strike[ ];#strike[first];#strike[
];#strike[element];#strike[ ];#strike[is];#strike[ ];#strike[1.];#strike[
];#strike[The];#strike[ ];#strike[last];#strike[
];#strike[element];#strike[ ];#strike[is];#strike[ ];#strike[4.]
#strike[Austen];#strike[ ];#strike[wrote];#strike[ ];#strike[Persuasion.]
#strike[Homer];#strike[ ];#strike[wrote];#strike[ ];#strike[The];#strike[
];#strike[Odyssey.]
#strike[The];#strike[ ];#strike[y];#strike[ ];#strike[coordinate];#strike[
];#strike[is];#strike[ ];#strike[2.]
#strike[(5,];#strike[ ];#strike[6,];#strike[ ];#strike[11)]
#strike[This];#strike[ ];#strike[is];#strike[ ];#strike[shown]
#strike[abc]
#strike[Hello];#strike[ \
];#strike[Heading];#strike[ \
];#strike[3];#strike[ ];#strike[is];#strike[ ];#strike[the];#strike[
];#strike[same];#strike[ ];#strike[as];#strike[ ];#strike[3]
#strike[4];#strike[ \
];#strike[3];#strike[ \
];#strike[a];#strike[ ];#strike[—];#strike[ ];#strike[b];#strike[
];#strike[—];#strike[ ];#strike[c]
#strike[Dobrze]
#strike[#strong[Date:];];#strike[ ];#strike[26.12.2022];#strike[ \
];#strike[#strong[Topic:];];#strike[ ];#strike[Infrastructure];#strike[
];#strike[Test];#strike[ \
];#strike[#strong[Severity:];];#strike[ ];#strike[High];#strike[ \
];#strike[abc];#strike[ \
];#strike[#strong[my text];];#strike[ \
];#strike[already];#strike[ ];#strike[low]
#strike[ABC];#strike[ \
];#strike[#strong[MY TEXT];];#strike[ \
];#strike[ALREADY];#strike[ ];#strike[HIGH]
#strike[“This];#strike[ ];#strike[is];#strike[ ];#strike[in];#strike[
];#strike[quotes.”]
#strike[“Das];#strike[ ];#strike[ist];#strike[ ];#strike[in];#strike[
];#strike[Anführungszeichen.”]
#strike[“C’est];#strike[ ];#strike[entre];#strike[
];#strike[guillemets.”]
#strike[1];#strike[#super[st];];#strike[ ];#strike[try!]
#strike[Italic];#strike[ ];#strike[Oblique]
#strike[This];#strike[ ];#strike[is];#strike[
];#underline[#strike[important];];#strike[.]
#strike[Take];#strike[ ];#underline[#strike[care];]
|
|
https://github.com/gabrielluizep/typst-ifsc | https://raw.githubusercontent.com/gabrielluizep/typst-ifsc/main/examples/ifscyan.example.typ | typst | Creative Commons Zero v1.0 Universal | #import "../templates/ifscyan.typ": *
#show: body => ifscyan-theme(aspect-ratio: "16-9", body)
#title-slide(title: "Slide Massa")[
<NAME>\
#text(.8em, link("<EMAIL>"))
#align(bottom)[
20/09/2023
]
]
#slide(title: "Slide Massa")[
#text([Título]) \ \
// #uncover(2)[
// #text([Subtítulo])
// ]
] |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-24.typ | typst | Other | // Error: 3-8 cannot mutate a temporary value
#(1 + 2 += 3)
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/028%20-%20Kaladesh/003_Torch%20of%20Defiance.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Torch of Defiance",
set_name: "Kaladesh",
story_date: datetime(day: 05, month: 09, year: 2016),
author: "<NAME>",
doc
)
#emph[A Planeswalker from Kaladesh ] visited Ravnica#emph[ to ask for the assistance of the Gatewatch. The consensus was that the Gatewatch should only intervene in the case of interplanar threats, however, and a possible threat to the Kaladesh Inventors' Fair was not deemed a matter for the Planeswalkers. For <NAME>, though, the plane of Kaladesh is personal—it's her home plane, a world she hasn't been back to since her spark ignited and she took her first planeswalk twelve years ago. Without consulting the others, she has planeswalked back to Kaladesh, back to her home.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Home was an atrophied muscle. The path back to Kaladesh was covered over with time the way a road gets reclaimed by weeds, and for a moment, Chandra wondered if she even remembered the way. Before she could take a deep, soothing breath, though, she had arrived.
Chandra stood in the center of a plaza of warm brick, reeling in surreal familiarity. Cardamom and incense, welded copper and gear grease, the musk of passing arborbacks, the tang of bandar fur. There were the familiar traces of aether in the air, fresh and open like sun-soaked linen, but with a prickle of action in it. It was the aether smell that told her, finally, that she was home—the raw potential that curled the clouds in the sky, surged in the hearts of airships, and coursed through the city in thick glass pipes.
#figure(image("003_Torch of Defiance/01.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The last day she had been on this world had hung in the past, interrupted and partial. That day had resumed, except everything looked busier and—taller. Wasn't visiting your childhood home supposed to make you feel bigger?
People swept past her in a customary Kaladeshi hurry. The melody of their voices jolted her. She heard morsels of conversation that could have come right from her own family home—eager predictions about some famous inventor in the Fair, gruff opinions on the merits of this or that airship design, clipped exchanges about onrushing deadlines.
Chandra grabbed her own elbows. She longed to curl up in her childhood hammock, suspended from the walkways of the old mine from before the aether boom, above the machine shop where her parents hunched over some new invention. She wanted to hang there, listening to their voices, as they shaped metal. She longed to just #emph[go home] , except she #emph[was] home and it wasn't her home anymore, and she wasn't eleven anymore and she would never have her mother wrap her arms around her—
She growled and stamped her foot. She doused her hands on her thighs and wiped an eye. #emph[No] .
Somewhere in this crowd was the renegade she sought, the inventor who was in danger—and the rest of the Gatewatch didn't care. Her family had worked against the Consulate when she was growing up, dodging patrols to supply aether to brilliant inventors. She didn't know why this person was so important to her, or why this mission had been the thing to draw her back to Kaladesh. She just knew she needed to find this inventor, and soon.
Ghirapur thrived all around her, a city of thousands of faces. She didn't even know what this renegade might look like. Chandra felt a splinter of that familiar feeling—the feeling of having gotten herself into something without any plan of how to get back out. She felt a tiny urge to about-face back to Ravnica.
A pair of Consulate lawkeepers glanced at her, evaluated her, and moved on—and the reassuring spike of defiance chased away her urge to flee. She instinctively hid a reflexively-made fist, and grabbed a handful of a nearby banner. She put her foot up onto a decorated copper strut, yanked on a hanging Consulate flag, and hauled herself up onto the balcony of the level above.
As she climbed, the city spread out before her. Vehicles and people surged through the streets, gathering for the Inventors' Fair. Glassed-in rooftop gardens rotated, facing the sun's arc. At the city's center, an enormous single spire reached high into the sky, aether-driven airships orbiting it like moths. She wondered if she could ever explain the tangled emotional knot that was Kaladesh, for her. But even if she had a friend here, someone who could understand, she could still never explain—
"So this is your home," said a woman next to her.
Chandra started, then scowled. Standing on the formerly unoccupied balcony next to her was Liliana, leaning her crossed arms on a rail and looking out over Ghirapur.
#figure(image("003_Torch of Defiance/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
A gray-haired man slipped through Ghirapur with a series of sideways moves. He avoided main thoroughfares and stayed off the ticketed Express, zigzags drawing him in and out of parts shops, along aether arteries, and through shadowed courtyards. He snatched his hood around his cheeks, keeping his face hidden from patrols and thopters. No one stepped on his shadow as he made his way closer and closer to the Inventors' Fair.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Chandra gripped the balcony rail and glared at Liliana. "If you think you're here to convince me to come home, you can just go."
Liliana scoffed. "Wouldn't dream of it. You #emph[are] home."
"I'm not going back until I find whoever this Baan was looking for." She gritted her teeth, hitching her mother's shawl around her waist. "No matter what you or the others want."
"It's what #emph[you] want that matters. Damn the others, if they don't see what your home means to you."
"They mean well," Chandra jabbed back. "They just...they wouldn't understand all of this." A hundred explanations of what Kaladesh #emph[did] mean fought their way to the surface of her mind, but none of them were large or complicated enough. What could your childhood home mean, when it took your childhood away from you? How was home supposed to mean anything at all, when you became who you are by #emph[leaving] it?
"Tell me," Liliana said. "Maybe I can help."
"You wouldn't understand, either," Chandra said.
"I understand that home can be a source of pain," Liliana said. Her face was a series of unreadable lines. "I understand that Baan is a dull series of regulations in a pretty uniform."
"Baan's one of #emph[them] . The Consulate. They keep the city running, but they also hate anyone or anything who dares paint outside the lines. Outcasts. Renegades."
"Fun people, in other words."
"I just mean, people like me. And my parents." Chandra put her hands on the railing. A trickle of smoke rose from the wood.
Liliana conjured a violet glow around her fingertips, and her lips widened into a grin. "Then I think it's high time we celebrated your grand return to your hometown."
Chandra cocked an eyebrow. "I'm here to accomplish something."
"We can still look for your precious renegade along the way. But look at you! You're not even enjoying the giant party going on down there. Besides. I think you and I, in this town? Could get ourselves into some deeply satisfying trouble."
#figure(image("003_Torch of Defiance/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Chandra's own grin came unbidden. "Liliana, you're two centuries older than me. Exactly which of us is supposed to be the responsible one?"
"Let me tell you a secret." Liliana cupped a hand playfully near Chandra's ear. "There doesn't have to #emph[be] a responsible one."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The man in the hood wrapped himself in the hum of the Inventors' Fair, and listened. He kept his face and right arm hidden, no longer to dodge the Consulate soldiers or prying eyes of the bright-lensed thopters, but to walk freely among the fairgoers. Inventors would recognize him instantly, of course, and interrupt his work. He couldn't have that. He needed to complete his mission before anyone had a chance to notice him.
He slipped into the flow of the crowd, and he listened, following their words to his target.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The aether trails in the sky faded from soft eddies of azure and white, to gold and copper, to salmon and violet, and finally to luminous turquoise against sparkling black. Chains of aether-powered lights twinkled to life, and light and music spilled from every doorway in the city. Chandra's and Liliana's search for the renegade had become a series of chats with renegade sympathizers, which had become hours of mingling with inventors in society halls and ballrooms, which had become, somehow, dancing. Chandra found herself in reels with spins and acrobatic leaps, ceremonial dances to hail the achievements of great artificers and pilots, some expressive wriggling that borrowed from her time as a Regathan monk.
Chandra's cheeks glowed. She glanced back at Liliana, who, having spent all of a day on this world, looked irritatingly, perfectly at home. Liliana leaned by a wall of the club with a drink in her hand, quietly launching a full charisma assault on a vedalken in Consulate uniform, looking something like a lion toying with a wounded antelope.
When the vedalken soldier's blue face suddenly flushed to purple, and his smile reversed, Chandra's fight-or-flight reflex kicked in. She hurried over to hear the Consulate man go into accusatory mode.
The vedalken's eyes were thin slits now. "And even if I #emph[did] know about threats to the Fair," he said, "what business would it be of #emph[yours] , madam? If you've witnessed something, it's your #emph[duty] to report it."
Liliana's swagger-turn toward him was elaborate. "Well I think it's #emph[your] duty to—" And then she dropped a vulgarity so shocking that it would have been the equivalent of tossing her drink into the vedalken's face—which she then also did. Liquid dripped from the man's taken-aback face and dribbled down the straight lines of his Consulate uniform.
Chandra's mouth made an O. She was unsure whether to gasp in horror or burst out laughing.
"Serves him right, eh, Chandra?" Liliana winked at her. "This is my colleague Chandra. A proud renegade sympathizer."
Alarms went off in Chandra's head.
"#emph[Renegades] ," said the vedalken soldier, the way one would pronounce the name of a species of vermin upon finding them residing under the floorboards. He mopped his face with a scarf, and reached into his pocket for something. "You two," he said. "You're going to come with me."
When Chandra saw what the Consulate vedalken had produced from his uniform—a simple pair of restraints, jewel-like in their filigreed artistry–the rage appeared. Her hair became fire. Her fingers became a fist. She was eleven years old again and riding a rising wave of fury.
The soldier made a startled face at Chandra's hair display, and that might have been motivation enough. But it was when he sneered, "Hold out your wrists," that Chandra's fist arced around and collided with his jawbone in one fluid motion. The man's face swung around to face the wall of the nightclub, a tooth ricocheted off the wall, and he slumped to the floor in a heap.
Liliana laughed as a kind of applause, like someone watching dominoes topple in sequence. She raised her glass.
Chandra felt the faces of everyone in the club turning to her. "Let's get out of here," she said.
"But don't you want to show this crowd what else you're capable of? Give this goon what's coming to him?"
"Let's go, #emph[now!] "
Chandra hopped a guardrail and ducked through the back of the nightclub. She pushed through the back door, with Liliana following her into the alley. They dodged past two inventors who rumbled their automatons at each other—one device fanned its intricate copper feathers while the other spun on a gyroscopic wheel.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
It was dark by the time the man in the hood found the marks he was looking for. A line of young people hurried out of the shadowed stands at Ovalchase, the copper legs and grippers of their not-particularly-legal automatons sticking out from the packs on their backs. Renegade inventors.
He intercepted them, taking care to look carefully casual. He kept the long coils of his silver hair hidden under the hood, but he offered his hand—not #emph[that] one, the other one—in such a way as to show off a Leaking Spire symbol hidden on the inside of his glove.
A dwarf woman noted the Leaking Spire and shook, meeting the symbol with her own. "I'm afraid we're drained tonight, friend."
"Not looking for aether," he said. He used a subtle spell to scan the contents of her pack. Her automaton had a listener module inside it. Perfect. Now he just needed to keep her talking. "I'm looking for an associate. Hoping you might know where her little demonstration is planned for tomorrow."
"Lot of demonstrations going on. You got a name?" She was trying to make eye contact, to see his face. Appropriately cautious.
His information was partial, but that fit the narrative that he was a cautious renegade anyway. "She said not to use names. I'm just supposed to meet her. You haven't heard about this?" Meanwhile his next spell did its work. The little metallic listener module obeyed his commands, prying itself out of her device. It floated silently out of her pack and into his jacket pocket.
"Sorry," she said with a shrug. "Don't know who or what you're talking about."
But he knew she was an associate of his target. He smiled expansively in apology. "Very sorry. I'll stop troubling you."
"No harm done," the dwarf said. "How can we contact you if we hear something about your friend? What do you go by—?"
He turned and waved. "Have a good evening."
He gathered his hood around him again and walked on. He glanced down at his hand—#emph[that] hand—in which he held the small, ornate copper module. As he walked, he willed it to activate, and as its gears rotated, it told him everything it had heard—conversations, times, dates. And a #emph[location] .
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Every time Chandra and Liliana saw a patrol they turned a corner, and each turn brought them on a twisting tour of the city. They ducked through a market tent and sprinted up a set of elegant stairs. They looked down out of a window, and below them was a quiet alleyway, out of the way of guard routes.
"Down there," Chandra said. Liliana's disapproval was evident, but they skidded down a set of ladders into the alley.
They caught their breath, leaning on opposite walls. Shafts of daylight scraped the tops of the buildings. The crowds had begun to reappear for the day.
"I'm about done with this 'breathless racing through the city' thing." Liliana dabbed her brow ruefully. "I am more of a 'dramatic strut' person."
But Chandra was just looking at the mosaic on the wall beside her.
#figure(image("003_Torch of Defiance/04.jpg", width: 100%), caption: [Art by <NAME>si], supplement: none, numbering: none)
The mosaic was chipped and worn. The inventor depicted in the round frame looked off to one side, his goggles on his forehead. He looked as kindly as ever. Gently amused, the way he would look at her. Chandra found a chip of color in the dust of the road, picked it up, and tried to press it back into place, but it wouldn't stick.
Liliana stood at Chandra's side, looking at the mosaic.
"This was my father," Chandra said. "Kiran."
"You've got his nose. And his goggles."
"He and my mother were both great inventors. They were killed when I was a child."
"I'm sorry. By whom? The Consulate?"
Chandra squeezed her eyes shut for a moment. "By a psychopath in a uniform. Baral. My parents died because of him. Because he hated me. Because they tried to protect me."
Liliana was looking at her with curious interest. Chandra wished she wouldn't.
"That's not your fault. It's his."
"I shouldn't have come back here. Why did I come back here?"
"Because you feel you owe them. We all have to face the choices we made when we were younger." Liliana looked at the mosaic and wiped a streak of dust from the portrait. "Perhaps we should look up this Baral of yours."
"This place...this is where I learned to expect tragedy. Where I learned to be suspicious of people."
"It's also where you learned to stand out. Where you learned to be #emph[dangerous] ."
"You say that like it's a good thing."
"Most people are content to take life as it comes. The world tells them they're weak, and they agree. They eat disappointment, let it rot inside of them, and then they lie down and die. The rest of us? We learn how to refuse. How to spit and throw things. We learn how to #emph[survive] . You're a survivor, Chandra."
Chandra looked into the eyes of her father. She grasped the hem of the shawl, her mother's shawl, that she wore around her waist.
Liliana smirked. "If Baral hated your family that much, we should find out if he's still around, just to be safe. And besides, if we ran into him, you could look #emph[him] in the eye, instead of that portrait, and tell him what you think of him. You deserve that."
#figure(image("003_Torch of Defiance/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"I don't know," Chandra said. "Baral probably thinks I died that day."
"Then just imagine the look on his face when he realizes you didn't. When he realizes you survived."
Chandra cheered at little, thinking of that.
Liliana looked her in the eyes then, and her face was serious. "When you #emph[burn him to cinders] ."
Chandra jerked her head back in shock, but at the same time, a dark thrill dared to roll through her chest. Baral had killed her father in front of her. And she knew that Baral commanded the soldiers who lit the fires that destroyed their village, that must have killed her mother. Her entire family lost, because of one man. How satisfying it would be to see him #emph[burn] .
"If he's still alive," Chandra said, "I swear he's going to pay for what he did."
Liliana's voice was a low whisper. "It's only right to pay back the pain he caused you."
"It's only right," Chandra murmured, and her hair caught fire.
#figure(image("003_Torch of Defiance/06.jpg", width: 100%), caption: [Art by <NAME>uve], supplement: none, numbering: none)
"That's them!" two uniformed men shouted from one end of the alley, and rushed toward the two Planeswalkers. Spotted.
Chandra made to sprint in the other direction, but Liliana grabbed her. "We don't have to run," the necromancer said, looking evenly at the guards. "There's another way to end this chase."
"No. We don't do that."
"We do what it takes," Liliana said, her words underscored by the blast of a train's whistle a couple streets over.
Chandra shook off Liliana's hand. She looked at the two men, and cast a swirling blast of flame. But instead of slamming into the Consulate guards, the spell splashed onto the brick floor, spreading into a wall of fire that spanned the alley's width. The guards stopped short.
She looked at Liliana. "Don't tell me what to do," she said. "Come on. Got an idea."
They emerged on a main thoroughfare. The Aradara dawn train was enormous, yet sat balanced elegantly in a single groove in the bricks, sunlight shining off its polished wood flanks. Riders hurried into doors all along its winding length. Chandra ran and stepped up, putting her hand in the way as the doors tried to close.
She and Liliana boarded as the train hissed to a start. Through the windows, they could see the Consulate guards giving up the chase and receding in the distance.
A complicated mechanism at the entrance clattered at them for tickets. Chandra slammed her fist into the mechanism, cratering it. It stopped clattering.
They sat. Chandra leaned her head against glass, watching the buildings of her childhood rattle past. Neither Planeswalker spoke.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The train lurched and brakes squealed. Chandra grabbed her seat and stood up, only to get slammed into the seats in front of her. The train's whistle blared repeatedly, and the wheels locked underneath them, and red warning lights flashed along the ceiling of the car.
Chandra looked through the windows as the train heaved. Outside—a display of constrained chaos. A squad of special Consulate inspectors waved crowds into designated zones. In the distance, burst aether pipes billowed scintillating gases into the air, and airship crews dropped dragnets to round up stray thopters. Whole buildings had gone dark, cut off from their aether supply. Fairgoers chattered and pointed skyward excitedly, but whatever had happened had seemingly already come and gone.
A disruption. The aftermath of some kind of aerial display. It had to be the work of the renegade—the one Dovin Baan was worried about.
An announcement squawked over the train's pipes. "This train is making an unscheduled stop. Please remain in your seats—"
"Let's go," Chandra said to Liliana over her shoulder, and dashed past several seated passengers to an exit door.
"—until instructed by an Aradara conductor or Consulate official. Thank you."
Chandra hot-punched the door handle. The handle mechanism vanished in a muted burst of fire, leaving a glowing-hot melted hole. She gave a kick and the door buckled open. The street still whooshed by.
"This could be the renegade," Chandra said. "Has to be."
Liliana nodded, and they leaped. Their feet hit the pavement before the train had completely halted. All around, Consulate guards were trying to herd people away from the direction of the disruption. Chandra plunged into the crowd, nudging through a steady tide of bodies that were trying to move #emph[away] from the emergency as they were trying to get close to it.
"Chandra," Liliana said. Something had caught her eye.
"What?"
"There. In the hood."
#figure(image("003_Torch of Defiance/07.jpg", width: 100%), caption: [Art by Daarken], supplement: none, numbering: none)
Chandra followed her eyeline. A figure crisscrossed through the crowd expertly, keeping his face carefully hidden by a dark hood. He hadn't noticed them. He cut a path around the restricted area, keeping the source of the disruption in sight.
"Conspicuously inconspicuous, don't you think?"
Chandra nodded firmly. Their renegade. They had to warn him. "Hey!" she called out. "Hey you!"
Either he didn't hear, or "Hey you!" was exactly what the Fair-disrupting renegade inventor didn't want to have yelled at him across a crowd full of officials. In either case, he dashed away from them, through a bank of onlookers and around a Consulate checkpoint.
Chandra and Liliana gave chase, catching up to him only once he stopped to accost an older woman.
#figure(image("003_Torch of Defiance/08.jpg", width: 100%), caption: [Art by <NAME>anland], supplement: none, numbering: none)
The man's hood was down now, revealing a headful of gray locks. His right hand, emerging from his sleeve, was a metallic claw, which he pointed at the woman.
They had caught up to the man, emerging out of the crowd behind him. But it was the woman who commanded Chandra's attention. She had auburn hair like Chandra's, but darker, and now with wisps of gray. She wore welding goggles and carried a handheld welder, and glared at the claw-handed man.
Chandra's heart stopped and hot tears sprang to her eyes. She couldn't figure out how to say anything.
"I've found you at last, Renegade Prime," the man said, aiming his metal hand at her as if he were pointing a weapon. "Do you think your little spectacle is going to matter to my Fair?"
The woman sneered at him. "We'll stop you, #emph[Head Judge] . If not today, one day soon."
Liliana grabbed the man and spun him around to her. She uttered a name that Chandra didn't recognize, with a disgust she didn't understand:
"#emph[Tezzeret.] "
And then, gaping at the woman with the hair like hers, Chandra finally found a word of her own. She coaxed it to the surface of her mind out of a sea of shock, and finally managed to breathe it out loud:
"...#emph[Mom?] "
#figure(image("003_Torch of Defiance/09.png", height: 40%), caption: [], supplement: none, numbering: none)
|
|
https://github.com/roife/resume | https://raw.githubusercontent.com/roife/resume/master/resume-en.typ | typst | MIT License | #import "chicv.typ": *
#show: chicv
= #redact(alter: "roife")[placeholder]
#fa[#phone] #redact(mark: true)[00000000000] |
#fa[#envelope] <EMAIL> |
#fa[#github] #link("https://github.com/roife")[roife] |
#fa[#globe] #link("https://roife.github.io")[roife.github.io] |
#fa[#location-arrow] Hong Kong
== Education
#cventry(
tl: [Nanjing University],
tr: [2023.09 - 2026.06 (expected)],
bl: [Master's Degree in #emph[Computer Science and Technology] | #link("https://pascal-lab.net")[Pascal Lab]. Tutor: #redact(mark: true)[Place] Li | Focus on PL, program analysis and HDL],
)[]
#cventry(
tl: [Beihang University],
tr: [2019.09 - 2023.06],
bl: [Bachelor’s Degree in #emph[Computer Science and Technology] | GPA 3.84/4.00],
)[]
== Work Experience
#cventry(
tl: [Rust Foundation Fellowship Program],
tl_comments: redact(alter: "")[ (10 recipients worldwide)],
tr: [2024.09 - 2025.06 (expected)],
)[
- *Contributing to rust-analyzer* (the official Rust IDE)
- Ranked *19/970* in contributors; resolved *over 50 issues* and contributing to multiple modules (e.g. *semantic analysis*, etc.), improving robustness of the project. Also introduced several new features (e.g. *control flow navigation*, etc.);
- Implemented a *SIMD* version of the line-breaking algorithm, leading to a *6.5x* speedup for this module on ARM;
- *Resolved a P0 incident in v0.3.1992*. 4 hours after the release, the community encountered a critical bug that drained resources and blocked processes. I identified the issue *in 3 hours* and designed a new algorithm as fix. This emergency fix mitigated the incident, preventing widespread disruptions for Rust users and improving project stability.
- *Open-source community maintenance*: Including meeting discussions, bug fixes, PR reviews, and more.
]
== Awards
- 2022 *National Scholarship* (ranked 1/195 in the major), *Outstanding Graduate* of Beihang University
- *First Prize* in the #link("https://compiler.educg.net")[NSCSCC Compilation System Design Competition] (Huawei Bisheng Cup) 2021, ranking 2nd overall.
- Additionally awarded over ten provincial and university-level awards and scholarships
== Projects
#cventry(
tl: [Vizsla],
tl_comments: [, a modern Verilog/SV IDE for hardware development (Rust / SystemVerilog)],
tr: [(In development)],
)[
- (*Independently Developed*) Designed the core architecture of the IDE, the incremental computation processes, intermediate representation, semantic analysis module, etc. Also implemented most of the IDE functionalities.
- Aimed to equip chip design with modern IDE features (e.g. *code navigaiton*, *completion*, etc.) to enhance productivity.
- Based on the LSP, built an *incremental semantic analysis framework*#redact(alter: "")[, achieving world-class performance and usability].
]
#cventry(
tl: [LLVM-Lite],
tl_comments: [, a lightweight edge-side compiler for neural network operators (C++ / LLVM / ARM)],
tr: ghrepo("roife/llvm-lite", icon: true),
)[
- (*Independently Developed*) Huawei research project, received an excellent evaluation as my undergraduate thesis.
- Utilizing shape information of neural networks to perform optimizations on operators, reducing its runtime cost.
- Successfully *reduced runtime by 6%* and *target file size by 38%* of the neural network operators in test cases.
]
#cventry(
tl: "Ayame",
tl_comments: [, project of the Huawei Bisheng Cup, a compiler of a C-subset (Java / LLVM / ARM)],
tr: ghrepo("No-SF-Work/ayame", icon: true),
)[
- (*Co-author*) Implemented the graph-coloring register-allocation, arch-specific optimizations, the local evaluator and CI;
- The project ranked *1st in nearly half of the testcases* and outperformed `gcc -O3` and `clang -O3` on 1/3 of the examples.
]
#cventry(
tl: [Open-source contributions],
)[
- *Rust-lang Member*, rust-analyzer contributors team. Mainly worked on #ghrepo("rust-lang/rust-analyzer", icon: false). Also contributed to #ghrepo("rust-lang/rust-clippy", icon: false), #ghrepo("rust-lang/rustup", icon: false), #ghrepo("rust-lang/rust-mode", icon: false);
- #ghrepo("llvm/llvm-project", icon: false), #ghrepo("clangd/vscode-clangd", icon: false), #ghrepo("google/autocxx", icon: false), #ghrepo("yuin/goldmark", icon: false) and #link("https://github.com/roife")[more on my GitHub].
]
== Skills
- #emph[Programming Languages:] Not limited to specific language. Especially proficient in C, C++, Java, Rust, Python, Verilog/SystemVerilog. Comfortable with Ruby, Swift, JavaScript, OCaml, Coq, Haskell, etc.
- #emph[PL Theory:] Familiar with *type systems*, formal semantics, formal verification and theory of computation.
- #emph[Compilers / IDE:] *4 YoE*. Proficient in compilation optimizations and various IR (like SSA, CPS, etc.). Knowledgeable about LLVM. Familiar with IDE based on LSP and *incremental computation*.
- #emph[Program Analysis:] *2 YoE*. Familiar with static analysis algorithms (e.g. dataflow analysis, pointer analysis, etc.).
- #emph[System Programming:] Familiar with Arch and OS, capable of low-level development and debugging.
- #emph[Tools:] Proficient in Emacs; comfortable working in macOS and Linux; skilled in leveraging AI.
== Misc
- *Languages*: Chinese (native), English (fluent)
- *Teaching Assistant*: _Programming in Practice_ (Fall 2020), _Object-oriented Design and Construction_ (Fall 2021, Spring 2022), _Principles and Techniques of Compilers_ (Spring 2024).
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/list-marker-04.typ | typst | Other | // Error: 19-21 array must contain at least one marker
#set list(marker: ())
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/demos/ratio.typ | typst | #import "@local/typkit:0.1.0": *
#import "@local/mathematical:0.1.0": *
#let ratio(size: 12, ratios: (1, 2), fills: ("blue", "green")) = {
let store = ()
let d = ratios.sum()
let n = int(size / d)
let callback((i, n)) = {
return colored(resolve-math-content(n), getter(fills, i))
}
let p = ratios.enumerate().map(callback).join(marks.math.plus)
for n in range(1, n + 1) {
let t = [*total: * $#(n * d)$]
store.push((p, t))
}
x-table(..store, align: horizon + left)
}
#let ribbon-ratio(size: 12, ratios: (1, 2), fills: ("blue", "green")) = {
let d = ratios.sum()
let x = 0
draw.canvas({
for (index, n) in ratios.enumerate() {
let amount = int(size * n / d)
for i in range(amount) {
let pos = (s.get().at(0), 0)
square(pos, getter(fills, index))
s.step()
}
}
map(size, square())
})
}
ratio()
|
|
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/introduction/tool_research.typ | typst | #import "../../../style.typ": *
= Existing tools <existing_tools>
There already are tools available that could fill the role of a visual
functional programming language as described in @motivation.
But even if they fail to live up to the specific goals of this project, they
may still be helpful as inspiration or a starting point for a VisualFP.
This section discusses these tools, their strengths and weaknesses.
#let tool_research_directory = "design_concept/content/introduction/tool_research/"
#include_section(tool_research_directory + "snap.typ", heading_increase: 1)
#include_section(tool_research_directory + "eros.typ", heading_increase: 1)
#include_section(tool_research_directory + "flo.typ", heading_increase: 1)
#include_section(tool_research_directory + "enso.typ", heading_increase: 1)
#include_section(tool_research_directory + "reddit_suggestion_visual_fp.typ", heading_increase: 1)
#include_section(tool_research_directory + "agda.typ", heading_increase: 1)
|
|
https://github.com/hongjr03/shiroa-page | https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DSA/chapters/2线性表.typ | typst |
#import "../template.typ": *
#import "@preview/pinit:0.1.4": *
#import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge
#import "/book.typ": book-page
#show: book-page.with(title: "线性表 | DSA")
= 线性表
#definition[
*线性结构*是一个数据元素的有序(次序)集,集合中必存在唯一的一个“第一元素”和唯一的一个“最后元素”,除第一个元素外,集合中的每个元素均有唯一的前驱,除最后一个元素外,集合中的每个元素均有唯一的后继。
]
== 线性表的定义
设线性表为 $(a_1, a_2, dots, a_i, dots, a_n)$,称 $i$ 为 $a_i$ 在线性表中的*位序*。
#note_block[
例 2-1:
假设:有两个集合 A 和 B 分别用两个线性表 LA 和 LB 表示,即:线性表中的数据元素即为集合中的成员。现要求一个新的集合A=A∪B。
解:```cpp
void union(SqList &La, SqList Lb) {
int La_len = ListLength(La); // 求线性表的长度
int Lb_len = ListLength(Lb);
for (int i = 1; i <= Lb_len; i++) {
ElemType e;
GetElem(Lb, i, e); // 取出线性表中的第 i 个元素,赋给 e
if (!LocateElem(La, e)) {
// 在线性表中查找元素 e,若不存在则插入
ListInsert(La, ++La_len, e);
// 在线性表中第 La_len 个位置插入元素 e
}
}
}
```
]
== 线性表的顺序表示和实现
<线性表的顺序表示和实现>
#definition[
// 顺序映象:以 x 的存储位置和 y 的存储位置之间某种关系表示逻辑关系<x,y>。
*顺序映象*:以 $x$ 的存储位置和 $y$ 的存储位置之间某种关系表示逻辑关系 $<x, y>$。
]
数据元素存储位置的计算:<顺序表存储结构> $ "LOC"(a_i) = "LOC"(a_(i-1)) + C $
$ "LOC"(a_i) = #pin(101)"LOC"(#pin(103)a_1)#pin(102) + (i-1)×C $
其中,$C$ 为一个数据元素所占存储量。
#pinit-highlight(101, 102)
#pinit-point-from(103)[基地址]
*特点*:
1. 所有数据放在一个连续的地址空间
2. 数据的逻辑关系由存储位置来表现
=== 初始化
```c
Status InitList_Sq(SqList &L) {
// 构造一个空的线性表
L.elem = (ElemType *) malloc(LIST_INIT_SIZE(sizeof(ElemType));
if (!L.elem)
exit(OVERFLOW);//存储分配失败
L.length = 0; //空表长度为 0
L.listsize = LIST_INIT_SIZE //初始存储容量
return OK;
}// InitList_Sq
```
=== 查找元素
基本操作是:将顺序表中的元素逐个和给定值 e 相比较。
```C
int LocateElem_Sq(SqList L, ElemType e,
Status (*compare)(ElemType, ElemType)) {
i = 1; // i 的初值为第 1 元素的位序
p = L.elem;// p 的初值为第 1 元素的存储位置
while (i <= L.length && !(*compare)(*p++, e)) ++i;
if (i <= L.length) return i;
else
return 0;
}// LocateElem_Sq
```
算法的时间复杂度为: $O( "ListLength"(L) )$
但如果是获取某个元素的值,时间复杂度为 $O(1)$。
=== 插入元素
时间复杂度:$O(n)$
在长度为 $n$ 的线性表中插入一个元素所需移动元素次数的期望值为:$ E_(i s) = sum_(i=1)^(n+1) p_i (n-i+1) $
假定在线性表中任何一个位置进行插入的概率都是相等的,则移动元素的期望值为:$ E_(i s) = 1/(n+1) sum_(i=1)^(n+1) (n-i+1) = n/2 $
=== 删除元素
时间复杂度:$O(n)$
移动元素次数的期望值为:$ E_(d l) = sum_(i=1)^(n-1) p_i (n-i) = n/2 $
== 线性表的链式表示和实现
<线性表的链式表示和实现>
#definition[
*链式映象*:以附加信息(指针)表示后继关系。需要用一个和 `x` 在一起的附加信息指示 `y` 的存储位置。
]
*特点*:
1. 用一组*任意*的存储单元来存放线性表的结点。因此,链表中结点的逻辑次序和物理次序不一定相同。
2. 因为链表除了存放数据元素之外,还要存放指针,因此链表的存储密度不及顺序存储。
=== 线性单链表
#note_block[
#align(center)[
结点 = 元素 + 指针
]
- 元素:数据元素的映象
- 指针:指示后继元素存储位置
由于此链表的每个结点中只包含一个指针域,故称为线性链表或单链表。
]
#note_block[
#let lnode(pin, data, next) = {
show table.cell: it => {
// if it.x == 0 {
// cell.stroke
// }
align(center + horizon)[#it]
}
set table(stroke: (x, y) => (
y: if x > 1 {
1pt
},
left: if x > 1 {
1pt
} else {
0pt
},
right: 1pt,
))
table(
columns: (1em, 0.5em, 2em, 1em),
rows: (2em),
[], pin, [#data], [#next],
)
}
#grid(
columns: 8,
)[
#align(center + horizon)[
#v(1em)
#pin(1)
#h(1em)
]
][
#lnode([#pin(2)], [], "^")
#pinit-arrow(1, 2)
#pinit-place(2, dy: 13.5pt)[
#set text(size: 8pt)
头结点
]
][
#h(2em)
][
#lnode([], [$a_1$], pin(3))
][
#lnode(pin(4), [$a_2$], pin(5))
#pinit-arrow(3, 4)
][
#lnode(pin(6), [$...$], pin(7))
#pinit-arrow(5, 6)
][
#lnode(pin(8), [$a_n$], [^])
#pinit-arrow(7, 8)
]
以线性表中第一个数据元素 $a_1$ 的存储地址作为线性链表的地址,称作线性链表的头指针。
有时为了操作方便,在第一个结点之前虚加一个“头结点”,以指向头结点的指针为链表的头指针。
加入头结点的*优势*:
- 由于头结点的位置被存放在头结点的指针域中,所以在链表的第一个位置上的操作就和在表的其他位置上的操作一致,无须进行特殊处理。
- 无论链表是否为空,其头指针是指向头结点的非空指针(空表中头结点的指针域空),因此空表和非空表的处理也就一致了。
]
```C
typedef struct LNode {
ElemType data; // 数据域
struct LNode *next; // 指针域
} LNode, *LinkList;
LinkList L; // L 为单链表的头指针
```
- ```C p->next```:下一个结点的地址
- ```C p->data```:当前结点的数据
- ```C p = p->next```:指向下一个结点(指针后移)
==== 操作的时间复杂度
- 查找:$O(n)$
- 插入:$O(n)$ (找到插入位置)
- 删除:$O(n)$ (找到删除位置)
- 插入和删除结点的时间复杂度为 $O(1)$,但是需要先找到插入或删除位置。
- 清空链表:$O(n)$
- 创建链表:$O(n)$
#note_block[
算法 2.13:
```c
void MergeList_L(LinkList &La, LinkList &Lb, LinkList &Lc) {
// 已知单链线性表La和 Lb的元素按值非递减排列
//归并La和 Lb得到新的单链线性表Lc,Lc的元素也按值非递减排列
pa = La->next;
pb = Lb->next;
Lc = pc = La;
//用的La头结点作为Lc的头结点
While(pa && pb) {
if (pa->data <= pb->data) {
pc->next = pa;
pc = pa;
pa = pa->next;
} else {
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;//插入剩余段
free(Lb); //释放Lb的头结点
}// MergeList_L
```
]
=== 循环链表
#definition[
*循环链表*:最后一个结点的指针域的指针又指回第一个结点的链表。
]
和单链表的差别仅在于,判别链表中最后一个结点的条件不再是“后继是否为空”,而是“后继是否为头结点”。
=== 双向链表
==== 插入
#grid(
columns: (0.3fr, 1fr),
)[
#image("../assets/2024-06-16-18-44-27.png")
][```c
s->next = p->next;
p->next = s;
s->next->prior = s;
s->prior = p;
```]
#grid(
columns: (0.3fr, 1fr),
)[
#image("../assets/2024-06-16-18-48-55.png")
][```c
s->prior = p->prior;
p->prior->next = s;
s->next = p;
p->prior = s;
```]
```C
Status ListInsert_ DuL(DuLinkList &L, int i, ElemType e) {
//i 的合法值为 1≤i≤表长 +1.
if (!(p = GetElemP_ DuL(L, i)))//大于表长加 1,p=NULL;
return ERROR; //等于表长加 1 时,指向头结点;
if (!(s = (DuLinkList) malloc(sizeof(DuLNode))))
return ERROR;
s->data = e;
s->prior = p->prior;
p->prior->next = s;
s->next = p;
p->prior = s;
return OK;
}// ListInsert_ DuL
```
==== 删除
#grid(
columns: (0.3fr, 1fr),
)[
#image("../assets/2024-06-16-18-51-01.png")
][```c
p->next = p->next->next;
p->next->prior = p;
```]
#grid(
columns: (0.3fr, 1fr),
)[
#image("../assets/2024-06-16-18-51-45.png")
][```c
p->prior->next = p->next;
p->next->prior = p->prior;
```]
```C
Status ListDelete_DuL(DuLinkList &L, int i, ElemType &e) {
//i 的合法值为 1≤i≤表长
if (!(p = GetElemP_ DuL(L, i)))
return ERROR;//p=NULL,即第 i 个元素不存在
e = p->data;
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
return OK;
}// ListDelete_ DuL
```
== 比较几种主要链表
#image("../assets/2024-06-16-18-53-41.png", width: 100%)
#image("../assets/2024-06-16-18-53-46.png", width: 100%)
#image("../assets/2024-06-16-18-53-50.png", width: 100%)
#image("../assets/2024-06-16-18-53-57.png", width: 100%)
== 边界条件
=== 几个特殊点的处理
- 头指针处理
- 非循环链表尾结点的指针域保持为NULL
- 循环链表尾结点的指针回指头结点
=== 链表处理
- 空链表的特殊处理
- 插入或删除结点时指针勾链的顺序
- 指针移动的正确性
- 插入
- 查找或遍历
== 实现方法比较
=== 顺序表
*优点*:
- 没有使用指针,不用花费额外开销
- 线性表元素的读访问非常简洁便利
*特点*:
- 插入、删除运算时间代价$O(n)$,查找则可常数时间完成
- 预先申请固定长度的数组
- 如果整个数组元素很满,则没有结构性存储开销
=== 链表
*优点*:
- 无需事先了解线性表的长度
- 允许线性表的长度动态变化
- 能够适应经常插入删除内部元素的情况
*特点*:
- 插入、删除运算时间代价$O(1)$,但找第$i$个元素运算时间代价$O(n)$
- 存储利用指针,动态地按照需要为表中新的元素分配存储空间
- 每个元素都有结构性存储开销
#note_block[
- 顺序表是存储静态数据的不二选择,适用于读操作比插入删除操作频率大的场合
- 链表是存储动态变化数据的良方,适用于插入删除操作频率大的场合;当指针的存储开销,和整个结点内容所占空间相比其比例较大时,应该慎重选择
]
|
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/1%20-%20Candidatura/Verbali/Interni/21-10-23/21-10-23.typ | typst | ERROR\_418 \
Verbale 21/10/23
#figure(
align(center)[#table(
columns: 2,
align: (col, row) => (left,left,).at(col),
inset: 6pt,
[Mail:],
[<EMAIL>],
[Redattori:],
[<NAME>, <NAME>],
[Verificatori:],
[<NAME>, <NAME>, <NAME>],
[Amministratori:],
[<NAME>, <NAME>],
[Destinatari:],
[<NAME>, <NAME>],
)]
)
#figure(
align(center)[#table(
columns: 2,
align: (col, row) => (center,center,).at(col),
inset: 6pt,
[Inizio Meeting: 08:00 Fine Meeting: 09:15 Durata:1:15h],
[],
[Presenze:],
[],
)]
)
#block[
#figure(
align(center)[#table(
columns: 5,
align: (col, row) => (center,center,center,center,center,).at(col),
inset: 6pt,
[Nome], [Durata Presenza], [], [Nome], [Durata Presenza],
[Antonio],
[1:15h],
[],
[Alessio],
[1:15h],
[Riccardo],
[1:15h],
[],
[Giovanni],
[1:15h],
[Rosario],
[1:10h],
[],
[Silvio],
[1:15h],
[Mattia],
[/],
[],
[],
[],
)]
)
]
Ordine del giorno:
- Discussione introduttiva al metodo di lavoro;
- Presentazione lavoro svolto su configurazione ambiente git;
- Presentazione lavoro svolto su template della documentazione;
- Scelta finale del logo.
= GitHub
<github>
Antonio ha creato una repository su GitHub e ha impostato Project, issue
, tag e milestone sulla stessa, andando poi a dare spiegazione dei
principali rami creati al suo interno. \
Si è deciso di utilizzare i feature branch per il lato implementativo. \
= Documenti
<documenti>
Creazione e ottimizzazione del template per i verbali del meeting. \
Creazione delle prime issues su GitHub \
Decisione di adottare Overleaf per il live editing dei fil .tex.
= Way of working
<way-of-working>
La prima versione del documento va presentata entro il 31/10/2023 per la
candidatura. \
Spunti di ragionamento a tal proposito:
- Cicli di una settimana;
- Meeting periodici;
- Feature branch con main protetto;
- Test Driven Development;
- Continuous Integration con GitHub Actions;
- Continuous Deployment con Docker.
= Meeting aziendale
<meeting-aziendale>
Scrivere e-mail alle aziende per concordare un meeting, concentrandosi
sull’analisi dei requisiti e su eventuali domande specifiche. \
Creazione di file condiviso su GitHub per scrivere ognuno le domande da
porgere alle aziende. \
Fissato il compito individuale di trovare 1-2 domande da porre per ogni
capitolato entro il 22/10/2023.
= Logo
<logo>
Logo deciso.
= Obiettivi
<obiettivi>
- Caricare logo su Github;
- \(Entro il 22/10/2023) raccogliere domande per le aziende;
- \(Entro il 31/10/2023) preparazione Norme di progetto e lettera di
presentazione con disponibilità oraria;
- Caricamento di due file su GitHub, uno per le domande da rivolgere ai
proponenti e l’altro con una bozza del Way of Working.
|
|
https://github.com/GartmannPit/Praxisprojekt-II | https://raw.githubusercontent.com/GartmannPit/Praxisprojekt-II/main/Praxisprojekt%20II/PVA-Templates-typst-pva-2.0/template/conf.typ | typst | #let style(content) = {
set text(
font: "Times New Roman", // set global font
size: 12pt, // and size
lang: "de" // set language of document: influencing auto-generating describtions and some character placing like ' and ""
)
set heading(
numbering: "1.1", // set global heading style
outlined: true
)
set page(
paper: "a4",
margin: (
top: 2.5cm, // set gloabl page design and margins
bottom: 2cm,
left: 2.5cm,
right: 2.5cm
),
numbering: "1", // set page numbering style
number-align: right // and number alignment
)
set par(
justify: true, // justifing paragraphs?
leading: 1.5em // leading paragraphs?
)
set cite(style: "apa") // set global cite style here
show figure: set text(size: 0.85em) // set figure caption size here
content
}
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz-plot/0.1.0/src/chart/piechart.typ | typst | Apache License 2.0 | #import "/src/cetz.typ": draw, styles, palette, util, vector, intersection
#import util: circle-arclen
#import "/src/plot/legend.typ"
// Piechart Label Kind
#let label-kind = (value: "VALUE", percentage: "%", label: "LABEL")
// Piechart Default Style
#let default-style = (
stroke: auto,
fill: auto,
/// Outer chart radius
radius: 1,
/// Inner slice radius
inner-radius: 0,
/// Gap between items. This can be a canvas length or an angle
gap: 0.5deg,
/// Outset offset, absolute or relative to radius
outset-offset: 10%,
/// Pie outset mode:
/// - "OFFSET": Offset slice position by outset-offset
/// - "RADIUS": Offset slice radius by outset-offset (the slice gets scaled)
outset-mode: "OFFSET",
/// Pie start angle
start: 90deg,
/// Pie stop angle
stop: 360deg + 90deg,
/// Pie rotation direction (true = clockwise, false = anti-clockwise)
clockwise: true,
outer-label: (
/// Label kind
/// If set to a function, that function gets called with (value, label) of each item
content: label-kind.label,
/// Absolute radius or percentage of radius
radius: 125%,
/// Absolute angle or auto to use secant of the slice as direction
angle: 0deg,
/// Label anchor
anchor: "center",
),
inner-label: (
/// Label kind
/// If set to a function, that function gets called with (value, label) of each item
content: none,
/// Absolute radius or percentage of the mid between radius and inner-radius
radius: 150%,
/// Absolute angle or auto to use secant of the slice as direction
angle: 0deg,
/// Label anchor
anchor: "center",
),
legend: (
..legend.default-style,
/// Label used for the legend
/// The legend gets rendered as soon as at least one item with a label
/// exists and the `legend-label.content` is set != none. This field
/// accepts the same values as inner-label.content or outer-label.content.
label: "LABEL",
/// Anchor of the charts data bounding box to place the legend relative to
position: "south",
/// Anchor of the legend bounding box to use as origin
anchor: "north",
/// Custom preview function override
/// The function takes an item dictionary an is responsible for drawing
/// the preview icon. Stroke and fill styles are set to match the items
/// style.
preview: none,
/// See lenged.typ for the following style keys
orientation: ltr,
offset: (0,-.5em),
stroke: none,
item: (
spacing: .25,
preview: (
width: .3,
height: .3,
),
),
)
)
#let piechart-default-style = default-style
/// Draw a pie- or donut-chart
///
/// #example(```
/// let data = (24, 31, 18, 21, 23, 18, 27, 17, 26, 13)
/// let colors = gradient.linear(red, blue, green, yellow)
///
/// chart.piechart(
/// data,
/// radius: 1.5,
/// slice-style: colors,
/// inner-radius: .5,
/// outer-label: (content: "%",))
/// ```)
///
/// = Styling
/// *Root* `piechart` \
/// #show-parameter-block("radius", ("number"), [
/// Outer radius of the chart.], default: 1)
/// #show-parameter-block("inner-radius", ("number"), [
/// Inner radius of the chart slices. If greater than zero, the chart becomes
/// a "donut-chart".], default: 0)
/// #show-parameter-block("gap", ("number", "angle"), [
/// Gap between chart slices to leave empty. This does not increase the charts
/// radius by pushing slices outwards, but instead shrinks the slice. Big
/// values can result in slices becoming invisible if no space is left.], default: 0.5deg)
/// #show-parameter-block("outset-offset", ("number", "ratio"), [
/// Absolute, or radius relative distance to push slices marked for
/// "outsetting" outwards from the center of the chart.], default: 10%)
/// #show-parameter-block("outset-offset", ("string"), [
/// The mode of how to perform "outsetting" of slices:
/// - "OFFSET": Offset slice position by `outset-offset`, increasing their gap to their siblings
/// - "RADIUS": Offset slice radius by `outset-offset`, which scales the slice and leaves the gap unchanged], default: "OFFSET")
/// #show-parameter-block("start", ("angle"), [
/// The pie-charts start angle (ccw). You can use this to draw charts not forming a full circle.], default: 90deg)
/// #show-parameter-block("stop", ("angle"), [
/// The pie-charts stop angle (ccw).], default: 360deg + 90deg)
/// #show-parameter-block("clockwise", ("bool"), [
/// The pie-charts rotation direction.], default: true)
/// #show-parameter-block("outer-label.content", ("none","string","function"), [
/// Content to display outsides the charts slices.
/// There are the following predefined values:
/// / LABEL: Display the slices label (see `label-key`)
/// / %: Display the percentage of the items value in relation to the sum of
/// all values, rounded to the next integer
/// / VALUE: Display the slices value
/// If passed a `<function>` of the format `(value, label) => content`,
/// that function gets called with each slices value and label and must return
/// content, that gets displayed.], default: "LABEL")
/// #show-parameter-block("outer-label.radius", ("number","ratio"), [
/// Absolute, or radius relative distance from the charts center to position
/// outer labels at.], default: 125%)
/// #show-parameter-block("outer-label.angle", ("angle","auto"), [
/// The angle of the outer label. If passed `auto`, the label gets rotated,
/// so that the baseline is parallel to the slices secant. ], default: 0deg)
/// #show-parameter-block("outer-label.anchor", ("string"), [
/// The anchor of the outer label to use for positioning.], default: "center")
/// #show-parameter-block("inner-label.content", ("none","string","function"), [
/// Content to display insides the charts slices.
/// See `outer-label.content` for the possible values.], default: none)
/// #show-parameter-block("inner-label.radius", ("number","ratio"), [
/// Distance of the inner label to the charts center. If passed a `<ratio>`,
/// that ratio is relative to the mid between the inner and outer radius (`inner-radius` and `radius`)
/// of the chart], default: 150%)
/// #show-parameter-block("inner-label.angle", ("angle","auto"), [
/// See `outer-label.angle`.], default: 0deg)
/// #show-parameter-block("inner-label.anchor", ("string"), [
/// See `outer-label.anchor`.], default: "center")
/// #show-parameter-block("legend.label", ("none","string","function"), [
/// See `outer-label.content`. The legend gets shown if this key is set != none.], default: "LABEL")
///
/// = Anchors
/// The chart places one anchor per item at the radius of it's slice that
/// gets named `"item-<index>"` (outer radius) and `"item-<index>-inner"` (inner radius),
/// where index is the index of the sclice data in `data`.
///
/// - data (array): Array of data items. A data item can be:
/// - A number: A number that is used as the fraction of the slice
/// - An array: An array which is read depending on value-key, label-key and outset-key
/// - A dictionary: A dictionary which is read depending on value-key, label-key and outset-key
/// - value-key (none,int,string): Key of the "value" of a data item. If for example
/// data items are passed as dictionaries, the value-key is the key of the dictionary to
/// access the items chart value.
/// - label-key (none,int,string): Same as the value-key but for getting an items label content.
/// - outset-key (none,int,string): Same as the value-key but for getting if an item should get outset (highlighted). The
/// outset can be a bool, float or ratio. If of type `bool`, the outset distance from the
/// style gets used.
/// - outset (none,int,array): A single or multiple indices of items that should get offset from the center to the outsides
/// of the chart. Only used if outset-key is none!
/// - slice-style (function,array,gradient): Slice style of the following types:
/// - function: A function of the form `index => style` that must return a style dictionary.
/// This can be a `palette` function.
/// - array: An array of style dictionaries or fill colors of at least one item. For each slice the style at the slices
/// index modulo the arrays length gets used.
/// - gradient: A gradient that gets sampled for each data item using the the slices
/// index divided by the number of slices as position on the gradient.
/// If one of stroke or fill is not in the style dictionary, it is taken from the charts style.
#let piechart(data,
value-key: none,
label-key: none,
outset-key: none,
outset: none,
slice-style: palette.red,
name: none,
..style) = {
import draw: *
// Prepare data by converting it to tuples of the format
// (value, label, outset)
data = data.enumerate().map(((i, item)) => (
if value-key != none {
item.at(value-key)
} else {
item
},
if label-key != none {
item.at(label-key)
} else {
none
},
if outset-key != none {
item.at(outset-key, default: false)
} else if outset != none {
i == outset or (type(outset) == array and i in outset)
} else {
false
}
))
let sum = data.map(((value, ..)) => value).sum()
if sum == 0 {
sum = 1
}
group(name: name, ctx => {
anchor("default", (0,0))
let style = styles.resolve(ctx,
merge: style.named(), root: "piechart", base: default-style)
let gap = style.gap
if type(gap) != angle {
gap = gap / (2 * calc.pi * style.radius) * 360deg
}
assert(gap < 360deg / data.len(),
message: "Gap angle is too big for " + str(data.len()) + "items. Maximum gap angle: " + repr(360deg / data.len()))
let radius = style.radius
assert(radius > 0,
message: "Radius must be > 0.")
let inner-radius = style.inner-radius
assert(inner-radius >= 0 and inner-radius <= radius,
message: "Radius must be >= 0 and <= radius.")
assert(style.outset-mode in ("OFFSET", "RADIUS"),
message: "Outset mode must be 'OFFSET' or 'RADIUS', but is: " + str(style.outset-mode))
let style-at = if type(slice-style) == function {
slice-style
} else if type(slice-style) == array {
i => {
let s = slice-style.at(calc.rem(i, slice-style.len()))
if type(s) == color {
(fill: s)
} else {
s
}
}
} else if type(slice-style) == gradient {
i => (fill: slice-style.sample(i / data.len() * 100%))
}
let start-angle = style.start
let stop-angle = style.stop
let f = (stop-angle - start-angle) / sum
let get-item-label(item, kind) = {
let (value, label, ..) = item
if kind == label-kind.value {
[#value]
} else if kind == label-kind.percentage {
[#{calc.round(value / sum * 100)}%]
} else if kind == label-kind.label {
label
} else if type(kind) == function {
(kind)(value, label)
}
}
let start = start-angle
let enum-items = if style.clockwise {
data.enumerate().rev()
} else {
data.enumerate()
}
group(name: "chart", {
for (i, item) in enum-items {
let (value, label, outset) = item
if value == 0 { continue }
let origin = (0,0)
let radius = radius
let inner-radius = inner-radius
// Calculate item angles
let delta = f * value
let end = start + delta
// Apply item outset
let outset-offset = if outset == true {
style.outset-offset
} else if outset == false {
0
} else if type(outset) in (float, ratio) {
outset
} else {
panic("Invalid type for outset. Expected bool, float or ratio, got: " + repr(outset))
}
if type(outset-offset) == ratio {
outset-offset = outset-offset * radius / 100%
}
if outset-offset != 0 {
if style.outset-mode == "OFFSET" {
let dir = (calc.cos((start + end) / 2), calc.sin((start + end) / 2))
origin = vector.add(origin, vector.scale(dir, outset-offset))
radius += outset-offset
} else {
radius += outset-offset
if inner-radius > 0 {
inner-radius += outset-offset
}
}
}
// Calculate gap angles
let outer-gap = gap
let gap-dist = outer-gap / 360deg * 2 * calc.pi * radius
let inner-gap = if inner-radius > 0 {
gap-dist / (2 * calc.pi * inner-radius) * 360deg
} else {
1 / calc.pi * 360deg
}
// Calculate angle deltas
let outer-angle = end - start - outer-gap * 2
let inner-angle = end - start - inner-gap * 2
let mid-angle = (start + end) / 2
// Skip negative values
if outer-angle < 0deg {
// TODO: Add a warning as soon as Typst is ready!
continue
}
// A sharp item is an item that should be round but is sharp due to the gap being big
let is-sharp = inner-radius == 0 or circle-arclen(inner-radius, angle: inner-angle) > circle-arclen(radius, angle: outer-angle)
let inner-origin = vector.add(origin, if inner-radius == 0 {
if gap-dist >= 0 {
let outer-end = vector.scale((calc.cos(end - outer-gap), calc.sin(end - outer-gap)), radius)
let inner-end = vector.scale((calc.cos(end - inner-gap), calc.sin(end - inner-gap)), gap-dist)
let outer-start = vector.scale((calc.cos(start + outer-gap), calc.sin(start + outer-gap)), radius)
let inner-start = vector.scale((calc.cos(start + inner-gap), calc.sin(start + inner-gap)), gap-dist)
intersection.line-line(outer-end, inner-end, outer-start, inner-start, ray: true)
} else {
(0,0)
}
} else if is-sharp {
let outer-end = vector.scale((calc.cos(end - outer-gap), calc.sin(end - outer-gap)), radius)
let inner-end = vector.scale((calc.cos(end - inner-gap), calc.sin(end - inner-gap)), inner-radius)
let outer-start = vector.scale((calc.cos(start + outer-gap), calc.sin(start + outer-gap)), radius)
let inner-start = vector.scale((calc.cos(start + inner-gap), calc.sin(start + inner-gap)), inner-radius)
intersection.line-line(outer-end, inner-end, outer-start, inner-start, ray: true)
} else {
(0,0)
})
// Draw one segment
let stroke = style-at(i).at("stroke", default: style.stroke)
let fill = style-at(i).at("fill", default: style.fill)
if data.len() == 1 {
// If the chart has only one segment, we may have to fake a path
// with a hole in it by using a combination of multiple arcs.
if inner-radius > 0 {
// Split the circle/arc into two arcs
// and fill them
merge-path({
arc(origin, start: start-angle, stop: mid-angle, radius: radius, anchor: "origin")
arc(origin, stop: start-angle, start: mid-angle, radius: inner-radius, anchor: "origin")
}, close: false, fill:fill, stroke: none)
merge-path({
arc(origin, start: mid-angle, stop: stop-angle, radius: radius, anchor: "origin")
arc(origin, stop: mid-angle, start: stop-angle, radius: inner-radius, anchor: "origin")
}, close: false, fill:fill, stroke: none)
// Create arcs for the inner and outer border and stroke them.
// If the chart is not a full circle, we have to merge two arc
// at their ends to create closing lines
if stroke != none {
if calc.abs(stop-angle - start-angle) != 360deg {
merge-path({
arc(origin, start: start, stop: end, radius: inner-radius, anchor: "origin")
arc(origin, start: end, stop: start, radius: radius, anchor: "origin")
}, close: true, fill: none, stroke: stroke)
} else {
arc(origin, start: start, stop: end, radius: inner-radius, fill: none, stroke: stroke, anchor: "origin")
arc(origin, start: start, stop: end, radius: radius, fill: none, stroke: stroke, anchor: "origin")
}
}
} else {
arc(origin, start: start, stop: end, radius: radius, fill: fill, stroke: stroke, mode: "PIE", anchor: "origin")
}
} else {
// Draw a normal segment
if inner-origin != none {
merge-path({
arc(origin, start: start + outer-gap, stop: end - outer-gap, anchor: "origin",
radius: radius)
if inner-radius > 0 and not is-sharp {
if inner-angle < 0deg {
arc(inner-origin, stop: end - inner-gap, delta: inner-angle, anchor: "origin",
radius: inner-radius)
} else {
arc(inner-origin, start: end - inner-gap, delta: -inner-angle, anchor: "origin",
radius: inner-radius)
}
} else {
line((rel: (end - outer-gap, radius), to: origin),
inner-origin,
(rel: (start + outer-gap, radius), to: origin))
}
}, close: true, fill: fill, stroke: stroke)
}
}
// Place outer label
let outer-label = get-item-label(item, style.outer-label.content)
if outer-label != none {
let r = style.outer-label.radius
if type(r) == ratio {r = r * radius / 100%}
let dir = (r * calc.cos(mid-angle), r * calc.sin(mid-angle))
let pt = vector.add(origin, dir)
let angle = style.outer-label.angle
if angle == auto {
angle = vector.add(pt, (dir.at(1), -dir.at(0)))
}
content(pt, outer-label, angle: angle, anchor: style.outer-label.anchor)
}
// Place inner label
let inner-label = get-item-label(item, style.inner-label.content)
if inner-label != none {
let r = style.inner-label.radius
if type(r) == ratio {r = r * (radius + inner-radius) / 200%}
let dir = (r * calc.cos(mid-angle), r * calc.sin(mid-angle))
let pt = vector.add(origin, dir)
let angle = style.inner-label.angle
if angle == auto {
angle = vector.add(pt, (dir.at(1), -dir.at(0)))
}
content(pt, inner-label, angle: angle, anchor: style.inner-label.anchor)
}
// Place item anchor
anchor("item-" + str(i), (rel: (mid-angle, radius), to: origin))
anchor("item-" + str(i) + "-inner", (rel: (mid-angle, inner-radius), to: origin))
start = end
}
})
legend.legend((name: "chart", anchor: style.legend.position), {
let preview-fn = if style.legend.preview != none {
style.legend.preview
} else {
(_) => { rect((0,0), (1,1)) }
}
for (i, item) in enum-items.rev() {
let label = get-item-label(item, style.legend.label)
let preview = (item) => {
let stroke = style-at(i).at("stroke", default: style.stroke)
let fill = style-at(i).at("fill", default: style.fill)
set-style(stroke: stroke, fill: fill)
preview-fn(item)
}
legend.item(label, preview)
}
}, ..style.at("legend", default: (:)))
})
}
|
https://github.com/wizicer/gnark-cheatsheet | https://raw.githubusercontent.com/wizicer/gnark-cheatsheet/main/gnark-cheatsheet.typ | typst | #set document(title: "gnark cheatsheet", author: "<NAME> @wizicer")
#set page(
paper: "a4",
margin: (x: 1cm, top: 1cm, bottom: 1cm),
// header: align()[
// A fluid dynamic model for
// glacier flow
// ],
// numbering: "1",
)
// #set par(justify: true)
#set text(
size: 9pt,
)
#show heading.where(
level: 1
): it => block(width: 100%)[
#set align(center)
#set text(22pt, font: "Bodoni 72 Smallcaps", weight: "semibold")
// #set text(22pt, font: "Encode Sans Condensed", weight: "regular")
// #smallcaps(it.body)
#underline(stroke: 8pt + rgb(37, 76, 202, 50), offset: -1pt, evade: false, [#it.body])
]
#show heading.where(
level: 2
): it => text(
size: 16pt,
weight: "regular",
font: "Arial",
// style: "italic",
it.body,
)
#show heading.where(
level: 3
): it => block(width: 100%, height: 6pt)[
#set align(center)
#set text(11pt,
font: "Arial",
fill: rgb("#284ecb").darken(20%),
style: "italic",
weight: "regular")
--- #it.body ---
]
#import "@preview/codly:1.0.0": *
#show: codly-init.with()
#codly(languages: (
// go: (name: "", icon:rect(), color: rgb("#5daad4")),
go: (name: "", icon:rect(), color: luma(200)),
),
display-icon: false,
number-format: none,
zebra-fill: rgb("#f9f9f9"),
// lang-format: none,
)
#let in_circuit_color = 0.5pt + rgb("#254cca")
#let out_circuit_color = 0.5pt + rgb("#29851c")
#show: rest => columns(3, gutter: 8pt, rest)
#figure(
placement: bottom,
box(
width: 100%,
inset: 2pt,
[
#set align(start)
Made by #link("https://zkshanghai.xyz")[<NAME>],
#datetime.today().display().
Inspired by #link("https://golang.sk/images/blog/cheatsheets/go-cheat-sheet.pdf")[golang.sk]
]
),
)
= Gnark Cheat Sheet
// == Concepts
// === zk-SNARK and gnark
// #text(
// size:7pt,
// [
// A zk-SNARK is a cryptographic construction that allows you to provide a proof of knowledge (Argument of Knowledge) of secret inputs satisfying a public mathematical statement, without leaking any information on the inputs (Zero Knowledge).
// With `gnark`, you can write any circuit using the gnark API.
// An instance of such a circuit is
// $op("hash")(x)=y$, where $y$ is public and $x$ secret.
// ]
// )
== Getting started
=== Installing Gnark
#codly(stroke: out_circuit_color)
```sh
go get github.com/consensys/gnark@latest
```
- `frontend.Variable` is abbreviated as `Var`
#codly(display-name: false)
- #box(stroke: in_circuit_color.paint + 1.2pt, width: 6pt, height: 6pt) is in-circuit code,
#box(stroke: out_circuit_color.paint + 1.2pt, width: 6pt, height: 6pt) is out-circuit code
=== Define Circuit
#codly(stroke: in_circuit_color)
```go
import "github.com/consensys/gnark/frontend"
type Circuit struct {
PreImage Var `gnark:",secret"`
Hash Var `gnark:"hash,public"`
}
func (c *Circuit) Define(
api frontend.API) error {
m, _ := mimc.NewMiMC(api)
m.Write(c.PreImage)
api.AssertIsEqual(c.Hash, m.Sum())
}
```
=== Compile
#codly(stroke: out_circuit_color)
```go
var mimcCircuit Circuit
cur := ecc.BN254.ScalarField()
r1cs, err := frontend.Compile(
cur, r1cs.NewBuilder, &mimcCircuit)
vals := &Circuit { Hash: "161...469", PreImage: 35 }
w, _ := frontend.NewWitness(vals, cur)
pubw, _ := w.Public()
```
=== Prove: Groth16
```go
pk, vk, _ := groth16.Setup(cs)
proof, _ := groth16.Prove(cs, pk, w)
err := groth16.Verify(proof, vk, pubw)
```
=== Prove: PlonK
```go
srs, lag, _ := unsafekzg.NewSRS(cs)
pk, vk, _ := plonk.Setup(cs, srs, lag)
proof, _ := plonk.Prove(cs, pk, w)
err := plonk.Verify(proof, vk, pubw)
```
== API
#codly(stroke: in_circuit_color)
=== Assertions
```go
// fails if i1 != i2
AssertIsEqual(i1, i2 Var)
// fails if i1 == i2
AssertIsDifferent(i1, i2 Var)
// fails if v != 0 and v != 1
AssertIsBoolean(i1 Var)
// fails if v ∉ {0,1,2,3}
AssertIsCrumb(i1 Var)
// fails if v > bound.
AssertIsLessOrEqual(v Var, bound Var)
```
#colbreak()
=== Arithemetics
```go
// = i1 + i2 + ... in
Add(i1, i2 Var, in ...Var) Var
// a = a + (b * c)
MulAcc(a,b, c Var) Var
Neg(i1 Var) Var // -i.
// = i1 - i2 - ... in
Sub(i1, i2 Var, in ...Var) Var
// = i1 * i2 * ... in
Mul(i1, i2 Var, in ...Var) Var
// i1 /i2. =0 if i1 = i2 = 0
DivUnchecked(i1, i2 Var) Var
Div(i1, i2 Var) Var // = i1 / i2
Inverse(i1 Var) Var // = 1 / i1
```
=== Binary
```go
// unpacks to binary (lsb first)
ToBinary(i1 Var, n ...int) []Var
// packs b to element (lsb first)
FromBinary(b ...Var) Var
// following a and b must be 0 or 1
Xor(a, b Var) Var // a ^ b
Or(a, b Var) Var // a | b
And(a, b Var) Var // a & b
```
=== Flow
```go
// performs a 2-bit lookup
Lookup2(b0,b1 Var,i0,i1,i2,i3 Var) Var
// if b is true, yields i1 else i2
Select(b Var, i1, i2 Var) Var
// returns 1 if a is zero, 0 otherwise
IsZero(i1 Var) Var
// 1 if i1>i2, 0 if i1=i2, -1 if i1<i2
Cmp(i1, i2 Var) Var
```
=== Debug
Run the program with `-tags=debug` to display a more verbose stack trace.
```go
Println(a ...Var) //like fmt.Println
```
// === Advanced
// ```go
// // for advanced circuit development
// Compiler() Compiler
// ```
// ```go
// // NewHint is a shortcut to api.Compiler().NewHint()
// // Deprecated: use api.Compiler().NewHint() instead
// NewHint(f solver.Hint, nbOutputs int, inputs ...Variable) ([]Variable, error)
// // ConstantValue is a shortcut to api.Compiler().ConstantValue()
// // Deprecated: use api.Compiler().ConstantValue() instead
// ConstantValue(v Variable) (*big.Int, bool)
// ```
== Standard Library
=== MiMC Hash
```go
import "github.com/consensys/gnark/std/hash/mimc"
fMimc, _ := mimc.NewMiMC()
fMimc.Write(circuit.Data)
h := fMimc.Sum()
```
=== EdDSA Signature
```go
import t "github.com/consensys/gnark-crypto/ecc/twistededwards"
import te "github.com/consensys/gnark/std/algebra/native/twistededwards"
type Circuit struct {
pub eddsa.PublicKey
sig eddsa.Signature
msg frontend.Variable
}
cur, _ := te.NewEdCurve(api, t.BN254)
eddsa.Verify(cur, c.sig, c.msg, c.pub, &fMimc)
```
#colbreak()
=== Merkle Proof
```go
import "github.com/consensys/gnark/std/accumulator/merkle"
type Circuit struct {
M merkle.MerkleProof
Leaf frontend.Variable
}
c.M.VerifyProof(api, &hFunc, c.Leaf)
```
== Selector
```go
import "github.com/consensys/gnark/std/selector"
```
=== Slice
```go
// out[i] = i ∈ [s, e) ? in[i] : 0
Slice(s, e Var, in []Var) []Var
// out[i] = rs ? (i ≥ p ? in[i] : 0)
// : (i < p ? in[i] : 0)
Partition(p Var, rs bool, in []Var) []Var
// out[i] = i < sp ? sv : ev
stepMask(outlen int, sp, sv, ev Var) []Var
```
=== Mux
```go
// out = in[b[0]+b[1]*2+b[2]*4+...]
BinaryMux(selBits, in []Var) Var
// out = vs[i] if ks[i] == qkey
Map(qkey Var, ks, vs []Var) Var
// out = in[sel]
Mux(sel Var, in ...Var) Var
// out[i] = ks[i] == k ? 1 : 0
KeyDecoder(k Var, ks []Var) []Var
// out[i] = i == s ? 1 : 0
Decoder(n int, sel Var) []Var
// out = a1*b1 + a2*b2 + ...
dotProduct(a, b []Var) Var
```
== Concepts
=== Glossary
`cs`: constraint system,
`w`: (full) witness,
`pubw`: public witness,
`pk`: proving key,
`vk`: verifying key,
`r1cs`: rank-1 constraint system,
`srs`: structured reference string.
=== Schemas
#text(
size: 8pt,
[
$
"Groth16: "
cal(L) arrow(x) dot cal(R) arrow(x) = cal(O) arrow(x)
$
$
"PlonK: "
q_l_i a_i + q_r_i b_i + q_o_i c_i + q_m_i a_i b_i + q_c_i = 0
$
$
"SAP(Polymath): "
x dot y = (x\/2 + y\/2)^2 -(x\/2 - y \/2)^2
$
]
)
#let m1=math.op($bold(m_1)$)
#let m2=math.op($bold(m_2)$)
#text(
size: 6pt,
[
#table(
columns: (auto, auto, auto, auto),
inset: 3pt,
align: horizon,
stroke: 0.5pt + rgb("#bbb"),
table.header(
[*Schema*],
[*CRS/SRS*],
[*Proof Size*],
[*Verifier Work*],
),
[Groth16],
$(3n+m) GG_1$,
$2 GG_1 + 1 GG_2$,
$3P + ell m1$,
[PlonK],
$(n+a) GG_1+GG_2$,
$9GG_1+7FF$,
$2P+18 m1$,
[Polymath],
$(tilde(m) + 12 tilde(n)) GG_1$,
$3 GG_1+1FF$,
$2P + 2 m1 + m2 + tilde(ell) FF$,
)
\*$m=$wire num, $n=$multiplication gates,
$tilde(m) approx 2m$, $tilde(n) approx 2n$,
$bold(m_L) = GG_L exp$.
$a=$addition gates, $P=$pairing, $ell=$pub inputs num, $tilde(ell) = O(ell log ell)$ PlonK is universal setup
]
)
// REF: Gabizon, Ariel, <NAME>, and <NAME>. “PLONK: Permutations over Lagrange-Bases for Oecumenical Noninteractive Arguments of Knowledge,” 2019. https://eprint.iacr.org/2019/953.
=== Resources
- https://docs.gnark.consensys.io/
- https://play.gnark.io/
- https://zkshanghai.xyz/
#colbreak()
== Serialization
#codly(stroke: out_circuit_color)
// === Serialization
// ```go
// cur := ecc.BN254
// // CS Serialize
// var buf bytes.Buffer
// cs.WriteTo(&buf)
// // CS Deserialize
// cs := groth16.NewCS(cur)
// cs.ReadFrom(&buf)
// // Witness Serialize
// w, _ := frontend.NewWitness(&val, cur)
// data, _ := w.MarshalBinary()
// json, _ := w.MarshalJSON()
// // Witness Deserialize
// w, _ := witness.New(cur)
// err := w.UnmarshalBinary(data)
// w, _ := witness.New(cur, ccs.GetSchema())
// err := w.UnmarshalJSON(json)
// pubw, _ := witness.Public()
// ```
=== CS Serialize
```go
var buf bytes.Buffer
cs.WriteTo(&buf)
```
=== CS Deserialize
```go
cs := groth16.NewCS(ecc.BN254)
cs.ReadFrom(&buf)
```
=== Witness Serialize
```go
w, _ := frontend.NewWitness(&assignment, ecc.BN254)
data, _ := w.MarshalBinary()
json, _ := w.MarshalJSON()
```
=== Witness Deserialize
```go
w, _ := witness.New(ecc.BN254)
err := w.UnmarshalBinary(data)
w, _ := witness.New(ecc.BN254, ccs.GetSchema())
err := w.UnmarshalJSON(json)
pubw, _ := witness.Public()
```
== Smart Contract
=== Export Solidity
```go
f, _ := os.Create("verifier.sol")
err = vk.ExportSolidity(f)
```
=== Export Plonk Proof
```go
_p, _ := proof.(interface{MarshalSolidity() []byte})
str := "0x" + hex.EncodeToString(
_p.MarshalSolidity())
```
=== Export Groth16 Proof
```go
buf := bytes.Buffer{}
_, err := proof.WriteRawTo(&buf)
b := buf.Bytes()
var p [8]string
for i := 0; i < 8; i++ {
p[i] = new(big.Int).SetBytes(
b[32*i : 32*(i+1)]).String()
}
str := "["+strings.Join(p[:],",")+"]"
```
== Standard Library
=== MiMC Hash
```go
import "github.com/consensys/gnark-crypto/ecc/bn254/fr/mimc"
fMimc := mimc.NewMiMC()
fMimc.Write(buf)
h := fMimc.Sum(nil)
```
=== EdDSA Signature
```go
import "math/rand"
import t "github.com/consensys/gnark-crypto/ecc/twistededwards"
import "github.com/consensys/gnark-crypto/hash"
curve := t.BN254
ht := hash.MIMC_BN254
seed := time.Now().Unix()
rnd := rand.New(rand.NewSource(seed))
s, _ := eddsa.New(curve, rnd)
sig, _ := s.Sign(msg, ht.New())
pk := s.Public()
v, _ := s.Verify(sig, msg, ht.New())
c.PublicKey.Assign(curve, pk.Bytes())
c.Signature.Assign(curve, sig)
```
=== Merkle Proof
```go
import mt "github.com/consensys/gnark-crypto/accumulator/merkletree"
depth := 5
num := uint64(2 << (depth - 1))
seg := 32
mod := ecc.BN254.ScalarField()
// Create tree by random data
mlen := len(mod.Bytes())
var buf bytes.Buffer
for i := 0; i < int(num); i++ {
leaf, _:= rand.Int(rand.Reader, mod)
b := leaf.Bytes()
buf.Write(make([]byte, mlen-len(b)))
buf.Write(b)
}
// build merkle tree proof and verify
hGo := hash.MIMC_BN254.New()
idx := uint64(1)
root, path, _, _ := mt.BuildReaderProof(&buf, hGo, seg, idx)
verified := mt.VerifyProof(hGo, root, path, idx, num)
c.Leaf = idx
c.M.RootHash = root
c.M.Path = make([]Var, depth+1)
for i := 0; i < depth+1; i++ {
c.M.Path[i] = path[i]
}
```
// == Unit test
// ```go
// assert := groth16.NewAssert(t)
// var c Circuit
// assert.ProverFailed(&c, &Circuit{
// Hash: 42,
// PreImage: 42,
// })
// assert.ProverSucceeded(&c, &Circuit{
// Hash: "1613...8469",
// PreImage: 35,
// })
// ```
// == Hints
// ```go
// var b []frontend.Variable
// var Σbi frontend.Variable
// base := 1
// for i := 0; i < nBits; i++ {
// b[i] = cs.NewHint(hint.IthBit, a, i)
// cs.AssertIsBoolean(b[i])
// Σbi = api.Add(Σbi, api.Mul(b[i], base))
// base = base << 1
// }
// cs.AssertIsEqual(Σbi, a)
// ```
// TODO: how to convert byte[] to number to equal to number in-circuit print by api.Println
// TODO: selctor under github.com/consensys/gnark/std/selector |
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/2%20-%20RTB/Documentazione%20esterna/Verbali/23-12-06/23-12-06.typ | typst | #import "/template.typ": *
#show: project.with(
date: "06/12/23",
subTitle: "Colloquio tecnico su tecnologie e PoC",
docType: "verbale",
externalParticipants : (
(name: "<NAME>", role: "Referente aziendale"),
),
authors: (
"<NAME>",
),
reviewers: (
"<NAME>",
),
timeStart: "16:00",
timeEnd: "16:40",
location: "Zoom",
);
= Ordine del giorno
- Discussione sulle tecnologie implementate e da implementare;
- Dimostrazioni tecniche tramite screen sharing dei PoC realizzati;
- Chiarimenti tecnici sull'implementazione dei PoC;
- Discussione di un eventuale prossimo meeting.
== Tecnologie implementate
Sono state presentate al Proponente le tecnologie attualmente implementate e sono stati dati riferimenti per quanto riguarda le tecnologie ancora da implementare:
- implementate: Three.js, Express.js, MySQL;
- da implementare: Docker, Next.js.
== Dimostrazioni tecnologiche
Sono stati presentati al Proponente due PoC, denominati A e B.
=== PoC A
- Funzionalità implementate:
- creazione degli scaffali, con dimensioni regolabili;
- spostamento degli scaffali, con grid-snapping (basato su una scacchiera con passo regolabile);
- eliminazione degli scaffali;
- gestione delle collisioni tra scaffali;
- UI nativa Three.js con possibilità di definire le dimensioni e il passo della "scacchiera" di snapping.
- Valutazione:
- apprezzata la possibilità di effettuare _zoom in_ e _zoom out_ e di ruotare la vista sull'asse verticale;
- il movimento della camera sui tre assi è ritenuto opzionale.
=== PoC B
- Funzionalità implementate:
- creazione del piano dell'area di lavoro di un magazzino tramite file SVG;
- possibilità di creazione manuale specificando le dimensioni del magazzino;
- integrazione con database tramite Express.js come _middleware_.
- Valutazione:
- una variazione proposta dal referente aziendale è quella di mantenere l'area del magazzino come implementata nel PoC A, e adattare il caricamento del file SVG alle dimensioni di default.
== Chiarimenti tecnici sull'implementazione dei PoC
A seguito del confronto con il Proponente, il gruppo è giunto alle seguenti conclusioni:
- si ritiene necessario trovare un compromesso tra precaricare l'intero database nel programma all'interno di una struttura dati e mantenere una continua comunicazione tra applicazione e database;
- la definizione delle altezze dopo il caricamento del file SVG può essere implementata (desiderabile) tramite trascinamento verso l'alto;
- si ritiene opzionale implementare la rotazione degli scaffali con angoli diversi da 90°.
== Pianificazione del prossimo meeting
Con l'avvicinarsi delle vacanze di Natale e della conseguente pausa delle attività dell'azienda, il Proponente ha dato disponibilità per un ultimo incontro sincrono prima della fine del 2023. Il gruppo, valutati i progressi, confermerà il meeting quanto prima.
Il Proponente ha comunque dato la propria disponibilità ad interloquire con il gruppo tramite e-mail anche durante la pausa natalizia. |
|
https://github.com/raygo0312/Typst_template | https://raw.githubusercontent.com/raygo0312/Typst_template/main/template-common.typ | typst | #import "@preview/physica:0.9.3": *
// font setting
#let font-serif = (
"CMU Serif",
"<NAME>",
)
#let font-sans = (
"CMU Sans Serif",
"<NAME>",
)
// color setting
#let theme-color = (
title: state("title", rgb("#66a5ad")),
ex: state("ex", rgb("#e3e2b4")),
axm: state("axm", rgb("#f4acb7")),
def: state("def", rgb("#bfc8d7")),
thm: state("thm", rgb("#a2b59f")),
other: state("other", rgb("#f9f8c4")),
)
#let preset-color = (
pastel: (
title: rgb("#fbd8b5"),
ex: rgb("#f9f8c4"),
axm: rgb("#f8ced3"),
def: rgb("#d2d5ec"),
thm: rgb("#daecd4"),
),
dark: (
title: rgb("#483b6d"),
ex: rgb("#53531f"),
axm: rgb("#612828"),
def: rgb("#2b4263"),
thm: rgb("#2b5e24"),
),
)
#let change-color(
theme: "",
name: "title",
color: rgb("#AADDFF"),
) = {
if preset-color.keys().contains(theme) {
for (key, value) in preset-color.at(theme) {
change-color(name: key, color: value)
}
return
}
theme-color.at(name).update(x => {
color
})
}
// 数式コマンド
#let cal(a) = text(font: "KaTeX_Caligraphic")[#a]
#let scr(a) = text(font: "KaTeX_Script")[#a]
// common style setting
#let common-style(it) = {
// 設定日本語
set text(lang: "ja")
// リンクに下線を引く
show link: underline
// インデント設定
set list(indent: 1.5em)
set enum(indent: 1.5em)
// 表のキャプションを上に
show figure.where(kind: table): set figure.caption(position: top)
// 数式外の丸括弧の外側に隙間を開ける処理
let cjk = "(\p{Hiragana}|\p{Katakana}|\p{Han})"
show regex("(" + cjk + "[(])|([)]" + cjk + ")"): it => {
let a = it.text.match(regex("(.)(.)"))
a.captures.at(0)
h(0.25em)
a.captures.at(1)
}
// block数式の中のfracをdisplayに変更
show math.equation.where(block: true): it => {
show math.frac: math.display
it
}
// 数式とcjk文字の間に隙間を開ける処理
show math.equation: it => {
// size0にするとpreviewででかく表示されるバグがある
hide[#text(size: 0.00000000000001pt)[\$]]
it
hide[#text(size: 0.00000000000001pt)[\$]]
}
it
} |
|
https://github.com/i-am-wololo/cours | https://raw.githubusercontent.com/i-am-wololo/cours/master/TP/i21/1/main.typ | typst | #import "./templates.typ": *
#show: project.with(title: "TP1 i21")
= Echecs
L'exercice consiste a trouver les positions possibles dans une grille, on attend de l'eleve a retranscrire les regles de deplacement en indices sur une matrice qui fait office d'abstraction pour un plateau d'echecs. Personellement pour les pieces fou, tour et reine j'ai utilise une boilerplate que je modifie selon mes besoins.
Exemple pour le fou:
#py("
moves = []
directions = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
for dx, dy in directions:
i, j = x + dx, y + dy
while 0 <= i < 8 and 0 <= j < 8:
moves.append((i, j))
i += dx
j += dy
return moves
" )
j'ai une liste contenant les soustractions/addition necessaire pour obtenir la case. Puisque ces pieces n'ont pas de limitations (on peut se deplacer en E4 comme en F3), on itere jusqu'a ce qu'on atteint les bords du plateau, c'est a dire quand on est a l'indice 0 ou 8 sur au moins un des deux axes
Pareille pour tour et reine:
#py("
def cases_tour(x, y):
moves = []
directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]
for dx, dy in directions:
i, j = x + dx, y + dy
while 0 <= i < 8 and 0 <= j < 8:
moves.append((i, j))
i += dx
j += dy
return moves
")
#py("
def cases_reine(x, y):
moves = []
directions = [(0, 1), (1, 0), (-1, 0), (0, -1), (1,1), (-1,-1), (1,-1), (-1, 1)]
for dx, dy in directions:
i, j = x + dx, y + dy
while 0 <= i < 8 and 0 <= j < 8:
moves.append((i, j))
i += dx
j += dy
return moves
")
Pour les pieces comme le roi et le cavalier, j'ai juste enleve la boucle while, pour que les deplacements se font qu'une fois:
#py("
def cases_roi(col,lig):
moves = []
directions = [(0, 1), (1, 0), (-1, 0), (0, -1), (1,1), (-1,-1), (1,-1), (-1, 1)]
for x, y in directions:
if 0<x+col< 8 and 0<lig+y<8:
moves.append((x+lig, y+col))
return moves
")
#py("
def cases_cavalier(lig, col):
moves = []
directions = [(1,2), (1, -2), (2,1), (2, -1), (-2, 1), (-2, -1), (-1, 2), (-1, -2)]
for x, y in directions:
if 0<=x+col< 8 and 0<=lig+y<8:
moves.append((y+lig, x+col))
return moves
")
pour le pion, j'ai simplement verifie les coordonnes, et soustrait -2 sur y si il est encore place correctement, sinon soustrait seulement par -1
#py("
def cases_pion(col,lig):
if lig == 6:
return [(col, lig-1), (col, lig-2)]
return [(col, lig-1)]
")
= Parcours
les 2 premiers parcours sont realisable facilement, jvais juste mettre le code pour les effectuer
#py("def parcours_ligne(n):
i = 0
result = []
while i<n:
j=0
while j<n:
result.append((j,i))
j+=1
i+=1
print(result, n)
return result
def parcours_colonne(n):
i = 0
result = []
while i<n:
j=0
while j<n:
result.append((i, j))
j+=1
i+=1
return result
")
on itere juste par colonne ou par ligne
Pour sinusoide et zigzag, tant que la ligne/colonne a pas ete parcouru, on itere dans la colonne/ligne, a la fin de la boucle interieur, on soustrait pour avoir une boucle qui parcours a l'envers. Les 2 fonctions sont similaire, il suffit seulement de changer les variables
#py("
def parcours_sinusoidal(n):
result = []
i = 0
j = 0
direct = 1
while j<=n:
while 0<=i<n and 0<=j<n:
result.append((j,i))
i+=direct
direct = -direct
i+=direct
j+=1
print(result)
return result
def parcours_zigzag(n):
result = []
i = 0
j = 0
direct = 1
while j<=n:
while 0<=i<n and 0<=j<n:
result.append((i,j))
i+=direct
print(result)
direct = -direct
i+=direct
print()
j+=1
print(result)
return result
")
#py("def parcours_serpentin(n):
result = []
i = 0
j = 0
inc = 0
mini = 0
while inc<n**2:
while i<n-1:
print(i,j)
result.append((i,j))
inc+=1
i+=1
print('premiere')
while j<n-1:
result.append((i,j))
print(i,j)
inc+=1
j+=1
print('2ieme')
while i>mini:
result.append((i,j))
print(i,j)
inc+=1
i-=1
print('3em')
mini+=1
while j>mini:
result.append((i,j))
print(i,j)
j-=1
inc+=1
print('fin')
n-=1
return result")
= Puissance 4
|
|
https://github.com/EunTilofy/NumComputationalMethods | https://raw.githubusercontent.com/EunTilofy/NumComputationalMethods/main/Chapter9/Chapter9-1.typ | typst | #import "../template.typ": *
#show: project.with(
course: "Computing Method",
title: "Computing Method - Chapter9-1",
date: "2024.5.14",
authors: "<NAME>, 3210106357",
has_cover: false
)
*Problems:Chapter9-1,2,Chapter8-10*
#HWProb(name: "1")[
用幂法计算矩阵$
A = bmatrix(4,2,2;2,5,1;2,1,6)
$
的最大特征值和相应的特征向量。
]
#solution[
```python
import numpy as np
def solve(A, x, eps, N):
k = 1
mu = 0
y = np.zeros(np.shape(x))
while (1):
l = x[0]
for y in x:
if abs(y) > abs(l):
l = y
y = x / l
x = A @ y
print("k =", k, "y_k =", y, "x_(k+1) =", x)
if abs(l - mu) < eps:
break
else :
k = k + 1
mu = l
if k == N:
print ("Time Limit Exceeded!")
break
return [l, y]
A = np.array([[4,2,2],[2,5,1],[2,1,6]])
x = np.array([1,1,1])
print(solve(A, x, 5e-5, 100))
```
求解过程如下:
```
k = 1 y_k = [1. 1. 1.] x_(k+1) = [8. 8. 9.]
k = 2 y_k = [0.88888889 0.88888889 1. ] x_(k+1) = [7.33333333 7.22222222 8.66666667]
k = 3 y_k = [0.84615385 0.83333333 1. ] x_(k+1) = [7.05128205 6.85897436 8.52564103]
k = 4 y_k = [0.82706767 0.80451128 1. ] x_(k+1) = [6.91729323 6.67669173 8.45864662]
k = 5 y_k = [0.81777778 0.78933333 1. ] x_(k+1) = [6.84977778 6.58222222 8.42488889]
k = 6 y_k = [0.81304073 0.78128297 1. ] x_(k+1) = [6.81472885 6.53249631 8.40736442]
k = 7 y_k = [0.81056661 0.77699693 1. ] x_(k+1) = [6.79626027 6.50611784 8.39813014]
k = 8 y_k = [0.80925875 0.77471029 1. ] x_(k+1) = [6.78645557 6.49206895 8.39322779]
k = 9 y_k = [0.80856325 0.77348895 1. ] x_(k+1) = [6.78123092 6.48457126 8.39061546]
k = 10 y_k = [0.80819231 0.77283619 1. ] x_(k+1) = [6.77844163 6.48056556 8.38922081]
k = 11 y_k = [0.80799418 0.77248718 1. ] x_(k+1) = [6.7769511 6.47842429 8.38847555]
k = 12 y_k = [0.80788828 0.77230055 1. ] x_(k+1) = [6.77615423 6.47727932 8.38807712]
k = 13 y_k = [0.80783166 0.77220074 1. ] x_(k+1) = [6.7757281 6.47666699 8.38786405]
k = 14 y_k = [0.80780137 0.77214735 1. ] x_(k+1) = [6.77550019 6.47633949 8.3877501 ]
k = 15 y_k = [0.80778518 0.77211879 1. ] x_(k+1) = [6.77537829 6.47616433 8.38768915]
k = 16 y_k = [0.80777651 0.77210352 1. ] x_(k+1) = [6.7753131 6.47607063 8.38765655]
k = 17 y_k = [0.80777188 0.77209535 1. ] x_(k+1) = [6.77527822 6.47602052 8.38763911]
[8.38765654798032, array([0.80777188, 0.77209535, 1. ])]
```
所以 $lambda = 8.3876565, vm = [0.80777188, 0.77209535, 1. ]^T$。
]
#HWProb(name: "2")[
求下面三对角矩阵$
A = bmatrix(0,5,0,0,0,0;1,0,4,0,0,0;0,1,0,3,0,0;0,0,1,0,2,0;0,0,0,1,0,1;0,0,0,0,1,0)
$
的特征值。
]
#solution[
```python
A = np.array([[1,5,0,0,0,0],[1,1,4,0,0,0],[0,1,1,3,0,0],[0,0,1,1,2,0],[0,0,0,1,1,1],[0,0,0,0,1,1]])
def QR(A):
for i in range(1000):
Q, R = np.linalg.qr(A)
A = R @ Q
eigenvalues = np.diag(A)
return eigenvalues
print(QR(A) - np.array([1,1,1,1,1,1]))
```
使用 QR 法计算 $A + I$ 的特征值,然后分别减去 1.
最后计算结果为: [3.32425743 1.88917588 -3.32425743 0.61670659 -1.88917588 -0.61670659]
]
#HWProb(name: "10")[
设 $lambda$ 是 $n$ 阶矩阵 $A$ 的一个特征值,试证存在 $k$,$
abs(lambda - a_(k k)) leq sum_(j eq.not k) abs(a_(k j)) equiv R_k
$
从而所有特征值在下面 Gerschgoring 圆盘的并集中$
G_k = {lambda: abs(lambda - a_(k k)) leq R_k quad k = 1, 2, dots.c, n} quad k = 1, 2, dots.c, n
$
]
#Proof[
对于 $A$ 的任意特征值 $lambda$,设 $xm$ 为其对应的特征向量。那么 $A xm = lambda xm arrow.double sum_(j=1)^n a_(i j) x_j = lambda x_i(forall i = 1,2,dots,n)$。
令 $k = arg max_k abs(x_k)$,那么有
$
sum_(j=1)^k a_(k j) x_j = lambda x_k
arrow.double x_k (lambda - a_(k k)) = sum_(j eq.not k) a_(k j) x_j \
arrow.double abs(x_k)abs(lambda-a_(k k)) = abs(sum_(j eq.not k) a_(k j)x_j) leq sum_(j eq.not k) abs(a_(k j)) abs(x_j) leq abs(x_k) sum_(j eq.not k) abs(a_(k j)) \
arrow.double abs(lambda - a_(k k)) leq sum_(j eq.not k) abs(a_(k j)) = R_k
$
] |
|
https://github.com/DaAlbrecht/thesis-TEKO | https://raw.githubusercontent.com/DaAlbrecht/thesis-TEKO/main/content/Evaluation.typ | typst | #import "@preview/tablex:0.0.5": tablex, cellx
#import "@preview/codelst:1.0.0": sourcecode
== API Library
The microservice needs to interact with RabbitMQ and read from the broker.
These interaction happen over the AMQP protocol. To not reinvent the wheel,
off-the-shelf library of the AMQP protocol should be used.
#linebreak()
There are two different types of client libraries:
- An AMQP 0.9.1 client library that can specify optional queue and consumer arguments#footnote([https://www.rabbitmq.com/streams.html#usage])
- RabbitMQ streams client libraries that support the new protocol#footnote([https://www.rabbitmq.com/devtools.html])
Since the streaming protocol is still subject to change, and the microservice is
not acting as a high throughput consumer or publisher, the extra speed, gained
with the streaming protocol, is not needed. Additionally, after a first look at
the documentation and examples provided for the streaming protocol, it appeared
to be not as actively used compared to the AMQP 0.9.1 client libraries, leading
to encounters with broken code snippets and API changes.
As a result, the RabbitMQ stream client libraries are excluded from
consideration and instead focused on evaluating the AMQP 0.9.1 client
libraries, which offer support for optional queue and consumer arguments.
To evaluate the AMQP 0.9.1 client libraries, a simple publisher and
consumer application, which publishes a message to a queue and then consumes it is created.
This simple demo application was then used to evaluate the client libraries.
*Setup*
For this application, a RabbitMQ server, deployed as a docker container is used. RabbitMQ
can be deployed with the following command:
#figure(
sourcecode(numbering: none)[```bash
docker run -it --rm --name rabbitmq -p 5552:5552 -p 5672:5672 -p 15672:15672 rabbitmq:3.12-management
```],
caption: "RabbitMQ as docker container",
)<api-lib-setup>
The RabbitMQ management interface can be accessed at #link("http://localhost:15672/") with
the following credentials:
- username: guest
- password: <PASSWORD>
#pagebreak()
=== Rust - lapin
Rust is my most familiar language. I have used it for many different projects.
There are several different client libraries available for Rust, but I decided
to use lapin, because it is the most popular and well-maintained client library.
==== Installation
lapin is available on crates.io, the Rust package registry. It can be installed with the following command:
#figure(
sourcecode(numbering: none)[```bash
cargo add lapin
```],
caption: "lapin installation",
)
Additionally, lapin requires an asynchronous runtime. I decided to use tokio,
because it is the most popular asynchronous runtime for Rust.
#figure(
sourcecode(numbering: none)[```bash
cargo add tokio --features full
```],
caption: "tokio installation",
)
==== API usage
First, the clients need to establish a connection to the RabbitMQ server.
The server is running on localhost and the default port is 5672. The credentials
are the default credentials for RabbitMQ.
With the following code snippets, a connection to the RabbitMQ server is established.
#figure(
sourcecode()[```rs
#[tokio::main]
async fn main() -> Result<()> {
let channel = create_rmq_connection(
"amqp://guest:guest@localhost:5672".to_string(),
"connection_name".to_string(),
)
.await;
Ok(())
}
```
],
caption: "lapin connection main",
)
The process of establishing a connection is a bit more complicated compared to other languages due to the asynchronous nature of Rust.
To make the code more idiomatic, the connection is established in a separate function.
#figure(
sourcecode()[```rs
pub async fn create_rmq_connection(connection_string: String, connection_name: String) -> Channel {
let start_time = Instant::now();
let options = ConnectionProperties::default()
.with_connection_name(connection_name.into())
.with_executor(tokio_executor_trait::Tokio::current())
.with_reactor(tokio_reactor_trait::Tokio);
loop {
let connection = Connection::connect(connection_string.as_ref(), options.clone())
.await
.unwrap();
if let Ok(channel) = connection.create_channel().await {
return channel;
}
assert!(
start_time.elapsed() < std::time::Duration::from_secs(2 * 60),
"Failed to connect to RabbitMQ"
);
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
```],
caption: "lapin connection",
)
Rust does not have a built-in asynchronous runtime. Instead, it relies on
external asynchronous runtimes. lapin supports several different asynchronous
runtimes. This makes it a bit more complicated to establish a connection compared
to other languages, where the asynchronous runtime is built into the language.
#figure(
sourcecode()[```rs
let options = ConnectionProperties::default()
.with_connection_name(connection_name.into())
.with_executor(tokio_executor_trait::Tokio::current())
.with_reactor(tokio_reactor_trait::Tokio);
```],
caption: "lapin connection options",
)
After setting up the connection options, a connection is tried to be established.
If the connection is successful, a channel is created and returned.
If the connection is not established within 2 minutes, the program exits.
#figure(
sourcecode()[```rs
loop {
let connection = Connection::connect(connection_string.as_ref(), options.clone())
.await
.unwrap();
if let Ok(channel) = connection.create_channel().await {
return channel;
}
assert!(
start_time.elapsed() < std::time::Duration::from_secs(2 * 60),
"Failed to connect to RabbitMQ"
);
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
```],
caption: "lapin connection loop",
)
After the connection is established, an exchange is created.
#figure(
sourcecode()[```rs
channel
.exchange_declare(
"baz_exchange",
ExchangeKind::Direct,
declare_options,
FieldTable::default(),
)
.await?;
```],
caption: "lapin exchange declaration",
)
After the exchange is created, a queue is created.
#figure(
sourcecode()[```rs
channel
.queue_declare(
"foo_queue",
QueueDeclareOptions {
durable: true,
auto_delete: false,
..Default::default()
},
stream_declare_args(),
)
.await
.context("Failed to create stream")?;
```],
caption: "lapin queue declaration",
)
The `queue_declare` function takes additional arguments with the type
`FieldTable`#footnote(
[https://docs.rs/amq-protocol-types/7.1.2/amq_protocol_types/struct.FieldTable.html],
).
These additional arguments are used to specify the optional queue and consumer
arguments needed for RabbitMQ streams.
#figure(
sourcecode()[```rs
pub fn stream_declare_args() -> FieldTable {
let mut queue_args = FieldTable::default();
queue_args.insert(
ShortString::from("x-queue-type"),
AMQPValue::LongString("stream".into()),
);
queue_args.insert(
ShortString::from("x-max-length-bytes"),
AMQPValue::LongLongInt(600000000),
);
queue_args.insert(
ShortString::from("x-stream-max-segment-size-bytes"),
AMQPValue::LongLongInt(500000000),
);
queue_args
}
```],
caption: "lapin queue arguments",
)
Mainly the `x-queue-type` argument is used to specify the queue as a stream
queue. The `x-max-length-bytes` argument is used to specify the maximum size of
the queue in bytes. The `x-stream-max-segment-size-bytes` argument is used to
specify the maximum size of a segment in bytes.
After the queue is created, a new thread is spawned, which is used to consume messages from the queue.
#figure(
sourcecode()[```rs
tokio::spawn(async move {
let channel_b = create_rmq_connection(
"amqp://guest:guest@localhost:5672".to_string(),
"connection_name".to_string(),
)
.await;
channel_b
.basic_qos(1000u16, BasicQosOptions { global: false })
.await
.unwrap();
let mut consumer = channel_b
.basic_consume(
"foo_queue",
"foo_consumer",
BasicConsumeOptions::default(),
stream_consume_args(),
)
.await
.unwrap();
while let Some(delivery) = consumer.next().await {
println!("Received message");
let delivery_tag = delivery.expect("error in consumer").delivery_tag;
channel_b
.basic_ack(delivery_tag, BasicAckOptions::default())
.await
.expect("ack");
}
});
```],
caption: "lapin consume messages",
)
the `basic_consume` function also takes additional arguments with the type `FieldTable`#footnote(
[https://docs.rs/amq-protocol-types/7.1.2/amq_protocol_types/struct.FieldTable.html],
).
These arguments are created with the `stream_consume_args` function.
#figure(
sourcecode()[```rs
pub fn stream_consume_args() -> FieldTable {
let mut queue_args = FieldTable::default();
queue_args.insert(
ShortString::from("x-stream-offset"),
AMQPValue::LongString("first".into()),
);
queue_args
}
```],
caption: "lapin consume arguments",
)
The `x-stream-offset` argument is used to specify the offset from which the consumer should start consuming messages@x-stream-offset.
The main thread concurrently publishes a message to the queue, the consumer thread is consuming messages from.
#figure(
sourcecode()[```rs
loop {
println!("Publishing message");
channel
.basic_publish(
"baz_exchange",
"baz_exchange",
BasicPublishOptions::default(),
b"Hello world!",
AMQPProperties::default(),
)
.await?;
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
```],
caption: "lapin publish message",
)
This publishes a message to the exchange `baz_exchange` with the routing key `baz_exchange`. The payload of the message is `Hello world!`.
=== Java - rabbitmq-java-client
==== Installation
The rabbitmq-java-client is available on maven central. It can be installed by adding the following dependency to the pom.xml file.
#figure(
sourcecode(numbering: none)[```xml
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.18.0</version>
</dependency>
```],
caption: "rabbitmq-java-client installation",
)
==== API usage
Similar to lapin, first a connection to the RabbitMQ server is established.
#figure(
sourcecode()[```java
ConnectionFactory factory = new ConnectionFactory();
factory.setUri("amqp://guest:[email protected]:5672");
Connection conn = factory.newConnection();
System.out.println("Connection established");
```
],
caption: "rabbitmq-java-client connection",
)
After the connection is established, a new thread is spawned, which is used to
consume messages from the queue. This thread gets its own channel.
#figure(sourcecode()[```java
new Thread(() -> {
try {
Channel channel = conn.createChannel();
channel.exchangeDeclare(exchangeName, "direct", true);
System.out.println("Exchange declared");
channel.queueDeclare(
"java-stream",
true, // durable
false, false, // not exclusive, not auto-delete
Collections.singletonMap("x-queue-type", "stream"));
channel.queueBind("java-stream", exchangeName, exchangeName);
channel.basicQos(100); // QoS must be specified
channel.basicConsume(
"java-stream",
false,
Collections.singletonMap("x-stream-offset", "first"), // "first" offset specification
(consumerTag, message) -> {
System.out.println("Received message: " + new String(message.getBody(), "UTF-8"));
channel.basicAck(message.getEnvelope().getDeliveryTag(), false); // ack is required
},
consumerTag -> {
});
} catch (IOException e) {
e.printStackTrace();
}
}).start();
```], caption: "rabbitmq-java-client consume messages")
In the same way as with lapin, the queue is declared as a stream queue with the
`x-queue-type` argument. The only difference between the two clients is that
lapin returns an iterator over the messages, while rabbitmq-java-client uses a
callback function to consume messages. Otherwise, the two clients are very
similar.
#linebreak()
In the main thread, a new channel is created, which is used to publish messages to the queue.
#figure(
sourcecode()[```java
while (true) {
byte[] messageBodyBytes = "Hello, world!".getBytes();
channel_b.basicPublish(exchangeName, exchangeName, null, messageBodyBytes);
System.out.println("Sent message: " + new String(messageBodyBytes, "UTF-8"));
}
```],
caption: "rabbitmq-java-client publish message",
)
The publishing of messages is also very similar to lapin.
=== Go - amqp091-go
==== Installation
The amqp091-go client library is available on GitHub. It can be installed with the following command:
#figure(
sourcecode(numbering: none)[```bash
go get https://github.com/rabbitmq/amqp091-go```],
caption: "amqp091-go installation",
)
The library changed its name from `streadway/amqp` to `rabbitmq/amqp091-go`. To reduce friction with the api documentation and examples, an alias is advised.
#figure(
sourcecode(numbering: none)[```go
amqp "github.com/rabbitmq/amqp091-go"```],
caption: "amqp091-go alias",
)
==== API usage
Similar to the other clients, first a connection to the RabbitMQ server is established.
#figure(
sourcecode()[```go
connectionString := "amqp://guest:guest@localhost:5672/"
connection, _ := amqp.Dial(connectionString)
```],
caption: "amqp091-go connection",
)
After the connection is established, a channel is created and used to declare an exchange as well as a queue.
#figure(
sourcecode()[```go
channel, _ := connection.Channel()
channel.ExchangeDeclare("golang-exchange", "direct", true, false, false, false, nil)
Queueargs := make(amqp.Table)
Queueargs["x-queue-type"] = "stream"
channel.QueueDeclare("golang-queue", true, false, false, false, Queueargs)
channel.QueueBind("golang-queue", "golang-exchange", "golang-exchange", false, nil)
```],
caption: "amqp091-go exchange and queue declaration",
)
After the queue is declared, a new thread is spawned, which is used to consume messages from the queue.
#figure(
sourcecode()[```go
args := make(amqp.Table)
args["x-stream-offset"] = "first"
channel.Qos(100, 0, false)
go func() {
stream, err := channel.Consume("golang-queue", "", false, false, false, false, args)
if err != nil {
panic(err)
}
for message := range stream {
println(string(message.Body))
}
}()
```],
caption: "amqp091-go consume messages",
)
On the main thread, a new channel is created, which is used to publish messages to the queue.
#figure(
sourcecode()[```go
channel_b, _ := connection.Channel()
for {
channel_b.Publish("golang-exchange", "golang-exchange", false, false, amqp.Publishing{
Body: []byte("Hello World"),
})
time.Sleep(100 * time.Millisecond)
println("Message sent")
}
```],
caption: "amqp091-go publish messages",
)
Overall, the experience with amqp091-go was very similar to the other libraries.
#pagebreak()
=== Evaluation matrix
The previously tested libraries for the languages Rust, Java, and Go are evaluated
in the following table. The criteria are weighted with a value from 1 to 5, where
5 is the best and 1 is the worst. The total score is calculated by multiplying the
weight with the score for each criterion. The total score is then used to compare
the libraries.
#figure(
tablex(
columns: (3fr, 2fr, 3fr, 1fr,1fr,1fr),
rows: (auto),
align: (left + horizon , center + horizon, left + horizon, center + horizon, center + horizon, center + horizon),
[*Criteria*],
[*Weight(1-5)*],
[*Description*],
[*Rust*],
[*Java*],
[*Go*],
[Installation],
[2],
[Easy and documented installation process],
[5],
[2],
[2],
[API Clarity and Consistency],
[5],
[Clear, consistent, and intuitive API design],
[4],
[5],
[4],
[Documentation],
[5],
[Clear, complete and maintained documentation],
[4],
[4],
[3],
[Community],
[4],
[Active and helpful community],
[4],
[4],
[4],
[language familiarity],
[5],
[How familiar I am with the language],
[5],
[2],
[2],
[Platform Compatibility],
[4],
[Support for Unix based systems],
[4],
[5],
[5],
[Performance],
[3],
[Message throughput],
[5],
[5],
[5],
[Error Handling],
[3],
[Clear and consistent error handling],
[5],
[3],
[4],
[Licensing Terms],
[5],
[Open-source license],
[5],
[5],
[5],
[*Total*],
[*180*],
[],
[*162*],
[*140*],
[*130*]
)
)
The installation process for all three libraries was well documented. With Java,
the initial setup was not as easy as with the other two. The only annoyance with
Go was, that the maintainer changed resulting in a new repository. This resulted
in extra steps. All APIs were clear and consistent. The documentation for all
three libraries was clear and complete. The community for all three libraries
was active and helpful. The APIs all implement the same standard and therefore
are very similar in use and functionality. Furthermore, all three libraries were
open-source and featured permissive licenses, none of which were copyleft
licenses. As demonstrated in the examples, their usage and functionality were
remarkably alike. In the end, it boils down to personal preference and
familiarity with the language. Since I am most familiar with Rust, I decided to
use lapin for the microservice.
#pagebreak()
== Architecture<architecture>
The microservice is implemented in Rust. Two off-the-shelf libraries are used to
implement the microservice. The first library is lapin, which is used to interact
with RabbitMQ. The second library is axum, which is used to implement the webserver.
#figure(
image("../assets/microservice_components.svg"),
caption: "Microservice Architecture",
kind: image,
)
The central component of the microservice is the replay component. The replay logic
implements the use cases described in @Use_cases.
#pagebreak()
The replay component is split into three use cases.
#figure(
image("../assets/replay_components.svg"),
caption: "Replay Architecture",
kind: image,
)
For each use case, a separate sequence diagram is provided.
#pagebreak()
*Get*<replay-get>
A get request with a queue and a timeframe (from, to) is sent to the
microservice. The replay component creates a new consumer and starts consuming
messages from the queue starting at the first offset of the stream. The consumer is stopped after the timeframe is reached or all messages are consumed.
The consumer does not have any meta information about the queue, leading to the problem
that the consumer does not know when the queue is empty or if all messages are consumed.
To retrieve the needed meta information, a request is sent to the RabbitMQ management API.
#figure(
image("../assets/sequence_diagram_get.svg"),
caption: "Replay Sequence Diagram Get",
kind: image,
)
The consumed messages get aggregated and returned to the client.
#pagebreak()
*Post (timeframe)*<replay-post-timeframe>
A post request with a queue and a timeframe (from, to) is sent to the microservice.
The replay component creates a new consumer and starts consuming messages from the queue.
The consumer is stopped after the timeframe is reached. Each consumed message gets
published to the same queue.
#figure(
image("../assets/sequence_diagram_post_timeframe.svg"),
caption: "Replay Sequence Diagram Post Timeframe",
kind: image,
)
The messages that get published to the queue acquire a new transaction ID on publish.
After all messages are published, a list of transaction IDs is returned to the client.
#pagebreak()
*Post (transaction)*<replay-post-transaction>
A post request with a queue and a single transaction ID is sent to the microservice.
The replay component creates a new consumer and consumes the message with the given
transaction ID from the queue.
#figure(
image("../assets/sequence_diagram_post_transaction.svg"),
caption: "Replay Sequence Diagram Post Transaction",
kind: image,
)
The consumed message gets published again to the same queue but with a new transaction ID.
The newly created transaction ID is returned to the client.
#pagebreak()
|
|
https://github.com/jonaspleyer/peace-of-posters | https://raw.githubusercontent.com/jonaspleyer/peace-of-posters/main/themes.typ | typst | MIT License | #let _state-poster-theme = state("poster-theme", (
"body-box-args": (
inset: 0.6em,
width: 100%,
),
"body-text-args": (:),
"heading-box-args": (
inset: 0.6em,
width: 100%,
fill: rgb(50, 50, 50),
stroke: rgb(25, 25, 25),
),
"heading-text-args": (
fill: white,
),
))
#let uni-fr = (
"body-box-args": (
inset: 0.6em,
width: 100%,
),
"body-text-args": (:),
"heading-box-args": (
inset: 0.6em,
width: 100%,
fill: rgb("#1d154d"),
stroke: rgb("#1d154d"),
),
"heading-text-args": (
fill: white,
),
)
#let update-theme(..args) = {
for (arg, val) in args.named() {
_state-poster-theme.update(pt => {
pt.insert(arg, val)
pt
})
}
}
#let set-theme(theme) = {
_state-poster-theme.update(pt => {
pt=theme
pt
})
}
|
https://github.com/Leo1003/resume | https://raw.githubusercontent.com/Leo1003/resume/main/secrets.typ | typst | #let secret_data = toml("secrets.toml")
#let secret(key) = {
secret_data.at(key, default: "<REDACTED>")
}
|
|
https://github.com/MultisampledNight/flow | https://raw.githubusercontent.com/MultisampledNight/flow/main/src/presentation.typ | typst | MIT License | #import "info.typ"
#import "palette.typ": *
#import "@preview/polylux:0.3.1": *
#let slide(body) = {
// don't register headings that don't have any content
// this way one can use a bare `=` for an empty slide
// and a bare `==` for a new slide without heading
show heading.where(body: []): set heading(
numbering: none,
outlined: false,
)
show outline: block.with(width: 60%)
set outline(depth: 1)
set line(stroke: (thickness: 0.15em))
polylux-slide(body)
}
#let prominent(body) = align(center + horizon, {
set heading(numbering: none, outlined: false)
show heading: set text(1.5em)
body
})
// Splits the array `seq` based on the function `check`.
// `check` is called with each element in `seq` and
// needs to return a boolean.
// Elements that `check` returns true for are called *edges*.
// Each edge marks a split.
// What the edge is done with is determined by `edge-action`:
//
// - "discard" causes the edge to be forgotten.
// It is neither in the ended nor started array.
// - "isolate" puts the edge into its own array
// between the just ended and started ones.
// - "right" puts the edge as the *first* item
// in the *just started* array.
#let _split-by(seq, check, edge-action: "discard") = {
if edge-action not in ("discard", "isolate", "right") {
panic()
}
let out = ()
for ele in seq {
let is-edge = check(ele)
if is-edge {
out.push(())
if edge-action == "discard" {
continue
}
}
if out.len() == 0 {
out.push(())
}
// indirectly also handles "right" == edge-action
out.last().push(ele)
if is-edge and edge-action == "isolate" {
out.push(())
}
}
out
}
#let _progress-bar(now, total) = {
let ratio = (now - 1) / (total - 1)
move(
dy: 0.35em,
line(
length: ratio * 100%,
stroke: gamut.sample(35%),
),
)
}
#let _prelude(body) = {
set page(
paper: "presentation-16-9",
footer: context {
let now = logic.logical-slide.get().first()
let total = logic.logical-slide.final().first()
grid(
columns: (1fr, auto),
align: (left, right),
gutter: 0.5em,
_progress-bar(now, total),
dim[#now / #total],
)
},
)
body
}
#let _also-check-children(it, check) = {
it.fields().at("children", default: (it,)).any(check)
}
#let _is-heading-with(it, check) = _also-check-children(
it,
it => (it.func() == heading and check(it.depth))
or (it.func() == outline and check(1)),
)
#let _is-heading(it) = _is-heading-with(it, _ => true)
#let _is-toplevel-heading(it) = _is-heading-with(it, d => d == 1)
#let _is-subheading(it) = _is-heading-with(it, d => d > 1)
#let _used-slide-delimiter-shorthand(slide) = _also-check-children(
slide,
it => "body" in it.fields() and it.body == []
)
// Traverses the body and splits into slides by headings.
// *The body needs to be un-styled for this,
// i.e. call this after before you've applied anything to the content.
// This can be accomplished by putting it as the last show rule
// after all set rules.*
#let _split-onto-slides(body) = {
_split-by(
body.children,
_is-heading,
edge-action: "right"
)
.map(array.join)
}
#let _process-title(slides, args) = {
// title slide is from first toplevel heading to then-next heading (of any kind)
let title-start = slides.position(_is-toplevel-heading)
let title-end = slides.slice(title-start + 1).position(slide =>
_is-toplevel-heading(slide) or (
"children" in slide.fields() and
slide.children.at(0).func() == heading
)
) + title-start + 1
let title = slides.slice(title-start, title-end).join()
title = prominent({
title
info.render(info.preprocess(args))
})
slides.slice(0, title-start).map(slide => {
set heading(numbering: none)
align(center + horizon, slide)
})
(title,)
slides.slice(title-end)
}
#let _process-final(slides) = {
// final slide is everything after last toplevel heading
let final-start = (
slides.len() -
slides.rev().position(_is-toplevel-heading) -
1
)
let final = slides.slice(final-start).join()
final = prominent(final)
slides.slice(0, final-start)
(final,)
}
#let _center-section-headings(slides) = slides.map(slide => {
// don't want to render something centered just because a slide delimiter was used
if (
_used-slide-delimiter-shorthand(slide)
or not _is-toplevel-heading(slide)
) {
return slide
}
align(center + horizon, slide)
})
#let _process(body, handout: false, args) = {
let slides = _split-onto-slides(body)
slides = _process-title(slides, args)
slides = _process-final(slides)
slides = _center-section-headings(slides)
enable-handout-mode(handout or not cfg.render)
slides.map(slide).join()
}
|
https://github.com/justinvulz/typst_packages | https://raw.githubusercontent.com/justinvulz/typst_packages/main/lecture.typ | typst | #import "@preview/ctheorems:1.1.2": *
#import "@preview/cuti:0.2.1": show-fakebold
#import "./symbol.typ": *
#let exercise = thmbox(
"exercise",
"Exercise",
stroke: black + 1pt,
base: none,
).with(numbering: "I")
#let theorem = thmbox(
"id1",
"Theorem",
// fill: rgb("e8e8f8"),
base_level: 1,
padding: (y: 0em)
).with(
inset: 0em
)
#let definition = thmbox(
"id1",
"Definition",
// fill: rgb("e8f8e8"),
base_level:1,
padding: (y: 0em)
).with(
inset: 0em
)
#let conjecture = thmbox(
"id1",
"Conjecture",
// fill: rgb("e8f8e8"),
base_level:1,
padding: (y: 0em)
).with(
inset: 0em
)
#let lemma = thmbox(
"id1",
"Lemma",
// fill: rgb("e8e8f8"),
// stroke: black,
base_level: 1,
padding: (y: 0em)
).with(
inset: 0em
)
#let remark = thmbox(
"id1",
"Remark",
// stroke: black,
base_level: 1,
padding: (y: 0em)
).with(
inset: 0em
)
#let corollary = thmbox(
"id1",
"Corollary",
// fill: rgb("e8e8f8"),
base_level: 1,
padding: (y: 0em)
).with(
inset: 0em
)
#let discussion = thmbox(
"id1",
"Discussion",
base_level: 1,
breakable: true,
// stroke: black + 1pt,
padding: (y: 0em)
).with(
inset: 0em
)
#let proof = thmproof("pkoof","Proof").with(inset:0em)
#let example = thmplain("example","Example").with(
inset: (top: 0.5em, bottom: 0.5em),//, left: 1em, right: 1em),
numbering: none
)
// #let remark = thmplain("remark","Remark").with(
// inset: (top: 0.5em, bottom: 0.5em, left: 1em, right: 1em),
// numbering: none
// )
#let textb(it) = [
#set text(font: ("Times New Roman","DFKai-SB"))
#text(weight: "bold")[#it]
]
#let textr(it) = [
#set text(font: ("Times New Roman","DFKai-SB"))
#it
]
#let heading-without-number(title) = [
#set heading(numbering: none)
= #title
#set heading(numbering: "1.")
]
// test
#let al(itm) = {
return n => grid(
columns: (0em, auto),
align: bottom,
hide[一], numbering(itm, n)
)
}
#let listal = {
grid(
columns: (0em, auto),
align: bottom,
hide[一], [•]
)
}
// #let to-string(content) = {
// if content.has("text") {
// content.text
// } else if content.has("children") {
// content.children.map(to-string).join("")
// } else if content.has("body") {
// to-string(content.body)
// } else if content == [ ] {
// " "
// }
// }
// #let numeq(content) = [
// #context[
// #let l = numbering(
// "1.1",counter(heading).get().first(),
// counter(math.equation).get().first()+1
// )
// #math.equation(
// block: true,
// numbering: num => numbering("(1.1)", counter(heading).get().first(), num),
// content
// )//#label(l)
// ]
// ]
#let numeq(content) = math.equation(
block: true,
numbering: num => numbering("(1.1)", counter(heading).get().first(), num),
content
)
#let makeTitle = [
#let title = context {
text(20pt)[#state("title").get()]
}
#let author = context {
text(size: 14pt)[#state("author").get()]
}
#let subtitle = context {
text(16pt)[#state("subtitle").get()]
}
#set align(center)
#set par(leading: 2em)
#if title!= none [#title\ ]
#if subtitle!= none [#subtitle\ ]
#if author!= none [#author\ ]
]
#state("title","")
#state("author","")
#let conf(
title:none,
subtitle:none,
author:none,
doc
) = {
set document(title: title, author: author)
set page(
paper: "a4",
number-align: center,
numbering: "1",
// footer: rect(width: 100%, height: 100%,fill: silver),
)
state("title").update(title)
state("author").update(author)
state("subtitle").update(subtitle)
show: show-fakebold.with(reg-exp: "\p{script=Han}")
show: thmrules
set text(
font: ("Times New Roman","DFKai-SB"),
top-edge: "ascender",
bottom-edge: "descender",
size: 12pt
)
set heading(numbering: "1.")
show heading: it =>[
#text(weight: "bold")[#it]
// #v(0.65em)
]
show heading.where(level: 1): it => {
counter(math.equation).update(0)
text(weight: "bold")[#it]
// v(0.65em)
}
set par(leading: 0.8em)
show math.equation: set text(weight: "extralight")
show math.equation: set block(spacing: 0em)
show math.equation.where(block: true): e => [
// #set block(fill: lime)
#block(width: 100%, inset: 0.3em)[
#set align(center)
#set par(leading: 0.65em)
#e
]
]
show ref: it => {
let eq = math.equation
let el = it.element
if el != none and el.func() == eq {
// Override equation references.
[Eq. ]
numbering(
el.numbering,
..counter(eq).at(el.location())
)
} else {
// Other references as usual.
it
}
}
set text(size: 11pt)
set list(marker: listal)
set enum(numbering: al("1."))
doc
}
|
|
https://github.com/drupol/master-thesis | https://raw.githubusercontent.com/drupol/master-thesis/main/resources/typst/equivalence-classes-of-reproducibility.typ | typst | Other | #import "../../src/thesis/imports/preamble.typ": *
#table(
columns: (1fr, 1fr),
align: left + horizon,
stroke: none,
table.header(
[*Equivalence class*],
table.vline(stroke: .5pt),
[*Examples*],
table.hline(stroke: .5pt),
),
[Same phenomenon],
[Human experts],
table.hline(stroke: .5pt),
[Same statistics],
[Software like GNUplot, Matplotlib, R],
table.hline(stroke: .5pt),
[Same data],
[Checksum of file contents],
table.hline(stroke: .5pt),
[Same bits],
[Checksum of file contents and metadata],
)
|
https://github.com/jneug/typst-codetastic | https://raw.githubusercontent.com/jneug/typst-codetastic/main/checksum.typ | typst | MIT License |
#import "util.typ"
#let gtin(code) = {
assert.eq(type(code), "array")
assert(
code.len() in (4, 7, 11, 12, 13),
message: "GTIN codes may be 4,7,11,12 or 13 digits long (excluding checksum). Got " + str(code.len()),
)
let cs = util.weighted-sum(code.rev(), (3, 1))
let rem = calc.rem(cs, 10)
if rem == 0 {
return 0
} else {
return 10 - calc.rem(cs, 10)
}
}
#let gtin-test(code, checksum: auto, version: auto) = {
assert.eq(type(code), "array")
if type(version) == "integer" {
assert.eq(code.len(), version)
} else {
assert(code.len() in (5, 8, 12, 13, 14))
}
if checksum == auto {
checksum = int(code.at(-1))
code = code.slice(0, -1)
}
return checksum == gtin(code)
}
#let ean5(code) = {
assert.eq(type(code), "array")
assert.eq(code.len(), 5)
let cs = util.weighted-sum(code, (3, 9))
return calc.rem(cs, 10)
}
#let ean5-test(code, checksum: auto) = {
assert.eq(type(code), "array")
assert.eq(code.len(), if checksum == auto { 6 } else { 5 })
if checksum == auto {
checksum = int(code.at(-1))
code = code.slice(0, -1)
}
return checksum == ean5(code)
}
#let ean8(code) = {
assert.eq(type(code), "array")
assert.eq(code.len(), 7)
return gtin(code)
}
#let ean8-test(code, checksum: auto) = {
assert.eq(type(code), "array")
assert.eq(code.len(), if checksum == auto { 8 } else { 7 })
return gtin-test(code, checksum: checksum)
}
#let ean13(code) = {
assert.eq(type(code), "array")
assert.eq(code.len(), 12)
return gtin(code)
}
#let ean13-test(code, checksum: auto) = {
assert.eq(type(code), "array")
assert.eq(code.len(), if checksum == auto { 13 } else { 12 })
return gtin-test(code, checksum: checksum)
}
#let isbn10(code) = {
assert.eq(type(code), "array")
assert.eq(code.len(), 9)
let cs = util.weighted-sum(code.rev(), (i) => i + 2)
cs = 11 - calc.rem(cs, 11)
if cs < 10 {
return cs
} else {
return "X"
}
}
#let isbn10-test(code, checksum: auto) = {
assert.eq(type(code), "array")
assert.eq(code.len(), if checksum == auto { 10 } else { 9 })
if checksum == auto {
checksum = int(code.at(-1))
code = code.slice(0, -1)
}
if checksum == "X" {
checksum = 10
}
return checksum == isbn10(code)
}
#let isbn13 = ean13
#let isbn13-test = ean13-test
#let upc-a = gtin
#let upc-a-test = gtin-test
|
https://github.com/maxgraw/bachelor | https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/6-evaluation/method.typ | typst | #import "../charts.typ": *
Um die Untersuchung der Zielfrage durchzuführen, wurde eine Studie in Form einer Online-Umfrage über einen Zeitraum von zwei Wochen durchgeführt. Die Teilnehmenden wurden über persönliche Kontakte rekrutiert.
Innherhalb der Studie wurden 21 Teilnehmende rekrutiert. Hierbei waren 3 Teilnehmende weiblich und 18 Teilnehmende männlich. Das Durchschnittsalter der Teilnehmenden lag bei 30 Jahren. Die jüngste teilnehmende Person war 19 Jahre alt, während die älteste teilnehmende Person 60 Jahre alt war. Die Verteilung der Altersgruppen und Geschlechter ist in @figure-ageGender dargestellt. Zur Wahrung der Anonymität der Teilnehmenden wurde jedem eine eindeutige ID zugewiesen.
#figure(
age_gender,
caption: "Verteilung der Altersgruppen und Geschlechter der Probanden",
) <figure-ageGender>
Wie bereits in der Einleitung beschrieben, handelt es sich bei der Studie um eine Online-Umfrage. Hierbei wurde mithilfe von Google Forms ein Fragebogen erstellt, der die Teilnehmenden durch die Studie führte. Darüber hinaus wurde auf der Website #link("https://ar.maxgraw.com") die zuvor entwickelte Anwendung bereitgestellt und innerhalb der Studie verwendet.
Um die Benutzererfahrung der Anwendung zu evaluieren, wurde der User Experience Questionnaire gewählt. Der UEQ zielt darauf ab, die subjektiven Eindrücke der Nutzer bezüglich der Benutzererfahrung und des Nutzungserlebnisses einer Anwendung zu messen. Der UEQ besteht aus 26 gegensätzlichen Begriffspaaren, die auf einer 7-Punkte-Likert-Skala bewertet werden. Die einzelnen Items des UEQ lassen sich in sechs Dimensionen unterteilen. Die Attraktivität erfasst den Gesamteindruck des Produkts und wird mit sechs Items gemessen, während die anderen Dimensionen jeweils mit vier Items geprüft werden. Die Durchschaubarkeit prüft, wie einfach es ist, sich mit dem Produkt vertraut zu machen und dessen Bedienung zu erlernen. Die Effizienz misst, ob die Nutzer ihre Aufgaben ohne unnötigen Aufwand erledigen können und wie die Reaktionszeiten wahrgenommen werden. Die Steuerbarkeit befasst sich damit, ob die Nutzer die Interaktionen mit dem System unter Kontrolle haben und ob diese sicher und vorhersehbar sind. Die Stimulation untersucht, wie spannend, motivierend und unterhaltend die Nutzung für die Anwender ist. Die Originalität misst, wie kreativ und innovativ die Anwendung ist und ob dadurch das Interesse der Nutzer geweckt wird @ueq-handbook. Die Usability lässt sich hierbei durch die Dimensionen Effizienz, Durchschaubarkeit und Steuerbarkeit abdecken und stellen somit pragmatische Qualitäten dar. Die User Experience hingegen wird durch die Dimensionen Stimulation und Originalität repräsentiert, die die hedonische Seite des standardisierten Fragebogens bilden @ueq-handbook, @ueq-website.
Es handelt sich um einen standardisierten Fragebogen, der bereits in zahlreichen Studien zur Evaluation der User Experience von Softwareanwendungen eingesetzt wurde. Der Fragebogen ermöglicht eine quantitative Analyse und deckt sowohl pragmatische als auch hedonische Qualitäten ab @ueq-handbook.
=== Ablauf und Durchführung
Im Folgenden wird der Ablauf der Studie dargestellt. Die Studie wurde als Online-Umfrage konzipiert. Über ein bereitgestelltes Online-Formular wurde zunächst eine Einführung in die Thematik der Studie gegeben. Hierbei wurde eine Situation beschrieben, die die Nutzung der Anwendung simuliert.
Wie im Kapitel der Zielgruppenanalyse definiert, richtet sich die Primärzielgruppe an Personen, die die Anwendung zur Entscheidungsunterstützung nutzen möchten. In der Einleitung wurde eine passende Situation entworfen, die diese Zielgruppe anspricht. Die Teilnehmenden sollten sich vorstellen, dass sie das Möbelsystem "Stackcube" in ihrem Zimmer verwenden möchten, jedoch unsicher sind, ob die Möbelstücke in den Raum passen. Durch diese einleitende Beschreibung wurde den Teilnehmenden eine realitätsnahe Nutzungssituation vermittelt, die ihnen helfen sollte, sich besser in die Anwendung hineinzuversetzen und ihre Benutzererfahrung entsprechend zu bewerten.
Anschließend wurde die Anwendung unter #link("https://ar.maxgraw.com") bereitgestellt. Die Teilnehmenden wurden aufgefordert, die Anwendung zu öffnen und die bereitgestellten Aufgaben durchzuführen. Es wurden drei Aufgaben bereitgestellt, die die Teilnehmenden in der Anwendung durchführten. Dabei wurde die Komplexität der Aufgaben schrittweise erhöht. Alle Aufgaben folgten dem gleichen Ablauf: Zunächst wurde das Ziel der Aufgabe definiert, anschließend wurden die Schritte zur Durchführung der Aufgabe dargestellt. Nach Abschluss der Aufgabe wurde die Anwendung für die nächste Aufgabe vorbereitet.
Die erste Aufgabe bestand darin, ein Möbelstück auszuwählen und zu platzieren. Hierbei sollten die Probanden den grundlegenden Ablauf der Anwendung sowie die grundlegenden Funktionen kennenlernen. Die zweite Aufgabe erweiterte die erste Aufgabe, indem die Probanden ein Möbelstück platzieren und anschließend wieder löschen mussten. Nach Abschluss dieser beiden Aufgaben waren die Probanden mit den grundlegenden Funktionen der Anwendung vertraut. Die dritte Aufgabe forderte die Probanden auf, eine größere Möbelstruktur zu erstellen, wobei die Funktion des Anhängens von Möbelstücken genutzt werden musste.
Nach Abschluss der Aufgaben wurden die demographischen Daten der Probanden erhoben, um ein besseres Verständnis der Benutzergruppe zu ermöglichen. Dies umfasste Angaben wie Alter und Geschlecht. Anschließend wurde der UEQ-Fragebogen bereitgestellt sowie die Möglichkeit innerhalb eines Freitextfeldes Anmerkungen zur Anwendung zu hinterlassen. Die genaue Struktur des Fragebogens findet sich in @appendix-task. |
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/edu/seminars/2024-10-23.typ | typst | = Про итоговое задание
Нужно:
- Выложить в SmartLMS план-сценарий или презентацию для занятия
- Провести часть вашего занятия для одногруппников и преподавателя (20 минут):
- Нужно сказать, какую аудиторию должны отыграть другие
Оценивается тремя способами:
- Оценивание учителем
- Взаимооценивание
- Самооценивание
Все критерии есть в SmartLMS
= Итоговое и формирующее оценивание
== Что такое оценивание
Оценка в представлении многих --- это "что-то уже случившееся". Оценка уже есть,
изменить нельзя. Но должно быть по-другому.
== Разница между оценкой и отметкой
- Оценка --- это процесс оценивания знаний
- Отметка --- это числовая или буквенная оценка
== Основные принципы оценивания
- Дифференцирующий характер (индивидуализация)
- Открытость
- Объективность критериев
- Накопительный характер (оценка должна сопровождать процесс)
- Отсылка к планируемым образовательным результатам
== Виды оценивания
- Формирующее: на основе оценки можно что-то изменить (суп пробует повар)
- Итоговое: уже ничего не изменить (суп пробуют гости)
== Итоговое оценивание
Цель: определить уровень достижения целей
- Более объективно
- В более сильных рамках
- Больше для учителя
=== Принципы составления итогового теста
- Начните с легких вопросов
- Структурируйте тест
- Предлагайте 3--4 варианта ответа
- Формулируете привлекательные неверные ответы
- Убедитесь, что задание измеряет именно то, что вы хотите измерить
==== Принципы формулирования заданий с выбором ответа
- Принцип *противоречивости* --- во вариантах использовать отрицание
- Принцип *противоположность* --- во вариантах использовать антонимы
- Принцип *однородности* --- в ответах используются члены одного множества, одного
гомологического ряда
- Принцип *градуирования* --- используется градация по одной из характеристик
- Принцип *комуляциии* -- каждый предыдущий ответ включается в последующих
- Принцип *сочетания* --- вариант ответа складывается из нескольких элемент группы
=== Формы тестовых заданий
- Задания в закрытой форме
- Выбор ответа
- Выбор одного ответа
- Выбор нескольких ответов
- Градуированный ответ
- Установление соответствия
- Установление последовательности
- Задания в открытой форме
- Дополнение
- Свободное изложение
== Формирующее оценивание
Ничего не подытоживает
=== Критерии формирующего оценивания
- Обезличено
- Облегчает активное обучение
- Обратная связь
- Рефлексия и постановка целей на будущее
- Сосредоточено на обучение
- Гибкое
- Быстрое
- Частое, регулярное
- Можно совмещать с игрой
=== Формирующее оценивание отвечает на вопросы
- Где ученик сейчас?
- Куда нужно прийти в результате?
- Как это сделать?
=== Приемы формирующего оценивания
- Билет на выход
- Вопрос одной минуты
- Парковка вопросов --- ученики клеят стикеры с тем, что им [не] понравилось на
уроке
- Фишбоун
== Критериальное оценивание
- Повышает объективность оценки, повышает доверие к результату
- Критерии являются основой для самооценки учеников
- Критерии позволяют четко структурировать деятельность учеников
- Способствует организации взаимооценивания
- Критерии являются основной для получения обратной связи
- Критериальные рубрики обеспечивают единый стандарт оценивания
В идеале критерии разрабатывать вместе с учениками
|
|
https://github.com/goshakowska/Typstdiff | https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_complex/text_formats/text_formats_updated_result.typ | typst | = Heading1
Paragraph with quotes “This is #strike[in];#underline[super] quotes.”
#strong[Date:] #strike[26.12.2022];#underline[26.02.2024] \
Date used in paragraph #strong[Date:]
#strike[26.12.2022];#underline[30.12.2022] \
#strong[Topic:] Infrastructure Test \
#strong[Severity:] High \
= Heading3
#emph[emphasis]
Some normal #strike[text];#underline[TEXT]
Italic
#strong[MY#underline[ ];#underline[NEW] TEXT] \
ALREADY #strike[HIGH];#underline[ALREADY]
#strike[#link("https://typst.app/");];#underline[#link("https://something.app/");]
= Heading4
abc
Link in paragraph:
#strike[#link("https://typst.app/");];#underline[#link("https://something.app/");]
= Heading5
|
|
https://github.com/pal03377/master-thesis | https://raw.githubusercontent.com/pal03377/master-thesis/main/thesis_typ/abstract_en.typ | typst | MIT License | #let abstract_en() = {
set page(
margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm),
numbering: none,
number-align: center,
)
let body-font = "New Computer Modern"
let sans-font = "New Computer Modern Sans"
set text(
font: body-font,
size: 12pt,
lang: "en"
)
set par(leading: 1em)
// --- Abstract (DE) ---
v(1fr)
align(center, text(font: body-font, 1em, weight: "semibold", "Abstract"))
// 1. *paragraph:* What is the motivation of your thesis? Why is it interesting from a scientific point of view? Which main problem do you like to solve?
// 2. *paragraph:* What is the purpose of the document? What is the main content, the main contribution?
// 3. *paragraph:* What is your methodology? How do you proceed?
// - Systems like the learning management system Artemis are used to support the learning process in programming courses. They are gaining more and more popularity.
// - To give high-quality feedback on all submitted exercises, the tutors have to invest a lot of time.
// - Recently, the idea of using machine learning to semi-automate the feedback process has been proposed.
// - Athena is a system that uses machine learning to semi-automate the feedback process for text exercises. It was recently developed at the University of Munich.
// - However, most exercises in programming courses are not text exercises, but programming exercises.
// - Artemis also supports a number of other types of exercises, like file upload exercises and modeling exercises.
// - Therefore, the goal of this thesis is to extend Athena to be capable of supporting more types of exercises. We focus on generalizing Athena to support programming exercises in addition to text exercises.
// - It is also very important to evaluate the quality of the feedback that different systems ("modules" in Athena) provide.
// - Therefore, we introduce a new module architecture that allows us to easily compare the quality of different modules by swapping them out.
// - One such module will be "ThemisML", which is the machine learning module that is used to provide feedback suggestions on programming exercises in the recently developed Themis app. We unify the ThemisML module with Athena.
// - Our methodology is to do this:
// * Analyze the current architecture of Athena
// * Design a new architecture that allows us to create new modules for any type of exercise and swap them out easily
// * Implement the new architecture
// * Contain the current Athena system in a module
// * Contain the current ThemisML system in a module
// * Integrate the new system into the learning management system Artemis
// * Evaluate the quality of the feedback that the new system provides
par(justify: true)[
Learning Management Systems like Artemis have become pivotal in administering programming courses as educational platforms evolve to accommodate modern learning paradigms. However, tutors still face the time-consuming task of providing detailed feedback. While the recently proposed Athena system has begun to semi-automate this process for text exercises, a gap remains for programming exercises. The research in this thesis aims to fill that void by adapting Athena to handle both text and programming exercises in a unified manner.
We present a modular design that streamlines the addition and interchangeability of feedback-generating components. This new architecture includes CoFee, the current text-exercise feedback module from Athena, and a machine-learning module specialized for programming exercises. We integrate this new Athena system into Artemis.
An analysis of Athena's existing framework reveals areas for improvement. We design and implement a modular structure to support multiple types of exercises and allow for the addition of new feedback modules. A brief evaluation follows to assess the quality of the system's automated feedback.
By expanding Athena's capabilities, this thesis aims to enrich the feedback loop in programming education, thereby offering advantages to both tutors and students.
]
v(1fr)
} |
https://github.com/DriedYellowPeach/project-vietnam | https://raw.githubusercontent.com/DriedYellowPeach/project-vietnam/main/project-vietnam.typ | typst | #set heading(numbering: "1.")
#set page(header: text(8pt, align(right)[
Project Vietnam 🇻🇳
]), numbering: "<1/1>", margin: (x: 2cm, y: 2cm))
#set par(justify: true)
#set text(font: "ComicCode Nerd Font", size: 11pt, lang: "en")
// The Title
#pad(top: 10pt, bottom: 10pt, [
#align(center, text(20pt, weight: "bold")[
Traveling Guide
])
])
= Preparation 📦
#line(length: 100%, stroke: 1pt)
== Visa 👮
To find a Vietnam visa application on Taobao, search for it and you will see
prices ranging from 200 to 300 RMB. You will need to provide certain documents,
which are listed in @visa-apply-document.
#figure(
image("./images/visa-apply-docs.PNG", height: 50%, width: 50%), caption: [
Visa Apply Documents
],
)<visa-apply-document>
The visa will be mailed to you on a separate piece of paper, similar to the visa
issued by North Korea, rather than as a sticker like the US visa. This method is
straightforward and ideal for travelers, as it does not leave a record in your
passport.
Although the visa is typically issued within 3 days after application, it is
advisable to apply early to avoid any potential emergencies.
== Route 🚗
We will start our journey in *Wuhan* and fly to *Hanoi*, the capital of Vietnam.
After spending several days relaxing in Hanoi, we will take a bus or car south
to *Ha Long Bay*. We will spend 2-3 days and 1-2 nights in Ha Long Bay. Then, we
will return to Hanoi and fly to *Da Nang*. After enjoying our last dance in this
seaside city, we will fly back home.
I scribbled the traveling route, shown in @scribble-route
#figure(image("./images/route.jpg", height: 50%, width: 40%), caption: [
traveling route
])<scribble-route>
== Schedule(WIP)
// typstfmt::off
#table(
columns: 4, [*Date*], [*Location*], [*Time Span*], [*Activities*],
[7/20], [Wuhan -> Hanoi], [12:00 pm - 16:45 pm], [
1. Flight from Wuhan to Hanoi, transfering at Guangzhou
2. Dinner at Hanoi
3. Go to the Hotel
],
[7/21], [Hanoi], [all day], [*TBD*],
[7/22], [Hanoi], [all day], [*TBD*],
[7/23], [Hanoi -> Ha Long], [HH:MM - HH:MM + 2.5hrs], [
1. taking bus to Ha Long
2. Find place to live
3. Find the travel agency for Ha Long Bay Tour
],
[7/24], [Ha Long Bay], [all day], [Ha Long Bay Touring, kayaking, hiking, cruising, food],
[7/25], [Ha Long City -> Hanoi], [all day], [
1. Touring the Ha Long City
2. SunWorld Ha Long Park
3. Go back to Ha noi
],
[7/26], [Hanoi -> Da Nang], [HH:MM - HH:MM + 1.5hrs], [
1. Taking flight from Hanoi -> Da Nang
2. Find the Hotel
],
[7/27], [Da Nang], [all day], [
1. Rent motorbike
2. buddaist temple, pink church, craving museum, market, beach, bridge
],
[7/28], [Da Nang], [all day], [
1. Ba Na Hills
2. *TBD*
],
[7/29], [Da Nang -> Hanoi], [all day], [
1. Fly back to Hanoi
],
[7/30], [Hanoi -> Guangzhou], [all day], [
1. Fly back to Guangzhou
],
)
// typstfmt::on
== Flight 🛫
We need to purchase a total of four flight tickets. Here are the options I found
for reference, detailed in @flights:
- Wuhan -> Hanoi
- Hanoi -> Da Nang
- Da Nang -> Hanoi
- Ha noi -> Wuhan
#figure(
grid(
columns: (auto, auto, auto, auto), gutter: auto, [ #image("./images/wh-to-hanoi.PNG", width: 90%, height: 30%) ], [ #image("./images/hanoi-to-danang.PNG", width: 90%, height: 30%) ], [ #image("./images/danang-to-hanoi.PNG", width: 90%, height: 30%) ], [ #image("./images/hanoi-to-wh.PNG", width: 90%, height: 30%) ],
), caption: [Flights],
) <flights>
=== The Cost
The flight costs, based on my initial research, are detailed in @flight-costs. I
know it's a bit expensive, but we can explore ways to find cheaper tickets.
#figure(
table(
stroke: none, columns: 2, [*Item*], [*Cost*], [Wuhan -> Hanoi], [¥1,000], [Hanoi -> Da Nang], [¥330], [Da Nang -> Hanoi], [¥330], [Hanoi -> Wuhan], [¥1,200], table.hline(), [*Total*], [¥2,860],
), caption: [Flight Costs],
)<flight-costs>
== Accommodation 🏠
=== Live in Hanoi
We will stay in Hanoi for 3 nights from July 20 to July 22. I am inclined to stay in a hostel, as it is convenient and saves a lot of money. I found the Mad Monkey Hostel online, detailed in @mad-monkey. It is extremely affordable, costing around ¥40 per person per night.
#figure(
image("./images/mad-monkey.png", width: 80%, height: 50%),
caption: [
mad monkey hostel
]
)<mad-monkey>
=== Live in Ha Long
We will stay 2 nights at Ha Long and Ha Long Bay:
- On the first day of our arrival, we need to find the travel agency and figure out the gathering point for the Ha Long Bay tour, so we will decide where to stay after we arrive.
- On the second day, after several days of roughing it at Mad Monkey Hostel, we should reward ourselves. I highly recommend staying at *Vinpearl Resort & Spa Ha Long*, detailed in @vinpearl. Although it is expensive, costing around ¥1,200 per night, this hotel is located on a standalone island and I believe it is a must-visit.
#figure(
grid(
columns: (auto, auto, auto),
gutter: auto,
[ #image("./images/vin1.png", width: 90%, height: 30%) ],
[ #image("./images/vin2.png", width: 90%, height: 30%) ],
[ #image("./images/vin3.png", width: 90%, height: 30%) ],
), caption: [ Vinpearl Resort & Spa Ha Long ],
) <vinpearl>
=== Live in Da Nang
We will stay in Da Nang for 3 nights from July 26 to July 28, and we have two accommodation options
- Stay at a resort, which is more expensive, costing around ¥400 - ¥700 per person per night.
- Stay at a hotel, which is much cheaper, costing around ¥100 per person per night.
Because Da Nang is a very famous seaside city, resorts are more expensive than in other places. For this reason, I am more inclined to stay in a hotel. I suggest we stay at Kua Casa Suite, detailed in @kua.
#figure(
grid(
columns: (auto, auto, auto),
gutter: auto,
[ #image("./images/kua1.jpg", width: 90%, height: 30%) ],
[ #image("./images/kua2.jpg", width: 90%, height: 30%) ],
[ #image("./images/kua3.jpg", width: 90%, height: 30%) ],
), caption: [Kua Casa Suite],
)<kua>
=== The Cost
Here is the total estimated accommodation cost per person for the 10-day trip in Vietnam, detailed in @accommodation-cost:
#figure(
table(
stroke: none, columns: 3,
[*Item*], [*Quantity*], [*Cost*],
[Mad Monkey], [ 5 nights ], [¥42],
[TBD hotel in Ha Long], [ 1 night], [around ¥150],
[Vinpearl Resort], [1 night], [¥430],
[Kua Casa Suite], [3 night], [¥110],
table.hline(),
[*Total*], [], [¥1,120],
), caption: [Accommodation Costs],
)<accommodation-cost>
== Currency 💵
The currency in Vietnam is the Vietnamese Dong (VND), and 1 CNY is equivalent to 3,500 VND. We can exchange some cash at the airport upon arrival. Credit cards and cash will be the main payment methods for this trip.
= Part I:Hanoi 🏙(WIP)
#line(length: 100%, stroke: 1pt)
We are going to explore these places:
-
-
= Part II: Ha Long Bay 🛶
#line(length: 100%, stroke: 1pt)
In the one-day Ha Long Bay cruise, We are going to explore these places, detailed in @HaLong:
- Cruise the otherworldly landscape of Halong, views from the top deck
- Kayak the lagoons of Halong and swim in the waters of Titop
- Enjoy an amazing Panorama view of Halong bay from *Titop island*
- Explore a beautiful cave in Halong Bay—*Surprise Cave*
#figure(
grid(
columns: (auto, auto, auto, auto),
gutter: auto,
[ #image("./images/cruise.jpeg", width: 90%, height: 30%) ],
[ #image("./images/kayaking.jpeg", width: 90%, height: 30%) ],
[ #image("./images/titop.jpeg", width: 90%, height: 30%) ],
[ #image("./images/cave.jpeg", width: 90%, height: 30%) ],
), caption: [Ha Long Bay Touring],
)<HaLong>
In the next day, we will go to explore Ha Long City, the Sun World Ha Long Park is worth going. We can take the cable car, which is called *Queen Cable Car*, to transit from the *Coastal Amusement Park* to *Ba Deo Hill*. This cable car is known as the world's largest passenger capacity: 230, shown in @cable-car.
#figure(
image("./images/cable-car.png", width: 50%, height: 30%),
caption: [Queen Cable Car],
)<cable-car>
Apart from the cable car, there are more to explore:
- Sun Whell Ha Long Wonder Wheel, nested on Ba Deo Hill at the height of 215m from the sea levelshown in @wheel
- Sun World Lighthouse, modeled after oldest Ke Ga Lighthouse of Vietnam, shown in @lighthouse,
#figure(
image("./images/wheel.png", width: 50%, height: 30%),
caption: [Sun Whell Ha Long Wonder Wheel],
)<wheel>
#figure(
image("./images/lighthouse.png", width: 50%, height: 30%),
caption: [Sun World Lighthouse],
)<lighthouse>
= Part IV: Da Nang 🏝️(WIP)
#line(length: 100%, stroke: 1pt)
We are going to explore these places:
- Dragon Bridge, Fri - Sun 9:00 pm fire show
- Temple of Lady Buddha
- Hoi An Ancient Village, taking canal through the river; Hoi An night market
- Ba Na Hills
- Da Nang Museum of Cham, sculpture
- Herb Bathing
= Useful Tools 📱
#line(length: 100%, stroke: 1pt)
These application would be useful:
- Google Map
- Google Translate
- Whatsapp: Vietnam WeChat
- grab: Vietnam Uber & Uber Eats
- vexere: purchase bus tickets
- agoda: hotel booking
|
|
https://github.com/Toniolo-Marco/git-for-dummies | https://raw.githubusercontent.com/Toniolo-Marco/git-for-dummies/main/slides/practice/init.typ | typst | #import "@preview/touying:0.5.2": *
#import themes.university: *
#import "@preview/numbly:0.1.0": numbly
#import "@preview/fletcher:0.5.1" as fletcher: node, edge
#let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide)
#import "../components/gh-button.typ": gh_button
#import "../components/git-graph.typ": branch_indicator, commit_node, connect_nodes, branch
To create a new project with Git, move to your project directory and initialize a repository with the command
#footnote("Let's ignore for now the output that will be parsed later."): `git init`
We have thus created the local repository, on our computer. Git is also based on the concepts of *local* and *remote*. So changes made locally *do not automatically* affect the remote.
Usually, for smaller projects, the remote repository is just one and will be hosted on *GitHub*.
This step requires having already created the organization to which the repository will belong. Alternatively, you can create it as your own and then pass ownership.
---
1. Open the page: _“https://github.com/orgs/organization/repositories”_
2. Press on the button: #box(fill: rgb("#29903B"),inset: 7pt, baseline: 25%, radius: 4pt)[#text(stroke: white, font: "Noto Sans", size: 7pt, weight: "light",tracking: 0.5pt)[New Repository]]
3. From here on fill in the fields, choosing the name, visibility and description of the repo. The README.md file can also be added later.
4. The repo page now advises us of the steps to follow directly on CLI: “_... create a new repository on the command line_”
```bash
echo "# title" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/orgs/organization/repository.git
git push -u origin main
```
---
The first command creates a file called README.md, if it does not already exist, and adds the string “\# title” to its contents. #footnote([The “\#” symbol in Markdown indicates a title.]) The other commands will be covered in the next chapters, however, for a concise description:
- `git init` we have just seen, initializes a git project locally
- `git add README.md` adds the file `README.md` to the staging area
- `git commit -m “first commit”` performs the commit
- `git branch -M main` sets _main_ as the main branch
- `git remote add origin ...` sets the newly created repository on GitHub as remote of our local repository
- `git push -u origin main` “publishes” on the remote repository the commit we just made.#footnote([Note: `-u` is the equivalent of `--set-upstream`, basically sets to which remote the branch in local should push to]) |
|
https://github.com/piepert/typst-seminar | https://raw.githubusercontent.com/piepert/typst-seminar/main/README.md | markdown | # Eine Einführung in [Typst](https://typst.app)
_(Diese Repository ist hauptsächlich für die Teilnehmer des Seminars am 2.6.2023 gedacht. Hier gibt es die Präsentation und einige Beispiele.)_
[Typst](https://typst.app) ist eine moderne Textsatz-Engine und eine mögliche Alternative zu LaTeX. Hier soll eine kleine Einführung in die grundlegenden Funktionalitäten geboten werden.
Die Präsentation liegt in [`main.typ`](main.typ) und kann in [`main.pdf`](main.pdf) angesehen werden.
In `Beispiele/` liegen einige kleine und große Dokumente, die mit Typst geschrieben wurden.
Ein paar weitere Infos zu Typst gibt es unter [`Beispiele/ImSeminarNichtBesprochen/main.pdf`](Beispiele/ImSeminarNichtBesprochen/main.pdf). |
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/docs/utilities/fit-to.md | markdown | ---
sidebar_position: 2
---
# Fit to Height / Width
Thanks to [ntjess](https://github.com/ntjess) for the code.
## Fit to Height
If you need to make an image fill the remaining slide height, you can try the `fit-to-height` function:
```typst
#utils.fit-to-height(1fr)[BIG]
```
Function definition:
```typst
#let fit-to-height(
width: none, prescale-width: none, grow: true, shrink: true, height, body
) = { .. }
```
Parameters:
- `width`: If specified, this will determine the width of the content after scaling. So, if you want the scaled content to fill half of the slide width, you can use `width: 50%`.
- `prescale-width`: This parameter allows you to make Typst's layout assume that the given content is to be laid out in a container of a certain width before scaling. For example, you can use `prescale-width: 200%` assuming the slide's width is twice the original.
- `grow`: Whether it can grow, default is `true`.
- `shrink`: Whether it can shrink, default is `true`.
- `height`: The specified height.
- `body`: The specific content.
## Fit to Width
If you need to limit the title width to exactly fill the slide width, you can try the `fit-to-width` function:
```typst
#utils.fit-to-width(1fr)[#lorem(20)]
```
Function definition:
```typst
#let fit-to-width(grow: true, shrink: true, width, body) = { .. }
```
Parameters:
- `grow`: Whether it can grow, default is `true`.
- `shrink`: Whether it can shrink, default is `true`.
- `width`: The specified width.
- `body`: The specific content. |
|
https://github.com/antonWetzel/Masterarbeit | https://raw.githubusercontent.com/antonWetzel/Masterarbeit/main/arbeit/main.typ | typst | #import "setup.typ": *
#import "lt.typ": lt
#set document(
author: "<NAME>",
title: "Berechnung charakteristischen Eigenschaften von botanischen Bäumen mithilfe von 3D-Punktwolken.",
keywords: ("Punktwolken", "botanische Bäume", "Rust", "WebGPU", "Visualisierung"),
)
// #show: word-count
// Wörter: #total-words
// #todo-outline() #pagebreak()
#show: (doc) => setup(doc, print: false)
#show: lt()
#include "deckblatt.typ"
#include "abstrakt.typ"
#{
show: style-outline
outline(depth: 3)
}
#set page(numbering: "1")
#counter(page).update(1)
#include "einleitung.typ"
#include "stand_der_technik.typ"
#include "segmentierung.typ"
#include "visualisierung.typ"
#include "triangulierung.typ"
#include "analyse.typ"
#include "implementierung.typ"
#include "auswertung.typ"
#include "fazit.typ"
#include "appendix.typ"
#include "eigenständigkeitserklärung.typ"
#bibliography("bibliographie.bib")
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/vec-00.typ | typst | Other | // Test wide cell.
$ v = vec(1, 2+3, 4) $
|
https://github.com/rdboyes/resume | https://raw.githubusercontent.com/rdboyes/resume/main/modules_fr/publications.typ | typst | // Imports
#import "@preview/brilliant-cv:2.0.2": cvSection, cvPublication
#let metadata = toml("../metadata.toml")
#let cvSection = cvSection.with(metadata: metadata)
#cvSection("Publications")
#cvPublication(
bib: bibliography("../src/publications.bib"),
keyList: ("smith2020", "jones2021", "wilson2022"),
refStyle: "apa",
)
|
|
https://github.com/MultisampledNight/flow | https://raw.githubusercontent.com/MultisampledNight/flow/main/README.md | markdown | MIT License | # flow
typst note template and utils
## How do I use this?
Compile `src/doc/manual.typ` using [Typst] and look at the resulting PDF!
Pass `--input dev=true` if you want some nicer colors!
## features
- Checkboxes just like with markdown syntax!
- Color palette management for absolutely no reason!
- Callouts for questions, notes, hints and warnings!
- Metadata queryable via the `<info>` label!
- Diagram helpers !
[Typst]: https://typst.app
|
https://github.com/adam-zhang-lcps/papers | https://raw.githubusercontent.com/adam-zhang-lcps/papers/main/animal-behavior.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "@preview/cetz:0.2.2"
#import "aet-lab-report-template.typ": aet-lab-report
#let species = [_Tribolium confusum_]
#show: doc => aet-lab-report(
title: [Investigating the Cheerios preference of #species],
course: "AET AP Biology",
teacher: "<NAME>",
partners: ([<NAME>],),
date: datetime(year: 2024, month: 09, day: 12),
doc,
)
= INTRODUCTION
== Purpose
Determine whether #species has a preference for plain Cheerios or Honey Nut Cheerios.
== Hypothesis
If #species has a choice between normal Cheerios and Honey Nut Cheerios, then they will choose the Honey Nut Cheerios due to their consumption of sweet foods, such as fruit @HagstrumSubramanyam2017:StoredProductInsectResource.
== Background
#species, also known colloquially as the "confused flour beetle", is a small insect, named for its tendency to infest grain-based food such as flour. Originally from Africa, #species is now found worldwide, and is particularly problematic in the United States. They are small beetles, around one-eighth of an inch long (0.32 centimeters), and is reddish-brown in color. Larvae hatch and grow relatively fast, making them a good candidate for experimentation @BaldwinFasulo2010ConfusedFlourBeetles @Calvin2023:ConfusedFlourBeetleRedFlourBeetle.
This experiment seeks to investigate animal behavior---specifically that of #species. When observing animal behavior, behaviors can be broadly categorized into two categories: "kinesis" and "taxis". Kinesis refers to undirected, or "random", movement in response to a stimulus. This usually refers to a change in speed or direction of movement. On the other hand, taxis refers to directed movement---usually towards or away from a stimulus, known as positive and negative taxis, respectively. Taxis are named after the type of stimulus---for example, hydrotaxis refers to a movement towards or away from moisture, while phototaxis refers to a movement towards or away from light @Gunn1937:ClassificTaxesKineses @Mackenzie2023:HowAnimalsFollow.
The taxis investigated in this experiment will be the movement of #species when given the choice between plain Cheerios and Honey Nut Cheerios in a choice chamber. Plain Cheerios and Honey Nut Cheerios share a very similar ingredients list, with the only notable difference being the addition of honey in the latter @CheeriosIngredients @HoneyNutCheeriosIngredients. If #species show a preference for one type of Cheerios, there should be observable positive taxis in their movement towards their preferred type of Cheerios.
This experiment will use a $chi^2$ test to draw a conclusion about the results of manipulating the independent variable. The $chi^2$ test allows for determining the relationship between two sets of data, and whether that relationship is "statistically significant"---not due to random chance. If the calculated $chi^2$ value surpasses a "critical value" for a certain probability#footnote[A table of critical values is available online #link("https://statisticsbyjim.com/hypothesis-testing/chi-square-table")[here].], the relationship can be concluded to be statistically significant, and not due to chance. The value for the $chi^2$ test is calculated by summing the difference of the "observed" and "expected" data sets squared, divided by the "expected" data set; see @chi-squared-equation @Pearson1900:X. This experiment will use a probability of 0.05, and thus the critical value will be 3.84.
$ chi^2 = sum_(i=0)^n (o_i - e_i)^2 / e_i $ <chi-squared-equation>
= EXPERIMENTAL METHOD
Place the choice chamber upon a consistent, level surface, oriented length-wise horizontally. Place ten plain Cheerios on the left side of the chamber and ten Honey Nut Cheerios in the right side of the chamber—this is the independent variable. Use a hard object to crush the Cheerios within the choice chamber. The experimental setup is now complete. See @setup for a photograph of this setup.
Place ten #species in the center of the chamber and begin a timer for ten minutes. Count the number of #species in each side of the chamber in intervals of 30 seconds. Record these values in @data-table—this is the dependent variable. Upon completion of the ten minute timer, return the beetles to the center of the choice chamber and repeat the procedure twice more to collect data for three total trials. Ensure the chamber contents are not disturbed between trials and remains in a constant state. See @mid-experiment for a photograph of the experiment in progress.
Ensure that appropriate safety guidelines are obeyed throughout the experiment. Handle #species with caution, as they are capable of secreting substances that can cause itchiness upon contact with skin @Mullen2009:MedicalVeterinarEntomolog. Upon conclusion of the experiment, follow all instructor directions to ensure safe post-experiment cleanup.
Note that both photographs included in this report show the Cheerios in an intact state, contrary to the procedure given. This is due to an oversight by the experimentators when collecting photographic documentation. All data collected in this experiment was collected with crushed Cheerios in the choice chamber. <whoops>
#figure(
caption: [Experimental Setup],
image(width: 80%, "assets/animal-behavior/setup.jpg"),
) <setup>
= RESULTS
== Qualitative Observations
Through the experiment, some #species appeared to struggle with movement, perhaps due to the density and inconsistency of the crushed Cheerios. Most beetles either frequently changed sides throughout a trial or did not change sides at all.
== Photographic Documentation
A photograph showing the experiment in progress is shown in @mid-experiment. Note that the trial shown in @mid-experiment was not a part of the final experimental data due to an oversight by the experimentators; see the #link(<whoops>, [experimental method]) section for more details.
#figure(
caption: [Beetles in the Chamber during Experimentation],
image(width: 80%, "assets/animal-behavior/mid-experiment.jpg"),
) <mid-experiment>
== Data
The data collected for all three trials is shown in @data-table. @graph-left shows a graph of the number of beetles in the left side of the choice chamber (containing plain Cheerios) for all three trials. @graph-right shows a graph of the number of beetles in the right side of the choice chamber (containing Honey Nut Cheerios) for all three trials.
#let data = csv("assets/animal-behavior/data.csv").slice(1)
#let totals = data.last()
#let data_non_totals = data.slice(0, 20)
#let data_raw = data_non_totals.map(row => {
let time = row.first()
let rest = row.slice(1).map(int)
let (minutes, seconds) = time.split(":")
let minutes = int(minutes)
let seconds = int(seconds)
(minutes * 60 + seconds, ..rest)
})
#figure(
caption: [Number of Beetles per Side of Choice Chamber],
table(
columns: (auto, 8%, 8%, 8%, 8%, 8%, 8%),
table.cell(rowspan: 2)[Time (m:s)],
table.cell(colspan: 2)[Trial 1],
table.cell(colspan: 2)[Trial 2],
table.cell(colspan: 2)[Trial 3],
..([Left], [Right]) * 3,
..data_non_totals.flatten(),
..totals.map(x => [*#x*])
),
) <data-table>
#figure(
caption: [Number of Beetles in the Left Chamber (plain Cheerios)],
cetz.canvas({
import cetz.plot
plot.plot(
size: (10, 8),
axis-style: "scientific-auto",
x-label: [Time (seconds)],
y-label: [],
y-min: 0,
y-max: 10,
y-tick-step: 1.0,
legend: "legend.north",
legend-style: (orientation: ltr, stroke: none, item: (spacing: 0.25)),
{
for i in (1, 3, 5) {
plot.add(
label: [Trial #{calc.ceil(i / 2)}],
data_raw.map(row => {
(row.at(0), row.at(i))
}),
)
}
},
)
}),
) <graph-left>
#figure(
caption: [Number of Beetles in the Right Chamber (<NAME>)],
cetz.canvas({
import cetz.plot
plot.plot(
size: (10, 8),
axis-style: "scientific-auto",
x-label: [Time (seconds)],
y-label: [],
y-min: 0,
y-max: 10,
y-tick-step: 1.0,
legend: "legend.north",
legend-style: (orientation: ltr, stroke: none, item: (spacing: 0.25)),
{
for i in (2, 4, 6) {
plot.add(
label: [Trial #{calc.ceil(i / 2)}],
data_raw.map(row => {
(row.at(0), row.at(i))
}),
)
}
},
)
}),
) <graph-right>
== Calculations
#let diff(o, e) = calc.pow(o - e, 2) / e
#let diffs = totals.slice(1).chunks(2).map(x => {
let (left, right) = x.map(int)
let left_diff = diff(left, 100)
let right_diff = diff(right, 100)
(
left: (val: left, diff: left_diff),
right: (val: right, diff: right_diff),
chi: left_diff + right_diff,
)
})
#let averages = {
let (left, right) = diffs
.fold(
(left: 0, right: 0),
(acc, cur) => {
(left: acc.left + cur.left.val, right: acc.right + cur.right.val)
},
)
.values()
.map(x => x / 3)
let left_diff = diff(left, 100)
let right_diff = diff(right, 100)
(
left: (val: left, diff: left_diff),
right: (val: right, diff: right_diff),
chi: left_diff + right_diff,
)
}
The result of the $chi^2$ test for each trial, as well as an average, is shown in @statistics. Given that this is a statistical experiment, the null and alternative hypotheses follow.
/ Null Hypothesis: When given the choice between plain Cheerios and Honey Nut Cheerios, there is no significant difference in the type of Cheerios that #species prefers.
/ Alternative Hypothesis: When given the choice between plain Cheerios and Honey Nut Cheerios, there is a significant difference in the number of #species that prefer Cheerios or Honey Nut Cheerios.
#figure(
caption: [$chi^2$ Calculations for Each Trial and Average],
table(
columns: 8,
table.cell(rowspan: 2)[Trial],
table.cell(colspan: 3)[Left (plain Cheerios)],
table.cell(colspan: 3)[Right (Honey Nut Cheerios)],
table.cell(rowspan: 2)[$ chi^2 $],
..(
[Observed],
[Expected],
[$ (o-e)^2 / e $],
) * 2,
..(
diffs.enumerate().map(((i, x)) => {
(
[Trial #{i+1}],
x.left.val,
100,
x.left.diff,
x.right.val,
100,
x.right.diff,
x.chi,
)
}).flatten().map(x => [#x])
),
[*Average*],
..{
(
averages.left.val,
100,
averages.left.diff,
averages.right.val,
100,
averages.right.diff,
averages.chi,
).map(x => [*#x*])
}
),
) <statistics>
The critical value for the $chi^2$test in this experiment is $3.84$. Since the average $chi^2$ test value is #averages.chi, and $0.5 < 3.84$, this experiment fails to reject its null hypothesis.
= QUESTIONS
There were no questions provided with this experiment.
= DISCUSSION
== Conclusions
This experiment failed to reject its null hypothesis, and thus does not support the original hypothesis. Since the $chi^2$ test showed no significant difference, #species does not have a preference for plain Cheerios or Honey Nut Cheerios. Their behavior appeared to exhibit no forms of taxis, merely kinesis or a lack of movement. This could be due to many different factors. One reason could be that #species are unable to feed off of Cheerios at all, since they generally feed on pure grain sources such as flour; however, Cheerios contains many non-grain ingredients, including vitamins and preservatives. Additionally, both plain Cheerios and Honey Nut Cheerios have a nearly-identical list of ingredients, differing only in sugar and honey content @CheeriosIngredients @HoneyNutCheeriosIngredients @BaldwinFasulo2010ConfusedFlourBeetles.
== Errors and Limitations
There were many potential sources of error throughout this experiment. One notable observation is that the #species population tended to exhibit little movement throughout trials, lacking kinesis. This is likely due to difficulty moving within the crushed Cheerios. Further experimentation should attempt to grind the Cheerios to a finer powder or ensure there is less present so as to not impede the movement of the #species population.
Additionally, the Cheerios were crushed by hand, and thus the distribution of crushed Cheerios was not perfectly fine---some chunks left were larger than others. Further experimentation should attempt to use a reproducible method to grind Cheerios, such as a blender, to ensure even and fine distribution of crushed Cheerios.
Finally, the choice chamber used had a center section free of the independent variable (see @mid-experiment). However, members of the population within this area were still counted as part of the side they were on, with the dividing line straight across the center of the chamber. This may have resulted in inconsistencies in the data, as the center did not have either Cheerios variant within it, and thus provides no insight into the preference of #species. Further experimentation should attempt to either minimize this uncertain area or properly account for it during statistical analysis.
== Applications
#species is infamous for infesting and destroying the storage of multiple different grain product. They can spread rapidly through a food source, and there are many strains with varying levels of adaptability and resistance to insecticides. Thus, understanding of the behavior of #species is economically important @Kavallieratos2020:BiologicFeaturesPopulationGrowthTwoSoutheas[pp.~1--2]. Experiments such as this help further develop understanding of the behavior of #species, and thus provide valuable insight into techniques to prevent their infestation. Additionally, a choice chamber is useful to study the behavior of many different species, such as the preferred water type of marine fishes @James2008:ChoiceRhabdosar.
|
https://github.com/chamik/gympl-skripta | https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-dila/16-audience.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/helper.typ": dilo, replika
#dilo("Audience", "audience", "<NAME>", "", "2. p. 20. st.", "ČSSR", "1975", "drama", "tragikomedie")
#columns(2, gutter: 1em)[
*Téma*\
absurdita socialismu
*Motivy*\
pivovar, intelektuálové $times$ burani, pracovní morálka, normalizace
*Časoprostor*\
\70. léta 20. st., ČSSR, sládkova kancelář
*Postavy*\
_(<NAME>_ -- spisovatel, inteligentní, musí pracovat v pivovaru, autorovo alter ego, ušlechtilý, spisovný jazyk\
_Sládek_ -- nadřízený Vaňka, jednoduchý buran, opilec\
zmíněni:\
herečka Jiřina "Bohdalka" Bohdalová,\
zpěvák <NAME>,\
spisovatel v exilu <NAME>
*Kompozice*\
jednoaktová, odděleno odchody Sládka na záchod
*Jazykové prostředky*\
opakování replik ("a nebuďte smutnej"), spisovná $times$ hovorová čeština, apoziopeze
#colbreak()
*Obsah*\
Levná kopie Čekání na Godota (@godot[]).
Spisovatel <NAME> musí za totality pracovat v pivovaru, kde válí sudy. Sládek chce Vaňka povýšit na skladníka, díky čemuž by i mohl psát své hry. Sládek pro StB píše zprávy o Vaňkovi, Vaněk by ale ve skladu musel sám na sebe donášet. Vaněk pochopí bezvýchodnost a absurditu situace, tak hru zakončí vyexováním piva a prohlášením "Je to všechno na hovno --".
Sládek během hry vypije spoustu piv.
*Literárně historický kontext*\
Normalizace = utužování síly komunistů. Postava <NAME> se objevuje v několika dílech od různých autorů. Na hru navazuje drama <NAME> -- Příjem. Hra nemohla vyjít, Havel měl zákaz, hrála se v zahraničí nebo potají.
]
#pagebreak()
*Ukázka*
#table(columns: 2, stroke: none,
..replika("Sládek", [A v tom skladu by to bylo přece taky dobrý, ne? Teplo -- fůra času --]),
..replika("Vaněk", [Bylo by to výborné --]),
..replika("", [_(Pauza)_]),
..replika("Sládek", [No -- tak o co teda jde?]),
..replika("", [_(Pauza)_]),
..replika("Vaněk", [Pane sládku --]),
..replika("Sládek", [Co je?]),
..replika("Vaněk", [Já jsem vám opravdu velmi vděčen za vše, co jste pro mne udělal -- vážím si toho, protože sám vím nejlíp, jak je takový postoj dnes vzácný -- vytrhl jste mi tak říkajíc trn z paty, protože já vážně nevím, co bych si bez vaší pomoci počal -- to místo ve skladu by pro mne znamenalo větší úlevu, než si možná myslíte -- jenomže já -- nezlobte se -- já přece nemůžu donášet sám na sebe --]),
..replika("Sládek", [Jaký donášení? Kdo tady mluví o donášení?]),
..replika("Vaněk", [Nejde o mě -- mně to uškodit nemůže -- ale jde přece o princip! Já se přece z principu nemůžu podílet na --]),
..replika("Sládek", [Na čem? No jen to řekni! Na čem se nemůžeš podílet?]),
..replika("Vaněk", [Na praxi, s kterou nesouhlasím --]),
..replika("", [_(Krátká, napjatá pauza)_]),
..replika("Sládek", [Hm. Tak nemůžeš. Ty teda nemůžeš. To je výborný! Teď ses teda vybarvil! Teď ses teda ukázal! _(Sládek vstane a začne rozčileně přecházet po místnosti)_ A co já? Mě v tom necháš, viď? Na mě se vykašleš! Já můžu bejt svině! Já se v tom bahně můžu patlat, na mně nezáleží, já jsem jen obyčejnej pivovarskej trouba -- ale pán, ten se podílet nemůže! Já se pošpinit můžu -- jen když pán zůstane čistej! Pánovi, tomu jde o princip! Ale co ostatní, na to už nemyslí! Jen když on je hezkej! Princip je mu milejší než člověk! To jste celí vy!]),
..replika("Vaněk", [Kdo my?]),
..replika("Sládek", [No vy! Inteligenti!]),
..replika("", [[...]]),
)
#pagebreak()
|
https://github.com/nimalu/mustermann-cv | https://raw.githubusercontent.com/nimalu/mustermann-cv/main/lib.typ | typst | #import "@preview/fontawesome:0.2.0": *
// const color
#let color-darknight = rgb("#131A28")
#let color-darkgray = rgb("#333333")
#let color-gray = rgb("#5d5d5d")
#let default-accent-color = rgb("#262F99")
// const icons
#let linkedin-icon = box(
fa-icon("linkedin", fill: color-darknight, font: "Font Awesome 6 Brands"),
)
#let github-icon = box(
fa-icon("github", fill: color-darknight, font: "Font Awesome 6 Brands"),
)
#let phone-icon = box(
fa-icon("phone", font: "Font Awesome 6 Free Solid")
)
#let email-icon = box(
fa-icon("envelope", fill: color-darknight),
)
#let github-link(github-path) = {
align(alignment.horizon)[
#fa-icon("github", font: "Font Awesome 6 Brands", fill: color-darkgray)
#link(
"https://github.com/" + github-path,
github-path,
)
]
}
#let resume(
author: (:),
language: "en",
accent-color: default-accent-color,
colored-headers: true,
date: datetime.today().display("[month repr:long] [day], [year]"),
body
) = {
if type(accent-color) == "string" {
accent-color = rgb(accent-color)
}
set document(
author: author.firstname + " " + author.lastname,
title: "resume",
)
set text(
font: ("Source Sans Pro", "source Sans 3"),
lang: language,
size: 11pt,
fill: color-darkgray,
fallback: true,
)
let bottom-margin = 25mm
let ratio = 2 / 3
let top-ratio = 3 / 5
set page(
paper: "a4",
margin: (left: bottom-margin * ratio, right: bottom-margin * ratio, top: bottom-margin * top-ratio, bottom: bottom-margin),
footer: [
#set text(
fill: gray,
size: 8pt,
)
#date
],
footer-descent: 0pt,
)
show par: set block(
above: 0.75em,
below: 0.5em,
)
set par(justify: true)
set heading(outlined: false)
show heading.where(level: 1): it => [
#set text(
size: 17pt,
weight: "bold",
)
#let color = if colored-headers {
accent-color
} else {
color-darkgray
}
#block(
above: 1.4em,
below: 1.0em
)[
#text(fill: color)[#it.body.text]
#box(width: 1fr, line(length: 100%, stroke: color-darkgray))
]
]
let name = {
align(center)[
#pad(bottom: 5pt)[
#block[
#set text(
size: 32pt,
style: "normal",
weight: "bold"
)
#text()[#author.firstname]
#text(fill: accent-color)[#author.lastname]
]
]
]
}
let address = {
align(center)[
#author.address
]
}
let contacts = {
let separator = box(width: 5pt)
align(center)[
#block[
#align(horizon)[
#if author.phone != none [
#phone-icon
#box[#text(author.phone)]
#separator
]
#if author.email != none [
#email-icon
#box[#link("mailto:" + author.email)[#author.email]]
]
#if author.github != none [
#separator
#github-icon
#box[#link("https://github.com/" + author.github)[#author.github]]
]
#if author.linkedin != none [
#separator
#linkedin-icon
#box[
#link("https://www.linkedin.com/in/" + author.linkedin)[#author.firstname #author.lastname]
]
]
]
]
]
}
name
address
contacts
body
}
#let resume-entry(
title: "",
location: none,
date: "",
description: "",
accent-color: default-accent-color,
) = {
block(below: 0.8em, above: 1.5em)[
#grid(
columns: (4fr, 1fr),
gutter: 6pt,
align: (alignment.left, alignment.right),
heading([
#if location != none {
title + text(weight: "regular", size: 11pt, ", " + location)
} else {
title
}
], level: 2),
date,
description
)
]
}
#let resume-item(body) = {
set text(
size: 10pt,
style: "normal",
weight: "light",
)
set par(leading: 0.50em)
body
}
|
|
https://github.com/arakur/typst-to-mathlog | https://raw.githubusercontent.com/arakur/typst-to-mathlog/master/README.md | markdown | MIT License | # Write Mathlog markup with Typst(WIP)
[Mathlog](https://mathlog.info/) のマークアップを [Typst](https://typst.app/) で書いて変換するツールです.
A tool to write [Mathlog](https://mathlog.info/) markup with [Typst](https://typst.app/).
## Example
Typst source:
```typst
// set mathlog style
#import "../style/mathlog_style.typ": *
//
= Gröbner 基底
== 単項式順序
$K$ を体,$R = K[X_1, ..., X_n]$ を $K$-上 $n$ 変数多項式環とする.
$R$ の単項式全体の集合を $cal(M)_R$ とおく.
$cal(M)_R$ は乗法に関して可換モノイドをなす.
#def(title: "単項式順序")[
多項式環 $R$ の *単項式順序* (_monomial order_) とは,$cal(M)_R$ 上の全順序 $prec.eq$ であって,任意の $mu, mu', nu in cal(M)_R$ に対して以下を満たすもののことである:
1. $1 prec.eq mu$;
2. $mu prec.eq mu' ==> mu dot nu prec.eq mu' dot nu$.
]
```
Mathlog result:
```mathlog
<!-- #import "../style/mathlog_style.typ": * -->
# Gröbner 基底
## 単項式順序
$K$を体,$R=K\left[X_{1},…,X_{n}\right]$を$K$-上$n$変数多項式環とする.$R$の単項式全体の集合を$\mathcal{M}_{R}$とおく.$\mathcal{M}_{R}$は乗法に関して可換モノイドをなす.
&&&def 単項式順序
多項式環$R$の**単項式順序**(*monomial order*) とは,$\mathcal{M}_{R}$上の全順序$≼$であって,任意の$\mu,\mu',\nu∈\mathcal{M}_{R}$に対して以下を満たすもののことである:
1. $1≼\mu$;
2. $\mu≼\mu'⟹\mu\cdot\nu≼\mu'\cdot\nu$.
&&&
```
## Usage
Install an asset on GitHub Releases(only for Windows) or build from source (requires cargo 1.70.0).
`style/mathlog_style.typ` is a style file for Mathlog-like environments and styles.
You can use it by
```typst
#import "style/mathlog_style.typ": *
```
in Typst source.
After you have written Typst source, then run `bin/typst-to-mathlog.exe` with the following arguments:
```sh
typst-to-mathlog <input> <output>
```
The directory `dictionary` includes a dictionary file `dictionary.json` to convert commands in Typst source to ones in TeX
`dictionary/dictionary_unicode.json` includes all characters which can be written in Typst, but it converts all to unicode characters.
`dictionary/dictionary_patch.json` is a patch file for this, which rewrite some commands into TeX native commands.
One can change the dictionary file by the following way:
1. rewrite `dictionary/dictionary_patch.json`,
2. run `make_dictionary.py`.
## TODO
- [ ] Support all environments
- [ ] Support links
- [ ] Support labels/refs
- [ ] Support tables
- [ ] Support images
- [ ] Support all math commands
## License
MIT License
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/align_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test that multiple paragraphs in subflow also respect alignment.
#align(center)[
Lorem Ipsum
Dolor
]
|
https://github.com/8LWXpg/jupyter2typst | https://raw.githubusercontent.com/8LWXpg/jupyter2typst/master/template/base.typ | typst | MIT License | // #import "template.typ": *
#show: template
#block[
= Jupyter Notebook files
#lorem(50)
== Markdown content
#lorem(50)
]
#block[
#code-block("import pandas as pd
pd.DataFrame([['hi', 'there'], ['this', 'is'], ['a', 'DataFrame']], columns=['Word A', 'Word B'])"
, lang: "python", count: 6)
]
#block[
#result-block(" Word A Word B
0 hi there
1 this is
2 a DataFrame")
]
#block[
#result-block("[1;31m---------------------------------------------------------------------------[0m
[1;31mNameError[0m Traceback (most recent call last)
Cell [1;32mIn[9], line 1[0m
[1;32m----> 1[0m this_will_error
[1;31mNameError[0m: name 'this_will_error' is not defined")
]
|
https://github.com/Arsenii324/matap-p2 | https://raw.githubusercontent.com/Arsenii324/matap-p2/main/t-repo/template.typ | typst | // The project function defines how your document looks.
// It takes your content and some metadata and formats it.
// Go ahead and customize it to your liking!
#let project(title: "", authors: (), body) = {
// Set the document's basic properties.
set document(author: authors.map(a => a.name), title: title)
set page(numbering: "1", number-align: center)
set text(font: "Linux Libertine", lang: "ru")
set heading(numbering: "1.1")
// Set run-in subheadings, starting at level 3.
show heading: it => {
if it.level > 2 {
parbreak()
underline(text(12pt, style: "italic", fill: red, weight: 500, it.body + "."))
} else {
it
}
}
// Title row.
align(center)[
#block(text(weight: 700, 1.75em, title))
]
// Author information.
pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center)[
*#author.name* \
#author.affiliation
]),
),
)
// Main body.
set par(justify: true)
body
}
// макросы
#let sumin(x) = $limits(sum)_(i = x)^n$
#let sumii(x) = $limits(sum)_(i = x)^infinity$ |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-A6A0.typ | typst | Apache License 2.0 | #let data = (
("BAMUM LETTER A", "Lo", 0),
("BAMUM LETTER KA", "Lo", 0),
("BAMUM LETTER U", "Lo", 0),
("BAMUM LETTER KU", "Lo", 0),
("BAMUM LETTER EE", "Lo", 0),
("BAMUM LETTER REE", "Lo", 0),
("BAMUM LETTER TAE", "Lo", 0),
("BAMUM LETTER O", "Lo", 0),
("BAMUM LETTER NYI", "Lo", 0),
("BAMUM LETTER I", "Lo", 0),
("BAMUM LETTER LA", "Lo", 0),
("BAMUM LETTER PA", "Lo", 0),
("BAMUM LETTER RII", "Lo", 0),
("BAMUM LETTER RIEE", "Lo", 0),
("BAMUM LETTER LEEEE", "Lo", 0),
("BAMUM LETTER MEEEE", "Lo", 0),
("BAMUM LETTER TAA", "Lo", 0),
("BAMUM LETTER NDAA", "Lo", 0),
("BAMUM LETTER NJAEM", "Lo", 0),
("BAMUM LETTER M", "Lo", 0),
("BAMUM LETTER SUU", "Lo", 0),
("BAMUM LETTER MU", "Lo", 0),
("BAMUM LETTER SHII", "Lo", 0),
("BAMUM LETTER SI", "Lo", 0),
("BAMUM LETTER SHEUX", "Lo", 0),
("BAMUM LETTER SEUX", "Lo", 0),
("BAMUM LETTER KYEE", "Lo", 0),
("BAMUM LETTER KET", "Lo", 0),
("BAMUM LETTER NUAE", "Lo", 0),
("BAMUM LETTER NU", "Lo", 0),
("BAMUM LETTER NJUAE", "Lo", 0),
("BAMUM LETTER YOQ", "Lo", 0),
("BAMUM LETTER SHU", "Lo", 0),
("BAMUM LETTER YUQ", "Lo", 0),
("BAMUM LETTER YA", "Lo", 0),
("BAMUM LETTER NSHA", "Lo", 0),
("BAMUM LETTER KEUX", "Lo", 0),
("BAMUM LETTER PEUX", "Lo", 0),
("BAMUM LETTER NJEE", "Lo", 0),
("BAMUM LETTER NTEE", "Lo", 0),
("BAMUM LETTER PUE", "Lo", 0),
("BAMUM LETTER WUE", "Lo", 0),
("BAMUM LETTER PEE", "Lo", 0),
("BAMUM LETTER FEE", "Lo", 0),
("BAMUM LETTER RU", "Lo", 0),
("BAMUM LETTER LU", "Lo", 0),
("BAMUM LETTER MI", "Lo", 0),
("BAMUM LETTER NI", "Lo", 0),
("BAMUM LETTER REUX", "Lo", 0),
("BAMUM LETTER RAE", "Lo", 0),
("BAMUM LETTER KEN", "Lo", 0),
("BAMUM LETTER NGKWAEN", "Lo", 0),
("BAMUM LETTER NGGA", "Lo", 0),
("BAMUM LETTER NGA", "Lo", 0),
("BAMUM LETTER SHO", "Lo", 0),
("BAMUM LETTER PUAE", "Lo", 0),
("BAMUM LETTER FU", "Lo", 0),
("BAMUM LETTER FOM", "Lo", 0),
("BAMUM LETTER WA", "Lo", 0),
("BAMUM LETTER NA", "Lo", 0),
("BAMUM LETTER LI", "Lo", 0),
("BAMUM LETTER PI", "Lo", 0),
("BAMUM LETTER LOQ", "Lo", 0),
("BAMUM LETTER KO", "Lo", 0),
("BAMUM LETTER MBEN", "Lo", 0),
("BAMUM LETTER REN", "Lo", 0),
("BAMUM LETTER MEN", "Lo", 0),
("BAMUM LETTER MA", "Lo", 0),
("BAMUM LETTER TI", "Lo", 0),
("BAMUM LETTER KI", "Lo", 0),
("BAMUM LETTER MO", "Nl", 0),
("BAMUM LETTER MBAA", "Nl", 0),
("BAMUM LETTER TET", "Nl", 0),
("BAMUM LETTER KPA", "Nl", 0),
("BAMUM LETTER TEN", "Nl", 0),
("BAMUM LETTER NTUU", "Nl", 0),
("BAMUM LETTER SAMBA", "Nl", 0),
("BAMUM LETTER FAAMAE", "Nl", 0),
("BAMUM LETTER KOVUU", "Nl", 0),
("BAMUM LETTER KOGHOM", "Nl", 0),
("BAMUM COMBINING MARK KOQNDON", "Mn", 230),
("BAMUM COMBINING MARK TUKWENTIS", "Mn", 230),
("BAMUM NJAEMLI", "Po", 0),
("BAMUM FULL STOP", "Po", 0),
("BAMUM COLON", "Po", 0),
("BAMUM COMMA", "Po", 0),
("BAMUM SEMICOLON", "Po", 0),
("BAMUM QUESTION MARK", "Po", 0),
)
|
https://github.com/HPDell/typst-mathshortcuts | https://raw.githubusercontent.com/HPDell/typst-mathshortcuts/main/lib.typ | typst | /**
* Shortcuts for Math
*
* Author: <NAME>
*/
#let va = $bold(a)$
#let vb = $bold(b)$
#let vc = $bold(c)$
#let vd = $bold(d)$
#let ve = $bold(e)$
#let vf = $bold(f)$
#let vg = $bold(g)$
#let vh = $bold(h)$
#let vi = $bold(i)$
#let vj = $bold(j)$
#let vk = $bold(k)$
#let vl = $bold(l)$
#let vm = $bold(m)$
#let vn = $bold(n)$
#let vo = $bold(o)$
#let vp = $bold(p)$
#let vq = $bold(q)$
#let vr = $bold(r)$
#let vs = $bold(s)$
#let vt = $bold(t)$
#let vu = $bold(u)$
#let vv = $bold(v)$
#let vw = $bold(w)$
#let vx = $bold(x)$
#let vy = $bold(y)$
#let vz = $bold(z)$
#let vA = $bold(A)$
#let vB = $bold(B)$
#let vC = $bold(C)$
#let vD = $bold(D)$
#let vE = $bold(E)$
#let vF = $bold(F)$
#let vG = $bold(G)$
#let vH = $bold(H)$
#let vI = $bold(I)$
#let vJ = $bold(J)$
#let vK = $bold(K)$
#let vL = $bold(L)$
#let vM = $bold(M)$
#let vN = $bold(N)$
#let vO = $bold(O)$
#let vP = $bold(P)$
#let vQ = $bold(Q)$
#let vR = $bold(R)$
#let vS = $bold(S)$
#let vT = $bold(T)$
#let vU = $bold(U)$
#let vV = $bold(V)$
#let vW = $bold(W)$
#let vX = $bold(X)$
#let vY = $bold(Y)$
#let vZ = $bold(Z)$
#let valpha = $bold(alpha)$
#let vbeta = $bold(beta)$
#let vchi = $bold(chi)$
#let vdelta = $bold(delta)$
#let vepsilon = $bold(epsilon)$
#let veta = $bold(eta)$
#let vgamma = $bold(gamma)$
#let viota = $bold(iota)$
#let vkappa = $bold(kappa)$
#let vlambda = $bold(lambda)$
#let vmu = $bold(mu)$
#let vomega = $bold(omega)$
#let vphi = $bold(phi)$
#let vpi = $bold(pi)$
#let vpsi = $bold(psi)$
#let vrho = $bold(rho)$
#let vsigma = $bold(sigma)$
#let vtau = $bold(tau)$
#let vtheta = $bold(theta)$
#let vupsilon = $bold(upsilon)$
#let vxi = $bold(xi)$
#let vzeta = $bold(zeta)$
#let vDelta = $bold(Delta)$
#let vGamma = $bold(Gamma)$
#let vLambda = $bold(Lambda)$
#let vOmega = $bold(Omega)$
#let vPhi = $bold(Phi)$
#let vPi = $bold(Pi)$
#let vPsi = $bold(Psi)$
#let vSigma = $bold(Sigma)$
#let vTheta = $bold(Theta)$
#let vUpsilon = $bold(Upsilon)$
#let vXi = $bold(Xi)$
#let vzero = $bold(0)$
#let vones = $bold(1)$
#let mT = $upright(T)$
#let mI = $-1$
#let mIG = $dash$
#let var = $op("var")$
#let cov = $op("cov")$
/// Write diagnostic statistics
///
/// - mark (any): The statistic's symbol
/// - label (content): An additional label attached to the symbol
/// - value (none, numbering): An optional value. If none, hide the equal sign; otherwise show the equal sign and the value.
#let diagnostic(mark, label: [], value: none) = {
if value == none [
$attach(#mark, br: text(label))$
] else [
$attach(#mark, br: text(label))=#value$
]
}
/// R squared
///
/// - value (none, numbering): An optional value.
///
/// *Example:*
///
/// - #msc.rsquare()
/// - #msc.rsquare(value: 0.8)
#let rsquare(value: none) = diagnostic($R^2$, value: value)
|
|
https://github.com/dainbow/MatGos | https://raw.githubusercontent.com/dainbow/MatGos/master/themes/8.typ | typst | #import "../conf.typ": *
= Достаточные условия дифференцируемости функции нескольких переменных
#definition[
Пусть $f$ определена в некоторой окрестности $x_0 in RR^n$. *Полным приращением* $f$ в
точке $x_0$ называется
#eq[
$Delta f(x_0) = f(x_0 + Delta x) - f(x_0) = f(x_(0, 1) + Delta x_1, ..., x_(0, n) + Delta x_n) - f(x_(0, 1), ..., x_(0, n))$
]
$f$ называется *дифференцируемой* в $x_0$, если
#eq[
$Delta f(x_0) = (A, Delta x) + o(norm(Delta x)), Delta x -> 0$
]
где $A in RR^n$ называется *градиентом*: $"grad" f(x_0) = A$
]
#definition[
*Дифференциалом* дифференцируемой в $x_0$ функции $f$ назовём выражение $(A, Delta x)$ из
определения дифференцируемости.
]
#definition[
*Частной производной* в точке $x_0$ называется предел (если он существует):
#eq[
$(partial f) / (partial x_j) (x_0) = lim_(Delta x -> 0) (f(x_(0, 1), ..., x_(0, j) + Delta x, ..., x_(0, n)) - f(x_(0, 1), ..., x_(0, j), ..., x_(0, n))) / (Delta x)$
]
]
#theorem(
"Необходимое условие дифференцируемости",
)[
Если $f$ дифференцируема в точке $x_0 in RR$, то существуют частные производные $forall j = overline("1,n")$,
причём
#eq[
$"grad" f(x) = ((partial f) / (partial x_1) (x_0), ..., (partial f) / (partial x_n) (x_0))$
]
]
#proof[
Сразу следует из определения - есть предел по всем многомерным приращениям, а
значит и по однокоординатным в том числе.
]
#theorem(
"Достаточное условие дифференцируемости",
)[
Если $f$ определена в некоторой окрестности точки $x_0$, вместе со своими
частными производными, причём они непрерывны в $x_0$, то $f$ дифференцируема в $x_0$.
]
#proof[
Воспользуемся $n$ раз "умным нулём", каждый из которых будет "снимать"
приращение по одной из координат:
#eq[
$Delta f(x_0) = \
f(x_(0, 1) + Delta x_1, ..., x_(0, n) + Delta x_n) - f(x_(0, 1) + Delta x_1, ..., x_(0, n - 1) + Delta x_(n - 1), x_(0, n)) + \
f(x_(0, 1) + Delta x_1, ..., x_(0, n - 1) + Delta x_(n - 1), x_(0, n)) -
f(x_(0, 1) + Delta x_1, ..., x_(0, n - 1), x_(0, n)) \ + ... +\
f(x_(0, 1) + Delta x_1, x_(0, 2), ..., x_(0, n)) - f(x_(0, 1), ..., x_(0,n )) attach(=, t: "<NAME>") \
(partial f) / (partial x_n) (x_(0, 1) + Delta x_1, ..., x_(0, n - 1) + Delta x_(n - 1), xi_n) Delta x_n + \
(partial f) / (partial x_(n - 1)) (x_(0, 1) + Delta x_1, ..., x_(0, n - 2) + Delta x_(n - 2), xi_(n - 1), x_(0, n))Delta x_(n - 1) \
+ ... + \
+ (partial f) / (partial x_1) (xi_1, x_(0, 2), ..., x_(0, n)) Delta x_1 attach(=, t: Delta x -> 0 => forall n : xi_n -> 0) \
sum_(i = 1)^n (partial f) / (partial x_i)(x_0) Delta x_i + o(norm(Delta x)), Delta x -> 0$
]
]
|
|
https://github.com/binhtran432k/ungrammar-docs | https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/system-implementation/service.typ | typst | === Ungrammar Language Service <subsec-impl-langservice>
The Ungrammar Language Service serves as the foundational module of our system.
Its independence from external dependencies ensures a focused implementation of
core Ungrammar language logic. This modular approach offers several key
advantages:
- *Centralized Logic*: All core language features, including parsing, semantic
analysis, and code generation, are encapsulated within this module, promoting
a well-organized and maintainable codebase.
- *Dependency Isolation*: The Language Service's independence from other
modules minimizes potential conflicts and simplifies testing and maintenance.
- *Reusability*: The Language Service can potentially be reused in other
projects or applications, demonstrating its versatility and value.
Integration with Other Components:
- *Language Server (@subsec-impl-langserver)*: The Language Server module acts as a
communication bridge between the Language Service and code editors, enabling
seamless integration and feature access.
- *VS Code Extension*: The VS Code extension leverages the Language
Service to provide LSP features within the VS Code environment, enhancing the
user experience.
- *Monaco Editor Integration (@subsec-impl-monaco)*: The Monaco editor can directly
interact with the Language Service, accessing its capabilities without the
need for a separate Language Server module.
==== CST to AST Transpiler
A key differentiator of our LSP ecosystem is its innovative approach to
converting Concrete Syntax Trees (CSTs) to Abstract Syntax Trees (ASTs) using
the Ungrammar language. This transformation is crucial for enabling effective
analysis and manipulation of the parsed code.
We've developed a script that utilizes the Ungrammar parser to implement a
CST-to-AST translator. By employing the Visitor design pattern, we've ensured
that the generated AST is robust, modular, and maintainable. Each node within
the AST is treated as an acceptor, allowing for flexible and extensible
traversal; and analysis.
This approach effectively decouples the LSP's core logic from the AST
structure, promoting better code organization and maintainability. By
separating concerns, we've made it easier to modify and extend the LSP's
functionality without affecting the underlying AST representation.
#[
#show figure: set block(breakable: true)
#set raw(block: true)
#figure(
raw(read("/assets/ungrammar.ungram")),
caption: [Ungrammar file of Ungrammar for Translator],
)
#figure(
raw(read("/assets/generated.ts"), lang: "ts"),
caption: [Generated AST (with hidden sections for clarity) totaling 439 lines of code],
)
]
==== Implementing LSP Core Services
To enhance the structure and maintainability of our Language Service module,
we've strategically divided it into multiple submodules. This modular approach
leverages the power of the Abstract Syntax Tree (AST) generated by our parser
to organize and manage different aspects of language analysis and support.
#figure(
raw(read("/assets/tree-service.txt"), block: true),
caption: [Tree of Ungrammar Language Service workspace],
)
==== Deployment to NPM
Upon completion of development, we successfully deployed the Ungrammar Language
Service to the NPM registry. This strategic move allows other developers to
easily discover, integrate, and extend our project for their own
language-related endeavors. By making the Language Service readily available on
NPM, we've expanded the accessibility and potential impact of our work within
the developer community.
Here is our deployed Ungrammar Language Service, which has been downloaded by
187 users since its public release and is currently hosted at
#link("https://www.npmjs.com/package/ungrammar-languageservice").
#figure(
image("/assets/service.jpg", width: 90%),
caption: [Deployed Ungrammar Language Service on NPM],
)
|
|
https://github.com/touying-typ/touying | https://raw.githubusercontent.com/touying-typ/touying/main/lib.typ | typst | MIT License | #import "src/exports.typ": *
#import "themes/themes.typ" |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/050_Phyrexia%3A%20All%20Will%20Be%20One.typ | typst | #import "@local/mtgset:0.1.0": conf
#show: doc => conf("Phyrexia: All Will Be One", doc)
#include "./050 - Phyrexia: All Will Be One/001_Cinders.typ"
#include "./050 - Phyrexia: All Will Be One/002_A Hollow Body.typ"
#include "./050 - Phyrexia: All Will Be One/003_Episode 1: Uncontrolled Descent.typ"
#include "./050 - Phyrexia: All Will Be One/004_Episode 2: Unstable Foundations.typ"
#include "./050 - Phyrexia: All Will Be One/005_Episode 3: Inconceivable Losses.typ"
#include "./050 - Phyrexia: All Will Be One/006_Hard as Anger, Bright as Joy.typ"
#include "./050 - Phyrexia: All Will Be One/007_Episode 4: Impossible Odds.typ"
#include "./050 - Phyrexia: All Will Be One/008_Episode 5: Inevitable Resolutions.typ"
#include "./050 - Phyrexia: All Will Be One/009_A Man of Parts.typ"
#include "./050 - Phyrexia: All Will Be One/010_Alone.typ"
|
|
https://github.com/pimm-dev/agreement-about-religion | https://raw.githubusercontent.com/pimm-dev/agreement-about-religion/main/typst/README.md | markdown | # ./typst
Typst sources are built by [`/build.sh`](../build.sh)
## Change Name of Lead Manager
Adjust parameter `lead_manager` in [`main.typ`](./main.typ) line 1.
## When Make New Revision and Release
Change page heading `종교에 관한 서약서, r1.1, 좌측` and `종교에 관한 서약서, r1.1, 우측` to new numbering of revision.
## Requirements
- typst
- pandoc
|
|
https://github.com/tingerrr/hydra | https://raw.githubusercontent.com/tingerrr/hydra/main/tests/features/fallback/test.typ | typst | MIT License | // Synopsis:
// - when a page starts with a primary element it is displayed
#import "/src/lib.typ": hydra
#set page(paper: "a7", header: context hydra(skip-starting: false, 2))
#set heading(numbering: "1.1")
#show heading.where(level: 1): it => pagebreak(weak: true) + it
#set par(justify: true)
= Content
== First Section
#lorem(150)
== Second Section
#lorem(50)
= Second Chapter
== Another Section
#lorem(10)
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/pagebreak-set-style.typ | typst | Apache License 2.0 | // https://github.com/typst/typst/issues/2162
// The styles should not be applied to the pagebreak empty page,
// it should only be applied after that.
#pagebreak(to: "even") // We should now skip to page 2
Some text on page 2
#pagebreak(to: "even") // We should now skip to page 4
#set page(fill: orange) // This sets the color of the page starting from page 4
Some text on page 4
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/prob/homeworks/to-2024-10-07.typ | typst | = ДЗ 4
== Задача 64
$H_i (i = 0, 1, 2)$ --- в первой двойке мячей игранных было $i$
$A$ --- во второй двойке мячей игранных было 0.
$ P(H_0) = 12/20 dot 11/19 = 0.347 $
$ P(H_1) = 12/20 dot 8/19 + 8/20 dot 12/19 = 0.505 $
$ P(H_2) = 8/20 dot 7/19 = 0.147 $
$ P(A | H_0) = 10/20 dot 9/19 = 0.237 $
$ P(A | H_1) = 11/20 dot 10/19 = 0.289 $
$ P(A | H_2) = 12/20 dot 11/19 = 0.347 $
$ P(A) = P(A | H_0) P(H_0) + P(A | H_1) P(H_1) + P(A | H_2) P(H_2) = 0.279 $
$ P(H_0 | A) = (P(H_0) P(A | H_0))/(P(A)) = 0.295 $
== Задача 65
$H_i (i = 1, 2, 3)$ --- телевизор был из $i$-ой фирмы
$A$ --- телевизор требует ремонта
$ P(H_1) = 0.1 $
$ P(H_2) = 0.3 $
$ P(H_3) = 0.6 $
$ P(A | H_1) = 0.15 $
$ P(A | H_2) = 0.10 $
$ P(A | H_3) = 0.07 $
$ P(A H_1) = P(A | H_1) P(H_1) = 0.015 $
$ P(A H_2) = P(A | H_2) P(H_2) = 0.03 $
$ P(A H_3) = P(A | H_3) P(H_3) = 0.042 $
$ P(A) = P(A H_1) + P(A H_2) + P(A H_3) = 0.087 $
$ P(H_1 | A) = P(A H_1) / P(A) = 0.172 $
$ P(H_2 | A) = P(A H_2) / P(A) = 0.345 $
$ P(H_3 | A) = P(A H_3) / P(A) = 0.483 $
$ P(H_1 | A) < P(H_2 | A) < P(H_3 | A) $
Ответ. В третью фирму (потом во вторую, потом в третью)
== Задача 72
Нас интересуют только детали, имеющие дефект. Далее рассматриваем только их.
$H_i (i = 1, 2)$ --- деталь проверял $i$-ый контролер
$A$ --- дефект был обнаружен
$ P(H_1) = P(H_2) = 1/2 $
$ P(A | H_1) = p_1 $
$ P(A | H_2) = p_2 $
$ P(A H_1) = P(A | H_1) P(H_1) = 1/2 p_1 $
$ P(A H_2) = P(A | H_2) P(H_2) = 1/2 p_2 $
$ P(A) = P(A H_1) + P(A H_2) = (p_1 + p_2) / 2 $
$ P(H_1 | A) = P(A H_1) / P(A) = p_1 / (p_1 + p_2) $
$ P(H_2 | A) = P(A H_2) / P(A) = p_2 / (p_1 + p_2) $
Ответ. а) $p_1 / (p_1 + p_2)$, б) $p_2 / (p_1 + p_2)$
== Задача 73
Нужно, чтобы студент
- либо знал два случайно выбранных билета
$P_1 = 15/20 dot 14/19$
- либо знал первых билет, не знал второй и знал ещё один случайный
$P_2 = 15/20 dot 5/19 dot 14/18$
- либо не знал первых билет, знал второй и знал ещё один случайный
$P_3 = 5/20 dot 15/19 dot 14/18$
$ P = P_1 + P_2 + P_3 = 0.8596 $
== Задача 77
Карандаш имеет сломанный грифель, если он из "плохой" коробки.
Таких коробок 4 из 20-ти.
$ P = 4/20 = 0.2 $
== Задача 78
$H_i (i = 1, 2)$ --- 13-ую страницу писала $i$-ая машинистка
$A$ --- на 13-ой странице есть опечатка
$ P(H_1) = 1/3 $
$ P(H_2) = 2/3 $
$ P(A | H_1) = 0.15 $
$ P(A | H_2) = 0.1 $
$ P(A H_1) = P(H_1) P(A | H_1) = 1/20 $
$ P(A H_2) = P(H_2) P(A | H_2) = 1/15 $
$ P(A) = P(A H_1) + P(A H_2) = 7/60 $
$ P(H_1 | A) = P(A H_1) / P(A) = (1/20) / (7/60) = 3/7 $
$ P(H_2 | A) = P(A H_2) / P(A) = (1/15) / (7/60) = 4/7 $
Ответ. $P(H_1 | A) = 3/7$
== Задача 79
$H_i (i = 1,2,3)$ --- пассажир пошел в $i$-ую кассу
$A$ --- в кассе *остались* билеты
$ P(H_1) = 1/3 $
$ P(H_2) = 1/6 $
$ P(H_3) = 1/2 $
$ P(A | H_1) = 1 - 3/4 = 1/4 $
$ P(A | H_2) = 1 - 1/2 = 1/2 $
$ P(A | H_3) = 1 - 2/3 = 1/3 $
$ P(A H_1) = P(H_1) P(A | H_1) = 1/12 $
$ P(A H_2) = P(H_2) P(A | H_2) = 1/12 $
$ P(A H_3) = P(H_3) P(A | H_3) = 1/6 $
$ P(A) = P(A H_1) + P(A H_2) + P(A H_3) = 1/3 $
$ P(H_1 | A) = P(A H_1) / P(A) = 1/4 $
Ответ. $P(H_1 | A) = 1/4$
== Задача 80
$H_1$ --- студент подготовлен *отлично* (знает $20/20$ вопросов)
$H_2$ --- студент подготовлен *хорошо* (знает $16/20$ вопросов)
$H_3$ --- студент подготовлен *удовлетворительно* (знает $10/20$ вопросов)
$H_4$ --- студент подготовлен *плохо* (знает $5/20$ вопросов)
$A$ --- студент ответил на все три вопроса
$ P(H_1) = 3/10 $
$ P(H_2) = 4/10 $
$ P(H_3) = 2/10 $
$ P(H_4) = 1/10 $
$ P(A | H_1) = 1 $
$ P(A | H_2) = 16/20 dot 15/19 dot 14/18 = 28/57 $
$ P(A | H_3) = 10/20 dot 9/19 dot 8/18 = 2/19 $
$ P(A | H_4) = 5/20 dot 4/19 dot 3/18 = 1/114 $
$ P(A H_1) = P(H_1) P(A | H_1) = 3/10 $
$ P(A H_2) = P(H_2) P(A | H_2) = 56/285 $
$ P(A H_3) = P(H_3) P(A | H_3) = 2/95 $
$ P(A H_4) = P(H_4) P(A | H_4) = 1/1140 $
$ P(A) = P(A H_1) + P(A H_2) + P(A H_3) + P(A H_4) = 197/380 $
$ P(H_1 | A) = P(A H_1) / P(A) = 114/197 = 0.57868 $
$ P(H_4 | A) = P(A H_4) / P(A) = 1/591 = 0.00169 $
Ответ. а) $P(H_1 | A) = 0.57868$ б) $P(H_4 | A) = 0.00169$
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/spacing_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test spacing for set comprehension.
#set page(width: auto)
$ { x in RR | x "is natural" and x < 10 } $
|
https://github.com/YDX-2147483647/herglotz | https://raw.githubusercontent.com/YDX-2147483647/herglotz/main/foreword/typst.md | markdown | # Typst
- 用[Typst][typst]编译非常快,常常快到以为没编译——切换窗口前就编译好了。初次编译`*.typ`都远快于一般`*.tex`增量编译,通常也比[从 *.md 生成的网页][mkdocs-serve]更新快。
- Typst的语法比LaTeX简洁。在数学公式中,“↦”就是`|->`(竖线、连字符、大于号),结合字体提供的连字,几乎所见即所得,比`\mapsto`清晰不少。
- [Typst嵌入了平易的脚本语言和“标准库”][typst-scripting],能弥补个人局部需求与公共通用功能间的空隙。LaTeX虽能力更强,但那种`\expandafter`或[`\tl_if_empty:nTF`][latex3]也不是随时就能写的。
- 调试`*.typ`也容易一些。安装环境简单,报错信息精确,文档集中统一且示例丰富,作用域清晰可隔离,编译快从而测试快,缓存透明而能忽略,……如果没有这些,真请来Hercule Poirot也要费一番功夫。
Typst还在频繁变化。例如前几月还改了词法分析器,来让汉字间的语法更简洁。
不过Typst似乎没有CTeX那样的工作组,中文排版能力不足。目前最大的问题是[无法生成伪粗体][typst/typst#394],只支持给设计了多种字重的字体加粗;而汉字太多,大部分既有字体都没设计。
另外有人宣传Typst学习成本低,这也许只是掩盖问题。排版固有的困难什么方法都绕不开。
[typst]: https://typst.app/ "Typst: Compose papers faster"
[latex3]: https://www.alanshawn.com/tech/2020/10/04/latex3-tutorial.html "LaTeX3: Programming in LaTeX with Ease | <NAME>’s Blog"
[mkdocs-serve]: https://www.mkdocs.org/user-guide/cli/#mkdocs-serve "mkdocs serve - Command Line Interface - MkDocs"
[typst-scripting]: https://typst.app/docs/reference/scripting/ "Scripting – Typst Documentation"
[typst/typst#394]: https://github.com/typst/typst/issues/394 "Fake text weight and style (synthesized bold and italic) · Issue #394 · typst/typst"
|
|
https://github.com/atareao/fondos-productivos | https://raw.githubusercontent.com/atareao/fondos-productivos/master/src/bash.typ | typst | MIT License | #import "@preview/fletcher:0.4.5" as fletcher: diagram, node, edge
#set page(
"presentation-16-9",
fill: black,
margin: 0.5cm)
#set text(size: 13pt, fill: white)
= Bash
#columns(3, gutter: 12pt)[
== Trabajando con procesos
#table(
columns: (1fr, 5fr),
gutter: -4pt,
`Ctrl+C`, "Mata un proceso",
`Ctlr+Z`, "Suspende un proceso",
`Ctlr+D`, "Cierra la shell",
)
== Controlando la pantalla
#table(
columns: (1fr, 5fr),
gutter: -4pt,
`Ctrl+L`, "Limpia la pantalla",
`Ctrl+S`, "Deja de pintar en pantalla",
`Ctrl+Q`, "Vuelve a pintar en pantalla",
)
== Moviendo el cursor
#table(
columns: (1fr, 5fr),
gutter: -4pt,
`Ctrl+A`, "Al inicio de la línea",
`Ctrl+E`, "Al final de la línea",
`Alt+B`, "A la izquierda de una palabra",
`Ctrl+B`, "A la izquierda un carácter",
`Alt+F`, "A la derecha una palabra",
`Ctrl+F`, "A la derecha un carácter",
`Ctrl+XX`, "Del principio al final y al revés",
)
== Borrando texto
#table(
columns: (1fr, 5fr),
gutter: -4pt,
`Ctrl+D`, "Al inicio de la línea",
`Alt+D`, "Al inicio de la línea",
`Ctrl+H`, "Al final de la línea",
`Ctrl+W`, "A la izquierda un carácter",
`Alt+F`, "A la derecha una palabra",
`Ctrl+F`, "A la derecha un carácter",
`Ctrl+XX`, "Del principio al final y al revés",
)
== Mayúsculas y minúsculas
#table(
columns: (1fr, 5fr),
gutter: -4pt,
`Alt+U`, "Mayúsculas hasta el final de la palabra",
`Alt+L`, "Minúsculas hasta el final de la palabra",
`Alt+C`, "Mayúsculas para el carácter",
)
== Errores
#table(
columns: (1fr, 5fr),
gutter: -4pt,
`Alt+T`, "Intercambia la palabra con la anterior",
`Ctrl+T`, "Intercambia dos caracteres",
`Ctrl+_`, "Deshacer",
)
== Movimientos
#set text(12pt)
#diagram(
node-stroke: 3pt,
edge-stroke: white + 1pt,
spacing: 0pt,
node((0, 0), `$`),
node((1, 0), ``),
node((2, 0), `rm`),
node((3, 0), ``),
node((4, 0), `file1.txt`),
node((5,0), `|`),
node((6,0), `file2.txt`),
node((7, 0), ``),
node((8,0), `file3.txt`),
node((9,0), ``),
edge((5,0), (9,0), `Ctrl+E`, "-|>", bend: 90deg),
edge((5,0), (7,0), `Alt+F`, "-|>", bend: 90deg),
edge((5,0), (1,0), `Ctrl+A`, "-|>", bend: -100deg),
edge((5,0), (3,0), `Alt+B`, "-|>", bend: -80deg),
)
== Autocompletado
#table(
columns: (1fr, 5fr),
gutter: -4pt,
`tab`, "Autocompleta",
)
== Historial
#table(
columns: (1fr, 5fr),
gutter: -4pt,
`Ctrl+P`, "Comando anterior",
`Ctrl+N`, "Comando siguiente",
`Ctrl+R`, "Busca comandos anteriores",
`Ctrl+O`, "Ejecuta el comando encontrado",
`Ctrl+G`, "Abandona la búsqueda",
`Alt+R`, "Revierte cambios editados",
`!!`, "Repite el último comando",
`!*`, "Repite solo los árgumentos",
`history`, "Mueltra la historia",
)
== Atajos de teclado
#table(
columns: (1fr, 4fr),
gutter: -4pt,
`bind -p`, "Muestra los atajos de teclado",
)
== Copiar y pegar
#table(
columns: (1fr, 2fr),
gutter: -5pt,
`Ctrl+Shift+C`, "Copia la selección",
`Ctrl+Shift+P`, "Pega",
)
]
|
https://github.com/mizlan/typst-resume-sans | https://raw.githubusercontent.com/mizlan/typst-resume-sans/main/resume.typ | typst | #set text(font: "Inter", fill: rgb("#222222"), hyphenate: false)
#show heading: set text(font: "General Sans", tracking: 1em/23)
#show link: underline
#set page(
margin: (x: 1.1cm, y: 1.3cm),
)
#set par(justify: true)
#let chiline() = {v(-2pt); line(length: 100%, stroke: rgb("#777777")); v(-5pt)}
#text(15pt)[= BELLATRIX LESTRANGE]
#link("mailto:<EMAIL>")[<EMAIL>] #text(gray)[$space.hair$|$space.hair$] #link("https://mzchael.com")[mzchael.com] #text(gray)[$space.hair$|$space.hair$] #link("https://github.com/mizlan")[github.com/mizlan] #text(gray)[$space.hair$|$space.hair$] #link("https://linkedin.com/in/not-me")[linkedin.com/in/not-me] #text(gray)[$space.hair$|$space.hair$] 123.456.7890
== EDUCATION
#chiline()
*University of Lorem Ipsum* --- 4.0 GPA #h(1fr) #text(gray)[09/2022 -- 06/2025] \
B.S. in Computer Science
- _Selected Coursework:_ Algorithms and Complexity, Operating Systems, Software Construction
- _Relevant Clubs & Societies:_ Association for Computing Machinery, Upsilon Pi Epsilon
== WORK EXPERIENCE
#chiline()
*Director of Lorem Ipsum* #h(1fr) #text(gray)[11/2023 -- present] \
Lorem Ipsum Co. #text(gray)[--- _Los Angeles, CA_]
- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.
- Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.
- Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
*Project Manager* #h(1fr) #text(gray)[08/2022 -- 10/2022] \
Random Company #text(gray)[--- _Remote_]
- Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est.
- Ultrices tincidunt arcu non sodales neque sodales ut etiam.
- Amet consectetur adipiscing elit pellentesque habitant morbi tristique senectus.
*Principal Maintainer* #h(1fr) #text(gray)[05/2021 -- 06/2022] \
Condimentum Mattis #text(gray)[--- _New York, NY_]
- Aenean et tortor at risus. Porttitor leo a diam sollicitudin. Lorem ipsum dolor sit amet consectetur.
- Tortor condimentum lacinia quis vel eros donec ac odio tempor. Libero justo laoreet sit amet.
*Software Engineer* #h(1fr) #text(gray)[10/2019 -- 09/2020] \
Malesuada Bibendum #text(gray)[--- _Chicago, IL_]
- Nibh cras pulvinar mattis nunc sed blandit libero volutpat.
- Aliquam etiam erat velit scelerisque in dictum non. Porttitor eget dolor morbi non arcu.
- Velit laoreet id donec ultrices tincidunt arcu. Et odio pellentesque diam volutpat commodo sed. Mauris pellentesque pulvinar pellentesque habitant.
== PROJECTS
#chiline()
*RandomProject* (#link("https://RandomProject.com/")[randomproject.com]) #h(1fr) #text(gray)[03/2023 -- 06/2023] \
- Nunc aliquet bibendum enim facilisis gravida neque. Leo vel fringilla est ullamcorper.
- Aenean euismod elementum nisi quis eleifend quam adipiscing vitae.
- Faucibus turpis in eu mi bibendum neque egestas. Imperdiet proin fermentum leo vel orci. Augue eget arcu dictum varius duis at.
*Generic Scraper* (#link("https://definitely-not-generic-scraper.com")[scraper.com]) #h(1fr) #text(gray)[08/2022 -- 05/2023] \
- Ac tincidunt vitae semper quis. Sagittis orci a scelerisque purus semper.
- Nullam eget felis eget nunc lobortis mattis aliquam faucibus purus. Quis auctor elit sed vulputate mi sit amet mauris commodo.
== SKILLS
#chiline()
- *Frontend* TypeScript, JavaScript, React, Redux, Next.js, HTML, CSS, Tailwind
- *Backend* Python, Node, PostgreSQL, SQLite, Java, C++, Haskell, OCaml, Perl, Lua, REST APIs
- *DevOps* Linux, CI/CD, Git, GitHub Actions, Docker, Bash, Agile
|
|
https://github.com/HEIGVD-Experience/docs | https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/WEB/docs/4-ObjectedOrientedJavaScript/objectoriented.typ | typst | #import "/_settings/typst/template-note-en.typ": conf
#show: doc => conf(
title: [
JavaScript
],
lesson: "WEB",
chapter: "3 - JavaScript",
definition: "The text covers educational objectives including creating objects with the class syntax, DOM manipulation, and drawing on the HTML Canvas with JavaScript. It emphasizes understanding methods, prototypes, and static methods in JavaScript classes, along with private properties and getters/setters. Additionally, it introduces modules for reusable code, DOM manipulation techniques, element selection, and event handling using both traditional and modern approaches.",
col: 1,
doc,
)
= Educational objectives
- Create object using the class syntax
- Use the extends keyword to create a class as the child of another class
- Use the super keyword to access and call functions on an object’s parent
- Use the static keyword to create static methods and properties
- Can manipulate the DOM using JavaScript
- Can draw in the HTML Canvas using JavaScript
- Can manipulate arrays and objects in JavaScript using the array methods
= Objects
An object is a mutable unordered collection of properties. A property is a tuple of a key and a value. A property key is either a string or a symbol. A property value can be any ECMAScript language value.
```javascrpit
let car = {
make: 'Ford',
model: 'Mustang',
year: 1969
}
```
Thoses properties can be accessed using the dot notation or the bracket notation.
== Methods
A method is a function associated with an object. A method is a property of an object that is a function. Methods are defined the same way as regular functions, except that they are assigned as the property of an object.
```javascript
var apple = {
color: 'red',
toString: function() {
return `This fruit is ${this.color}!`;
}
}
console.log(apple.toString()); // This fruit is red!
```
=== Prototype
Every JavaScript object has a prototype. The prototype is also an object. All JavaScript objects inherit their properties and methods from their prototype. Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype. Objects created with new Date() inherit the Date.prototype. The Object.prototype is on the top of the prototype chain. All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the Object.prototype.
==== Constructor invocation
Objects inherit the properties of their prototype, hence JavaScript is class-free.
If a function is invoked with the new operator:
- a new object that inherits from the function’s prototype is created
- the function is called and this is bound to the created object
- if the function doesn’t return something else, this is returned
```javascript
function Fruit(color) {
this.color = color;
}
Fruit.prototype.toString = function() {
return `This fruit is ${this.color}!`;
}
var apple = new Fruit("red");
console.log(apple.toString()); // This fruit is red!
```
= Context
The context of a function is the object to which the function belongs. The context is determined by how a function is invoked. The context of a function can be set using the call, apply, or bind methods.
```javascript
function doTwice(f) {
f()
f()
}
let human = {
age: 32,
getOlder() {
this.age++
}
}
doTwice(human.getOlder)
console.log(human.age)
```
In this case the context of the function getOlder is not shared when calling ```javascript doTwice(human.getOlder)```. The context is lost and the age property is not incremented. The program throw an error. To fix this, you can use the bind method to set the context of the function.
```javascript
function doTwice(f) {
f.call(this); // bind this to the current context
f.call(this); // bind this to the current context
}
let human = {
age: 32,
getOlder() {
this.age++;
}
}
doTwice.call(human, human.getOlder); // bind this to human
console.log(human.age); // Output will be 34
```
= Array object
The Array object is a global object that is used in the construction of arrays, which are high-level, list-like objects.
```javascript
let fruits = ['Apple', 'Banana', 'Pear'];
let fruits = new Array('Apple', 'Banana', 'Pear');
```
Note that Array is a function and the new operator makes it be used as a constructor.
== Indices
Because arrays are objects, getting `myArray[42]` is equivalent to accessing a property named "42" on the object myArray.
That’s why the for ... in loop, which iterates over an object’s properties, can be used to iterate over the indices of an array.
```javascript
let fruits = ['Apple', 'Banana', 'Pear'];
for (let index in fruits) {
console.log(index); // 0, 1, 2
}
```
= Object-oriented syntax
```javascript
class Fruit {
constructor(color) {
this.color = color;
}
toString() {
return `This fruit is ${this.color}!`;
}
}
class Apple extends Fruit {
constructor(color, name) {
super(color);
this.name = name;
}
toString() {
return super.toString();
}
}
let apple = new Apple("red", "golden");
console.log(apple.toString()); // This fruit is red!
```
- The extends keyword is used in class declarations or class expressions to create a class as the child of another class.
- The constructor method is a special method for creating and initializing an object described by a class.
- The super keyword is used to access and call functions on an object’s parent.
== Private properties, getter and setter
JavaScript offer the opportunity to define private properties or methods using the \# prefix.
```javascript
class Fruit {
#color;
get color() {
return this.#color;
}
set color(color) {
this.#color = color;
}
}
let apple = new Fruit();
apple.color = 'red'; // calls the setter
console.log(apple.color); // red (calls getter)
console.log(apple.#color); // SyntaxError: Private field '#color' must be declared in an enclosing class
```
#colbreak()
=== Static methods and properties
The static keyword defines a static method or property for a class. Static members (properties and methods) are called without instantiating their class and cannot be called through a class instance.
```javascript
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.hypot(dx, dy);
}
}
let p1 = new Point(5, 5);
let p2 = new Point(10, 10);
console.log(Point.distance(p1, p2)); // 7.0710678118654755
```
= Modules
Modules are reusable pieces of code that can be exported from one program and imported for use in another program.
```javascript
// Export upon declaring a value
export function sum(a, b) { ... }
export const ANSWER = 42
// Export a declared value
export { val1, val2, ... }
```
The imported script must be loaded as a module with the type="module" attribute.
```html
<script type="module" src="module.js"></script>
```
== Import
The import statement must always be at the top of the js file, before any other code.
```javascript
import { export1, export2, ... } from "module-name"; // import specific named values
import { export1 as alias1, ... } from "module-name"; // import value with alias (e.g. to solve name conflicts)
import * as name from "module_name"; // import all into an object
import name from "module-name"; // import the default export
// equivalent to
import { default as name } from "module-name";
import "module-name"; // imports for side-effects; runs it but imports nothing.
```
= DOM manipulation
- DOM stands for Document Object Model
- The DOM is a programming interface for HTML and XML
- The DOM represents the structure of a document in memory
- The DOM is an object-oriented representation of the web page
- The DOM lets other programming languages manipulate the document
== Accessing elements
In JavaScript, the Document interface represents any web page loaded in the browser and serves as an entry point into the web page’s content, which is the DOM tree.
```javascript
document;
document.location; // Getter returns location object (info about current URL).
document.location = "https://heig-vd.ch/"; // Setter to update displayed URL.
document.designMode = "on"; // Lets user interactively modify page content.
document.referrer; // URL of page that linked to this page.
```
== Selecting elements
```javascript
console.log(document.getElementById("id"));
console.log(document.getElementsByClassName("slide"));
console.log(document.getElementsByTagName("h1"));
```
=== QuerySelector
The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.
```javascript
document.querySelector("p");
document.querySelector(".slide");
```
== DOM events
DOM Events are sent to notify code of interesting things that have taken place. Each event is represented by an object that inherits from the Event object, and may have additional custom fields and/or functions used to get additional information about what happened.
```javascript
document.onkeydown = function(event) {console.log(event);}
document.addEventListener('keydown', event => console.log(event))
```
You can call a method when action on an element using the `onclick` attribute.
```html
<a href="http://www.heig-vd.ch" onclick="event.method();">
```
== Event listeners
Event listeners are a more modern way to handle events. They can be added to any DOM element, not just HTML elements. They are more flexible than using the on-event-attributes. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.