repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/diy/diy.md | markdown | # Do it yourself
Let's start with the absolute minimal effort.
What characterises a set of slides?
Well, each slide (or PDF page, as we already established) has specific dimensions.
Some time ago, a 4:3 format was common, nowadays 16:9 is used more often.
Typst has those built in:
```typ
#set page(paper: "presentation-16-9")
```
You probably don't want your audience to carry magnifying glasses, so let's set
the font size to something readable from the last row:
```typ
#set text(size: 25pt)
```
We should be ready do go to create some actual slides now.
We will use the function `polylux-slide` for this, which is kind of at the core
of this package.
```typ
// Remember to actually import polylux before this!
#polylux-slide[
Hello, world!
]
```
And here is the result (the gray border is not part of the output but it makes
the slide easier to see here):

Already kinda looks like a slide, but also a bit boring, maybe.
We should add a title slide before that so that our audience actually knows what
talk they are attending.
Also, let us choose a nicer font and maybe add some colour?
We modify the `#set page` and `#set text` commands for that:
```typ
#set page(paper: "presentation-16-9", fill: teal.lighten(90%))
#set text(size: 25pt, font: "Blogger Sans")
#polylux-slide[
#set align(horizon + center)
= My fabulous talk
<NAME>
Conference on Advances in Slide Making
]
```

Not bad, right?
Another thing that is usually a good idea is to have a title on each slide.
That is also no big deal by using off-the-shelf Typst features, so let's modify
our first slide:
```typ
#polylux-slide[
== My slide title
Hello, world!
]
```
This is starting to look like a real presentation:

## So what?
To be honest, everything we did so far would have been just as easy without
using polylux at all.
So why should you care about it?
Consider the following situation:
You have a slide where parts of the content appear or disappear, or the colour
of some text changes, or some other small-sized change.
Would you like to duplicate the whole slide just so to create this affect?
And then maintain multiple copies of the same content, making sure never to
forget updating all copies when your content evolves?
Of course you wouldn't and, gladly, polylux can handle this for you.
This kind of feature is called **dynamic content** or **overlays** (loosely
speaking, you might also say **animations** but that might be a bit of a stretch,
nothing actually "moves" on PDF pages).
So how does that work in polylux?
As a quick example, let's add a little quiz to our slides:
```typ
#polylux-slide[
== A quiz
What is the capital of the Republic of Benin?
#uncover(2)[Cotonou]
]
```

Note how two more slides have been created even though we declared only one.
The next sections will explain dynamic content in polylux in all its details.
For reference, here is the full source code for the slides we developed in this
section:
```typ
#import "@preview/polylux:0.2.0": *
#set page(paper: "presentation-16-9", fill: teal.lighten(90%))
#set text(size: 25pt, font: "Blogger Sans")
#polylux-slide[
#set align(horizon + center)
= My fabulous talk
<NAME>
Conference on Advances in Slide Making
]
#polylux-slide[
== My slide title
Hello, world!
]
#polylux-slide[
== A quiz
What is the capital of the Republic of Benin?
#uncover(2)[Cotonou]
]
```
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/packages/typst.node/__test__/index.spec.ts.md | markdown | Apache License 2.0 | # Snapshot report for `__test__/index.spec.ts`
The actual snapshot is saved in `index.spec.ts.snap`.
Generated by [AVA](https://avajs.dev).
## it queries label in `Hello, Typst! <my-label>`
> Snapshot 1
[
{
costs: {
hyphenation: '100%',
orphan: '100%',
runt: '100%',
widow: '100%',
},
func: 'text',
label: '<my-label>',
text: 'Hello, Typst!',
},
]
## it throws error`
> Snapshot 1
[
{
message: 'unclosed label',
package: '',
path: '/__main__.typ',
range: null,
severity: 1,
},
]
> Snapshot 2
[
{
message: 'unclosed label',
package: '',
path: '/__main__.typ',
range: {
end: {
column: 18,
line: 1,
},
start: {
column: 14,
line: 1,
},
},
severity: 1,
},
]
## it takes in the workspace and entry file in compiler ctor
> Snapshot 1
'Post 1'
## it modifys the entry file to another when call `compile`
> Snapshot 1
'Post 2'
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/05-features/feature-store.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/components.typ": note, cross-ref
#import "/lib/glossary.typ": tr
#show: web-page-template
// ## How features are stored
== 特性如何储存
#note[
// > You probably want to skip this section the first time you read this book. Come to think of it, you may want to skip it on subsequent reads, too.
如果这是你第一次阅读本书,可能会想暂时跳过本段内容。但还是看看吧,毕竟不管是第几次都是会想跳过的。
]
// We'll start our investigation of features once again by experiment, and from the simplest possible source. As we mentioned, the canonical example of a `GPOS` feature is kerning. (The `kern` feature - again one which is generally turned on by default by the font.)
我们还是通过实验来介绍特性的储存,而且这次只使用最简单的特性代码。正如前文所说,最经典的`GPOS`特性的例子就是#tr[kern]。而且通常来说,`kern`这个特性都是被字体默认开启的。
// > As with all things OpenType, there are two ways to do it. There's also a `kern` *table*, but that's a holdover from the older TrueType format. If you're using CFF PostScript outlines, you need to use the `GPOS` table for kerning as we describe here - and of course, using `GPOS` lets you do far more interesting things than the old `kern` table did. Still, you may still come across fonts with TrueType outlines and an old-style `kern` table.
#note[
OpenType的老生常谈又来了,还是有两种方式来完成#tr[kern]功能。除了我们一直介绍的这种之外还有一张就叫做`kern`的数据表,这是老版本的TrueType格式的遗留物。如果你使用的是PostScript的CFF格式的#tr[outline]描述,就只能使用`GPOS`表来实现#tr[kern]了。当然,使用`GPOS`表可以让你实现老`kern`表无法完成的更多更有趣的功能。但在生活中你还是可能会见到一些使用TrueType格式和老式`kern`表的字体。
]
// We're going to take our test font from the previous chapter. Right now it has no `GPOS` table, and the `GSUB` table contains no features, lookups or rules; just a version number:
我们使用上一章的测试字体,现在它里面还没有`GPOS`表,而且`GSUB`表里也没有任何特性、#tr[lookup]和规则存在。里面只有一个版本号:
```xml
<GSUB>
<Version value="0x00010000"/>
</GSUB>
```
// Now, within the Glyphs editor we will add negative 50 points of kerning between the characters A and B:
现在打开 Glyphs 编辑器,在AB#tr[character]间添加一个 -50 单位的#tr[kern]。
#figure()[#image("kern.png", width: 35%)]
// We'll now dump out the font again with `ttx`, but this time just the `GPOS` table:
然后重新用 `ttx` 处理字体文件,但这次我们只导出 `GPOS` 表:
```bash
$ ttx -t GPOS TTXTest-Regular.otf
Dumping "TTXTest-Regular.otf" to "TTXTest-Regular.ttx"...
Dumping 'GPOS' table...
```
得到的结果如下:
```xml
<GPOS>
<Version value="0x00010000"/>
<ScriptList>
<!-- ScriptCount=1 -->
<ScriptRecord index="0">
<ScriptTag value="DFLT"/>
<Script>
<DefaultLangSys>
<ReqFeatureIndex value="65535"/>
<!-- FeatureCount=1 -->
<FeatureIndex index="0" value="0"/>
</DefaultLangSys>
<!-- LangSysCount=0 -->
</Script>
</ScriptRecord>
</ScriptList>
<FeatureList>
<!-- FeatureCount=1 -->
<FeatureRecord index="0">
<FeatureTag value="kern"/>
<Feature>
<!-- LookupCount=1 -->
<LookupListIndex index="0" value="0"/>
</Feature>
</FeatureRecord>
</FeatureList>
<LookupList>
<!-- LookupCount=1 -->
<Lookup index="0">
<!-- LookupType=2 -->
<LookupFlag value="8"/>
<!-- SubTableCount=1 -->
<PairPos index="0" Format="1">
<Coverage Format="1">
<Glyph value="A"/>
</Coverage>
<ValueFormat1 value="4"/>
<ValueFormat2 value="0"/>
<!-- PairSetCount=1 -->
<PairSet index="0">
<!-- PairValueCount=1 -->
<PairValueRecord index="0">
<SecondGlyph value="B"/>
<Value1 XAdvance="-50"/>
</PairValueRecord>
</PairSet>
</PairPos>
</Lookup>
</LookupList>
</GPOS>
```
// Let's face it: this is disgusting. The hierarchical nature of rules, lookups, features, scripts and languages mean that reading the raw contents of these tables is incredibly difficult. (Believe it or not, TTX has actually *simplified* the real representation somewhat for us.) We'll break it down and make sense of it all later in the chapter.
说实话吧,这太糟糕了。这种语言#tr[script]、特性、#tr[lookup]、规则之间奇怪的层级嵌套关系根本无法阅读。(你可能不信,这还是`ttx`工具将真实的储存结构*简化*了之后的样子。)现在我们试图将它逐步分解,并尝试解释每一部分的意义。
// The OpenType font format is designed above all for efficiency. Putting a bunch of glyphs next to each other on a screen is not meant to be a compute-intensive process (and it *is* something that happens rather a lot when using a computer); even though, as we've seen, OpenType fonts can do all kinds of complicated magic, the user isn't going to be very amused if *using a font* is the thing that's slowing their computer down. This has to be quick.
OpenType字体格式的首要设计原则是高效。将一大堆#tr[glyph]一个接一个地显示在屏幕上绝不能是一个非常吃性能的过程,因为这是计算机上及其常见的使用场景。虽然OpenType可以完成我们介绍过的那么多复杂花样,但如果使用字体会拖慢电脑速度的话,用户是不会感到高兴的。这个过程就是得很快才行。
// As well as speed and ease of access, the OpenType font format is designed to be efficient in terms of size on disk. Repetition of information is avoided (well, all right, except for when it comes to vertical metrics...) in favour of sharing records between different users. Multiple different formats for storing information are provided, so that font editors can choose the most size-efficient method.
OpenType字体格式的设计不仅着眼于速度和便于取用,还希望高效利用磁盘空间。它避免信息重复(啊,好吧,竖排的那些#tr[metrics]值除外……),以便在不同的用户间共享记录。/*这句啥意思?*/ 它提供了多种信息存储方式,这样字体编辑器可以选择空间利用率最高的方法。
// But because of this focus on efficiency, and because of the sheer amount of different things that a font needs to be able to do, the layout of the font on the disk is... somewhat overengineered.
但就是因为如此关注效率,再加上字体需要能完成各种各样的功能,字体文件在磁盘上的格式有些……过度设计了。
// Here's an example of what actually goes on inside a `GSUB` table. I've created a simple font with three features. Two of them refer to localisation into Urdu and Farsi, but we're going to ignore them for now. We're only going to focus on the `liga` feature for the Latin script, which, in this font, does two things: substitutes `/f/i` for `/fi`, and `/f/f/i` for `/f_f_i`.
我用一个`GSUB`的例子来介绍字体内部到底是什么样的。为此,我创建了一个有三个特性的简单字体。其中两个特性是关于乌尔都语和波斯语本地化的,这两个我们先忽略,只关注拉丁文的`liga`特性。这个特性会完成两件事:将`f i`#tr[substitution]为`fi`,`f f i` #tr[substitution]为 `f_f_i`。
// In Adobe feature language, that looks like:
代码如下:
```fea
languagesystem DFLT dflt;
languagesystem arab URD;
languagesystem arab FAR;
feature locl {
script arab;
language URD;
# ...
language FAR;
# ...
}
feature liga {
sub f i by fi;
sub f f i by f_f_i;
}
```
// Now let's look at how that is implemented under the hood:
@figure:gsub-impl-internal 展示了在它在字体内部的实现。
#figure(
caption: [字体内部的结构图示]
)[#image("gsub.png")] <figure:gsub-impl-internal>
// Again, what a terrible mess. Let's take things one at a time. On the left, we have three important tables. (When I say tables here, I don't mean top-level OpenType tables like `GSUB`. These are all data structures *inside* the `GSUB` table, and the OpenType standard, perhaps unhelpfully, calls them "tables".) Within the `GPOS` and `GSUB` table there is a *script list*, a *feature list* and a *lookup list*. There's only one of each of these tables inside `GPOS` and `GSUB`; the other data structures in the map (those without bold borders) can appear multiple times: one for each script, one for each language system, one for each feature, one for each lookup and so on.
这看起来更是一团糟,不过让我们一个一个的来梳理。在最左边显示了三个非常重要的表。(我现在说的表不是指`GSUB`的这种OpenType的顶层数据表,而是指`GSUB`表内部的数据结构,但OpenType标准有点帮倒忙地把这些结构也叫做表。)`GSUB`和`GPOS`表的内部实现都包含#tr[scripts]列表(`Script List`)、特性列表(`Feature List`)和#tr[lookup]列表(`Lookup List`),这三种列表每种只有一个。其他数据结构(图中没有加粗黑边框的那些)可以多次出现。可能是每种#tr[script]一个,每种语言一个,或者每个特性一个,每个查询组一个之类的。
// When we're laying out text, the first thing that happens is that it is separated into runs of the same script and language. (Most documents are in a single script, after all.) This means that the shaper can look up the script we're using in the script list (or grab the default script otherwise), and find the relevant *script table*. Then we look up the language system in the language system table, and this tells us the list of features we need to care about.
当处理文本时,首先需要将它按照语言和#tr[script]划分成块(虽然大多数文档都只使用一种#tr[script])。此时#tr[shaper]就可以在#tr[scripts]列表中查找正在使用的#tr[script](没找到就用默认的那个),从而获取到相应的#tr[script]表格(`Script Table`)。然后找到其中所需的语言表格,这个表格会告诉我们有哪些特性可以使用。
// Once we've looked up the feature, we're good to go, right? No, not really. To allow the same feature to be shared between languages, the font doesn't store the features directly "under" the language table. Instead, we look up the relevant features in the *feature list table*. Similarly, the features are implemented in terms of a bunch of lookups, which can also be shared between features, so they are stored in the *lookup list table*.
找到特性之后就好办了对吧?并不太对。为了让某些特性可以在多种语言间共享,字体中的语言表格里并不直接存储特性的内容,我们还需要在特性列表里找到这些特性。与之类似,因为特性是由一堆#tr[lookup]组成的,它们也能在不同的特性间共享,所以也不直接储存在特性中,而是在#tr[lookup]列表里。
// Now we finally have the lookups that we're interested in. Turning on the `liga` feature for the default script and language leads us eventually to lookup table 1, which contains a list of lookup "subtables". Here, the rules that can be applied are grouped by their type. (See the sections "Types of positioning feature" and "types of substitution feature" above.) Our ligature substitutions are lookup type 4.
现在我们终于找到感兴趣的那个#tr[lookup]了,在默认语言#tr[script]的环境下打开`liga`特性最终会使用`lookup table 1`。而这个结构中又包含了一个“子表格”的列表。从这开始,规则就根据它们所属的类型进行分组了,我们这种#tr[ligature]#tr[substitution]属于`type 4`。(有关规则的各种类型,可参考后文#cross-ref(<section:substitution-rule-types>, web-path: "/chapters/06-features-2/substitution.typ", web-content: [#tr[substitution]规则的各种类型])和#cross-ref(<section:positioning-rule-types>, web-path: "/chapters/06-features-2/positioning.typ", web-content: [#tr[positioning]规则的各种类型]))
// The actual substitutions are then grouped by their *coverage*, which is another important way of making the process efficient. The shaper has, by this stage, gathered the features that are relevant to a piece of text, and now needs to decide which rules to apply to the incoming text stream. The coverage of each rule tells the shaper whether or not it's likely to be relevant by giving it the first glyph ID in the ligature set. If the shaper sees anything other than the letter "f", then we know for sure that our rules are not going to apply, so it can pass over this set of ligatures and look at the next subtable. A coverage table comes in two formats: it can either specify a *list* of glyphs, as we have here (albeit a list with only one glyph in it), or a *range* of IDs.
实际的#tr[substitution]规则根据它们的对参数的覆盖性来分组,这是让处理过程更加高效的一个重要手段。#tr[shaper]在这个阶段已经知道了有哪些特性和输入文本有关,下一步是要决定在文本上具体使用哪些规则。所谓覆盖性,就是通过只看#tr[ligature]中的第一个#tr[glyph],#tr[shaper]就能排除掉所有和当前位置无关的规则。比如只要#tr[shaper]看到第一个输入的#tr[glyph]不是`f`,它就能够确定我们当前这条规则肯定无需应用,可以直接去处理下一个“子表格”。覆盖性表格可能有两种格式:第一种就是我们这里展示的,它直接声明一些#tr[glyph];第二种是声明一个#tr[glyph]范围。
// OK, we're nearly there. We've found the feature we want. We are running through its list of lookups, and for each lookup, we're running through the lookup subtables. We've found the subtable that applies to the letter "f", and this leads us to two more tables, which are the actual rules for what to do when we see an "f". We look ahead into the text stream and if the next input glyph (which the OpenType specification unhelpfully calls "component", even though that also means something completely different in the font world...) is the letter "i" (glyph ID 256), then the first ligature substitution applies. We substitute that pair of glyphs - the start glyph from the coverage list and the component - by the single glyph ID 382 ("fi"). If instead the next two input glyphs have IDs 247 and 256 ("f i") then we replace the three glyphs - the start glyph from the coverage list and both components - with the single glyph ID 380, or "ffi". That is how a ligature substitution feature works.
很好,就快接近终点了。我们找到了想要的特性,得到了它所有的#tr[lookup]。对于每个#tr[lookup],都逐个处理它的“子表格”。接着我们找到了可能影响由字母`f`开头的文本的那个“子表格”,它又给了我们两个表,也就是当看到`f`时真正需要处理的规则。然后#tr[shaper]就会向前看下一个#tr[glyph],如果这个#tr[glyph](OpenType非常捣乱的把它叫做“部件”,但这个词在字体设计领域中又有另一个完全不同含义……)是字母`i`(也就是ID为256的#tr[glyph]),那么第一条#tr[substitution]规则就被应用了。我们把覆盖性表格中的起始#tr[glyph]和“部件”们整体替换成ID为382的#tr[glyph]`fi`。如果后两个#tr[glyph]是ID为247的`f`和ID为256的`i`,就把加上起始#tr[glyph]的这三个#tr[glyph]整体替换成ID为380的`ffi`。这就是#tr[ligature]#tr[substitution]特性的工作过程。
// If you think that's an awful lot of effort to go to just to change the letters "f i" into "fi" then, well, you'd be right. It took, what, 11 table lookups? But remember that the GPOS and GSUB tables are extremely powerful and extremely flexible, and that power and flexibility comes at a cost. To represent all these lookups, features, languages and scripts efficiently inside a font means that there has to be a lot going on under the hood.
如果你觉得这对于把`f i`换成`fi`这种小事来说工作量有点太大了,那么你说对了,毕竟这个过程中进行了11次的表格跳转。但要记住,因为 `GPOS` 和 `GSUB` 表的功能十分强大,而且有很强的灵活性,而这两者都是有代价的。为了能够在字体中高效的表示#tr[lookup]、特性、语言、#tr[script]这些所有概念,我们必须在这种看不见的地方为之努力。
// Thankfully, unless you're implementing some of these shaping or font editing technologies yourself, you can relax - it mostly all just works.
幸运的是,除非你是在自己编写字体编辑软件或#tr[shaper],不然日常生活还是能保持轻松的。这些技术基本上都工作得很好。
|
https://github.com/eliapasquali/typst-thesis-template | https://raw.githubusercontent.com/eliapasquali/typst-thesis-template/main/config/thesis-config.typ | typst | Other | #import "../config/constants.typ": chapter
#let config(
myAuthor: "<NAME>",
myTitle: "Titolo",
myLang: "it",
myNumbering: "1.",
body
) = {
// Set the document's basic properties.
set document(author: myAuthor, title: myTitle)
show math.equation: set text(weight: 400)
// LaTeX look (secondo la doc di Typst)
set page(margin: 1.75in, numbering: myNumbering, number-align: center)
// set par(leading: 0.55em, first-line-indent: 1.8em, justify: true)
set par(leading: 0.55em, justify: true)
set text(font: "New Computer Modern", size: 10pt, lang: myLang)
set heading(numbering: myNumbering)
show raw: set text(font: "New Computer Modern Mono", size: 10pt, lang: myLang)
show par: set block(spacing: 0.55em)
show heading: set block(above: 1.4em, below: 1em)
show heading.where(level: 1): it => {
stack(
spacing: 2em,
if it.numbering != none {
text(size: 1.5em)[#chapter #counter(heading).display()]
},
text(size:2em,it.body),
[]
)
}
body
}
#let useCase(useCaseDetails) = {
let n = 1
if useCaseDetails.number != "" and useCaseDetails.name != "" {
text(12pt, [ *UC#useCaseDetails.number: #useCaseDetails.name* ])
}
let result = for (k, v) in useCaseDetails {
if k != "number" and k != "name" {
(text(k, weight: "bold"),
v,)
}
n = n + 1
}
table(
inset: 8pt,
stroke: none,
columns: 2,
..result
)
} |
https://github.com/CarlColglazier/northwestern-thesis-quarto | https://raw.githubusercontent.com/CarlColglazier/northwestern-thesis-quarto/master/_extensions/northwestern-thesis/typst/typst-show.typ | typst | MIT License | #show: nuthesis.with(
$if(title)$ title: "$title$", $endif$
$if(abstract)$ abstract: [$abstract$], $endif$
$if(author)$ author: "$author$", $endif$
$if(date)$ date: "$date$", $endif$
$if(toc)$ toc: $toc$, $endif$
$if(lof)$ lof: $lof$, $endif$
$if(lot)$ lot: $lot$, $endif$
$if(toc-title)$ toc_title: [$toc-title$], $endif$
$if(document-type)$ document-type: "$document-type$", $endif$
$if(field)$ field: "$field$", $endif$
$if(mainfont)$ mainfont: "$mainfont$" $endif$
) |
https://github.com/lcharleux/LCharleux_Teaching_Typst | https://raw.githubusercontent.com/lcharleux/LCharleux_Teaching_Typst/main/src/sandbox/test.typ | typst | MIT License | #import "@preview/cetz:0.2.2"
#import cetz.draw: *
#let fonc = {
circle((0,0), name: "circle2")
// Draw a smaller red circle at "circle"'s east anchor
fill(red)
stroke(black)
circle("circle2.east", radius: 0.3)
circle((name:"circle2", anchor:30deg), radius: 0.3, stroke: black, fill: red)
}
#cetz.canvas({
fonc
})
#calc.rem(9, 2) |
https://github.com/khicken/CSDS310 | https://raw.githubusercontent.com/khicken/CSDS310/main/SI%20Midterm/Assignment%202.typ | typst | #import "@preview/lovelace:0.3.0": pseudocode-list
#set enum(numbering: "ai)")
#set align(right)
<NAME> \
10/11/24
#set align(center)
= CSDS 310 SI Midterm Session
#set align(left)
_Note: Arrays are zero-indexed._
== Problem 6
_Pseudocode:_
#pseudocode-list[
+ *procedure* MATCH(nuts, bolts, low, high):
+ *if* low < high *then*
+ pivotBoltIndex $<-$ PARTITION(bolts, low, high)
+ SWAP(pivotBoltIndex, high)
+ PARTITION(nuts, low, high)
+ MATCH(nuts, bolts, low, pivotBoltIndex - 1)
+ MATCH(nuts, bolts, pivotBoltIndex + 1, high)
+ *endif*
]
_Runtime:_ \
The runtime of this algorithm can be analyzed using the Master Theorem. The `PARTITION` method takes $O(n)$ time, and the problem is divided in half for the two subproblems. This means
$
T(n) = 2T(n/2) + O(n)
$
and $n^(log_2 2) = n$, which falls into case 2 of the Master Theorem. Thus, the runtime is $O(n log n)$.
\ \
_Proof by induction:_ \
*Base case:* When the size of the nuts and bolts subsets is 1, the single nut will match the single bolt. \
*Inductive step*: Assume the algorithm correctly matches all nuts and bolts for any set of size $k$. When the size is $k+1$ the algortihm chooses a pivot nut, partitions the bolts (which works as partition is defined in the textbook), finds the matching bolt, and then usees it to partition the nuts. The pivot nut and bolt are correctly matched. By the inductive hypothesis, since the subsets of nuts and bolts less than and greater than the pivot are of size less than or equal to $k$, they will also be correctly matched.
== Problem 5
#pseudocode-list[
+ *procedure* MISSING(D, C, low, high):
+
] |
|
https://github.com/brainworkup/neurotyp-pediatric | https://raw.githubusercontent.com/brainworkup/neurotyp-pediatric/main/README.md | markdown | MIT License | # Pediatric Neurotyp Format for Typst using Quarto
## Use report template
```bash
quarto use template brainworkup/neurotyp-pediatric
```
This will install the format extension and create an example .qmd file that you
can use as a starting place for your patient report.
## Update report template
```bash
quarto update template brainworkup/neurotyp-pediatric
```
This will update to the latest version.
## Add report template
```bash
quarto add template brainworkup/neurotyp-pediatric
```
Alternatively, you can add the format (without the template) into an existing project or directory:
## Using
_TODO_: Describe how to use your format.
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/代数学二/习题课.typ | typst | #import "../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark, proposition,der, partialDer, Spec
#import "../template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: note.with(
title: "代数学二习题课",
author: "YHTQ",
date: none,
logo: none,
)
= 前言
- 习题课助教:潘翔宇
- 邮箱:<EMAIL>,两周习题课交一次作业
= 素谱,极大谱
本门课前半学期着眼于交换代数,最初的目的是为了将代数几何严格化。
#definition[环的(素)谱(prime spectrum)][
设 $A$ 是一个环,$P$ 是 $A$ 的一个素理想(注意素理想一定是真理想)\
称环的素谱为 $A$ 的素理想的集合,记作 $Spec(A)$
]
#definition[零点集][
设 $E$ 是 $A$ 的子集,称:
$
V(E) = {P in Spec(A) | E subset P}
$
为 $E$ 的零点集
]
#remark[][
这看似与零点毫无关系,但后续课程中会学到 $A$ 中的元素可以看作 $A$ 的素谱上的函数,而 $E$ 的零点集可以看作这些函数的零点集
]
环的素谱是某种意义上多项式零点集的推广,其上具有良好的拓扑性质,我们的目标是模仿零点集给出谱上的拓扑。
#proposition[][
- $V(E) = V(I)$, 其中 $I$ 是 $E$ 的生成理想。这表明我们只需要考虑理想的零点集
- $V(0) = Spec(A)$
- $V(A) = V(1) = emptyset$
- $sect.big_i V(I_i) = V(sum_i I_i)$
- $V(I) union V(J) = V(I sect J) = V(I J)$
]
#proof[
- 注意到对任何素理想 $P, I subset P <=> E subset P$,结论显然
- $0$ 当然包含与任何素理想
- 任何素理想当然都不应该包含 $1$
- 一方面
$
I_j subset sum_i I_i => V(sum_i I_i) subset V(I_j)
$
另一方面,假设素理想 $P$ 满足 $P in sect.big_i V(I_i)$,这就导出 $P supset I_i, forall i$,表明 $P supset sum_i I_i$
- 首先 $I, J supset I sect J, I J$,因此 $V(I), V(J) subset I sect J, I J$。\
- 往证 $V(I J) subset V(I) union V(J)$\
注意到 $P$ 是素理想,因此 $P supset I J => P supset I or P supset J => P in V(I) union V(J)$
- 类似的,把 $I sect J$ 替换 $I J$ 结论都是正确的
]
注意到上面的命题实际上说明了:
- $Spec(A), emptyset$ 是某个集合的零点集
- 两个零点集的并,任意零点集的交仍是零点集
这恰好就是拓扑的闭集公理,由此我们就定义谱上的拓扑。
#theorem[][
$Spec(A)$ 上的由所有形如 $V(I)$ 的集合作为闭集生成一个拓扑
]
#example[][
-
容易计算得
$
Spec(ZZ) = {(p) | p "is prime"}\
V(n ZZ) = {(p) | p "is prime" and (p) supset (n)} = {(p) | p "is prime" and p | n}
$
不难发现,闭集恰为所有不含 $(0)$ 的有限集和全集。此时 ${(0)}$ 的闭包是全集,表明整数环的谱不是 $T_1$ 的。一般来说,只有很少的环满足 $T_1$ 或者 $T_2$
- 域的谱都是平凡的,因为只有平凡的素理想
- 考虑 $CC[x]$,这是 PID ,所有素理想都是素元的生成理想,而多项式是素元当切仅当它是一次多项式。因此 $Spec(CC[x]) = {(x - a) | a in CC} union {0}$,进而 $CC$ 中每个元素都对应着 $Spec(CC[x])$ 中的一个元素。\
同时,$CC[x]$ 的零点集当然就是任意若干个 $CC$ 中元素,再次体现了零点集概念的合理性。\
而:
$
V(f) = V(product_(i=1)^n x - a_i) = union.big_(i=1)^n {(x - a_i)} = {(x - a_i) | i = 1, 2, ..., n}
$
它的拓扑恰与余有限拓扑只相差一个零理想对应的单点集。这个事实对任何代数闭域都是成立的。
- 考虑 $RR[x]$,它的素谱比代数闭的情形多出二次不可约多项式,因此:
$
Spec(RR[x]) = {(0)} union {(x - a) | a in RR} union {(x-z)(x-overline(z)) | z in CC, im(c) > 0}
$
拓扑是类似的。粗略来说,可以认为 $Spec(RR[x]) tilde.eq Spec(CC[x]) quo Gal(CC quo RR)$ 至少在拓扑上是成立的
]
#definition[基本开集 (prime open set)][
对任意 $f in A$,称形如:
$
D_f = Spec(A) - V(f) = {P in Spec(A) | f in.not P}
$
的集合为基本开集/主开集
]
#proposition[][
- $D(f) sect D(g) = D(f g)$
- $D(f) = emptyset <=> f in sqrt(0)$
- $D(f) = Spec(A) <=> f in U(A)$
- $D(f) = D(g) <=> sqrt(f) = sqrt(g)$
]
#proof[
- $p in D(f) sect D(g) <=> f in.not p and g in.not p <=> f g in.not p$
- 由幂零根的概念和性质可知
- \
- 一方面 $f in U(A) => V(f) = emptyset$
- 另一方面,一个不可逆的元素应该包含于某个极大理想,而极大理想一定是素理想,因此成立
- 首先我们证明:
$
sect.big_(P in V(I)) = sqrt(I)
$
这是因为由对应定义,$V(I)$ 中的元素与 $Spec(A quo I)$ 中元素可以产生一一对应 $phi$。同时,注意到:
$
Spec(A quo I) = sect.big_(p in V(I)) p quo I
$
用 $phi$ 作用于两侧立得结论
]
#corollary[][
所有基本开集构成一个拓扑基
]
#proof[
这是非常自然的,因为开集均形如:
$
Spec(A) - V(E) = Spec(A) - (sect.big_(f in E) V(f)) = union.big_(f in E) D(f)
$
]
#definition[拟紧(quasi-compact)][
设 $X$ 是一个拓扑空间,称 $X$ 是拟紧的,如果 $X$ 的任意开覆盖都有有限子覆盖\
(在拓扑学中这就是紧,布尔巴基学派习惯将其称为伪紧)
]
#theorem[][
每个 $D(f)$ 都是拟紧的,特别的 $Spec(A) = D(0)$ 拟紧
]
#proof[
由于所有 $D(f)$ 构成拓扑基,因此不妨设开覆盖是拓扑基构成的,也即:
$
&D(f) subset union.big_(i in I) D(g_i)\
<=>& V(f) supset sect.big_(i in I) V(g_i)\
<=>& V(f) supset V(sum_(i in I) (g_i))\
<=>& f in sqrt(sum_(i in I) (g_i))\
<=>& f^k in sum_(i in I) (g_i)
$
注意到最后一式中 $f^k$ 一定可以被 $g_i$ 中的有限个元素表示,因此倒推可得 $D(f)$ 有有限子覆盖
]
#theorem[][
任意开集拟紧当且仅当是有限个基本开集的并
]
#proof[
- 有限个拟紧集的并当然拟紧。
- 若开集 $S$ 拟紧,由于基本开集是拓扑基:
$
S = union.big_(f in I) D(f)
$
而由 $S$ 拟紧,应当有上式右侧有限个即可覆盖 $S$,当然它们的并就是 $S$
]
类似素谱,我们可以定义极大谱。它的大部分性质与素谱类似,但在根的处理上更加复杂
#example[][
设 $X$ 是紧的 Hausdorff 空间,$C(X)$ 是其上的连续实函数环。对 $forall x in X$
$
P_x = {f in C(X) | f(x) = 0}
$
$P_x$ 将是 $C(X)$ 的一个极大理想,因为它恰好是代入映射:
$
funcDef(phi, C(X), RR, f, f(x))
$
的 ker
]
#theorem[][
该拓扑是一个 $T_0$ 可分离空间,单点集 ${x}$ 是闭集当且仅当 $x$ 代表的素理想是极大理想
]
#definition[][
称一个拓扑空间是不可约的,如果它非空且
- 不能写成两个真闭集的并
- 任意两个非空开集的交非空
- 每个非空开集都是稠密的
(以上三者等价)
]
#theorem[][
- 若 $Y$ 不可约,则它的闭包也不可约
- 每个不可约集包含一个最小的不可约子集,这个子集是闭的
- $Spec(A)$ 的最小不可约子集形如 $V(p), p$ 是 $A$ 中的极小素理想
]
#proof[
- 任取 $overline(Y)$ 中非空开集 $U, V$,事实上就是 $X$ 中开集与 $overline(Y)$ 的交非空,而它们与 $Y$ 的交一定也非空,进而结论成立。
]
#theorem[][
$Spec(A)$ 是不可约的当且仅当 $A$ 的幂零根是素理想
]<irreducible-lemma0>
#proof[
- 设 $I$ 作为幂零根是素理想,设 $U, V$ 是两个非空开集。由于我们证明主开集是拓扑基,我们只需证明主开集都有交即可\
注意到:
$
D_f = emptyset <=> f in sqrt(0) <=> f in I
$
因此对非空主开集 $D_f, D_g$,有 $f, g$ 不幂零,进而 $f g$ 也不幂零,因此 $D_f sect D_g = D_(f g)$ 非空
- 另一侧的证明是类似的:
$
f, g in.not I => D_f, D_g != emptyset => D_f sect D_g != emptyset => D_(f g) != emptyset => f g in.not I
$
]
#theorem[][
$V(I)$ 不可约当且仅当 $sqrt(I)$ 是素理想
]
#definition[][
设 $phi: A -> B$ 是环同态,它将诱导一个映射:
$
funcDef(phi^*, Spec(B), Spec(A), P, phi^(-1)(P))
$
(注意到素理想的原像是素理想)
并且满足:
- 主开集的原像是主开集,进而连续
- $Inv(phi^*) (V(I)) = V(I B)$, $I$ 是 $A$ 的理想
- $overline(phi^*(V(J))) = V(Inv(phi)(J))$
]
= Directed Limit | 正向极限
所谓 Directed Limit 是 coLimit 的一种特殊情况
#definition[Directed Set|正向集][
设 $I$ 是一个指标集,称 $I$ 是有向的,如果 $I$ 上有偏序且 $forall i, j in I, exists k in I : i <= k and j <= k$
]
#definition[Directed System][
设 $A$ 是环,$A-$ 模上的 Directed System |正向系统是指一个指标集 $I$ 以及:
- $phi: I -> A-"模"$
- $forall i, j, i <= j, exists$ 同态 $mu_(i j): M_i -> M_j$
- $mu_(i i)$ 是恒等变换
- $mu_(i j) compose mu_(k i) = mu_(k j)$
]
#let DLimit(t) = $lim_(arrow(#t))$
#definition[Directed Limit|正向极限][
给定 $I$ 是正向系统,称:
$
lim_(arrow(i in I)) M_i = plus.circle.big_(i in I) M_i quo generatedBy({x_i - mu_(i j) (x_i)| x_i subset M_i, i <= j})
$
为正向极限,并且给出典范的同态:
$
mu_i: M_i -> plus.circle.big_(i in I) M_i -> lim_(arrow(i in I)) M_i
$
显有 $mu_i = mu_j compose mu_(i j) forall j, i<= j$
]
#example[][
- 拓扑空间中某点的开邻域构成一个正向集(以反包含作为偏序),正向系统\
设 $C(U)$ 是邻域 $U$ 上的连续函数,则称
$
lim_(arrow(U in N(x))) C(U)
$
为 $x$ 点处连续函数的芽
]
#proposition[][
- $forall x in DLimit(i in I) M_i, exists i in I, x_i in M_i: mu_i (x_i) = x$
- $mu_i(x) = 0 <=> exists j >= i, mu_(i j)(x) = 0$
]
#proof[
- 将 $x$ 提升到直和上,设之为 $(x_i)_(i in I)$ \
直和要求仅有有限个不为零处,不妨从小到大设为 $i_1, i_2, ..., i_k$\
由于只有有限个元素,可以找到一个 $i$ 使得 $i_1, i_2, ..., i_k <= i$,进而:
$
x = sum_(j = 1)^k mu_(i_j)(x_(i_j)) = sum_(j = 1)^k mu_(i)(mu_(i_j i)(x_(i_j))) = mu_i (sum_(j = 1)^k mu_(i_j i)(x_(i_j)))
$
这就是原结论
-
- $arrow.l.double$ 显然
- $=>$ 由定义知 $x in generatedBy({x_i - mu_(i j) (x_i)| x_i subset M_i, i <= j})$\
注意到生成子模也是直和,其中仅有有限个指标参与运算。不妨设指标集为 $J$,每个指标 $j$ 在生成元中对应元素为 $i(j)$,所有这些元素将有下界 $m$,进而:
$
x_i = sum_(j in J) (x_(i(j)) - mu_(i(j) j)(x_(i(j))))\
mu_(i k)(x_i) = sum_(j in J) mu_(j k)(x_(i(j))) -mu_(j k) compose mu_(i(j) j)(x_(i(j))) = 0
$
最后一步是由相容性保证的,这就证明了原来的结论
]
#theorem[][
正向极限由泛性质唯一刻画,准确的说,设 $N$ 是 $A-$ 模,并且存在 $M_i -> N$ 的同态 $alpha_i$ 满足 $alpha_i = alpha_j compose mu_(i j)$,则存在唯一的同态:
$
alpha: DLimit(i in I)M_i -> N
$
满足 $alpha_i = alpha compose mu_i$
同时,若存在 $A-$ 模满足这样的泛性质,则它与正向极限同构
]
#example[][
设 $M_i$ 是一族子模,定义 $i <= j <=> M_i subset M_j$\
假设 $forall i , j in I, exists k : M_i + M_j subset M_k$\
此时便有:
$
DLimit(i in I) M_i tilde.eq union.big_(i in I) M_i
$
只需要验证 $union.big_(i in I) M_i$ 也满足之前所述的泛性质即可
]
#definition[正向系统的同态][
设 $(M_i, mu_i), (N_i, nu_i)$ 是两个以 $I$ 为指标集的正向系统,称两个正向系统的同态是:
- 一族同态 $phi_i: M_i -> N_i$
- 相容性条件 $nu_(i j) compose phi_i = phi_i compose nu_(i j)$
同时,在两个正向极限间将存在唯一的同态 $phi: M_i -> N_i$ 使得:
$
nu_i compose phi_i = phi compose mu_i
$
证明利用 $M_i$ 正向极限的泛性质即可
]
#theorem[][
设 $(M_i, mu_i), (N_i, nu_i), (P_i, alpha_i)$ 是三个正向系统,配合正向系统的同态:
$
phi_i : M_i -> N_i\
psi_i : N_i -> P_i
$
且对于每个 $i, M_i -> N_i -> P_i$ 正合,则对应的正向极限的链也正合
]
= 仿射代数簇
#definition[零点集][
设 $k$ 是代数闭域,$S subset k[x_1, x_2, ..., x_n]$,称 $S$ 的零点集为:
$
Z(S) = {p in k^n|f(k) = 0, forall f in S}
$
]
#proposition[][
- $S subset S' => Z(S') subset Z(S)$
- $Z(S) = Z(I(S)) = Z(sqrt(I))$
- $Z(0) = k^n, Z(k[x_1, x_2, ..., x_n]) = emptyset$
- $Z(I) union Z(J) = Z(I sect J) = Z(I J)$
- $sect_(n in N)Z(I_n) = Z(sum_(n in N)Z(I_n))$
进而 $Z$ 也给出一个拓扑,若取 $k = CC$,则这个拓扑将是欧式拓扑的子拓扑
]
#definition[理想|Ideal][
设 $Y subset k^n$,称 $Y$ 的理想为:
$
I(Y) = {f in k[x_1, x_2, ..., x_n]|f(p) = 0, forall p in Y}
$
它确实是 $k[x_1, x_2, ..., x_n]$ 的理想
]
#theorem[希尔伯特零点定理 1][
$
I(Z(J)) = sqrt(J)
$
]<Hilbert-Nullstellensatz1>
#proof[
它的证明非常复杂,留在后面
]
#proposition[][
- $Y subset Y' => I(Y') subset I(Y)$
- $I(Y union Z) = I(Y) sect I(Z)$
- $Z(I(Y)) = overline(Y)$
]
#proof[
- 显然
- 显然
- 显然有 $Y subset Z(I(Y))$,设 $W = Z(J) supset Y$ 是闭集,则:
$
Y subset Z(J) => J subset I(Z(J)) subset I(Y) => Z(J) supset Z(I(Y))
$
]
#theorem[希尔伯特零点定理 2][
$Z, I$ 在 $k[x_1, x_2, ..., x_n]$ 的根理想与 $k^n$ 的零点集之间给出了反序的一一对应,且:
- 素理想恰与不可约的闭集一一对应
- 极大理想恰与 $A^n$ 中的点一一对应,换言之极大理想均形如 $(x_1 - a_1, x_2 - a_2, ..., x_n - a_n)$ 这有时也被称作弱零点定理\
可以验证这个子映射给出了多项式环极大谱与 $A^n$ 的拓扑空间同胚
]
#proof[
设 $J$ 是根理想,则由@Hilbert-Nullstellensatz1:
$
I(Z(J)) = sqrt(J) = J
$
设 $Y$ 是闭集:
$
Z(I(Y)) = overline(Y) = Y
$
- 类似@irreducible-lemma0,假设 $Y$ 是两个闭集 $Z(A) sect Y, Z(B) sect Y$ 的并,也即:
$
Y subset Z(A) union Z(B) = Z(A sect B)\
I(Y) supset I(Z(A sect B)) = sqrt(A sect B) = sqrt(A) sect sqrt(B)
$
- 假设 $I(Y)$ 是素理想,则 $sqrt(A) sect sqrt(B) subset p$ 给出 $sqrt(A) subset p$ 或 $sqrt(B) subset p$,倒退即得两个闭集有一个为空,进而不可约
- 假设不可约,任取 $x, y in.not I(Y)$,若 $(x y) subset I(Y)$ 则:
$
sqrt(x) sect sqrt(y) = sqrt(x y) subset sqrt(I(Y)) => Z(x) union Z(y) = Z(sqrt(x) sect sqrt(y)) supset Z(sqrt(I(Y))) = Y
$
只需证明 $Z(x) sect Y, Z(y) sect Y$ 非空,事实上:
$
x in.not I(Y) <=> Z(I(Y)) = Y subset.not Z(x)
$
同理有 $Y subset.not Z(y)$,因此当然有 $Z(x) sect Y, Z(y) sect Y$ 非空
- 由反序性,极大理想当然与单点集一一对应
]
#corollary[][
- $k^n$ 是不可约的,因为它对应的理想 $(0)$ 在整环中是素理想
- 设 $f in k[x, y]$ 不可约,则 $(f)$ 是素理想,说明 $Z(f)$ 不可约
]
#definition[仿射代数簇|affine algebraic variety][
设 $k$ 是代数闭域,称 $Y subset k^n$ 是仿射代数簇,如果 $Y = Z(I)$,其中 $I$ 是 $k[x_1, x_2, ..., x_n]$ 的素理想
]
#definition[诺特空间|Noetherian Space][
称拓扑空间是诺特空间,如果:
- 闭集的降链最终稳定
- 开集的升链最终稳定
]
#proposition[][
- 诺特环的素谱/极大谱都是诺特空间
- 反之未必,存在不诺特的环使得素理想只有 $(0)$ 和唯一的极大理想,它的素谱,极大谱都是诺特空间
] |
|
https://github.com/WinstonMDP/math | https://raw.githubusercontent.com/WinstonMDP/math/main/exers/n.typ | typst | #import "../cfg.typ": *
#show: cfg
$
"Prove that"
all("divergent series with positive members" sum_(n = 1)^oo a_n): \
A_n = sqrt(sum_(k = 1)^n a_k) - sqrt(sum_(k = 1)^(n - 1) a_k) ->
sum_(n = 2)^oo A_n "diverges" and A_n =_(n -> oo) o(a_n)
$
$A_2 + A_3 + A_4 + ... + A_n =
sqrt(sum_(k = 1)^2 a_k) - sqrt(sum_(k = 1)^1 a_k) +
sqrt(sum_(k = 1)^3 a_k) - sqrt(sum_(k = 1)^2 a_k) +
sqrt(sum_(k = 1)^4 a_k) - sqrt(sum_(k = 1)^3 a_k) +
... =
sqrt(sum_(k = 1)^n a_k) - sqrt(a_1)$
$sum_(n = 2)^oo A_n$ diverges
$A_n = a_n/(sqrt(sum_(k = 1)^n a_k) + sqrt(sum_(k = 1)^(n - 1) a_k))$
$A_n/a_n = 1/(sqrt(sum_(k = 1)^n a_k) + sqrt(sum_(k = 1)^(n - 1) a_k)) -> 0$
$qed$
|
|
https://github.com/alex-touza/fractal-explorer | https://raw.githubusercontent.com/alex-touza/fractal-explorer/main/paper/src/style/page.typ | typst | /*#let header = context () => {
let get_header = () => {
let selector = selector(heading.where(level: 1)).before(here());
let elements = query(selector);
let current_page = here().page()
if elements.len() > 0 {
let el = elements.last();
let heading_page = counter(page).at(el.location())
if el.body.text != outline.title.text {
return el.body;
}
}
return false;
}
let number = counter(heading).at(here()).first();
let header = get_header()
if header == false {
return
}
set text(weight: "bold");
h(1fr)
[Capítol #number. ]
header
}*/ |
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/patterns/weeks/week6.typ | typst | #import "../../utils.typ": *
#subsection([Mutable Companion])
#set text(size: 14pt)
Problem | We need a way to mutate immutable variables later on, but that's
impossible. However, we can make a wrapper class around the immutable object and
just mutate that instead, e.g. creating a new instance of the immutable object
which isn't immutable.\
Participants :
- companion: factory object for immutable value
- immutable value
#set text(size: 11pt)
// images
```java
public final class YearCompanion {
private int value;
public YearCompanion(Year toModify) {
this.value = toModify.getValue();
}
public void next() {
value++;
}
public Year asValue() { // factory method
return Year.of(value);
}
}
// usage
var yearBuilder = new YearCompanion(
Year.of(2020));
yearBuilder.next();
var nextYear = yearBuilder.asValue();
```
#align(
center,
[#image("../../Screenshots/2023_10_27_10_55_32.png", width: 80%)],
)
#text(
teal,
)[The *asYear* function is called a *Plain Factory Method* that converts the
companion to the immutable value.]\
In multithreaded environments, it is often a good idea to combine methods as
that makes synchronization easier(*Combine Method idiom*):
#align(
center,
[#image("../../Screenshots/2023_10_27_10_56_56.png", width: 80%)],
)
#columns(
2,
[
#text(green)[Benefits]
- changes on immutable values
#colbreak()
#text(red)[Liabilities]
- requires double the amount of ram -> don't do this with extremely large structs
],
)
#subsection([Relative Values])
#set text(size: 14pt)
Problem | When we compare reference objects, we compare only the reference, how
can we make sure to compare the type/value instead? Create comparator(jafuck),
implement Eq trait(rust), overload comparison operators(C++).\
#set text(size: 11pt)
// images
```java
public final class Year implements Comparable<Year> {
@Override
public boolean equals(Object o) { // Bridge Method, override generic equals()
if (o == null || getClass() != o.getClass()) return false;
return equals((Year)o); // forward to typed method
}
public boolean equals(Year o) { // Override-Overload Method Pair
if (this == o) return true;
if (o == null) return false;
return value == o.value;
}
@Override
public int compareTo(Year o) { // Override-Overload Method Pair, Type Specific Overload
if (o.value == value) return 0;
return (value < o.value) ? -1 : 1;
}
}
```
#text(
teal,
)[Rust requires the Eq and PartialEq trait, C++ just requires overloading of
operators -> spaceship operator.]
#section("CHECKS Pattern")
How to differentiate good input from bad input -> ensure temperature has valid
value.
#align(
center,
[#image("../../Screenshots/2023_10_27_11_03_52.png", width: 100%)],
)
#subsection([Meaningful Quantities])
#subsubsection([Exceptional Behavior])
#set text(size: 14pt)
Problem | When receiving an input, the input can be an *exceptional value*, this
is often a null value or undefined -> Err value or None. This can be a valid
input for the backend, but the backend has to handle it.\
#set text(size: 11pt)
// images
```ts
export enum CalculationError {
DivByZero = "div/0",
NumeratorIsNaN = "NaN(numerator)",
DivisorIsNaN = "NaN(divisor)“
}
export class Calculator {
public static divide(numerator: number, divisor: number): number | CalculationError {
if (divisor === 0) { return CalculationError.DivByZero; }
if (isNaN(numerator)) { return CalculationError.NumeratorIsNaN; }
if (isNaN(divisor)) { return CalculationError.DivisorIsNaN; }
return numerator / divisor;
}
}
```
#subsubsection([Meaningless])
#set text(size: 14pt)
Problem | This is essentially just the idea of let's try to run it and handle
the errors later. E.g. try to divide by 0 and when something bad happens -> div
by 0, we will handle that state later.\
#set text(size: 11pt)
// images
```java
export class Calculator {
public static divide(numerator: number, divisor: number): number {
return numerator / divisor; // may result in Infinity (Java: NaN) if divisor is 0.0
}
}
```
#columns(2, [
#text(green)[Benefits]
- exceptions don't have to be added everywhere
#colbreak()
#text(red)[Liabilities]
- exceptions get a bit out of hand -> catch all needed
])
#section("Frameworks")
- implement common functionality
- don't reinvent the wheel
- avoid bad performance by using something that is established and optimized
- Control stays with user in contrast to a simple library
- *inversion of control*
- callback hooks
- extensions
- see react
#align(
center,
[#image("../../Screenshots/2023_10_27_11_22_33.png", width: 100%)],
)
#subsection("Application Frameworks")
- object-oriented class library
- main() lives in application framework
- provided hooks
- provides ready-made classes for use
- product lines use these -> office application all use the same base
#align(
center,
[#image("../../Screenshots/2023_10_27_11_20_41.png", width: 50%)],
)
#subsection("Micro Frameworks")
#subsubsection("Template Method")
The idea is, the abstract class provides methods that can be overriden and extended.
#align(
center,
[#image("../../Screenshots/2023_10_27_11_25_21.png", width: 80%)],
)
#subsubsection("Strategy")
Use different strategies based on context.
#align(
center,
[#image("../../Screenshots/2023_10_27_11_25_09.png", width: 80%)],
)
#subsubsection("Command Processor")
#align(
center,
[#image("../../Screenshots/2023_10_27_11_24_51.png", width: 80%)],
)
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/place-float-columns_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#set page(height: 200pt, width: 300pt)
#show: columns.with(2)
= Introduction
#figure(
placement: bottom,
caption: [A glacier],
image("/assets/files/glacier.jpg", width: 50%),
)
#lorem(45)
#figure(
placement: top,
caption: [A rectangle],
rect[Hello!],
)
#lorem(20)
|
https://github.com/tingerrr/typst-test | https://raw.githubusercontent.com/tingerrr/typst-test/main/.github/ISSUE_TEMPLATE/feature_request.md | markdown | MIT License | ---
name: Feature request
about: Request a feature or change in behavior
title: 'FR: '
labels: 'C-feature'
assignees: ''
---
<!--
Thank you for your feature request! Please describe your request here. For
questions, use the Typst community discord: https://discord.gg/2uDybryKPe.
Feel free to remove any of the sections below if they don't seem useful.
-->
## Description
A clear and concise description of what the problem is.
## Proposed Solution
A clear and concise description of what you want to happen.
## Alternative Solutions
A clear and concise description of any alternative solutions or features you've considered.
## Additional Context
Add any other context or screenshots about the feature request here.
|
https://github.com/Ayomided/Dissertation-report | https://raw.githubusercontent.com/Ayomided/Dissertation-report/main/Draft_Project_Report_6_Sep.typ | typst | #import "@preview/pintorita:0.1.1"
#set page(
paper: "us-letter",
margin: (top:2.5cm, right:2cm, bottom:2cm, left:2.5cm)
)
// Heading Styling
#show heading.where(level: 1): set text(22pt)
#show heading.where(level: 2): set text(18pt)
#show heading.where(level: 3): set text(16pt)
#show heading.where(level: 4): set text(14pt)
#show heading.where(level: 5): set text(12pt)
#show heading.where(level: 6): set text(11pt)
#show heading.where(level: 7): set text(11pt)
#show heading.where(level: 8): set text(10pt)
#show heading.where(level: 9): set text(10pt, style: "italic")
#set text(font:"Avenir", 11pt)
#set bibliography(style: "harvard-cite-them-right")
// Thesis title
#let Title = "This is the title, or not"
// Subject Degree
#let Subject = "Advanced Computing"
// Supervisor Name
#let Manager = "Stelios [NEED TO CONFIRM]"
// Birbeck Logo
#let Logo = image("Birbeck.svg", width: 35%)
#Logo
#v(12em)
#grid(
align: (center, center),
inset: 20pt,
columns: auto,
rows: (auto,40pt),
row-gutter: 10pt,
rect(width: 100%, stroke: none, text([#Title], fill: rgb(0, 0, 0, 100),28pt, weight: "extrabold")),
[[Comments]],
[*<NAME>*],
[*School of Computing and Mathematical Sciences\
Birkbeck, University of London*
],
[*XXX 000*],
[Draft],
)
#v(10em)
= Declaration
I, <NAME>, declare that the work carried out and reported on by this document and the contents of this document, titled *#Title*, and accompanying artefacts, except for where attributed to other sources by way of citations within the body of this document and listed under the References section of this document, is formed of my own original work, which has never before been produced for any other purpose, and has been created solely as part of delivery of *#Subject* for or under supervision of *#Manager*.
All information in this document and accompanying artefacts has been obtained and presented in accordance with the relevant ethical conduct and academic rules.
====== Signature:
// Insert Signature here
====== Date:
#datetime(
day: 28,
month: 08,
year: 2024
).display("[day]/[month]/[year]")
#set page(
numbering: "I",
header: [
#set text(11pt, fill: rgb(0, 0, 0, 90))
#set align(center)
#Title
],
footer: [
#set align(center)
#set text(11pt)
#counter(page).display(
"I",
)
]
)
= Abstract
This study explores the application of computational modeling techniques to optimize the performance of GitHub Actions within DevOps environments. As DevOps practices continue to grow, with up to 83% developer participation (Linux Foundation, 2024), enhancing efficiency in Continuous Integration/Continuous Deployment (CI/CD) processes becomes critical. This research develops models for resource usage analysis, execution time prediction, failure analysis, and security monitoring in GitHub Actions, which has become a dominant CI/CD tool since its release in 2019. The study leverages the frequent reuse of workflows in GitHub Actions, despite many workflows being outdated, to provide data-driven insights aimed at improving cross-team collaboration, resource allocation, and overall development efficiency.
The study aims to provide data-driven insights to improve cross-team collaboration, resource allocation, and overall development efficiency.
#v(56em)
#outline(
depth: 2,
indent: auto
)
#set heading(numbering: "1.")
#v(56em)
= Introduction
\
The software development landscape has undergone a significant transformation with the widespread adoption of DevOps practices. A 2024 report by the Linux Foundation indicates that up to 83% of developers are now involved in DevOps processes. This trend reflects the industry’s broader shift towards cloud-native architectures, with cloud providers like AWS leading the market. CI/CD tools like Jenkins and GitLab CI have been instrumental in this shift, but GitHub Actions has emerged as a key player due to its seamless integration with GitHub repositories and its ability to automate diverse workflows .
GitHub Actions, introduced in 2019, quickly became a dominant CI/CD tool, with over 43.9% of GitHub repositories utilizing it within 18 months of its release @Decan2022. This tool allows developers to automate tasks triggered by events such as code pushes, pull requests and regular schedules, integrating tightly with the GitHub ecosystem. Despite its advantages, GitHub Actions also introduces challenges related to resource usage, execution time predictability, failure rates, security, and cross-team collaboration, which this research seeks to address.
== Problem Statement
\
Despite the widespread adoption of GitHub actions since its introduction in 2018. There is still significant challenge in optimization that promotes performance and reduces costs. These challenges include:
- Resource Utilisation: Inefficient use of computational resources in CI/CD pipelines can lead to increased costs and reduced performance @Decan2022
- Execution Time Unpredictability: Unpredictable job execution times, often due to the reuse of outdated workflows without necessary updates, disrupt development schedules
- High Failure Rates: CI/CD pipelines frequently experience failures, with studies indicating that testing and integration issues are the most common causes at 10.0% - 17.4% failed workflow runs. @Bouzenia2024
== Research Objectives
\
This study aims to address these challenges by:
+ Developing computational models to analyse and predict resource usage in GitHub Actions.
+ Creating machine learning models for execution time forecasting.
+ Implementing pattern recognition algorithms for failure analysis and prevention.
== Structure
In @chapter2 we will go over the DevOps landscape along with its ...
#v(56em)
= Background <chapter2>
GitHub Actions (GHA), introduced in 2018, has rapidly emerged as a leading platform for automating CI/CD pipelines among developers. Its launch coincided with a shift in the CI/CD landscape, leading to a remarkable 43.9% adoption rate within just 18 months of its release @golzadeh_rise_2022. This swift adoption can be attributed to GHA's seamless integration with GitHub repositories and its flexible pricing model.
GitHub offers both free and paid tiers for Actions @GitHub. The free tier provides developers with 2,000 minutes per month and 500 MB of storage, making it accessible for small projects and individual developers. For larger teams and more demanding workflows, paid plans offer increased minutes and storage capacity. The pricing structure is based on usage, with costs calculated per minute of execution time and per GB of storage used.
#figure(
table(
align: center,
columns: (1fr, 1fr, 1fr),
inset: 5pt,
rows: auto,
table.header(
[*Plan*],[*Storage*],[*Minutes (Per month)*],
),
[GitHub Free],[500MB],[2,000],
[GitHub Pro],[1GB],[3,000],
[GitHub Team],[2GB],[3,000],
[GitHub Enterprise Cloud],[50GB],[50,000],
), caption: "GitHub Action Pricing 2024"
) <table-gh-pricing>
This table outlines the storage and minutes included in various GitHub plans. For usage beyond these limits, GitHub charges \$0.008 USD per GB of storage per day and applies per-minute rates based on the operating system used by the GitHub-hosted runner.
The pricing model also includes minute multipliers for different operating systems:
Linux: 1x (base rate)
Windows: 2x
macOS: 10x
These multipliers affect the consumption of included minutes but do not apply to the per-minute rates for additional usage.
GitHub Actions' flexibility and integration capabilities have made it a popular choice for automating various aspects of the software development lifecycle, including continuous integration, continuous deployment, and automated testing. Its ecosystem has grown to include a marketplace of pre-built actions, allowing developers to quickly implement complex workflows without starting from scratch.
As organizations increasingly rely on GitHub Actions for their development processes, understanding its pricing structure and optimizing workflows for both performance and cost-efficiency has become an important consideration in the software development landscape.
Even with the adoption of GitHub Actions (GHA), the need for optimization remains apparent. GitHub offers some built-in optimization options, such as caching and fail-fast strategies @Bouzenia2024. However, these methods provide only limited benefits. Additionally, due to insufficient documentation, many developers are unfamiliar with how to properly implement these features, which can lead to inefficient performance.
The lack of comprehensive guidance on these optimization techniques presents a challenge for developers trying to maximize the efficiency of their GitHub Actions workflows. This situation highlights a gap between the potential for optimization that GitHub Actions offers and the practical ability of many developers to implement these optimizations effectively.
#v(56em)
= Analysis
== Introduction
This chapter presents a comprehensive analysis of the proposed GitHub Actions monitoring system, addressing the key challenges identified in the problem statement: resource utilization, execution time unpredictability, and high failure rates. The analysis draws from empirical studies and industry data to provide a thorough examination of these issues and their potential solutions.
== Problem Analysis
=== Resource Utilization Challenges
According to the study by @Bouzenia2024, GitHub Actions, while powerful and widely adopted, often leads to inefficient use of computational resources. Their research found that CI/CD processes can be expensive, costing around \$504 per year for an average paid-tier repository. The study identified that the majority of resources are consumed by:
- Testing *(percentage not specified)*
- Building *(percentage not specified)*
These processes are primarily triggered by:
- Pull requests (50.7%)
- Pushes (30.9%)
- Regular scheduled workflows (15.5%)
The inefficient resource utilization results in:
1. Increased operational costs for organizations
2. Reduced overall performance of CI/CD pipelines
3. Environmental impact due to unnecessary resource consumption
=== Execution Time Unpredictability
The study by @Decan2022 observed that the reuse of outdated workflows without necessary updates has led to significant unpredictability in job execution times. Their research found that:
- Most workflows run on virtual machines (Action runners)
- The study analyzed 1.3 million runs over 30 months across 952 repositories
- Paid-tier workflows take 7-100x longer than free-tier workflows, depending on the triggering event
This unpredictability manifests as:
1. Disruptions to development schedules
2. Difficulty in planning and allocating resources effectively
3. Reduced developer productivity due to unexpected delays
@Bouzenia2024 further noted that pull requests in paid-tier repositories cost an average of 36 cents, compared to only 4 cents in free-tier repositories. This significant difference highlights the need for optimization, especially for paid-tier repositories.
=== High Failure Rates
The @Bouzenia2024 study reported failure rates of 10.0% - 17.4% in workflow runs, primarily due to testing and building issues. These high failure rates necessitate:
1. Robust failure analysis mechanisms
2. Predictive models for potential failures
3. Automated strategies for failure prevention and quick resolution
A specific example highlighted in the research shows a repository with a scheduled workflow set to execute every 5 minutes, which experienced 12,000 consecutive failures over several months. This case underscores the critical need for optimization techniques tailored to address failing jobs, timed-out workflows, and other types of failures.
== Current Optimization Techniques
=== Caching
@Bouzenia2024 identified caching as a mechanism provided by GitHub Actions to reuse files across multiple runners, reducing network utilization and runtime.
Prevalence and Impact:
- 32.9% of paid-tier repositories use caching
- 17.8% of free-tier repositories use caching
- Reduces execution time by an average of 3.4% for paid-tier and 6.0% for free-tier repositories
- Leads to an annual cost reduction of \$21.48 for paid-tier repositories
Despite its ease of use (requiring only one line addition to the workflow file) and impact on VM time, caching is underutilized, especially in paid-tier repositories.
=== Fail-Fast Strategy
The @Bouzenia2024 study also examined the fail-fast strategy, which applies to workflows that define a matrix of jobs, canceling all in-progress and queued jobs in the matrix as soon as any job fails.
Prevalence and Impact:
- Adopted by 83.5% of free-tier repositories
- Adopted by 75.9% of paid-tier repositories
The high adoption rate is likely due to its default enabling in matrix jobs. However, the specific time and cost savings were not quantified in the provided research.
== System Architecture Analysis
The proposed monitoring system architecture consists of several interconnected components:
1. Self-hosted Runner: Executes jobs and workflows, providing the primary source of data.
- Advantage: Offers full control over the execution environment.
- Challenge: Requires careful resource management to avoid impacting job performance.
2. cAdvisor: Collects hardware-level metrics from the runner.
- Advantage: Provides detailed resource utilization data with minimal overhead.
- Challenge: Requires secure deployment and maintenance on each runner.
3. Custom Log Exporter: Captures detailed job and step-level metrics.
- Advantage: Offers granular insights into workflow performance.
- Challenge: Needs to balance between data detail and collection overhead.
4. Prometheus: Serves as the central metrics collection and storage system.
- Advantage: Scalable and widely-supported time-series database.
- Challenge: Requires careful query optimization for large-scale deployments.
5. Central Aggregation Service: Processes and analyzes collected data.
- Advantage: Enables complex data processing and integration with machine learning models.
- Challenge: Must be designed for scalability and fault tolerance.
6. Machine Learning Models: Processes data for predictive analytics.
- Advantage: Provides insights for optimization and failure prediction.
- Challenge: Requires continuous training and validation to maintain accuracy.
7. User Dashboard: Visualizes data and insights for end-users.
- Advantage: Offers intuitive interface for monitoring and decision-making.
- Challenge: Must balance between comprehensive data display and user-friendliness.
This architecture addresses the identified challenges by providing a comprehensive monitoring and analysis solution for GitHub Actions workflows.
== Conclusion
The analysis, drawing from studies like "Resource Usage and Optimization Opportunities in Workflows of GitHub Actions" and "On the Use of GitHub Actions in Software Development Repositories," reveals significant opportunities for optimization in GitHub Actions workflows. The high costs associated with CI/CD processes, particularly for paid-tier repositories, underscore the importance of efficient resource utilization. Current optimization techniques like caching and fail-fast strategies show promise but are underutilized or not fully leveraged.
The proposed monitoring system architecture offers a comprehensive approach to addressing these challenges, providing detailed insights into resource usage, execution times, and failure patterns. By leveraging this system, organizations can potentially reduce costs, improve workflow efficiency, and enhance overall development productivity.
#v(10em)
= Implementation
== Data Pipeline setup
GitHub offers the ability to self host action runners which run on own hardware, by offering this both paid and free repositories, can set the resources they use for running their actions and CI/CD processes.
Since GitHub action runners typically run on virtual machines, option to run self hosted also provides the option to perform monitoring on the hardware and hence the the GitHub actions runner. In this implementation we will be using Prometheus, an open source systems monitoring and alerting toolkit.
Prometheus collects metrics and stores it as time series data which is the data shape which we want for our modeling. What this means is metrics are stored with time stamps alongside optional key-value pairs called labels.
Prometheus metrics typically look like.///
```Go
HELP go_threads Number of OS threads created
TYPE go_threads gauge
go_threads 7
```
#v(56em)
#bibliography("project_ref.bib",style: "harvard-cite-them-right") |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/repeat_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 2:2-2:13 repeat with no size restrictions
// #set page(width: auto)
// #repeat(".") |
https://github.com/Coyenn/thesis-template | https://raw.githubusercontent.com/Coyenn/thesis-template/main/document/main.typ | typst | #import "template.typ": *
#show: project.with(
title: "My Topic",
authors: (
(name: "<NAME>", email: "<EMAIL>"),
),
)
= Thesis
#lorem(30)
@my_source
#figure(
image("../dist/chart.svg", width: 50%),
caption: [
A caption
],
)
```js
const test = "Hello World"
console.log(test);
```
#pagebreak()
#bibliography("../bibliography/bibliography.yml") |
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/visualize/gradient-conic.typ | typst | Apache License 2.0 | // Test conic gradients
---
#square(
size: 50pt,
fill: gradient.conic(..color.map.rainbow, space: color.hsv),
)
---
#square(
size: 50pt,
fill: gradient.conic(..color.map.rainbow, space: color.hsv, center: (10%, 10%)),
)
---
#square(
size: 50pt,
fill: gradient.conic(..color.map.rainbow, space: color.hsv, center: (90%, 90%)),
)
---
#square(
size: 50pt,
fill: gradient.conic(..color.map.rainbow, space: color.hsv, angle: 90deg),
)
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/037%20-%20Ravnica%20Allegiance/008_The%20Gathering%20Storm%3A%20Chapter%2014.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Gathering Storm: Chapter 14",
set_name: "Ravnica Allegiance",
story_date: datetime(day: 11, month: 09, year: 2019),
author: "<NAME>",
doc
)
The city of Grek’ospen was old, as places in the Undercity went. The domains of the Golgari were ever-shifting, ever-renewed, everything recycled and reborn through the cycle of rot. It was one of the things that made it so difficult for the surface-dwellers to attack them—no map of the Swarm’s domains remained accurate for long.
But at Grek’ospen, the kraul had turned that cycle of decay to their own ends, and made a virtue of necessity. A river ran through the center of the huge cavern, and the air was heavy with moisture, which collected and dripped over innumerable stalagmites and stalactites. With the careful work of centuries, the kraul had coaxed these natural rock formations to grow according to their own plan, forming the bones of their massive hive towers. Fungal growths formed a part of the blueprints, too, huge shelf mushrooms serving as spongy floors, while colorful, decorative growths climbed up walls made of kraul resin.
Seeing Grek’ospen and cities like it had made Vraska first realize how much she admired the kraul. They embodied the true spirit of the Golgari, far more than the decadent devkarin. Individual kraul came and went, but the hive endured, growing bit by bit through every cycle of growth and decay.
#emph[And now we’re going to demolish the work of centuries in a few hours, because Ral Zarek can’t leave well enough alone.]
"Your people are in place?" she said to Mazirek.
The huge black kraul stood on one side of her, opposite the small, sickly-looking white form of Xeddick. Mazirek dipped his forelegs in obeisance, but there was a hesitation that she didn’t have to be an insect to interpret. #emph[Xeddick’s right. This one has grown too proud.]
"We are, Queen," he said. "Everything is waiting for your command."
#emph[The surface-dwellers are on the way] , Xeddick said in her mind. #emph[The trolls are angry at being held back.]
"They’ll get their turn." #emph[Almost certainly.] Vraska squared her shoulders and strode out into the open space that formed the center of the beautiful kraul city. #emph[If Ral is as stubborn as I think he is.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Once again, Ral found himself at the head of an army. These were not the armored, disciplined troops of the Boros Legion, however. The Orzhov forces were a teeming mass of black and gold, obedient but without the smooth precision of the professional soldiers. The majority of them were thrulls, scuttling things that were only vaguely humanoid, no two quite alike. They bore no weapons, only blank-faced masks of ancient coinage, but Ral had been on the receiving end of their mad fury in his assault on Orzhova and had no illusions about how dangerous they were.
Among them walked the knights, the Orzhov’s elite killers, in black armor inlaid with gold and carrying a bewildering variety of weapons—bows, swords, pole-arms, flails, and even more exotic contraptions. There were even a few giants, helmeted and faceless.
Kaya walked beside him, apparently carefree, as they made their way down the long, winding path into the caverns. Scouts had cleared the way, of course, and reported no contact with Golgari forces. #emph[Even so. She could have the decency to act a little nervous.] He certainly was.
"And this just goes on #emph[forever] ?" Kaya said, gesturing at the tunnel.
It was some ancient road, with the ruined walls of buildings still visible beside it, now buried beneath rock and debris by who-knew-what catastrophe. After ten thousand years, Ravnica was a city built on the ruins of itself, layer by layer.
"As far as anyone has been able to tell," Ral said. "There are oceans down here, if you dig far enough. The Simic zonots stretch down that far."
"Gods and monsters," Kaya said, shaking her head.
"Not much like where you grew up?" Ral said.
Kaya snorted. "I was born in a town with less than a hundred people. We have cities on my Plane, but not like this"
Ral tried to imagine that, living someplace where you could know #emph[everyone] , with none of the casual anonymity of a packed street. His mind rebelled.
"Mind you, I’ve been around a bit since then," Kaya said. "Spent a lot of time in cities, in fact. They tend to get a lot of ghosts."
"Ghost hunting is a curious business," Ral said.
"Someday I’ll tell you how I got started," Kaya said. "But it’s a long story, and I think we’re nearly there."
Ral nodded. Up ahead was a line of scouts, lightly armored Boros Legion goblins with crossbows slung over one shoulder. The road they were following passed through a half-collapsed brick archway into a larger space, and they’d stopped on the near side. Their lieutenant scurried over to Ral.
"We’re in the right place," she said. "Still no sign of the Golgari, but the cavern is as built-up as any neighborhood topside. Lots of places to hide."
"Wonderful," Ral said, glancing at Kaya. "This could get very ugly."
"Send the thrulls in," she said. "That’s what they’re for."
Ral nodded, but the scout spoke up.
"There’s someone waiting in the center of the city, sir. Looks like they’re waiting to speak to you. It’s . . . well, it looks like Vraska herself."
"That has to be a trap," Kaya said.
"Or an opportunity," Ral said. "All right. I’ll see what she wants. Bring the rest of our forces up behind, but try not to start any fights until you get my signal."
Kaya looked like she wanted to object, but she only frowned and nodded. Ral gestured for a couple of the scouts to follow and set off through the archway. Grek’ospen was as large as he’d been expecting, a vast, vaulted cavern, dimly lit by dozens of glowing green globes suspended high overhead. The architecture was alien, smooth rock and wet fungus layered over with papery stuff that put him in mind of a beehive. The towering spires had entrances on many levels, connected by soaring bridges or simply opening into space. #emph[All right, I suppose, if you’ve got wings.]
The lieutenant led him on a winding path, skirting the bases of several of the towers. Nothing seemed to move, not on the ground or overhead. #emph[Vraska must have evacuated.] He took a deep breath. #emph[If she offers to let us have the node, I have to take it and be thankful.] Eager as he might be to punish her betrayal, it could wait. #emph[Completing the plan is all the matters, until Bolas is defeated.]
They reached the central clearing, where a half-dozen spires all opened onto a space that might have been a town square. A narrow river cut through it, burbling in its course, with a dozen small footbridges crossing it. In front of these stood Vraska, dressed in dark, segmented leather-and-mail armor with a saber at her side. The green tendrils that gorgons sported in place of hair stood out from her skull, making her look larger.
"Stay here," Ral said. "If she tries anything, get back to Kaya and order the attack."
The lieutenant nodded, and Ral set off alone across the square. Vraska waited, arms crossed, until he stopped about twenty paces away. She raised her voice and called to him.
"A bit far for pleasant conversation, surely."
"Given the results of the guild summit," Ral said, "you’ll forgive me if I’m not eager to meet face to face."
"What a shame," Vraska said. "With that hair of yours, you’d make a wonderful addition to my sculpture garden."
Ral clenched his fists, feeling electricity crackle. His heart was beating hard. He knew first-hand how deadly Vraska could be, even if he hadn’t seen what she’d done to someone as powerful as Isperia. #emph[She has to be up close to use her petrification.] And a little research in the Izzet library had suggested that there was a moment’s warning before the effect took hold, a glow in the gorgon’s eyes that gave a prospective victim time to get out of the way. Even so, Ral wasn’t eager to test his reflexes against Vraska.
"Well?" he said. "I assumed you were waiting here because you wanted me to come and talk. Here I am."
"Here you are, with your strange little army," Vraska said. "But why? Revenge?"
"It ought to be," Ral said. "How can you work for Bolas? Don’t you know what he’ll do to you—to #emph[all] of us—if he wins?"
"And you’re so confident Niv-Mizzet will be a benevolent despot, once we give him leave to turn himself into a god?" Vraska shook her head, tentacles squirming. "I don’t have to explain myself to you, Zarek."
"You don’t." Ral paused. "And we’re not here for revenge. Someday, there may be a reckoning. But for now all we need is this place." He waved at the city around them. "Don’t interfere, and none of your people will be harmed."
"That’s all you need. One of the most ancient cities of the Golgari. So generous, you surface-dwellers."
"Then you plan to fight."
Vraska smiled, her teeth sharp and predatory. "I plan to #emph[win] ."
She raised a hand. Ral brought his gauntlets up, readying for a sudden rush, but the Gorgon didn’t move. Instead, far above, he heard the sound of distant thunder, and the floor of the cavern shook beneath his feet. Ral looked over his shoulder at the scouts, and found them stumbling and uncertain.
"What—" he called back to them, and then the roof fell on them.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Fireballs bloomed across Grek’ospen, along tower after tower.
Certain types of kraul resin, when properly treated, were highly explosive. The stuff was too heavy and unstable to make much of a weapon, but Vraska’s kraul engineers had had plenty of time to position it in advance, uncomplainingly turning their own ancient city into a carefully constructed deathtrap. The blasts sent washes of resin spurting from the spire doorways, followed by clouds of dust and choking black smoke. Then, slowly, the resin-and-fungus buildings began to collapse, their stone cores shattered.
Two of the largest fell across the archway the surface forces had used to enter the city, trapping many of them in the tunnel. If the trolls remembered their instructions, the blast was their signal, and Vraska had every hope that Ral’s rearguard would find itself beset by a mass of ravening, regenerating monstrosities. In the meantime, spires collapsed across the city, scattering shards of stone and fungus, blocking streets and separating the enemy forces into a hundred tiny pockets. Cut off from one another and from their leaders, they would be easy prey for the Golgari troops swarming from every tunnel and crevasse.
#emph[And speaking of leaders . . .] Vraska had kept her footing, and her engineers had arranged it so none of the spires would crush the central square. Dust and smoke filled the air, but she could see Ral retreating, in the company of one of his scouts. Vraska drew her saber with a fierce smile and set off after him.
The second scout, a goblin woman in Boros-silver armor, barred her way, and Vraska sidestepped a well-aimed arrow. The scout nocked another, and Vraska tensed to dodge, but before the Boros soldier could loose she staggered sideways. The bow fell from her hands as she clutched at her throat, face turning an ugly blue-black. With a choking gasp, she collapsed, legs kicking at the dirt. Mazirek stepped out of the smoke beside Vraska, his forelimbs still wreathed in flickering auras of death-magic. Xeddick came up on her other side, and she felt his concern press at her mind.
"I’m fine," she growled. "Come on. We’re going after Zarek."
Kraul droned through the air all around them as they pressed into the newly shattered city, flights of the big insects swooping and descending on the surface-dwellers wherever they found them. Crossbow bolts zipped upward, and magic boomed and crackled. Vraska heard the war cries of devkarin elves throwing themselves into battle, desperate to prove their loyalty to their new queen, and the dark intonations of Orzhov warrior-priests.
There was nothing she could do now, no control she could exert over the battle. That was fine, as far as she was concerned. She had never been a general, a leader.
#emph[What I am] , she thought, as she stalked Ral through the rubble, #emph[is an ] assassin#emph[.]
Enemy soldiers, cut off and confused, threw themselves at her. A dozen thrulls swarmed out of a broken doorway. Mazirek blasted several apart, and Vraska charged the rest, saber whirling around her in an exuberant dance of death. She left the inhuman creatures slashed and broken on the stone, their blood painting the wreckage, and went in search of more prey.
#emph[I was a fool.]
An Orzhov knight confronted her, a huge man with a greatsword that left shining golden trails in the air. He was a slow, lumbering thing, but his heavy armor turned her saber in a shower of sparks, and he confidently pressed his attack, massive blade swinging back toward her.
#emph[A fool to believe Zarek. To trust ] Jace#emph[. To believe what he told me about myself.]
Vraska ducked, letting the greatsword slice so close it clipped one of her tendrils. When it was past, she popped up inside the man’s reach, and let the power build behind her eyes. The glow washed over him, and he stiffened into solid, lifeless gray. She spun away from him, laughing.
#emph[This is what I was made for. ] She stalked through the smoke and dust, leaving death in her wake. #emph[This is who I am.]
#emph[Bolas knew that all along. I just . . . forgot myself.]
#emph[Forgot yourself?] Jace’s voice floated up from her memory. #emph[Or discovered you had a choice?]
#emph[Shut. Up. ] Vraska’s grin turned into a fixed snarl, and she pushed forward, dismembering another pack of thrulls and lashing the priest that accompanied them into bloody chunks. #emph[I never should have listened to you. Never should have . . .]
#emph[Boom.] Something shook the ground, again. #emph[More charges?]
She pulled up short at a gap in the wall of a fallen tower. From here, through gaps in the drifting smoke, she could see most of the city, including the archway where the surface-dwellers had entered. It was solidly blocked by chunks of stone and fungal debris, but as she watched a bit piece of rock hurtled away from the blockage, landing with a #emph[crunch] and a plume of dust. Another followed, and another. #emph[Something’s clearing the way.]
What stepped through, when the gap was big enough, was bigger than a giant, walking on seven spindly legs, with two massive arms ending in enormous fists and a third that projected some kind of tube. It twisted this last to aim near its feet, and a wash of flame burst out, running over the shattered stones like liquid. On the thing’s head, smaller shapes danced and capered with glee.
It wasn’t a creature, Vraska realized. It was a #emph[thing] , a construct, mizzium and steel assembled into a titanic killing machine in some mad chemister’s workshop. And it wasn’t the only one. As soon as it cleared the entrance, another huge vehicle came through, this one rumbling over the ground on overlapping treads. A third, bipedal, staggered after it, its upper portion already ablaze, to the consternation of its goblin crew. Then another, and another . . .
Vraska snarl grew broader. She lowered her gaze and saw Zarek, standing on a hunk of broken rock, watching the arrival of his reinforcements with a look of smug satisfaction.
#emph[I’ll wipe that look off your face.] Banishing the memory of Jace to the bottom of her mind, Vraska hurled herself forward.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The war-constructs of Nivix came through the gap, on legs and wheel and treads. Ral had emptied the laboratories of everything that could possibly serve as a weapon, every doomsday project and hidden secret. They were a motley group, not working together in the slightest, and several of them had already broken down, caught fire, or exploded. But those that remained were devastating, belching flame over the advancing Golgari hordes, sweeping them aside with vast limbs, or slashing them to pieces with a hundred rotating blades.
#emph[At least ] one#emph[ thing going according to plan.] He hadn’t expected Vraska to blow up her own city, just to throw his forces into confusion. He coughed at the smoke-choked air and wiped his forehead—a splinter of rock had nicked him, sending a steady trickle of blood down from his hairline and threatening to get into his eyes.
What was supposed to have been an organized battle had fragmented into a hundred tiny melees, and there was no way to tell who was winning and who was losing. Ral concluded he had better get himself back to the tunnel—#emph[Maybe I can find Kaya] —when he heard approaching footsteps. He spun, just in time.
#emph[Vraska] . She was #emph[fast] , faster than she had any right to be, springing off a broken stone wall and coming at him at a dead run, tendrils trailing behind her. Ral raised one palm, and lightning crackled out, snapping at her like a vicious dog. She dodged, then sprang backward as he sent another bolt after her.
"Mazirek!" she shouted. "Now!"
Something moved in the rubble. A humanoid—no, a #emph[former] humanoid, the corpse of a person now rotted down to scraps of skin and bones. Fungal growths held the thing together, and it shambled forward in a parody of life, disintegrating even as it came on. #emph[Rot zombie.] Ral flicked his fingers and blasted the slow-moving thing to burning cinders, but two more had already emerged, climbing up and over the broken rocks and bits of house-sized fungus. He burned those as well, and took a step back as a half-dozen of the things came into view.
"The thing is, Ral, I know you." Vraska’s voice came from somewhere he couldn’t see, among the rubble. "I know your strengths, and I know your weakness. We’re a long way from the sky, down here. No power for you to draw on. And you’ve got that accumulator on your back, but . . ." She gave a grim chuckle. "How long will it last?"
"Long enough," Ral snarled, as his lightning played across the line of undead. #emph[I hope.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Kaya twisted away from the troll’s swinging fist, her daggers drawing lines of green blood from its forearm. It roared and spun to follow her, the wound already healing. Kaya swore under her breath and backpedaled, waiting for an opportunity.
It came when the troll lunged forward, both arms outstretched to wrap her in a deadly bear hug. Kaya stepped sideways, phasing through the troll’s left arm, and planted one of her daggers in its shoulder. Using the blade as a handhold, she vaulted atop the ugly creature, grabbing the mane of matted hair at the back of its thick neck. She used the leverage to lean forward and drive her other dagger to the hilt in its eye.
The troll bucked and roared, and for a moment she thought it would survive even this, but eventually it got the message that it was dead and slumped forward to the rocky ground. Kaya dismounted, retrieved her daggers, and looked around.
There was a distressing lack of friendly forces anywhere nearby, she discovered. She’d had a pair of knights and a squadron of thrulls escorting her, but the troll had left their broken corpses scattered across the shattered alley. On the other hand, there were no enemies immediately apparent either. The main battle seemed to be centering on the tunnel entrance, where the Izzet constructs were tearing into the Golgari horde, but there were scattered detachments of Orzhov soldiers, flying kraul, and who knew what else fighting desperate skirmishes throughout the city. Kaya saw lightning flashing from a rock outcrop some distance off, which probably meant Ral, and she’d decided to head in that direction for lack of any better options when someone called out to her.
"Guildmaster!" A woman in the colors of an Orzhov priest dropped from a half-destroyed wall. "Are you hurt?"
"Just a few scratches," Kaya said, give her daggers a twirl and sheathing them. "I’m pretty thoroughly lost, though. Where are the other commanders?"
"The Knight of Despair sent me to find you," the priest said, with a bow. "He took command when you were cut off."
"Good for him," Kaya said.
"We should get back as soon as we can." The priest gestured at a gap in the rocks. "This way. We can stay clear of enemy forces."
Kaya nodded. The priest straightened up as she came forward—
#emph[And shouldn’t she be leading the way, not waving me onward like a palace flunky?]
Nasty, suspicious thoughts like these had played an important role in keeping Kaya alive all these years, and they proved their worth again, because she was already twisting aside when steel gleamed in the priest’s hands. She was too close to evade the blow entirely, but what was intended to be a stab in the kidney turned into a shallow cut along her ribs, bleeding freely but not seriously.
Kaya danced backward, snatching her own daggers from their sheathes. The priest flipped the small knife to her left hand and drew a larger blade with her right, dropping into a fighting crouch. They watched each other for a long, wary moment.
"I don’t suppose I can convince you this is a bad idea," Kaya muttered.
"You are a blight on the Orzhov," the woman hissed. "You must be removed."
"Didn’t think so."
Kaya charged, taking her opponent off-guard. Even so, the woman was good, offering her larger blade as a feint while aiming to strike Kaya’s flank with the smaller weapon. Kaya spun out of the way, circling, but the priest backed off with a slash that would have opened Kaya’s guts if she’d pushed too far forward. They squared off again, knives gleaming.
#emph[I haven’t got time for this] , Kaya thought. The wound in her side hurt like hell, and her shirt was matted with blood. All around them, kraul buzzed through the air, arrows flew, and magic crackled and boomed.
She charged again, and this time, when the priest lashed out with her long blade, Kaya phased right through it. Her body, glowing with purple energy, passed through the other woman’s like the ghosts that were Kaya’s prey, and once she was past she rematerialized and dropped into a spinning low kick that scythed the priest’s legs out from under her and sent her sprawling. Kaya rolled on top of her, one boot coming down hard on the woman’s hand where she still held her small knife, one of Kaya’s blades pressed tight across her opponent’s throat.
"Now," Kaya said. "Who are you working for? Which of my oh-so-loyal guildmates wants me dead?"
"Does it matter?" the priest spat back, her eyes defiant. "When we kill you, we will capture your spirit, and keep it in our dungeons to torture until there is nothing left of you but madness and pain—"
The woman’s eyes bulged, and her back arched. A moment later, blood welled from her mouth and eyes, and she sagged limply to the rock. Kaya felt a lingering trace of death-magic waft away on the breeze.
"Wonderful," she said aloud, rolling wearily off the corpse. She clambered to her feet, sheathed her daggers, and started walking in the direction of the near-continuous lightning flashes. "Just wonderful."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#linebreak The last wave of rot-zombies got closer than any of the others, clawed hands scrabbling at Ral’s clothes as they backed him against a tumbled rock, new decayed faces pressing in as he burned one after another. Lightning crackled around him like the bars in a cage, sprayed in gouts from his hands, and the dead crumpled and combusted under the forces of it. Eyes boiled and burst, skin blackened, rotten bones shattered. But still they came on, and he could feel the power in his accumulator running low, like a sick feeling in his gut.
"That’s enough, I think," Vraska said. The curtain of rot-zombies parted, and the gorgon strode forward, hands on her hips, the big black kraul on her right and the smaller white one on her left. "Well, Zarek? Feel like surrendering? I can be merciful, you know."
Ral fought for breath, a painful stitch in his side, and raised his hands again. Power crackled across them, but weakly. An arc of energy connected him to Vraska, and she flinched for a moment, then shrugged as it faded away.
"As I thought." The gorgon stepped forward. "I think I #emph[will] add you to my collection."
Her eyes began to glow.
"You will do no such thing, traitor!"
The voice thundered down from above, and Vraska sprang backward, drawing her saber. A moment later, Aurelia hit the earth in front of Ral, the force of her dive blasting out in a shockwave that cracked the stone and made Ral’s teeth buzz. The angel stood, facing the gorgon, and held out her hand. A long blade made of pure light took shape.
"I had my differences with Isperia," Aurelia said. "I cannot deny it. But I also cannot deny her commitment to the common good, to the defense of Ravnica, in spite of any philosophical arguments that might have divided us. She trusted you, and invited you to our meeting in good faith. You turned that trust against her." The angel levelled her blade at Vraska. "For that, I cannot forgive you."
"The common good," Vraska snarled. "What a comfort that is to everyone who was tossed into a cage and beaten on her orders."
Aurelia spread her wings, and closed the distance between them with a single mighty beat. Vraska stood her ground, her steel blade intercepting the angel’s magical one with a sound like nails on glass. Vraska’s skill with her saber with evident, but Aurelia was far stronger, and step by step the gorgon was driven back. The angel fought with a calm efficiency that belied the fury of her words, hammering at Vraska’s defense, darting back out of range whenever the gorgon’s eyes lit up with her petrifying gaze.
In the end, it was the saber in Vraska’s hand that could take no more. She parried, cross-wise, and the weapon shattered, fragments of steel pinging off the surrounding rocks. Vraska stumbled backward, wide-eyed, her tendrils writhing, a long cut on one cheek bleeding green.
"Mazirek!" she shouted, back-pedaling as Aurelia advanced.
But it was the albino kraul who appeared, cutting in between the gorgon and the angel. Ral felt the thing’s voice echo in his mind, loud enough to send him to his knees in pain.
#emph[NO!] the kraul telepath blasted out. #emph[Run, friend-Vraska!] #emph[] #linebreak "Xeddick!" Vraska screamed, hands clapped over her ears in a useless attempt to keep out the telepathic scream.
Aurelia alone withstood the mental assault, leaning forward like someone walking into the teeth of a storm. She took one step forward, then another, wings fully outstretched. The white kraul focused on her, redoubling his attack, and for a moment the angel halted.
#emph[Run] , the mental voice command. #emph[Please.] #emph[] #linebreak Vraska swore violently and threw herself over the nearest rocky barrier, vanishing from view just as Aurelia took another step forward. Her blade of light came down, carving the white kraul’s head in two in an explosion of ichor. The insect collapsed, and the mental pressure vanished all at once, leaving Ral panting for breath. His vision went gray for a moment. When it cleared, Aurelia stood in front of him, stretching out a hand.
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-2150.typ | typst | Apache License 2.0 | #let data = (
("VULGAR FRACTION ONE SEVENTH", "No", 0),
("VULGAR FRACTION ONE NINTH", "No", 0),
("VULGAR FRACTION ONE TENTH", "No", 0),
("VULGAR FRACTION ONE THIRD", "No", 0),
("VULGAR FRACTION TWO THIRDS", "No", 0),
("VULGAR FRACTION ONE FIFTH", "No", 0),
("VULGAR FRACTION TWO FIFTHS", "No", 0),
("VULGAR FRACTION THREE FIFTHS", "No", 0),
("VULGAR FRACTION FOUR FIFTHS", "No", 0),
("VULGAR FRACTION ONE SIXTH", "No", 0),
("VULGAR FRACTION FIVE SIXTHS", "No", 0),
("VULGAR FRACTION ONE EIGHTH", "No", 0),
("VULGAR FRACTION THREE EIGHTHS", "No", 0),
("VULGAR FRACTION FIVE EIGHTHS", "No", 0),
("VULGAR FRACTION SEVEN EIGHTHS", "No", 0),
("FRACTION NUMERATOR ONE", "No", 0),
("ROMAN NUMERAL ONE", "Nl", 0),
("ROMAN NUMERAL TWO", "Nl", 0),
("ROMAN NUMERAL THREE", "Nl", 0),
("ROMAN NUMERAL FOUR", "Nl", 0),
("ROMAN NUMERAL FIVE", "Nl", 0),
("ROMAN NUMERAL SIX", "Nl", 0),
("ROMAN NUMERAL SEVEN", "Nl", 0),
("ROMAN NUMERAL EIGHT", "Nl", 0),
("ROMAN NUMERAL NINE", "Nl", 0),
("ROMAN NUMERAL TEN", "Nl", 0),
("ROMAN NUMERAL ELEVEN", "Nl", 0),
("ROMAN NUMERAL TWELVE", "Nl", 0),
("ROMAN NUMERAL FIFTY", "Nl", 0),
("ROMAN NUMERAL ONE HUNDRED", "Nl", 0),
("ROMAN NUMERAL FIVE HUNDRED", "Nl", 0),
("ROMAN NUMERAL ONE THOUSAND", "Nl", 0),
("SMALL ROMAN NUMERAL ONE", "Nl", 0),
("SMALL ROMAN NUMERAL TWO", "Nl", 0),
("SMALL ROMAN NUMERAL THREE", "Nl", 0),
("SMALL ROMAN NUMERAL FOUR", "Nl", 0),
("SMALL ROMAN NUMERAL FIVE", "Nl", 0),
("SMALL ROMAN NUMERAL SIX", "Nl", 0),
("SMALL ROMAN NUMERAL SEVEN", "Nl", 0),
("SMALL ROMAN NUMERAL EIGHT", "Nl", 0),
("SMALL ROMAN NUMERAL NINE", "Nl", 0),
("SMALL ROMAN NUMERAL TEN", "Nl", 0),
("SMALL ROMAN NUMERAL ELEVEN", "Nl", 0),
("SMALL ROMAN NUMERAL TWELVE", "Nl", 0),
("SMALL ROMAN NUMERAL FIFTY", "Nl", 0),
("SMALL ROMAN NUMERAL ONE HUNDRED", "Nl", 0),
("SMALL ROMAN NUMERAL FIVE HUNDRED", "Nl", 0),
("SMALL ROMAN NUMERAL ONE THOUSAND", "Nl", 0),
("ROMAN NUMERAL ONE THOUSAND C D", "Nl", 0),
("ROMAN NUMERAL FIVE THOUSAND", "Nl", 0),
("ROMAN NUMERAL TEN THOUSAND", "Nl", 0),
("ROMAN NUMERAL REVERSED ONE HUNDRED", "Lu", 0),
("LATIN SMALL LETTER REVERSED C", "Ll", 0),
("ROMAN NUMERAL SIX LATE FORM", "Nl", 0),
("ROMAN NUMERAL FIFTY EARLY FORM", "Nl", 0),
("ROMAN NUMERAL FIFTY THOUSAND", "Nl", 0),
("ROMAN NUMERAL ONE HUNDRED THOUSAND", "Nl", 0),
("VULGAR FRACTION ZERO THIRDS", "No", 0),
("TURNED DIGIT TWO", "So", 0),
("TURNED DIGIT THREE", "So", 0),
)
|
https://github.com/CodingThrust/Templates | https://raw.githubusercontent.com/CodingThrust/Templates/main/workflows/README.md | markdown | ## Get started
You need a modern workflow (Linux, Git and VSCode) to get started.
- [How to get a Linux terminal](https://book.jinguo-group.science/stable/chap1/terminal/)
- [How to use Git for version control](https://book.jinguo-group.science/stable/chap1/git/)
- To install code/document editor VSCode, please refer [VSCode website](https://code.visualstudio.com/) for the installation guide.
This book "Willmore et al., 2017 - Introduction to scientific and technical computing" is also recommended.
## Conduct a survey
- Use [Google Scholar](https://scholar.google.com/) to search for the researchers you are interested in, and follow them to get updated with the latest research.
- Use [Zotero](https://www.zotero.org/) to manage your references.
For more details, please refer [how to conduct a literature survey?](conduct-survey.md).
## Technical writing
- In the informal writing such as web/blog/code, you can use the [Markdown](https://www.markdownguide.org/), please check [the markdown setup guide](markdown-vscode.md).
- For publishable writing, please use [Typst](https://typst.app/) or LaTeX. Please check the [typst template folder](typst/) after going through [the markdown setup guide](markdown-vscode.md).
## How to program?
- We recommend using Julia for scientific programming: [Julia Installation Guide](https://book.jinguo-group.science/stable/chap2/julia-setup/)
- You must use **git** to manage your code, and use **pull requests** to submit your code. Please refer to [this guide](https://book.jinguo-group.science/stable/chap1/git/) for more details.
- Follow the [Agile software development](https://en.wikipedia.org/wiki/Agile_software_development) methodology.
- **Remove uncertainty**, you can get help from me, or the community, e.g. https://julialang.org/community/
- I want to ..., but I don't know how to start.
- Is there any good example/existing code about...
- Is it possible to help me review my code? Ref: [Blog: The Best Way to Do a Code Review on GitHub](https://linearb.io/blog/code-review-on-github)
Whenever you have a bug in your code, please provide a [minimal reproducible example (MRE)](https://en.wikipedia.org/wiki/Minimal_reproducible_example) to help others understand your problem.
|
|
https://github.com/kokkonisd/typst-cross | https://raw.githubusercontent.com/kokkonisd/typst-cross/main/examples/simple/crossword.typ | typst | The Unlicense | #import "@local/cross:0.0.2" as cross
#set page(margin: 1cm)
#let crossword-data = toml("data.toml")
#align(center)[
= #crossword-data.title \
by #crossword-data.author
#grid(
columns: (1fr, 1fr, 1fr),
gutter: 20pt,
align: center + bottom,
// Show the board.
[
Empty board
#cross.board(crossword-data)
],
// Show the board with the solution on it.
[
Board with solution
#cross.board(crossword-data, show-solution: true)
],
// Show the board with the solution and the cell coordinates (helps when building the
// crossword).
[
Board with solution & cell coordinates
#cross.board(crossword-data, show-solution: true, show-cell-coordinates: true)
],
)
]
#v(1cm)
#block(height: 500pt)[
#cross.clues(crossword-data)
]
|
https://github.com/LuminolT/SHU-Bachelor-Thesis-Typst | https://raw.githubusercontent.com/LuminolT/SHU-Bachelor-Thesis-Typst/main/body/info.typ | typst | #let title = "基于copy&paste的毕业论文撰写"
#let college = "研讨与报告学院"
#let major = "寄算鸡咳血与寄术"
#let id = "114514"
#let name = "上大人"
#let teacher = "孔乙己"
#let data = "00000000 - ffffffff" |
|
https://github.com/wangwhh/AETG-algorithm | https://raw.githubusercontent.com/wangwhh/AETG-algorithm/master/report/report.typ | typst | #import "assets/report-template.typ": *
#show: project.with(
title: "AETG算法实现",
course: "软件质量保证与测试",
author: "王俊怡",
id: "3210106016",
advisor: "赵晓琼",
college: "计算机科学与技术学院",
major: "软件工程",
year: 2023,
month: 12,
day: 17,
)
#align(center, text(size: 17pt)[
*AETG Algorithm Implementation Experiment Report*
])
= Introduction
== Combinational Testing
Combinatorial testing, is a software testing technique used to systematically test different combinations of input parameters or configuration settings in order to identify defects or vulnerabilities in a software system.
In software development, there are often many possible combinations of input values or configuration settings that can affect the behavior of a system. Testing all possible combinations individually can be time-consuming and impractical, especially for complex software with numerous parameters. Combinational testing offers a more efficient way to cover a wide range of scenarios instead of testing each one separately.
== AETG
The AETG (Automated Efficient Test Generation) algorithm is a method to generate test cases in combination testing that cover all possible combinations of input parameters. This algorithm is a form of combinatorial testing designed to efficiently test complex systems with many interacting components or settings.
The AETG algorithm reduces the number of test cases needed to achieve significant coverage, thereby saving time and resources in the testing process.
@605761
= Algorithm Description
Assume that we have a system with $k$ test parameters and that the $i$ th parameter has $l_i$ different values. We select each test case by first generating M different candidate test cases and then choosing one that covers the most new pairs. Each candidate test case is selected by the following greedy algorithm:
+ Choose the first parameter $f$ and a value $l$ for $f$ such that it appears in the greatest number of uncovered pairs.
+ Let $f_1 = f$. Then randomly generate a order for the remaining parameters. Then, we have an order for all k parameters $f_1, ..., f_k$ .
+ For each parameter $f_i$ in the order, choose a value $l_i$ for $f_i$. The value $l_i$ is chosen by the following method.
- Assume that we have already selected $i-1$ values for parameters $f_1, ..., f_(i-1)$ and we will now select the value for $f_i$.
- if $i<=t$, for each value of $f_i$, we combine it with the $l_1, ..., l_(i-1)$. Now we have $l_1, ..., l_i$. Then calculate the number of new pairs that will be covered by the new case. Then we choose the value that covers the most new pairs.
- if $i>t$, for each value of $f_i$, we select $t-1$ parameters from $f_1, ..., f_(i-1)$ and traverse all possible combinations. Then we will follow the same steps as before, choose the value that covers the most new pairs.
+ After we have selected all $k$ values, we have a candidate test case. Then we choose the candidate test case that covers the most new pairs.
+ Repeat step 1-4 until the uncovered-pairs-set is empty.
= Algorithm Implementation
== Data Structure
=== Class `Data`
Class Data has 4 variables: `name, options, parameters, data`. `name` is the name of the data. `options` is the title of each parameters. `parameters` is an array stores the number of the values of each parameters, which will be used in AETG algorithm. `data` is a 2D array that stores the data.
For example, if we have parameters like this: `[5, 7, 2, 3, 6]`, it represents that we have 5 parameters and the first parameter has 5 values, the second parameter has 7 values, and so on. Then we can use this array in AETG to generate the test case.
=== Test Case
The test case in AETG algorithm is an array. For example, if the test case is `[-1, 0, 2, -1, 1]`, it means that the first parameter is not selected, the second parameter is the first value, the third parameter is the third value, and so on.
=== Uncoveres Pairs
At the beginning of the algorithm, all uncovered pairs (ucps) will be generated.
The uncovered pairs is an array that stores the pairs that are not covered. For each ucp, we find all combinations of *t* parameters and all combinations of the values for each parameters. We represent it as `[[0, 0, -1, -1, -1], [0, 1, 1, -1, -1], ...]` where t=2.
== Algorithm Implementation
=== Pseudo Code
#code(
stepnumber:1,
numbers: true,
)[```python
uncovered_pairs = generate_uncovered_pairs(parameters, t)
test_case = []
while uncovered_pairs is not empty:
# generate_candidate_test_cases
candidate_test_cases = []
for m: 1 to M
test_case = []
test_case[0] = choose_best_first_value()
for i: 1 to t
for each value in parameters[i]:
tmp_test_case[i] = value
pairs_count = count_pairs(tmp_test_case, uncovered_pairs)
best_value = choose_best_value()
test_case[i] = best_value
candidate_test_cases.append(test_case)
for i: t+1 to k
for each combination of t-1 parameters:
for each value in parameters[i]:
test_case[i] = value
candidate_test_cases.append(test_case)
test_case = choose_best_candidate(candidate_test_cases, uncovered_pairs)
uncovered_pairs = update_uncovered_pairs(test_case, uncovered_pairs)
```]
=== Details
+ Random selection
When selecting the first parameter and the best value for each parameters, we may encounter situations with multiple optimal solutions. In this case, I *ramdomly* choose one of them. If we always choose the first optimal solution, the algorithm may get stuck in a local optimal solution.
+ Dynamic M
In the AETG algorithm, we use the greedy algorithm to generate test cases multiple times and finally select the one with the most coverage from these test cases. At the beginning, the algorithm can easliy find a test case that covers a lot of pairs. However, as the number of uncovered pairs decreases, the algorithm will be more difficult to find a test case that covers a lot of pairs. To solve this problem, I designed a dynamic method to adjust the number of M.
#code(
stepnumber:1,
numbers: true,
)[```python
# User input the min and max value of M from the command line.
rate = 0
max_cover_count = int(math.factorial(len(parameters)) / math.factorial(t) / math.factorial(len(parameters) - t))
while len(uncovered_pairs) > 0:
# aetg code...
m = int(m_min + rate * (m_max - m_min))
for m_cnt in range(m):
# generate candidate test cases...
rate = (max_cover_count - best_test_case[1])/(max_cover_count - 10)
if rate > 1:
rate = 1
```]
= Results
The complete results can be seen in file 'result/output_website_t-wise.csv'.
== JingDong
=== CIT Model
#code(
stepnumber:1,
numbers: true,
)[```python
# 品牌
brand = ['ThinkPad', 'DELL', '华为', 'Lenovo', 'Apple', 'hp', 'ASUS', 'MI', 'HONOR']
# 能效等级
energy_efficiency = ['一级', '二级', '三级']
# SSD
ssd = ['3TB', '128GB', '256GB+1TB', '512GB+2TB', '3TB*2']
# 厚度
thickness = ['15.0mm及以下', '15.1-18.0mm', '18.1-20.0mm', '20.0mm以上']
# 机身材质
body_material = ['金属', '金属+复合材质', '复合材质', '含碳纤维']
# 屏幕尺寸
screen_size = ['13.0英寸以下', '13.0-13.9英寸', '14.0-14.9英寸', '15.0-15.9英寸', '16.0-16.9英寸']
# 刷新率
refresh_rate = ['144Hz', '60Hz', '120Hz', '90Hz', '165Hz']
```]
=== Partial Test Cases
+ 2-wise
#figure(
image("assets/2023-12-18-13-41-57.png", width: 100%),
caption: "2-wise-jingdong",
)
+ 3-wise
#figure(
image("assets/2023-12-18-13-44-08.png", width: 100%),
caption: "3-wise-jingdong"
)
== XieCheng
=== CIT Model
#code(
stepnumber:1,
numbers: true,
)[```python
# 票型
ticket_type = ['单程', '往返', '多程']
# 出发地
start = ['国内', '国际·中国港澳台热门', '亚洲', '欧洲', '美洲', '非洲', '大洋洲']
# 目的地
end = ['国内', '国际·中国港澳台热门', '亚洲', '欧洲', '美洲', '非洲', '大洋洲']
# 仅看直飞
direct = ['是', '否']
# 舱型
cabin_type = ['经济/超经舱', '公务/头等舱', '公务舱', '头等舱']
# 乘客类型
customer = ['仅成人', '成人与儿童', '成人与婴儿', '成人与儿童与婴儿']
```]
= Conclusion and Discussion
=== Partial Test Cases
+ 2-wise
#figure(
image("assets/2023-12-18-13-45-20.png", width: 100%),
caption: "2-wise-xiecheng"
)
+ 3-wise
#figure(
image("assets/2023-12-18-13-53-04.png", width: 100%),
caption: "3-wise-xiecheng",
)
#show: bibliography(
"assets/ref.bib",
title: "References"
)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/chordx/0.2.0/src/piano.typ | typst | Apache License 2.0 | #import "./utils.typ": parse-input-string, top-border-normal, top-border-round
// A dictionary with the key names for the white-keys and their indices
#let white-keys-dict = (
"C1": 0,
"D1": 1,
"E1": 2,
"F1": 3,
"G1": 4,
"A1": 5,
"B1": 6, "C2b": 6,
"C2": 7, "B1#": 7,
"D2": 8,
"E2": 9, "F2b": 9,
"F2": 10, "E2#": 10,
"G2": 11,
"A2": 12,
"B2": 13, "C3b": 13,
"C3": 14, "B2#": 14,
"D3": 15,
"E3": 16, "F3b": 16,
)
// A dictionary with the key names for the black-keys and their indices
#let black-keys-dict = (
"C1#": 1, "D1b": 1,
"D1#": 2, "E1b": 2,
"F1#": 4, "G1b": 4,
"G1#": 5, "A1b": 5,
"A1#": 6, "B1b": 6,
"C2#": 8, "D2b": 8,
"D2#": 9, "E2b": 9,
"F2#": 11, "G2b": 11,
"G2#": 12, "A2b": 12,
"A2#": 13, "B2b": 13,
"C3#": 15, "D3b": 15,
"D3#": 16, "E3b": 16,
)
// Returns the indices of a key array of white-keys-dict or black-keys-dict
#let keys-to-array-index(dict, key-array) = {
key-array
.map(k => dict.at(k, default: none))
.filter(k => k != none)
}
// Remove the number of the key name (C1# -> C#)
#let normalize-key-name(key) = {
return key.replace(regex("\d+"), "").replace(regex("b$"), "\u{266D}")
}
// Gets the indices min and max of the layout
#let piano-limits-from-layout(layout) = {
return if layout == "C" {
(min: 0, max: 9)
} else if (layout == "2C") {
(min: 0, max: 13)
} else if layout == "F" {
(min: 3, max: 13)
} else { // "2F"
(min: 3, max: 16)
}
}
// Returns the white-keys amount in the layout
#let white-keys-amount-from-layout(layout) = {
return if layout == "C" {
10
} else if layout == "F" {
11
} else {
14
}
}
// Returns the black-keys amount in the layout
#let black-keys-index-from-layout(layout) = {
return if layout in ("C", "2C") {
( left: (1, 4, 8, 11), mid: (5, 12), right: (2, 6, 9, 13) )
} else {
( left: (4, 8, 11, 15), mid: (5, 12), right: (6, 9, 13, 16) )
}
}
// Draws the piano
#let draw-piano(self) = {
// draws the white-keys
for i in range(self.white-keys.amount) {
let key-pressed = i + self.limit.min
let fill-color = if key-pressed in self.tabs.white-keys-index {self.color} else {white}
let x = i * self.white-keys.width
let radius-style = if self.style == "normal" {
0pt
} else {
if i == 0 {
(bottom: self.round, top-left: self.round)
} else if i == self.white-keys.amount - 1 {
(bottom: self.round, top-right: self.round)
} else {
(bottom: self.round)
}
}
place(
dx: x,
rect(
width: self.white-keys.width,
height: self.white-keys.height,
radius: radius-style,
stroke: self.stroke,
fill: fill-color
)
)
}
// draw the black-keys
for i in range(self.white-keys.amount) {
let key-pressed = i + self.limit.min
let fill-color = if key-pressed in self.tabs.black-keys-index {self.color} else {black}
let base = i * self.white-keys.width - self.black-keys.width / 2
let x = 0pt
if key-pressed in self.black-keys.left {
x = base - self.black-keys.shift
} else if key-pressed in self.black-keys.mid {
x = base
} else if key-pressed in self.black-keys.right {
x = base + self.black-keys.shift
} else {
continue
}
place(
dx: x,
rect(
width: self.black-keys.width,
height: self.black-keys.height,
radius: if self.style == "normal" {0pt} else {(bottom: self.round)},
stroke: self.stroke,
fill: fill-color
)
)
}
}
// Draws border top
#let draw-top-border(self) = {
let size = (
width: self.piano.width,
height: 1.2pt * self.scale
)
if self.style == "normal" {
top-border-normal(size, self.stroke, self.scale)
} else {
top-border-round(size, self.stroke, self.scale)
}
}
// Draws tabs or dots over the piano
#let draw-tabs(self) = {
// draws tabs on white-keys chord
for i in self.tabs.white-keys-index {
if i < self.limit.min or i > self.limit.max {
continue
}
let radius = 1.7pt * self.scale
let x = (i - self.limit.min + 0.5) * self.white-keys.width - radius
let y = self.piano.height - 4pt * self.scale - radius
place(dx: x, dy: y, circle(radius: radius, stroke: none, fill: black))
}
// draws tabs on black-keys chord
for i in self.tabs.black-keys-index {
if i < self.limit.min or i > self.limit.max {
continue
}
let radius = 1.7pt * self.scale
let x = 0pt
let y = self.black-keys.height - 3.5pt * self.scale - radius
let base = (i - self.limit.min) * self.white-keys.width - radius
if i in self.black-keys.left {
x = base - self.black-keys.shift
} else if i in self.black-keys.mid {
x = base
} else if i in self.black-keys.right {
x = base + self.black-keys.shift
} else {
continue
}
place(dx: x, dy: y, circle(radius: radius, stroke: none, fill: black))
}
}
// Draws pressed note names
#let draw-key-notes(self) = {
let gap-note = 1.8pt * self.scale
// white-keys
let white-keys = self.keys
.map(key => (white-keys-dict.at(key, default: none), normalize-key-name(key)) )
.filter(arr => arr.at(0) != none)
for (i, key-name) in white-keys {
if i < self.limit.min or i > self.limit.max {
continue
}
let x = (i - self.limit.min + 0.5) * self.white-keys.width
let y = self.piano.height + gap-note
place(dx: x, dy: y, place(center + top, text(6pt * self.scale)[#key-name]),
)
}
// black-keys
let black-keys = self.keys
.map(key => (black-keys-dict.at(key, default: none), normalize-key-name(key)) )
.filter(arr => arr.at(0) != none)
for (i, key-name) in black-keys {
if i < self.limit.min or i > self.limit.max {
continue
}
let x = 0pt
let y = -(self.top-border-height + gap-note)
let base = (i - self.limit.min) * self.white-keys.width
if i in self.black-keys.left {
x = base - self.black-keys.shift
} else if i in self.black-keys.mid {
x = base
} else if i in self.black-keys.right {
x = base + self.black-keys.shift
} else {
continue
}
place(dx: x, dy: y, place(center + bottom, text(6pt * self.scale)[#key-name]))
}
}
// Draws the chord name below the piano
#let draw-name(self) = {
let x = self.piano.width / 2
let y = self.piano.height + self.vertical-gap-name
place(dx: x, dy: y, place(center + horizon, text(12pt * self.scale)[#self.name]))
}
// Render the piano
#let render(self) = {
style(styles => {
let chord-name-size = measure(text(12pt * self.scale)[#self.name], styles)
let note-name-size = measure(text(6pt * self.scale)[#self.keys], styles)
let canvas = (
width: calc.max(self.piano.width, chord-name-size.width),
height: self.piano.height + self.vertical-gap-name + chord-name-size.height / 2 + note-name-size.height + self.top-border-height * 2,
dx: calc.max((chord-name-size.width - self.piano.width) / 2, 0pt),
dy: -(self.piano.height + self.vertical-gap-name + chord-name-size.height / 2)
)
box(
width: canvas.width,
height: canvas.height,
place(
left + bottom,
dx: canvas.dx,
dy: canvas.dy, {
draw-piano(self)
draw-top-border(self)
draw-tabs(self)
draw-key-notes(self)
draw-name(self)
}
)
)
})
}
/// Return a new function with default parameters to generate piano chords.
///
/// - layout (string): Presets the layout and size of the piano, ```js "C"```, ```js "2C"```, ```js "F"```, ```js "2F"```. *Optional*.
/// - ```js "C"```: the piano layout starts from key *C1* to *E2* (17 keys).
/// - ```js "2C"```: the piano layout starts from key *C1* to *B2* (24 keys, two octaves).
/// - ```js "F"```: the piano layout starts from key *F1* to *B2* (19 keys).
/// - ```js "2F"```: the piano layout stars from key *F1* to *E3* (24 keys, two octaves).
/// - scale (integer, float): Presets the scale. *Optional*.
/// - color (color): Presets the pressed key color. *Optional*.
/// - style (string): Sets the piano style. *Optional*.
/// - ```js "normal```: piano with right angles.
/// - ```js "round```: piano with round angles.
/// - font (string): Sets the name of the text font. *Optional*.
/// -> function
#let new-piano-chords(
layout: "C",
scale: 1,
color: gray,
style: "normal",
font: "Linux Libertine"
) = {
/// Is the returned function by *new-piano-chords*.
///
/// - keys (string): Keys chord notes from *C1* to *E3* (Depends on your layout). *Optional*.
/// #parbreak() Example: ```js "C1, E1b, G1"``` - (Cm chord)
/// - color (color): Sets the pressed key color. *Optional*.
/// - layout (string): Sets the layout and size of the piano, ```js "C"```, ```js "2C"```, ```js "F"```, ```js "2F"```. *Optional*.
/// - ```js "C"```: the piano layout starts from key *C1* to *E2* (17 keys).
/// - ```js "2C"```: the piano layout starts from key *C1* to *B2* (24 keys, two octaves).
/// - ```js "F"```: the piano layout starts from key *F1* to *B2* (19 keys).
/// - ```js "2F"```: the piano layout stars from key *F1* to *E3* (24 keys, two octaves).
/// - scale (integer, float): Sets the scale. *Optional*.
/// - name (string, content): Shows the chord name. *Required*.
/// -> content
let piano-chord(
keys: "",
color: color,
layout: layout,
scale: scale,
name
) = {
assert.eq(type(keys), "string")
assert.eq(type(color), "color")
assert(type(scale) in ("integer", "float"), message: "type of `scale` must to be a \"integer\" or \"float\"")
assert(upper(layout) in ("C", "2C", "F", "2F"), message: "`layout` must to be \"C\", \"2C\", \"F\" or \"2F\"")
assert(style in ("normal", "round"), message: "`style` must to be \"normal\" or \"round\"")
assert(type(name) in ("string", "content"), message: "type of `name` must to be \"string\" or \"content\"")
set text(font: font)
let step = 7.5pt
let layout = upper(layout)
let white-keys-amount = white-keys-amount-from-layout(layout)
let black-keys-index = black-keys-index-from-layout(layout)
let piano-limits = piano-limits-from-layout(layout)
let keys = parse-input-string(keys)
let self = (
white-keys: (
width: step * scale,
height: 25pt * scale,
amount: white-keys-amount,
),
black-keys: (
width: (step / 3) * scale * 2,
height: 17pt * scale,
shift: 1pt * scale, // small shifting of the black-keys
left: black-keys-index.left, // black-keys index with left shift
mid: black-keys-index.mid, // black-keys index without shift
right: black-keys-index.right, // black-keys index with right shift
),
piano: (
width: white-keys-amount * step * scale,
height: 25pt * scale
),
tabs: (
white-keys-index: keys-to-array-index(white-keys-dict, keys),
black-keys-index: keys-to-array-index(black-keys-dict, keys)
),
round: 1pt * scale,
stroke: black + 0.5pt * scale,
vertical-gap-name: 14pt * scale,
top-border-height: 1.1pt * scale,
keys: keys,
scale: scale,
limit: piano-limits,
style: style,
color: color,
name: name,
)
render(self)
}
return piano-chord
}
|
https://github.com/rabotaem-incorporated/algebra-conspect-1course | https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/02-complex-numbers/02-trig-form.typ | typst | Other | #import "../../utils/core.typ": *
== Тригонометрическая форма комплексного числа
#def[
$a + b i = r(cos phi + i sin phi)$
$a = r cos phi$
$b = r sin phi$
]
#def[
Модулем комплексного числа $z = a + b i in CC$ назовем:
$abs(z) = sqrt(a^2 + b^2)$
]
#pr[
+ $abs(z) >= 0, space abs(z) = 0 <==> z = 0$
+ $abs(z_1 z_2) = abs(z_1) abs(z_2)$
+ $abs(z_1 + z_2) <= abs(z_1) + abs(z_2)$
+ $abs(overline(z)) = abs(z)$
+ $z overline(z) = abs(z)^2$
]
#proof[
+ очевидно
+ #[
$z_1 = a_1 + b_1 i, space z_2 = a_2 + b_2 i$
$abs(z_1 z_2)^2 = (a_1 a_2 - b_1 b_2)^2 + (a_1 b_2 + a_2 b_1)^2 = a_1^2 a_2^2 + b_1^2 b_2^2 + a_1^2 b_2^2 + a_2^2 b_1^2 = $
$(a_1^2 + b_1^2) (a_2^2 + b_2^2) = abs(z_1)^2 abs(z_2)^2$
]
+ #[
$<==> abs(z_1 + z_2)^2 <= (abs(z_1) + abs(z_2))^2$
$<==> (a_1 + a_2)^2 + (b_1 + b_2)^2 <= a_1^2 + b_1^2 + a_2^2 + b_2^2 + 2 abs(z_1) abs(z_2)$
$<==> a_1 a_2 + b_1 b_2 <= sqrt((a_1^2 + b_1^2)(a_2^2 + b_2^2))$
$<== abs(a_1 a_2 + b_1 b_2) <= sqrt((a_1^2 + b_1^2)(a_2^2 + b_2^2))$
$<==> a_1^2 a_2^2 + b_1^2 b_2^2 + 2 a_1 a_2 b_1 b_2 <= (a_1^2 + b_1^2)(a_2^2 + b_2^2)$
$<==> 2 a_1 a_2 b_1 b_2 <= b_1^2 a_2^2 + a_1^2 b_2^2$
$<==> (b_1 a_2 - b_2 a_1)^2 >= 0$
]
+ очевидно
+ #[
$z = a + b i ==> overline(z) = a - b i$
$z overline(z) = (a + b i) (a - b i) = a^2 - (b i)^2 = a^2 + b^2 = abs(z)^2$
]
]
#notice[
$z^(-1) = (overline(z))/(abs(z)^2) = (a)/(a^2 + b^2) - i (b)/(a^2 + b^2)$
]
#def[
Пусть $z in CC$. Аргументом $z$ назовем такое $phi in RR$,
что $z = abs(z) (cos phi + i sin phi)$
]
#pr[
+ Если $z = 0$, то любой $phi in RR$ --- аргумент $z$
+ Если $z eq.not 0$, то: #[
+ аргумент существует
+ если $phi_0$ - аргумент $z$, и $phi$ - аргумент $z <==> phi = phi_0 + 2 pi k, space k in ZZ$
]
]
#proof[
+ тривиально
+ #[
$z_0 = (1)/(abs(z)) dot z$
$abs(z_0) = abs((1)/abs(z)) dot abs(z) = (1)/(abs(z)) dot abs(z) = 1$
$z_0 = a_0 + i b_0, space abs(z_0) = a_0^2 + b_0^2 = 1 ==> exists phi_0:
display(cases(
a_0 = cos phi_0,
b_0 = sin phi_0
))$
$z = abs(z) dot z_0 = abs(z)(cos phi_0 + i sin phi_0)$
"$arrow.l.double$":
$phi = phi_0 + 2 pi k ==>
display(cases(
cos phi = cos phi_0,
sin phi = sin phi_0
)) ==> phi$ --- аргумент
"$arrow.r.double$":
$phi$ --- аргумент $==> z = abs(z) (cos phi + i sin phi) ==>
display(cases(
cos phi = cos phi_0,
sin phi = sin phi_0
)) ==> phi - phi_0 = 2 pi k, space k in ZZ$
]
]
#def[
$arg(z) = phi$ означает $phi$ --- один из аргументов $z$
]
#notice[
Предположим оказалось, что $z = r(cos phi + i sin phi)$ для некоторых $r >= 0, space phi in RR$.
Тогда $r = abs(z), space phi = arg z$
]
#proof[
$abs(z) = sqrt((r cos phi)^2 + (r sin phi)^2) = sqrt(r^2) = r$, а $phi$ --- аргумент по определению
]
#pr[
+ $arg overline(z) = -arg z$
+ $z in RR <==> arg z = k pi, space k in ZZ$
+ $arg(z_1 z_2) = arg z_1 + arg z_2$
+ Пусть $z_2 eq.not 0 ==> arg (z_1)/(z_2) = arg z_1 - arg z_2$
]
#proof[
+ #[
$arg z = phi$
$z = abs(z)(cos phi + i sin phi)$
$overline(z) = abs(z) (cos phi - i sin phi) = abs(overline(z))(cos(-phi) + i sin(-phi)) ==>$
$arg overline(z) = -phi$
]
+ #[
"$arrow.r.double$":
$z > 0$:
$z = abs(z) dot 1 = abs(z) (cos 0 + i sin 0) ==> arg z = 0$
$z < 0$:
$z = abs(z) dot (-1) = abs(z) (cos pi + i sin pi) ==> arg z = pi$
"$arrow.l.double$":
$sin(k pi) = 0$
]
+ #[
$arg z_1 = phi_1, space arg z_2 = phi_2 ==>$
(!) $phi_1 + phi_2 = arg(z_1 z_2)$
$z_1 = abs(z_1)(cos phi_1 + i sin phi_1), space z_2 = abs(z_2)(cos phi_2 + i sin phi_2) ==>$
$z_1 z_2 = abs(z_1) dot abs(z_2) (cos phi_1 dot cos phi_2 - sin phi_1 dot sin phi_2 + i (sin phi_1 dot cos phi_2 + cos phi_1 dot sin phi_2)) =$
$abs(z_1 z_2) (cos(phi_1 + phi_2) + i sin(phi_1 + phi_2)) ==> arg(z_1 z_2) = phi_1 + phi_2$
]
+ $z_1 = (z_1)/(z_2) dot z_2 ==> arg z_1 = arg (z_1)/(z_2) + arg z_2 ==> arg (z_1)/(z_2) = arg z_1 - arg z_2$
]
#follow(name: [Формула Муавра])[
Пусть $z in CC, space abs(z) = r, space arg z = phi, space n in ZZ$.
Тогда $z^n = r^n (cos(n phi) + i sin(n phi))$
]
#proof[
+ #[
$n > 0:$ индукция по $n$
"База": $n = 1$ --- тривиально
"Переход": $n - 1 ~~> n$
$z^n = z^(n - 1) dot z = r^(n - 1) (cos((n - 1) phi) + i sin((n - 1) phi)) dot z = $
$r^(n - 1) (cos((n - 1) phi) + i sin((n - 1) phi)) dot r (cos phi + i sin phi) = $
$r^n (cos((n - 1) phi + phi) + i sin((n - 1) phi + phi)) = $
$r^n (cos(n phi) + i sin(n phi))$
]
+ $n = 0: 1 = r^0 (cos(0) + i sin(0)) = 1$
+ #[
$n < 0:$ $n = -k, space k in NN$
$z^n = (1)/(z^k)$
$abs(z^n) = (1)/(abs(z^k)) = (1)/(abs(z)^k) = abs(z)^(-k) = abs(z)^n$
$arg z^n = arg 1 - arg z^k = 0 - k phi = n phi$
]
] |
https://github.com/DarrenKwonDev/resume | https://raw.githubusercontent.com/DarrenKwonDev/resume/master/README.md | markdown | # resume
~~written in latex and exported to pdf.~~
written in typst, better and easier than latex.
## clean up your git log
```bash
git checkout master
git reset $(git commit-tree HEAD^{tree} -m ".")
git push origin master --force
```
|
|
https://github.com/typst-doc-cn/tutorial | https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/basic/reference-data-process.typ | typst | Apache License 2.0 | #import "mod.typ": *
#show: book.ref-page.with(title: [参考:数据读写与数据处理])
#let table-lnk(name, ref, it, scope: (:), res: none, ..args) = (
align(center + horizon, link("todo", name)),
it,
align(horizon, {
set heading(bookmarked: false, outlined: false)
eval(it.text, mode: "markup", scope: scope)
}),
)
== read
== 数据格式
== 字节数组
== image.decode
== 字符串Unicode
== 正则匹配
== wasm插件
== metadata
== typst query
|
https://github.com/taooceros/MATH-542-HW | https://raw.githubusercontent.com/taooceros/MATH-542-HW/main/HW3/HW3.typ | typst | #import "@local/homework-template:0.1.0": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Math 542 HW2",
authors: ("<NAME>",),
)
#let (
theorem,
lemma,
corollary,
remark,
proposition,
example,
proof
) = (
thm,
lemma,
corollary,
remark,
proposition,
example,
proof
)
#let tensor = $times.circle$
#let qt(x,y) = $#x\/#y$
#let div = $\/$
#show: thmrules
#import "@preview/commute:0.1.0": node, arr, commutative-diagram
= Q1
== 10.4.10
Suppose $R$ is commutative and $N cong R^n$ is a free $R$-module of rank $n$ with $R$-module basis $e_1, ..., e_n$.
===
For any nonzero $R$-module $M$ show that every element of $M tensor N$ can be written uniquely in the form $sum_(i=1)^n m_i tensor e_i$ where $m_i in M$. Deduce that if $sum_(i=1)^n m_i tensor e_i = 0$ in $M tensor N$ then $m_i = 0$ for $i = 1, ..., n$.
#solution[
$N cong R^n => M tensor N cong M tensor R^n cong underbrace((M tensor R) plus.circle ... plus.circle (M tensor R), n "times")$
Because the construction is a free module, so every entries are linearly independent, so summing them is equivalent to the cartisian product.
Therefore, if $sum_(i=1)^n m_i tensor e_i = 0$, every entries must equal to $0$, then either $m_i = 0$ or $e_i = 0$ for all $i$. However, we know that $e_i != 0$, then $m_i = 0$.
]
===
Show that if $sum m_i tensor n_i = 0$ in $M tensor N$ where $n_i$ are merely assumed to be $R$-linearly independent then it is not necessarily true that all the $m_i$ are $0$.
#solution[
Consider the $1 tensor 2$ in the proposed Hint.
In $qt(ZZ, 2ZZ) tensor ZZ$, we have proved that $1 tensor 2 = 0$ in last homework, but this is a counterexample for the claim above as $1!=0 in qt(ZZ,2ZZ)$.
]
== 10.4.16
Suppose $R$ is commutative and let $I$ and $J$ be ideals of $R$, so $qt(R,I)$ and $qt(R,J)$ are natrually $R$-modules.
===
Prove that every element of $R/I tensor_R R/J$ can be written as simple tensor of the form $(1 mod I) tensor (r mod J)$.
#solution[
Assume we have $a tensor b + c tensor d in R/I tensor R/J$. By the property of tensor product, it must satisfy $a tensor b + c tensor d= a (1 tensor b) + c(1 tensor d) = (1 tensor a b) + (1 tensor c d) = 1 tensor (a b + c d)$. This is doable because $R/I$ and $R/J$ are subring of $R$.
]
===
Prove that there is an $R$-module isomorphism $qt(R,I) tensor_R qt(R, J) cong qt(R, (I+J))$ mapping $(r mod I) tensor (r' mod J)$ to $r r' mod (I + J)$.
#solution[
To prove surjectivity, we already have every element of $R/I tensor R/J$ can be written as $(1 mod I) tensor (r mod J)$, and thus implies that $1 r' mod (I+J)$ is everything in $R div (I+J)$.
To prove injectivity, we have the only element maps to $0$ to be the element when $r=0$ or $r' = 0$. However, each will mean they are $0$ in the tensor product.
]
= Short Exact Sequences
Let $R$ be a commutative ring. A sequence of $R$-modules
$ 0 -> N arrow.long^iota A arrow.long^p Q arrow.long 0 $
is _short exact_ if $iota : N -> A$ is an injective $R$-module homomorphism whose image is the kernel of the surjective $R$-module homomorphism $p$. Let $B$ be an $R$-module.
==
Show that $p tensor id : A tensor B -> Q tensor B$ is still surjective and that the image of $iota tensor id$ is still its kernel.
#solution[
We know that both $p$ and $id$ are surjective. Then we can prove that $p tensor id$ is surjective by the property of tensor product.
Consider the following diagram:
#align(center)[#commutative-diagram(
node((0, 0), [$A plus.circle B$]),
node((0, 1), [$A tensor B$]),
node((1, 0), [$Q plus.circle B$]),
node((1, 1), [$Q tensor B$]),
arr((0, 0), (0, 1), [$f$]),
arr((1, 0), (1, 1), [$tilde(f)$], label-pos: -1em),
arr((0, 0), (1, 0), [$p cplus id$], label-pos: -2em),
arr((0, 1), (1, 1), [$p tensor id$], label-pos: -1.5em, "dashed"),
)]
The kernel of $p tensor id$ will be also be the kernel of $p cplus id$ as only $0$ be sent to $0$ and the diagram commute. Because $p cplus id$ is surjective, and thus $p tensor id$ is also surjective.
With a similar reasoning, the image of $iota$, which is the kernel of $p$ also lies in the kernel of $p tensor id$.
]
==
Now consider a short exact sequence of abelian groups $0 -> ZZ -> ZZ -> ZZ div n -> 0$ and let $B = ZZ div m$ where $n$ and $m$ are positive integers. Show that $iota tensor id$ is injective if and only if $gcd(m,n)=1$.
#solution[
Consider the following graph:
#align(center)[#commutative-diagram(
node((0, 0), $ZZ cplus ZZ div m$),
node((0, 1), [$ZZ plus.circle ZZ div m$]),
node((0, 2), [$ZZ tensor ZZ div m cong ZZ div m$]),
node((0, 3), $ZZ tensor ZZ div m$),
node((1, 1), [$ZZ div n plus.circle ZZ div m$]),
node((1, 2), [$ZZ div n tensor ZZ div m$]),
arr((0, 0), (0, 1), [$iota cplus id$], "inj"),
arr((0, 1), (0, 2), [$f$]),
arr((0, 3), (0, 2), [$iota tensor id$]),
arr((1, 1), (1, 2), [$tilde(f)$], label-pos: -1em),
arr((0, 1), (1, 1), [$p cplus id$], label-pos: -2em),
arr((0, 2), (1, 2), [$p tensor id$], label-pos: -1.5em, "dashed"),
)]
If $iota cplus id$ is injective, then the kernel of $p cplus id$ are the whole $ZZ cplus ZZ div m$. Thus, the kernel of $p tensor id$ is also $ZZ tensor ZZ div m$.
We have $A tensor_ZZ ZZ div n cong A div n A => ZZ div n tensor ZZ div m = ZZ div (n (m ZZ))$.
If $gcd(m,n) = 1$, $ZZ div (n m ZZ) cong ZZ div m ZZ cong ZZ tensor ZZ div m$, thus $ZZ div m tensor ZZ div n$ is the trivial group, and thus kernel of $p tensor id$ is the whole $ZZ div m$, whcih means $iota tensor id$ is injective.
On the other hand, $iota tensor id$ is injective menas that $ZZ div n tensor ZZ div m$ is the trivial group, and thus implies that $gcd(m,n) = 1$.
]
= Tensor Proudcts of Linear Maps
Suppose that $A : V_1 -> V_2$ and $B : W_1 -> W_2$ are $k$-linear maps between $k$-linear vectors spaces. Let $"rank"(C)$ be the rank of a linear map $C$, i.e. the dimension of its image. Show that $"rank"(A tensor B) = "rank"(A) "rank"(B)$.
#solution[
This can be done by consider the basis of image of $A$ and image of $B$. Then the image of $A tensor B$ is the tensor product of the basis of the image of $A$ and $B$, which will contains $"rank"(A)"rank"(B)$ elements.
]
= Classifying Simple Modules
==
For each positive integer $n$, find all simple $RR[ZZ div n ZZ]$-modules up to isomorphism and their endomorphism algebras. (Hint: Each simple module will be at most $2$-dimensional; think about rotations)
#solution[
We know that rotation matrix is simple under $RR[ZZ div n ZZ]$. Then for $ZZ div n ZZ$, we just consider the rotation matrix with angle $(2pi) / n$.
Because we have the theorem $abs(ZZ div n ZZ) = sum dim(S_i)^2/"End"(S_i)$. Because we have $dim(S_i) = 2$ for all $i$, then the dimension of the endomorphism rings must be $4$.
]
==
Recall that $HH$ is a 4-dimensional algebra over $RR$ whose elements can be written as $a+b i + c j + d k$ for some real numbers $a,b,c,d$ where $i^2 = j^2 = k^2 = -1, i j =k, j k = i, j i = -k, i k = -j, k j = - i$.
Let $Q_8 subset HH$ be the group of order $8$ which is generated by $i,j$. Its elements are ${plus.minus 1, plus.minus i, plus.minus j, plus.minus k}$.
===
Show that there are four non-isomorphic one-dimensional $RR[Q_8]$-modules. (Note that $Q_8 div [Q_8, Q_8] cong ZZ div 2 times ZZ div 2$).
#solution[
An one dimensional $RR[Q_8]$ module are in the following form:
$
{a + b i + c j + d k | a,b,c,d in RR}
$
For one dimensional module, we are essentially consider the homomorphism between $Q_8 -> RR^times$, but $RR^times$ is commutative, which means it suffices to consider $Q_8 div [Q_8, Q_8] -> RR^times$, which is essentially $ZZ div 2 times ZZ div 2 -> RR^times$, which is $"Hom"(ZZ div 2, RR^times)^2$, which has size 4.
]
===
Show that $"End"_(RR[Q_8])(HH)$ is isomorphic to $HH$ as a ring.
#solution[
We can see that $RR[Q_8]$ is isomorphic to $HH$ as a ring, and thus $"End"_(RR[Q_8])(HH) cong HH$.
]
===
Use previous one to conclude, up to isomorphism, $HH$ is the unique simple $RR[Q_8]$-module that is not one-dimensional.
#solution[
Since we have 4 one dimensional simple module and one 4 dimensional simple module, then we have $abs(Q_8) = sum dim(S_i)^2/"End"(S_i) = 4 + 4 = 8$.
Then we know $HH$ is the unique simple $RR[Q_8]$-module that is not one dimensional.
]
==
Show that there is a unique simple $CC[Q_8]$-module that is not one-dimensional. (Hint: It is two-dimensional, but you don't have to construct it. You can deduce its existence from fact we have shown and the four one-dimensional $CC[Q_8]$-modules that you found in the previous part.)
#solution[
We know that $abs(Q_8) = 8$, and we have four one dimensional simple module, so the last one must be two dimensional by the formula.
]
= Maschke
Let $k$ be a field. Let $V$ be a finite-dimensional $k$-vector space. Suppose that $V$ is a $k[G]$-module where $G$ is a finite group.
==
A linear map $pi : V->V$ is called a _projection onto_ $W$ if its image is $W$ and if $pi(w) = w$ for all $w in W$. Show that, given such a map, $V$ is isomorphic (as a vector space) to $ker(pi) cplus W$.
#solution[
By rank-nullity theorem, we have $ker(pi) = abs(V) - abs(W)$. Then we can see that $V = ker(pi) cplus W$ as long as $ker(pi)$ and $W$ are disjoint except ${0}$. However this is clear given $pi(w) = w$.
]
==
A linear map $pi : V->V$ is called $G$-equivariant if $pi (g dot v) = g dot pi(v)$ for all $g in G$. Show that if $pi$ is $G$-equivariant then its kernel and image are $k[G]$-submodules of $V$.
#solution[
We know that $pi$ is $G$-equivariant, then $forall g in G: pi(g dot v) = g dot pi(v)$. Thus it means that $pi in "Hom"_(k[G])(V, V)$, which suggests that its kernel and image are $k[G]$-submodules of $V$.
]
==
Suppose that $pi : V->V$ is a projection onto a submodule $W$. Suppose $abs(G)$ is invertible in $k$ (this could fail for instance if $G$ has even order and $k=ZZ div 2$ since 2 is not invertible in $k$ as it coincides with $0$). Define a new function $p : V->V$ by $p(v)=1/abs(G) sum_(g in G) g dot pi(g^(-1) dot v)$. Show that $p$ is a $G$-equaiariant projection onto $W$. Conclude that $V$ is isomorphic to $W cplus ker(pi)$ as a $k[G]$-module.
#solution[
$
p(g' w) = 1/abs(G) sum_(g in G) g (g^(-1)g' w) = 1/abs(G) sum_(g in G) g' g'^(-1) g(g^(-1) g' w) = g' sum_(g'' in G) g'' pi(g''^(-1) w) = g' pi(w)
$
Then $p$ is $G$-equivarant projection, then $W$ and $ker(pi)$ are all $k[G]$-submodule, which implies that $V$ is isomorphic to $W cplus ker(pi)$ as a $k[G]$-module.
]
==
Conclude that $V$ is a direct sum of simple $k[G]$-modules.
#solution[
We can make $W$ a simple $k[G]$-module, and $W$ is a direct sum of a simple module and its kernel. Then we do the same thing to the kernel. Then we can conclude that $V$ is a direct sum of simple $k[G]$-modules.
] |
|
https://github.com/GYPpro/DS-Course-Report | https://raw.githubusercontent.com/GYPpro/DS-Course-Report/main/Rep/06.typ | typst | #import "@preview/tablex:0.0.6": tablex, hlinex, vlinex, colspanx, rowspanx
#import "@preview/codelst:2.0.1": sourcecode
// Display inline code in a small box
// that retains the correct baseline.
#set text(font:("Times New Roman","Source Han Serif SC"))
#show raw.where(block: false): box.with(
fill: luma(230),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
#show raw: set text(
font: ("consolas", "Source Han Serif SC")
)
#set page(
paper: "a4",
)
#set text(
font:("Times New Roman","Source Han Serif SC"),
style:"normal",
weight: "regular",
size: 13pt,
)
#let nxtIdx(name) = box[ #counter(name).step()#counter(name).display()]
#set math.equation(numbering: "(1)")
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
#set math.equation(numbering: "(1)")
#set page(
paper:"a4",
number-align: right,
margin: (x:2.54cm,y:4cm),
header: [
#set text(
size: 25pt,
font: "KaiTi",
)
#align(
bottom + center,
[ #strong[暨南大学本科实验报告专用纸(附页)] ]
)
#line(start: (0pt,-5pt),end:(453pt,-5pt))
]
)
/*----*/
= 树上dfs(基础信息)
\
#text(
font:"KaiTi",
size: 15pt
)[
课程名称#underline[#text(" 数据结构 ")]成绩评定#underline[#text(" ")]\
实验项目名称#underline[#text(" ") 树上dfs(基础信息) #text(" ")]指导老师#underline[#text(" 干晓聪 ")]\
实验项目编号#underline[#text(" 06 ")]实验项目类型#underline[#text(" 设计性 ")]实验地点#underline[#text(" 数学系机房 ")]\
学生姓名#underline[#text(" 郭彦培 ")]学号#underline[#text(" 2022101149 ")]\
学院#underline[#text(" 信息科学技术学院 ")]系#underline[#text(" 数学系 ")]专业#underline[#text(" 信息管理与信息系统 ")]\
实验时间#underline[#text(" 2024年6月13日上午 ")]#text("~")#underline[#text(" 2024年7月13日中午 ")]\
]
#set heading(
numbering: "1.1."
)
= 实验目的
在树上进行dfs
= 实验环境
计算机:PC X64
操作系统:Windows + Ubuntu20.0LTS
编程语言:C++:GCC std20
IDE:Visual Studio Code
= 程序原理
统计树每个节点的子树大小、节点深度 与 子树节点权值和。
对于节点$i$,其子节点列表$S_i$,父节点$p_i$,有状态转移:
$ "subTreeSize"_n = sum_{"all" i in S_n} "subTreeSize"_i $
$ "depth"_n = "depth"_p_n + 1 $
$ "subTreeSum"_n = sum_{"all" i in S_n} "subTreeSum"_i + "Wei"_n $
#pagebreak()
= 程序代码
== `dfs.cpp`
#sourcecode[```cpp
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <map>
#include <algorithm>
using namespace std;
using pii = pair<int,int>;
#define int long long
#define pb push_back
#define F first
#define S second
#define all(x) x.begin(),x.end()
#define loop(i,n) for(int i = 0; i < n; i++)
const int mod = 1e9 + 7;
const int INF = 1e18;
// 子树大小 节点深度 子树节点值和
void solve()
{
int n;
cin >> n;
vector<vector<int>> cnj(n+1);
vector<int> wei(n+1);
vector<int> subTreeSize(n+1),depth(n+1),subTreeSum(n+1);
loop(i,n-1)
{
int u,v;
cin >> u >> v;
cnj[u].pb(v);
cnj[v].pb(u);
}
loop(i,n) cin >> wei[i+1];
auto dfs = [&](auto self,int p,int f) -> pii {
int size = 1;
int sum = wei[p];
depth[p] = depth[f] + 1;
for(auto &x : cnj[p])
{
if(x == f) continue;
auto [subSize,subSum] = self(self,x,p);
size += subSize;
sum += subSum;
}
subTreeSize[p] = size;
subTreeSum[p] = sum;
return {size,sum};
};
dfs(dfs,1,0);
cout << "subTreeSize \n";
loop(i,n) cout << subTreeSize[i+1] << " ";
cout << "\n";
cout << "depth \n";
loop(i,n) cout << depth[i+1] << " ";
cout << "\n";
cout << "subTreeSum \n";
loop(i,n) cout << subTreeSum[i+1] << " ";
cout << "\n";
}
signed main()
{
// std::ios::sync_with_stdio(false);
// std::cin.tie(nullptr);
// std::cout.tie(nullptr);
int T = 1;
cin >> T;
while(T--)
solve();
return 0;
}
```]
= 测试数据与运行结果
运行上述`_PRIV_TEST.cpp`测试代码中的正确性测试模块,得到以下内容:
```
2
8
1 2
1 3
1 4
3 5
3 6
6 7
6 8
9 4 3 1 15 7 3 7
subTreeSize
8 1 5 1 1 3 1 1
depth
1 2 2 2 3 3 4 4
subTreeSum
49 4 35 1 15 17 3 7
6
1 2
2 3
3 4
4 5
5 6
1 1 4 5 1 4
subTreeSize
6 5 4 3 2 1
depth
1 2 3 4 5 6
subTreeSum
16 15 14 10 5 4
```
可以看出,代码运行结果与预期相符,可以认为代码正确性无误。
|
|
https://github.com/typst-doc-cn/tutorial | https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/prefaces/mod.typ | typst | Apache License 2.0 | #import "/src/book.typ"
#import "../mod.typ": code, exec-code
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/i18n/zh/docusaurus-plugin-content-docs/current/layout.md | markdown | ---
sidebar_position: 3
---
# 排篇布局
为了更好地掌管 slides 里的每一处细节,并得到更好的渲染结果,就像 Beamer 一样,Touying 不得不引入了一些 Touying 特有的概念。这能帮助您更好地维护全局信息,以及让您可以在不同的主题之间方便地切换。
## 全局信息
你可以通过
```typst
#let s = (s.methods.info)(
self: s,
title: [Title],
subtitle: [Subtitle],
author: [Authors],
date: datetime.today(),
institution: [Institution],
)
```
分别设置 slides 的标题、副标题、作者、日期和机构信息。
其中 `date` 可以接收 `datetime` 格式和 `content` 格式,并且 `datetime` 格式的日期显示格式,可以通过
```typst
#let s = (s.methods.datetime-format)(self: s, "[year]-[month]-[day]")
```
的方式更改。
:::tip[原理]
在这里,我们会稍微引入一点 Touying 的 OOP 概念。
您应该知道,Typst 是一个支持增量渲染的排版语言,也就是说,Typst 会缓存之前的函数调用结果,这就要求 Typst 里只有纯函数,即无法改变外部变量的函数。因此我们很难真正意义上地像 LaTeX 那样修改一个全局变量。即使是使用 `state` 或 `counter`,也需要使用 `locate` 与回调函数来获取里面的值,且实际上这种方式会对性能有很大的影响。
Touying 并没有使用 `state` 和 `counter`,也没有违反 Typst 纯函数的原则,而是使用了一种巧妙的方式,并以面向对象风格的代码,维护了一个全局单例 `s`。在 Touying 中,一个对象指拥有自己的成员变量和方法的 Typst 字典,并且我们约定方法均有一个命名参数 `self` 用于传入对象自身,并且方法均放在 `.methods` 域里。有了这个理念,我们就不难写出更新 `info` 的方法了:
```
#let s = (
info: (:),
methods: (
// update info
info: (self: none, ..args) => {
self.info += args.named()
self
},
)
)
#let s = (s.methods.info)(self: s, title: [title])
Title is #s.info.title
```
这样,你也能够理解 `utils.methods()` 函数的用途了:将 `self` 绑定到 `s` 的所有方法上并返回,并通过解包语法简化后续的使用。
```typst
#let (init, slide, slides) = utils.methods(s)
```
:::
## 节与小节
与 Beamer 相同,Touying 同样有着 section 和 subsection 的概念。
在 `#show: slides` 模式下,section 和 subsection 分别对应着一级标题和二级标题,例如
```typst
#import "@preview/touying:0.2.1": *
#let (init, slide, slides) = utils.methods(s)
#show: init
#show: slides
= Section
== Subsection
Hello, Touying!
```

不过二级标题并非总是对应 subsection,具体的映射方式因主题而异。
而在更通用的 `#slide[..]` 模式下,section 和 subsection 分别作为参数传入 `slide` 函数中,例如
```typst
#slide(section: [Let's start a new section!])[..]
#slide(subsection: [Let's start a new subsection!])[..]
```
会分别新建一个 section 和一个 subsection。当然,这种变化默认只会影响到 Touying 内部的 `sections` state,默认是不会显示在 slide 上的,具体的显示方式依主题而异。
注意,`slide` 的 `section` 和 `subsection` 参数,既能接收内容块,也能接收形如 `([title], [short-title])` 格式的数组,或 `(title: [title], short-title: [short-title])` 格式的字典。其中 `short-title` 会在一些特殊场景下用到,例如 `dewdrop` 主题的 navigation 中将会用到。
## 目录
在 Touying 中显示目录很简单:
```typst
#import "@preview/touying:0.2.1": *
#let (init, slide, touying-outline) = utils.methods(s)
#show: init
#slide[
== Table of contents
#touying-outline()
]
```
其中 `touying-oultine()` 的定义为:
```typst
#let touying-outline(enum-args: (:), padding: 0pt) = { .. }
```
你可以通过 `enum-args` 修改内部 enum 的参数。
如果你对目录有着复杂的自定义需求,你可以使用
```typst
#slide[
== Table of contents
#states.touying-final-sections(sections => ..)
]
```
## 页面管理
由于 Typst 中使用 `set page(..)` 命令,会导致创建一个新的页面,而不能修改当前页面,因此 Touying 选择在单例 `s` 中维护一个 `s.page-args` 成员变量,只在创建新 slide 时才会应用这些参数。
:::warning[警告]
因此,你不应该自己使用 `set page(..)` 命令,而是应该修改 `s` 内部的 `s.page-args` 成员变量。
:::
通过这种方式,我们可以通过 `s.page-args` 实时查询当前页面的参数,这对一些需要获取页边距或当前页面背景颜色的函数很有用,例如 `transparent-cover`。
## 页面分栏
如果你需要将页面分为两栏或三栏,你可以使用 Touying `slide` 函数默认提供的 `compose` 功能,最简单的示例如下:
```typst
#slide[
First column.
][
Second column.
]
```

如果你需要更改分栏的方式,可以修改 `slide` 的 `composer` 参数,其中默认的参数是 `utils.with.side-by-side(columns: auto, gutter: 1em)`,如果我们要让左边那一栏占据剩余宽度,可以使用
```typst
#slide(composer: utils.side-by-side.with(columns: (1fr, auto), gutter: 1em))[
First column.
][
Second column.
]
```

|
|
https://github.com/darioglasl/Arbeiten-Vorlage-Typst | https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/01_Einleitung/01_industrial_partner.typ | typst | == Industrie Partner <headingIndustrialPartner>
|
|
https://github.com/taooceros/CV | https://raw.githubusercontent.com/taooceros/CV/main/cv.typ | typst | // Imports
#import "@preview/brilliant-cv:2.0.2": cv
#let metadata = toml("./metadata.toml")
#let importModules(modules, lang: metadata.language) = {
for module in modules {
include {
"modules_" + lang + "/" + module + ".typ"
}
}
}
#show: cv.with(
metadata,
profilePhoto: image("./src/signature.png")
)
#importModules((
"education",
"publications",
"research",
"open-source",
"award",
"community",
"projects",
"skills",
))
|
|
https://github.com/jpssrocha/templates | https://raw.githubusercontent.com/jpssrocha/templates/main/typst/lncc_report/README.md | markdown | MIT License | # Typst template - Simple report
This will generate the layout for a simple report with the common title pages
required on Brazil's universities, summary and bibliography sessions.
## How to use
To use this template just copy this entire folder to your computer and start
editing the `report.typ` file, compile it using your favorite method (typst
compiler, or 3rth party ones) . The setup function receives the configuration
metadata for formatting the title pages and metadata. Put your references on
the `references.bib` file, or point to your own on the keyword argument for
that in the configuration function.
PS: It isn't necessary to touch the other files, unless you want to customize the
template.
|
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/brainstorm-subsystems.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/template/entries.typ": create_entry
#import "/template/widgets.typ": *
#create_entry(
title: "Brainstorm: Subsystems",
type: "brainstorm",
start_date: datetime(year: 2023, month: 7, day: 29),
)[
#heading(([Possible Subsystems], level: 1)
#heading(([Picking Up Triballs], level: 2)
- claw
- intake
- side intake
- top intake
#heading(([Moving Triballs], level: 2)
- picking up, and then driving
- shooting
- catapult
- flywheel
- puncher
#heading(([Scoring Triballs in Goal], level: 2)
- pushing
- flaps
- intake/claw
#heading(([Climbing], level: 2)
- scissor lift
- 4 bar
- 2 bar
- double reverse 4 bar
#heading(([Possible Configs], level: 1)
#heading(([Option 1], level: 2)
- intake
- puncher
- flaps
- 4 bar
#heading(([Option 2], level: 2)
- claw
- puncher
- flaps
- 2 bar
#heading(([Option 3], level: 2)
- claw
- puncher
- flaps
- 2 bar
]
|
https://github.com/antonWetzel/Masterarbeit | https://raw.githubusercontent.com/antonWetzel/Masterarbeit/main/arbeit/auswertung.typ | typst | #import "setup.typ": *
= Auswertung <auswertung>
== Testdaten
Der benutze Datensatz#footnote[Terrestrial, UAV-borne, and airborne laser scanning point clouds of central European forest plots, Germany, with extracted individual trees and manual forest inventory measurements] beinhaltet zwölf Hektar Waldfläche in Deutschland, Baden-Württemberg @data. Die Daten sind mit Laserscans aufgenommen, wobei die Scans von Flugzeugen (ALS#footnote([aircraft laser scan])), Drohnen (ULS#footnote([uncrewed aerial vehicle laser scan])) und vom Boden (TLS#footnote([terrestrial laser scan])) aus durchgeführt wurden. Die 3D-Punktwolken sind im komprimierten LASzip Dateiformat gegeben.
Für die meisten Waldgebiete existieren ALS-, ULS- und TLS-Daten. Dabei enthalten die ALS-Daten die wenigsten und die TLS-Daten die meisten Punkte. Bei den ALS- und ULS-Daten sind die Punkte gleichmäßig über das gescannte Gebiet verteilt. Bei den TLS-Daten wird von einem festen Punkt aus gescannt, wodurch die Punktdichte nach außen immer weiter abnimmt.
Der Datensatz ist bereits in einzelne Bäume unterteilt. Zusätzlich wurden für sechs Hektar die Baumart, Höhe, Stammdurchmesser auf Brusthöhe und Anfangshöhe und Durchmesser der Krone gemessen. Mit den bereits bestimmten Eigenschaften können automatisch berechnete Ergebnisse validiert werden.
== Importgeschwindigkeit
In @auswertung_import_geschwindigkeit sind die Importgeschwindigkeiten gegeben. Die Eigenschaften vom verwendeten System sind in @systemeigenschaften und die genauen Messwerte in @messwerte gelistet. Für jedes Waldgebiet wurde jeweils ein zufälliger Datensatz von den ALS-, ULS- und TLS-Daten verwendet.
#figure(
caption: [Geschwindigkeit vom Import in Punkte pro Sekunde.],
image("../data/punkte_pro_sekunde.svg"),
) <auswertung_import_geschwindigkeit>
Bei den ALS-Daten wird für die meisten Datensätze eine Importgeschwindigkeit von #number(500000) Punkte pro Sekunde erreicht. Durch die kleinen Datenmengen schwankt aber die Importgeschwindigkeit stark. Für die ULS-Daten liegt die Importgeschwindigkeit bei #number(400000) und für die TLS-Daten bei #number(250000).
In @auswertung_import_phasen sind die absoluten und relativen Dauern für die einzelnen Phasen vom Import aufgeschlüsselt. Am längsten wird für die Analyse der Segmente benötigt, weil für jeden Punkt die benötigten Eigenschaften berechnet werden.
#figure(
caption: [Dauer für die einzelnen Importphasen pro Punkt.],
grid(
gutter: 1em,
subfigure(image("../data/mikrosekunde_phase_pro_punkt.svg"), caption: [Absolut]),
subfigure(image("../data/phasen_percent.svg"), caption: [Relativ]),
) ,
) <auswertung_import_phasen>
Bei den TLS-Daten enthalten durch die ungleiche Punktdichte manche Segmente überproportional viele Punkte, wodurch die Analyse von diesen Segmenten pro Punkt länger dauert.
Wie in @auswertung_ka_flat zu sehen, ist bei den `ALS-KAxx`-Daten der Boden sehr eben, wodurch die Baumkronen ähnliche Höhen haben. Dadurch haben viele Punkte die gleiche Höhe und die Segmentierung dauert länger.
#figure(
caption: [Seitenansicht für die Punktwolke `ALS-KA10`.],
image("../images/auto-crop/ka10-side.png"),
) <auswertung_ka_flat>
== Segmentierung von Waldgebieten
Beispiele für die Segmentierung sind in @segmentierung_ergebnis gegeben. Die meisten Bäume werden korrekt erkannt und zu unterschiedlichen Segmenten zugeordnet. Je weiter die Spitzen der Bäume voneinander getrennt sind, desto besser können die Bäume voneinander unterschieden werden. Für Bäume, bei denen die Baumkronen keine klare Trennung haben, werden die Bäume fehlerhaft zu einem Segment zusammengefasst.
#figure(
caption: [Segmentierung von unterschiedlichen Punktwolken.],
grid(
gutter: 1em,
grid(
columns: (1.3fr, 1fr),
subfigure(caption: [ALS], image("../images/auto-crop/segments-ka11-als.png")), subfigure(caption: [ULS], image("../images/auto-crop/segmentation_uls.png")),
),
subfigure(caption: [TLS], image("../images/auto-crop/segmentation_tls.png")),
),
) <segmentierung_ergebnis>
Punkte, welche zu keinem Baum gehören, werden trotzdem zu den Segmenten zugeordnet. Dadurch entstehen Segmente wie in @auswertung_segmentierung_keine_bäume. Die Punkte in den freien Flächen werden zu eigenen Segmenten zusammengefasst, welche zu keinem Baum gehören. Wenn die Punkte in der Nähe von einem Baum liegen, werden diese als Boden zu dem Baum hinzugefügt.
#figure(
caption: [Segmente bei Gebieten ohne Bäume.],
rect(image("../images/auto-crop/segmentation_no_trees.png", width: 90%), inset: 0.5pt),
) <auswertung_segmentierung_keine_bäume>
Kleine Bereiche werden vor der Zuordnung entfernt. Dadurch wird vermieden, dass ein Baum in mehrere Segmente unterteilt wird. Wenn die Spitze von einem Baum gerade so in einer Scheibe liegt, so ist der zugehörige Bereich klein und wird gefiltert. Dadurch wird kein neues Segment für den Baum erstellt und die Punkte werden dem falschen nächsten Baum zugeordnet. Der Effekt ist in @auswertung_segmentierung_spitze zu sehen. Die Spitzen von den umliegenden Bäumen wurden dem nächsten größeren Baum zugeordnet.
#figure(
caption: [Segmentierungsfehler bei Baumspitzen.],
grid(
columns: 1 * 2,
gutter: 1em,
subfigure(rect(image("../images/segmentation_top_error_full.png"), inset: 0.5pt), caption: [Alle Segmente]),
subfigure(rect(image("../images/segmentation_top_error.png"), inset: 0.5pt), caption: [Segment einzeln]),
),
) <auswertung_segmentierung_spitze>
#pagebreak(weak: true)
== Triangulierung
Ein Beispiel für die Triangulation ist in @auswertung_triangulierung gegeben. Mit dem Ball-Pivoting Algorithmus wird eine äußere Hülle für die Punkte bestimmt, wodurch der Algorithmus auch für eine Baumkrone mit Blättern geeignet ist.
#figure(
caption: [Beispiel für eine Triangulierung von einem Baum mit #box($alpha = #number(1, unit: [m])$).],
grid(
columns: 1 * 3,
gutter: 1em,
subfigure(caption: [Punkte], image("../images/crop/triangulation_big_points.png")),
subfigure(caption: [Dreiecke umrandet], image("../images/crop/triangulation_big_lines.png")),
subfigure(caption: [Dreiecke ausgefüllt], image("../images/crop/triangulation_big_mesh.png")),
),
) <auswertung_triangulierung>
Beim Baumstamm liegen alle Punkte auf der Oberfläche, wodurch diese ohne Probleme trianguliert werden können. Bei der Krone sind die Punkte im Raum verteilt, wodurch diese nicht auf einer eindeutigen Oberfläche liegen.
Mit einem ausreichend großen Wert für $alpha$ wird eine passende äußere Hülle berechnet. Bei Bereichen ohne Punkte wird für kleine $alpha$ keine passende Oberfläche gefunden, wodurch das berechnete Dreiecksnetz fehlerhaft ist.
== Visualisierung
Die gleiche Punktwolke ist in @auswertung_vis_example jeweils mit und ohne Detailstufen und Eye-Dome-Lighting gegeben. Die Detailstufen sind nicht von den originalen Punkten optisch zu unterscheiden und das Eye-Dome-Lighting ermöglicht eine bessere Wahrnehmung der verlorenen Tiefeninformationen.
//KA09-OFF-ULS
#figure(
caption: [Visualisierung von einem Datensatz mit #number(59967504) Punkten.],
grid(
columns: 1 * 2,
gutter: 2em,
subfigure(image("../images/auto-crop/perf_full_no.png"), caption: [originalen Punkte]),
subfigure(image("../images/auto-crop/perf_lod_no.png"), caption: [Detailstufen]),
subfigure(image("../images/auto-crop/perf_full_eye.png"), caption: [originalen Punkte #linebreak() Eye-Dome-Lighting]),
subfigure(image("../images/auto-crop/perf_lod_eye.png"), caption: [Detailstufen #linebreak() Eye-Dome-Lighting]),
),
) <auswertung_vis_example>
Wie in @auswertung_vis_time zu sehen, ist die Renderzeit durch die Detailstufen ein Bruchteil im Vergleich zur Dauer für die originalen Punkte. Das Eye-Dome-Lighting hat unabhängig von der Anzahl der sichtbaren Punkte keinen relevanten Effekt auf die Renderzeit.
#figure(
caption: [Renderzeit für einen Datensatz mit #number(59967504) Punkten.],
image("../data/renderzeit.svg"),
) <auswertung_vis_time>
Der Speicherbedarf für die Detailstufen ist in @auswertung_vis_lod_memory gelistet. Für diese wird im Durchschnitt zusätzlich die Hälfte vom Speicherbedarf von den originalen Punkten benötigt.
#figure(
caption: [Speicherbedarf für die Punkte vom Datensatz und der Detailstufen.],
image("../data/ratio_source_lod_points.svg"),
) <auswertung_vis_lod_memory>
== Analyse von Bäumen
=== Punkteigenschaften
In @auswertung_curve ist ein Segment basierend auf der Krümmung eingefärbt. Die Punkte mit der größten Krümmung gehören zu den Blättern, was eine Filterung ermöglicht. Die Punkte beim Stamm und teilweise in der Krone haben eine geringere Krümmung.
#figure(
caption: [Punktwolke basierend auf der Krümmung eingefärbt.],
box(width: 75%, grid(
columns: 1 * 3,
gutter: 5em,
subfigure(image("../images/crop/prop_curve_all.png"), caption: [Alle Punkte]),
subfigure(image("../images/crop/prop_curve_low.png"), caption: [Geringe Krümmung]),
subfigure(image("../images/crop/prop_curve_high.png"), caption: [Hohe Krümmung]),
)),
) <auswertung_curve>
Die Krümmung wurde für jeden Punkt mit den $31$ nächsten Punkten bestimmt, wodurch für dichtere Bereiche in der Punktwolke nur ein sehr kleines Gebiet betrachtet wird. Um den Einflussradius zu erhöhen, können mehr Punkte für die Nachbarschaft verwendet werden, dadurch steigt aber auch der Berechnungsaufwand. Eine andere Option ist es, für jeden Punkt die durchschnittliche Krümmung der umliegenden Punkte zu verwenden. Der Durchschnitt kann mit der bereits vorhandenen Nachbarschaft einfach berechnet werden.
Der gleiche Baum ist in @auswertung_var basierend auf der horizontalen Ausdehnung eingefärbt. Punkte zugehörig zu einer geringen horizontalen Ausdehnung gehören immer zum Stamm oder der Spitze der Krone, wodurch der Übergang vom Stamm zur Baumkrone gefunden werden kann.
#figure(
caption: [Punktwolke basierend auf der Ausdehnung eingefärbt.],
box(width: 75%, grid(
columns: 1 * 3,
gutter: 5em,
subfigure(image("../images/crop/prop_var_all.png"), caption: [Alle Punkte]),
subfigure(image("../images/crop/prop_var_trunk.png"), caption: [Geringe Ausdehnung]),
subfigure(image("../images/crop/prop_var_crown.png"), caption: [Hohe Ausdehnung]),
)),
) <auswertung_var>
=== Baumeigenschaften
Für die Auswertung von der Berechnung der Baumeigenschaften werden die berechneten Werte mit den direkt am Baum gemessenen Werten verglichen.
Für die Berechnung wurden die einzelnen bereits segmentierten Bäume aus dem Datensatz verwenden. Die Positionen der Bäume wurde mit einer Kombination von den ALS-, ULS- und TLS-Daten und einer manuellen Unterteilung der Punkte berechnet. Danach wurden alle Punktwolken der Waldgebiete mit den Baumpositionen unterteilt, wodurch besonders für die ALS- und ULS-Daten für manche Bäume nur wenig Punkte bekannt sind @pang. Eine Visualisierung vom Unterschied ist in @auswertung_vergleich_scanner und @auswertung_vergleich2_scanner gegeben.
// BR01\single_trees\QuePet_BR01_P21T14
#figure(
caption: [Vergleich zwischen den unterschiedlichen Daten für einen Baum mit wenig Punkten.],
grid(
columns: 1 * 4,
gutter: 3em,
subfigure(image("../images/crop/compare2_als.png"), caption: [ALS#linebreak()#number(1503) Punkte]),
subfigure(image("../images/crop/compare2_uls_off.png"), caption: [ULS-off#linebreak()#number(7156) Punkte]),
subfigure(image("../images/crop/compare2_uls_on.png"), caption: [ULS-on#linebreak()#number(6273) Punkte]),
subfigure(rect(width: 100%, height: 37%, radius: 5pt, align(center + horizon)[Keine Daten]), caption: [TLS#linebreak() -- Punkte]),
),
) <auswertung_vergleich_scanner>
// BR02\single_trees\FagSyl_BR02_02
#figure(
caption: [Vergleich zwischen den unterschiedlichen Daten für einen Baum mit vielen Punkten.],
grid(
columns: 1 * 4,
gutter: 2em,
subfigure(image("../images/crop/compare_als.png"), caption: [ALS#linebreak()#number(6446) Punkte]),
subfigure(image("../images/crop/compare_uls_off.png"), caption: [ULS-off#linebreak()#number(58201) Punkte]),
subfigure(image("../images/crop/compare_uls_on.png"), caption: [ULS-on#linebreak()#number(74262) Punkte]),
subfigure(image("../images/crop/compare_tls.png"), caption: [TLS#linebreak()#number(1687505) Punkte]),
),
) <auswertung_vergleich2_scanner>
Die Datenpunkte sind in @analyse_baumeigenschaften zu sehen. Entlang der x-Achse sind die gemessenen Werte und entlang der y-Achse sind die berechneten Werte. Im Idealfall sind beide Werte gleich, wodurch ein Datenpunkt auf der Diagonalen entsteht. Wenn ein Punkt oberhalb der Diagonalen ist, wurde ein zu großer Wert berechnet und ist der Punkt unterhalb, ist der berechnete Wert zu klein.
#figure(
caption: [Vergleich zwischen den Messwerten und Approximation von den Baumeigenschaften.],
grid(
columns: 1 * 2,
column-gutter: 1em,
row-gutter: 3em,
subfigure(image("../data/data_tree_height.svg", height: 195pt), caption: [Gesamthöhe vom Baum]),
subfigure(image("../data/data_trunk_diameter.svg", height: 195pt), caption: [Stammdurchmesser bei #number(130, unit: [cm])]),
subfigure(image("../data/data_crown_start.svg", height: 195pt), caption: [Anfangshöhe der Baumkrone]),
subfigure(image("../data/data_crown_diameter.svg", height: 195pt), caption: [Durchmesser der Baumkrone]),
),
) <analyse_baumeigenschaften>
Für die Gesamthöhe vom Baum liegen weniger Messwerte vor, wodurch weniger Vergleiche mit der Approximation möglich sind. Die Approximation für die Baumhöhe ist mit den ALS-, ULS- und TLS-Daten möglich, weil die Gesamthöhe gesucht wird, welche unabhängig von der Punktdichte berechnet werden kann.
Die Berechnung vom Stammdurchmesser funktioniert für die TLS-Daten am besten. Der Stamm wird als Kreis approximiert, wodurch die berechneten Werte kleiner als die gemessenen Werte sind. Bei den ULS-Daten ist eine Korrelation zu sehen, aber die Ergebnisse weichen stark von den gemessenen Werten ab. Mit den ALS-Daten kann der Stammdurchmesser nicht berechnet werden. Bei vielen Punktwolken waren zu wenig Datenpunkte im verwendeten Bereich für die Berechnung, wodurch der Standardwert von $50$ cm verwendet wurde.
Auch die Berechnung von der Anfangshöhe der Baumkrone funktioniert mit den TLS-Daten am besten. Mit den ALS- und den ULS-Daten ist eine Approximation möglich, wobei die Ergebnisse bei den ALS Daten weiter von den gemessenen Werten abweichen.
Für die Berechnung vom Durchmesser der Baumkrone sind die ALS-, ULS- und TLS-Daten geeignet. Durch die Approximation der Baumform als Kreis ist der berechnete Wert kleiner als der gemessene Wert. Bei den gemessenen Werten würde der Durchschnitt zwischen der größten Ausdehnung und zugehörigen orthogonalen Ausdehnung bestimmt, wodurch die Baumform als Ellipse approximiert wird. Der Radius vom Kreis mit gleichem Umfang wie die Ellipse ist kleiner, wodurch der systematische Fehler entsteht.
|
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/README.md | markdown | # [Touying](https://github.com/touying-typ/touying) 
[Touying](https://github.com/touying-typ/touying) (投影 in chinese, /tóuyǐng/, meaning projection) is an powerful and efficient package for creating presentation slides in Typst. Touying is a package derived from [Polylux](https://github.com/andreasKroepelin/polylux). Therefore, many concepts and APIs remain consistent with Polylux.
Touying provides an object-oriented programming (OOP) style syntax, allowing the simulation of "global variables" through a global singleton. This makes it easy to write themes. Touying does not rely on `counter` and `locate` to implement `#pause`, resulting in better performance.
If you like it, consider [giving a star on GitHub](https://github.com/touying-typ/touying). Touying is a community-driven project, feel free to suggest any ideas and contribute.
[](https://touying-typ.github.io/touying/)




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

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

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

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

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

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

It's simple. Congratulations on creating your first Touying slide! 🎉
## More Complex Examples
In fact, Touying provides various styles for writing slides. For example, the above example uses first-level and second-level titles to create new slides. However, you can also use the `#slide[..]` format to access more powerful features provided by Touying.
```typst
#import "@preview/touying:0.2.1": *
#let s = themes.metropolis.register(s, aspect-ratio: "16-9")
#let s = (s.methods.enable-transparent-cover)(self: s)
#let (init, slide) = utils.methods(s)
#show: init
// simple animations
#slide[
a simple #pause *dynamic*
#pause
slide.
#meanwhile
meanwhile #pause with pause.
][
second #pause pause.
]
// complex animations
#slide(setting: body => {
set text(fill: blue)
body
}, repeat: 3, self => [
#let (uncover, only, alternatives) = utils.methods(self)
in subslide #self.subslide
test #uncover("2-")[uncover] function
test #only("2-")[only] function
#pause
and paused text.
])
// math equation animations
#slide[
== Touying Equation
#touying-equation(`
f(x) &= pause x^2 + 2x + 1 \
&= pause (x + 1)^2 \
`)
#meanwhile
Touying equation is very simple.
]
// multiple pages for one slide
#slide[
== Multiple Pages for One Slide
#lorem(200)
]
// appendix by freezing last-slide-number
#let s = (s.methods.appendix)(self: s)
#let (slide,) = utils.methods(s)
#slide[
== Appendix
]
```

## Acknowledgements
Thanks to...
- [@andreasKroepelin](https://github.com/andreasKroepelin) for the `polylux` package
- [@Enivex](https://github.com/Enivex) for the `metropolis` theme
- [@drupol](https://github.com/drupol) for the `university` theme
- [@ntjess](https://github.com/ntjess) for contributing to `fit-to-height`, `fit-to-width` and `cover-with-rect`
|
|
https://github.com/LEXUGE/typzk | https://raw.githubusercontent.com/LEXUGE/typzk/main/manual.typ | typst | MIT License | #import "@typzk/zkgraph:0.1.0": *
#import "@preview/physica:0.9.2": *
#let ii = sym.dotless.i
#let to = sym.arrow.r
#let vb(body) = $bold(upright(body))$
#let cdot = sym.dot.c
#let inv(body) = $body^(-1)$
#let conj(body) = $overline(body)$
#show: set math.equation(numbering: "(1.1)")
= Simple Examples
#figure(render_graph(), caption: [Example Graph]) <complete>
@complete is rendered by
```typst
#figure(
render_graph(),
caption: [Example Graph]
)
```
We can also create graph using a certain subgraph:
#figure(render_graph(path: ("qm", "dynamics")), caption: [Example Subgraph]) <subgraph>
@subgraph is rendered by
```typst
#figure(
// `path`: subgraph identities
render_graph(path: ("qm", "dynamics")),
caption: [Example Subgraph]
)
```
#pagebreak()
#subgraph(
"qm", desc: [Quantum Mechanics],
)[
= Quantum Mechanics
#subgraph(
"postulates", desc: [Postulates],
)[
== Postulates
#node(
"hilbert_space", desc: [Hilbert Space],
)[The states of quantum mechanical objects live in a Hilbert Space. The dimension
of the Hilbert Space is determined by the complete set of commutative operators.\ ]
#node(
"observable", desc: [Observables\ are Hermitian], links: ("sch_eqn",),
)[Observables are represented by Hermitian operators with real eigenvalues.\ ]
#node(
"measurement", desc: [Measurement],
)[Measurements are represented by projecting (and renormalizing) state vectors
onto the corresponding eigenspaces.\ ]
]
#subgraph(
"dynamics", desc: [Basic Dynamics],
)[
== Dynamics
#node(
"sch_eqn", back_links: ("hilbert_space",), desc: [Schrödinger equation],
)[
*Schrodinger equation:* Let $ket(phi(t)): RR to cal(H)$ describes the trajectory
of some system with Hamiltonian $op(H)$, then
$ ii hbar pdv(ket(phi(t)), t) = op(H) ket(phi(t)) $
]
#node("prob_current", back_links: ("sch_eqn",), desc: [Probability Current])[
*Probability Current*:
$ vb(J) = hbar / m rho grad theta $
]
]
]
#pagebreak()
= Graph Generation Code
```typst
// Usage: subgraph(identity: string, desc: content)[body]
// `identity` must be a valid graphviz term
#subgraph("qm", desc: [Quantum Mechanics])[
// Arbitrary content is allowed here
= Quantum Mechanics
// Subgraph can be nested
#subgraph("postulates", desc: [Postulates])[
== Postulates
#node("hilbert_space", desc: [Hilbert Space])[The states of quantum mechanical objects live in a Hilbert Space. The dimension of the Hilbert Space is determined by the complete set of commutative operators.\ ]
// Links to other nodes are supported
#node("observable", desc: [Observables\ are Hermitian], links: ("sch_eqn",))[Observables are represented by Hermitian operators with real eigenvalues.\ ]
#node("measurement", desc: [Measurement])[Measurements are represented by projecting (and renormalizing) state vectors onto the corresponding eigenspaces.\ ]
]
#subgraph("dynamics", desc: [Basic Dynamics])[
== Dynamics
// Backlinks are also supported
#node("sch_eqn", back_links:("hilbert_space", ), desc: [Schrödinger equation])[
*Schrodinger equation:* Let $ket(phi(t)): RR to cal(H)$ describes the trajectory of some system with
Hamiltonian $op(H)$, then
$ ii hbar pdv(ket(phi(t)), t) = op(H) ket(phi(t)) $
]
#node("prob_current", back_links: ("sch_eqn",), desc: [Probability Current])[
*Probability Current*:
$ vb(J) = hbar / m rho grad theta $
]
]
]
```
= Metadata Introspection
To explore the graphviz code generated and internal state, insert metadata with
```typst
#context [
#metadata(gen_graphviz(digraphState.final().graph)) <graphviz_code>
#metadata(digraphState.final()) <internal_state>
]
```
and run
```bash
$ typst query manual.typ "<graphviz_code>"
[
{
"func": "metadata",
"value": "digraph {subgraph cluster_qm {label=\"\";subgraph cluster_postulates {label=\"\";hilbert_space;observable;measurement; };subgraph cluster_dynamics {label=\"\";sch_eqn;prob_current; }; };observable->sch_eqn;hilbert_space->sch_eqn;sch_eqn->prob_current;}",
"label": "<graphviz_code>"
}
]
```
and similarly for internal state
```typst
{
"graph": {
"cluster_qm": {
"cluster_postulates": {
"hilbert_space": [],
"observable": [
"observable->sch_eqn"
],
"measurement": []
},
"cluster_dynamics": {
"sch_eqn": [
"hilbert_space->sch_eqn"
],
"prob_current": [
"sch_eqn->prob_current"
]
}
}
},
"hierarchy": [],
"labels": {
"hilbert_space": {
"func": "link",
"dest": "<node_hilbert_space>",
"body": {
"func": "text",
"text": "Hilbert Space"
}
},
"observable": {
"func": "link",
"dest": "<node_observable>",
"body": {
"func": "sequence",
"children": [
{
"func": "text",
"text": "Observables"
},
{
"func": "linebreak"
},
{
"func": "space"
},
{
"func": "text",
"text": "are Hermitian"
}
]
}
},
"measurement": {
"func": "link",
"dest": "<node_measurement>",
"body": {
"func": "text",
"text": "Measurement"
}
},
"sch_eqn": {
"func": "link",
"dest": "<node_sch_eqn>",
"body": {
"func": "text",
"text": "Schrödinger equation"
}
},
"prob_current": {
"func": "link",
"dest": "<node_prob_current>",
"body": {
"func": "text",
"text": "Probability Current"
}
}
},
"clusters": {
"cluster_qm": {
"func": "link",
"dest": "<cluster_qm>",
"body": {
"func": "text",
"text": "Quantum Mechanics"
}
},
"cluster_postulates": {
"func": "link",
"dest": "<cluster_postulates>",
"body": {
"func": "text",
"text": "Postulates"
}
},
"cluster_dynamics": {
"func": "link",
"dest": "<cluster_dynamics>",
"body": {
"func": "text",
"text": "Basic Dynamics"
}
}
}
}
```
#context [
#metadata(gen_graphviz(digraphState.final().graph)) <graphviz_code>
#metadata(digraphState.final()) <internal_state>
]
|
https://github.com/Hamoudasfaxi/Lab-3 | https://raw.githubusercontent.com/Hamoudasfaxi/Lab-3/main/Lab-3.typ | typst | #import "Class.typ": *
#show: ieee.with(
title: [#text(smallcaps("Lab #3: Web Application with Genie"))],
abstract: [
#lorem(10).
],
authors:
(
(
name: "<NAME>",
department: [Senior-lecturer, Dept. of EE],
organization: [ISET Bizerte --- Tunisia],
profile: "a-mhamdi",
),
(
name: "<NAME>",
department: [Dept. of EE],
organization: [ISET Bizerte --- Tunisia],
profile: "Hamoudasfaxi",
),
(
name: "<NAME>",
department: [Dept. of EE],
organization: [ISET Bizerte --- Tunisia],
profile: "med-nabil",
),
)
// index-terms: (""),
// bibliography-file: "Biblio.bib",
)
= Exercise
In this lab, We will create a basic web application using *Genie* framework in Julia. The application will allow us to control the behaviour of a sine wave, given some adjustble parameters. We are required to carry out this lab using the REPL as in @fig:repl.
#figure(
image("Images/REPL.png", width: 100%, fit: "contain"),
caption: "Julia REPL"
) <fig:repl>
#exo[Sine Wave Control][We provide the Julia and HTML codes to build and run a web app that allows us to control the amplitude and frequency of a sine wave. *Plotly* is used to plot the corresponding graph. We also added a slider to change the number of samples used to draw the figure. The latter setting permits to grasp the influence of sampling frequency on the look of our chart.]
#let code=read("../Codes/web-app/app.jl")
#raw(code, lang: "julia")
#let code=read("../Codes/web-app/app.jl.html")
#raw(code, lang: "html")
```zsh
julia --project
```
```julia
julia> using GenieFramework
julia> Genie.loadapp() # Load app
julia> up() # Start server
```
We can now open the browser and navigate to the link #highlight[#link("localhost:8000")[localhost:8000]]. We will get the graphical interface as in .
#figure(
image("Images/Genie-sinewave.png", width: 100%),
caption: "Genie -> Sine Wave",
) <fig:genie-webapp>
We add Phase and Offset in app.jl.HTML:
#figure(
image("Images/Adding Phase.png", width: 100%),
caption: "Adding Phase",
) <fig:genie-webapp>
#figure(
image("Images/Adding Offset.png", width: 100%),
caption: "Adding Offset",
) <fig:genie-webapp>
Now We add phase and Offset in app.jl
#figure(
image("Images/New sine Wave.png", width: 100%),
caption: "app.jl",
) <fig:genie-webapp>
We can now open the browser and navigate to the link #highlight[#link("localhost:8000")[localhost:8000]]
#figure(
image("Images/Sine Wave.png", width: 100%),
caption: "Genie -> Sine Wave",
) <fig:genie-webapp>
|
|
https://github.com/appare45/Typst-template | https://raw.githubusercontent.com/appare45/Typst-template/main/default.typ | typst | #let template(doc, title, author) = [
#set text(font: "Hiragino Mincho ProN")
#set heading()
#show heading: set text(font: "Hiragino Kaku Gothic ProN")
#set document(title: title, author: author)
#set text(lang: "ja")
#doc
]
|
|
https://github.com/piepert/grape-suite | https://raw.githubusercontent.com/piepert/grape-suite/main/src/slides.typ | typst | MIT License | #import "@preview/polylux:0.3.1"
#import "german-dates.typ": semester, weekday
#import "colors.typ": *
#import "todo.typ": todo, list-todos, todo-state, hide-todos
#import "elements.typ": *
#let uncover = polylux.uncover
#let only = polylux.uncover
#let pause = polylux.pause
#let slide(..args) = polylux.polylux-slide(..args)
#let slides(
no: 0,
series: none,
title: none,
topics: (),
head-replacement: none,
title-replacement: none,
footer: none,
author: none,
email: none,
page-numbering: (n, total) => {
text(size: 0.75em, strong[#n.first()])
text(size: 0.5em, [ \/ #total.first()])
},
show-title-slide: true,
show-author: true,
show-semester: true,
show-date: true,
show-outline: true,
show-todolist: true,
show-footer: true,
show-page-numbers: true,
box-task-title: standard-box-translations.at("task"),
box-hint-title: standard-box-translations.at("hint"),
box-solution-title: standard-box-translations.at("solution"),
box-definition-title: standard-box-translations.at("definition"),
box-notice-title: standard-box-translations.at("notice"),
box-example-title: standard-box-translations.at("example"),
sentence-supplement: "Example",
outline-title-text: "Outline",
date: datetime.today(),
body
) = {
let left-footer = if footer != none {
footer
} else {
text(size: 0.5em, (
if show-semester [#semester(short: true, date)],
[#series \##no],
title,
if show-author { author }).filter(e => e != none).join[ --- ]
)
}
show footnote.entry: set text(size: 0.5em)
show heading: set text(fill: purple)
set text(size: 24pt, font: "Atkinson Hyperlegible")
set page(paper: "presentation-16-9",
footer: {
(context if (show-outline and here().page() > 2) or here().page() > 1 {
set text(fill: if here().page() > 2 or not show-outline {
purple.lighten(25%)
} else {
blue.lighten(25%)
})
left-footer
h(1fr)
if show-page-numbers {
page-numbering(counter(page).at(here()), counter(page).final())
}
})
}
)
state("grape-suite-box-translations").update((
"task": box-task-title,
"hint": box-hint-title,
"solution": box-solution-title,
"definition": box-definition-title,
"notice": box-notice-title,
"example": box-example-title,
))
state("grape-suite-element-sentence-supplement").update(sentence-supplement)
show: sentence-logic
if show-title-slide {
slide(align(horizon, [
#block(inset: (left: 1cm, top: 3cm))[
#if head-replacement == none [
#text(fill: purple, size: 2em, strong[#series ] + if no != none [\##no]) \
] else { head-replacement }
//
#if title-replacement == none [
#text(fill: purple.lighten(25%), strong(title))
] else { title-replacement }
#set text(size: 0.75em)
#if show-author [#author #if email != none [--- #email ] \ ]
#if show-semester [#semester(date) \ ]
#if show-date [#weekday(date.weekday()), #date.display("[day].[month].[year]")]
]
]))
}
if show-outline {
set page(fill: purple, footer: context if show-footer {
set text(fill: if here().page() > 2 or not show-outline {
purple.lighten(25%)
} else {
blue.lighten(25%)
})
left-footer
})
slide[
#set text(fill: white)
#heading(outlined: false, text(fill: blue.lighten(25%), [#outline-title-text]))
#context {
let elems = query(selector(heading).after(here()))
enum(..elems
.filter(e => e.level == 1 and e.outlined)
.map(e => {
e.body
}))
}
]
}
if show-todolist {
context {
if todo-state.final().len() > 0 {
slide[
#list-todos()
]
}
}
}
counter(page).update(1)
set page(fill: white)
body
} |
https://github.com/tingerrr/chiral-thesis-fhe | https://raw.githubusercontent.com/tingerrr/chiral-thesis-fhe/main/src/prelude/subpar.typ | typst | #let (super, grid) = {
import "/src/packages.typ" as _pkg
import "/src/utils.typ" as _utils
let subpar-args = (
numbering: n => _utils.chapter-relative-numbering("1-1", n),
numbering-sub-ref: (n, m) => _utils.chapter-relative-numbering("1-1a", n, m),
show-sub-caption: (n, it) => grid(
columns: (auto, 1fr),
gutter: 0.5em,
align: left + top,
n,
emph(it.body),
),
)
(
_pkg.subpar.super.with(..subpar-args),
_pkg.subpar.grid.with(..subpar-args),
)
}
|
|
https://github.com/linhduongtuan/DTU-typst-presentation | https://raw.githubusercontent.com/linhduongtuan/DTU-typst-presentation/main/Beispiele/MatheDeltaEpsilon/edk_typst.typ | typst | #set page(margin: 0.5cm, width: 22cm, height: 5.5cm)
#set text(size: 14pt, font: "New Computer Modern")
#set par(justify: true)
*#smallcaps([Definition 1.])* _Sei $D subset.eq RR$ und sei $f: D -> RR$ eine Funktion. f ist stetig in $x_0 in D$ genau dann, wenn die folgende Aussage gilt:_
_Für alle $epsilon > 0$ existiert ein $delta > 0$, sodass $| f(x)-f(x_0) | < epsilon$ für alle $x in D$ mit $| x-x_0 | < delta$._
_Oder Alternativ: $forall epsilon > 0 exists delta > 0 forall x in D : |y-y_0| < delta => |f(x)-f(x_0)| < epsilon$_
#v(1em)
(Typst) |
|
https://github.com/jamesrswift/blog | https://raw.githubusercontent.com/jamesrswift/blog/main/assets/packages/booktabs/rigor.typ | typst | MIT License | #import "style.typ": *
#import "footnotes.typ" as footnotes
// Query is an array of key, value, and inherit
#let recurse-columns(columns, queries) = {
for column in columns {
let queries = queries
for (key, query) in queries {
let default = query.at("default", default: none)
let value = query.at("value", default: default)
queries.at(key).value = column.at(
key,
default: if (query.at("inherit", default: true)) {
value
} else {query.default}
)
}
if "children" in column {
recurse-columns(
column.children,
queries
)
} else {
(queries,)
}
}
}
#let build-header(columns, max-depth: 1, start: 0) = {
// For every column
for entry in columns {
if (entry.length == 0) {continue}
// Make a cell that spans its recusive length (and limit rowspan if it has children)
(table.cell(
x: start,
y: entry.depth,
rowspan: if entry.length == 1 {max-depth - entry.depth} else {1},
colspan: entry.length,
// Header cells should be horizon aligned. Ideally it should default to `start`
// but I've shadowed that variable.
align: horizon + entry.at("align", default: left),
entry.header
),)
// If it has nested columns, build those too.
// NOTE: Return values are collated using automatic array joining!
if "children" in entry and entry.children.len() > 0 {
build-header(
entry.children,
max-depth: max-depth,
start: start // Pass along
)
}
// If it has a hline, add it under the cell
if ("hline" in entry){
(
table.hline(
y: entry.depth + 1,
start: start,
end: start + entry.length,
..entry.hline
),
)
}
if ("vline" in entry){ (table.vline(x: start + 1, ..entry.vline),) }
// Keep track of which column we are in. This could be precalculated.
start += entry.length
}
}
#let sanitize-input(columns, depth: 0, max-depth: 1, length: 0) = {
// For every column
for (key, entry) in columns.enumerate() {
// if it has children
if "children" in entry {
// Recurse
let (children, child-depth, child-length) = sanitize-input(
entry.children,
depth: depth + 1,
max-depth: max-depth + 1
)
// record the recursive length
columns.at(key).insert("length", child-length)
columns.at(key).children = children
length += child-length
// Keep track of the deepest yet seen rabit hole
max-depth = calc.max(max-depth, child-depth)
// Bottom of the rabit hole, must have a length of 1
} else {
length += 1
columns.at(key).insert("length", 1)
}
// In all cases, keep track of depth
columns.at(key).insert("depth", depth)
}
// Pass the results on
return (columns, max-depth, length)
}
#let data-from-key(dictionary, key, default: none) = {
if type(key) == str { key = key.split(".").rev()}
if (key.len() == 1){ return dictionary.at(key.last(), default: default) }
data-from-key(
dictionary.at(key.pop(), default: (:)),
key,
default: default
)
}
#let make(
columns: (),
data: (),
hline: none,
toprule: toprule,
midrule: midrule,
bottomrule: bottomrule,
notes: footnotes.display-list, // ADDED
..args
) = {
let (columns, max-depth, length) = sanitize-input(columns, depth: 0)
let query-result = recurse-columns(columns, (
fill: (inherit: true, default: none),
align: (inherit: true, default: start),
gutter: (inherit: true, default: 0em),
width: (inherit: true, default: auto),
display: (inherit: true, default: none),
key: (inherit: false, default: ""),
))
let row-display = query-result.map(it=>it.key.value).zip(
query-result.map(it=>it.display.value)
)
set text(size: 9pt)
set math.equation(numbering: none)
footnotes.clear() + table( // ADDED
stroke: none,
fill: query-result.map(it=>it.fill.value),
align: query-result.map(it=>it.align.value),
column-gutter: query-result.map(it=>it.gutter.value),
columns: query-result.map(it=>it.width.value),
table.header(
table.hline(stroke: toprule),
..build-header(columns, max-depth: max-depth),
table.hline(stroke: midrule, y: max-depth),
),
..args,
..(
for entry in data{
row-display.map( ((key, display))=>{
let data = data-from-key(entry, key, default: none)
if ((display) == none) {return data}
display(data)
})
if hline != none {(hline,)}
}
),
table.hline(stroke: bottomrule)
) + if (notes != none) {footnotes.display-style(notes)} // ADDED
}
|
https://github.com/dead-summer/math-notes | https://raw.githubusercontent.com/dead-summer/math-notes/main/notes/ScientificComputing/ch1-intro-to-scicomp/stability.typ | typst | #import "/book.typ": book-page
#import "../../../templates/conf.typ": *
#import "@preview/mitex:0.2.4": *
#show: book-page.with(title: "Efficiency")
#show: codly-init.with()
#show: thmrules.with(qed-symbol: $square$)
#codly_init()
= 6 Stability
Stability means sensitivity of solution to external perturbation. We say a numerical method is stable if its solution to a problem is insensitive to external perturbation; otherwise, a numerical method is unstable if its solution is sensitive to external perturbation.
#exm[
Evaluate the integral
$
I_n = integral_0^1 x^n/(10+x) dif x
$
for some $n = 20, 30, 40$.
]
First note that
$
I_n + 10 I_(n-1) = integral_0^1(x^n + 10 x^(n-1)/(10+x)) dif x = integral_0^1 x^(n-1) dif x = 1/n.
$
We have the recursion,
$
I_n = 1/n - 10 I_(n-1), n = 1, 2, dots.h, N
$
with
$
I_0 = integral_0^1 1/(10+x) dif x = ln(11/10).
$
```cpp
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
int main(int argc, char *argv[])
{
int n = 20;
float I0 = log(1.1);
for (int i = 1; i <= n; i++) {
float I = 1.0 / i − 10.0 * I0;
std::cout << "i = " << i << ", I = " << I << std::endl;
I0 = I;
}
return EXIT SUCCESS;
}
```
The results in the experiments are wrong since the values should always be positive (the sequence ${I_n}$ is strictly monotonely decreasing) and actually we have the estimate
$
1/(11(n+1)) = 1/11 integral_0^1x^n dif x < I_n < 1/10 integral_0^1 x^n dif x = 1/(10(n+1))
$
which is never greater than one.
As an alternative approach, one can work with the following recursion
$
I_(n-1) = 1/(10n) - 1/10 I_n, n = N, N-1, ..., 2, 1,
$
starting with a number $N$ larger than $n$ except that the value $I_N$ is unknown and can only be replaced with an approximate value.
For example, when $N = 99$ , since we have
$
1/1100 < I_(99) < 1/1000,
$
we can approximate $I_(99)$ by
$
tilde(I)_(99) equiv 1/2 (1/1100 + 1/1000) = 21/22000,
$
with the error between $I_(99)$ and $tilde(I)_(99)$ be less than $1 \/ 22000$.
At the first glance, one may think that a good approximation for $I_N$ should be provided. In fact, there is no such need at all. One can try with a very rough value for $I_N$ as long as $N$ is sufficiently large.
For any $n$ , one can choose $N > n + 20$ and even try with $tilde(I)_N = 1$ , which has an obviously large error, close to one. But the error will decay quickly to zero by the recursion.
```cpp
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
int main(int argc, char *argv[ ])
{
int n = 40;
int N = 60;
float I1 = 1.0;
for (int i = N; i >= n; i--) {
float I = 1.0 / (10.0 * i) - 0.1 * I1;
std::cout << "i = " << i << ", I = " << I << std::endl;
I1 = I;
}
return EXIT SUCCESS;
}
```
|
|
https://github.com/sebastos1/light-report-uia | https://raw.githubusercontent.com/sebastos1/light-report-uia/main/lib.typ | typst | MIT License | // This is just a latex copy of a LaTeX template. Originally made by these guys: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
// english and norwegian support
#let translations = (
en: (
contents: "Contents",
figure: "Figure",
table: "Table",
listing: "Listing",
list_of_figures: "Figures",
list_of_tables: "Tables",
list_of_listings: "Listings",
consisting_of: "consisting of",
and_: "and",
in_: "in",
faculty: "Faculty of Engineering and Science",
university: "University of Agder",
references: "References",
),
no: (
contents: "Innhold",
figure: "Figur",
table: "Tabell",
listing: "Listing",
list_of_figures: "Figurer",
list_of_tables: "Tabeller",
list_of_listings: "Listinger",
consisting_of: "av",
and_: "og",
in_: "i",
faculty: "Fakultet for teknologi og realfag",
university: "Universitetet i Agder",
references: "Referanser",
)
)
#let report(
title: none,
authors: none,
group_name: none,
course_code: none,
course_name: none,
date: none,
lang: "en",
location: "Grimstad", // possibly different?
references: "references.yml", // in case user wants to use their own file
body
) = {
set document(title: [#title - #group_name], author: authors)
set text(font: "Linux Libertine", lang: lang)
set par(justify: true) // blocky paragraphs
show link: underline
show heading: set block(above: 18pt, below: 18pt)
if lang == "nb" or lang == "nn" {
lang = "no"
}
assert(lang in translations.keys(), message: "Unsupported language code: " + lang + ". Supported codes are: " + translations.keys().join(", "))
let t = translations.at(lang)
// to have language-specific figure namings (and correct targeted outlines)
show figure.where(kind: image): set figure(supplement: t.figure)
show figure.where(kind: table): set figure(supplement: t.table)
show figure.where(kind: raw): set figure(supplement: t.listing)
let format_authors(authors, and_word) = {
if authors.len() == 1 {
authors.first()
} else {
authors.slice(0, -1).join(", ") + " " + and_word + " " + authors.last()
}
}
// FRONT PAGE
set align(center)
block(height: 25%, image("media/UIA_" + lang + ".svg", height: 140%))
v(1cm)
text(25pt, weight: "bold", title)
v(3mm)
text(18pt, group_name)
v(3mm)
text(12pt, t.consisting_of)
v(3mm)
text(18pt, format_authors(authors, t.and_))
v(3mm)
text(12pt, t.in_)
v(3mm)
text(18pt)[
#course_code
#linebreak()
#course_name
]
v(1fr) // to bottom
text(12pt)[
#t.faculty
#linebreak()
#t.university
]
v(3mm)
text(15pt)[#location, #date]
pagebreak()
// contents page
set align(left)
set heading(numbering: "1.")
outline(indent:auto, title: t.contents)
pagebreak()
// Page with lists of figures, tables and listings. Each list, or potentially the entire page, will be hidden if there's no matching elements
context {
let has_type(type) = query(figure.where(kind: type)).len() > 0
let show_this_page = false
if has_type(image) {
show_this_page = true
[ #outline(title: t.list_of_figures, target: figure.where(kind: image)) ]
}
if has_type(table) {
show_this_page = true
[ #outline(title: t.list_of_tables, target: figure.where(kind: table)) ]
}
if has_type(raw) {
show_this_page = true
[ #outline(title: t.list_of_listings, target: figure.where(kind: raw)) ]
}
if show_this_page {
pagebreak()
}
}
// after the front page and content things
set page(numbering: "1", number-align: center)
// main.typ
body
pagebreak()
// https://github.com/typst/hayagriva/blob/main/docs/file-format.md
bibliography("template/" + references, title: t.references)
} |
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/AnalisiDeiRequisiti/meta.typ | typst | MIT License | #let title = "Analisi dei Requisiti" |
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/web3/weeks/week12.typ | typst | #import "../../utils.typ": *
#section("ASP NET")
- .not framework
- server side rendering -> expressjs, go server stuff, ruby on rails
#subsection("C worse")
#subsubsection("HTML Tags")
Csharp obviously doesn't know about HTML tags or its properties, this can be
fixed with ASP.NET tags:
```cs
[Required]
[StringLength(100, MinimumLength = 10)]
public string Name { get; set; }
[HttpPost]
public ActionResult About()
public static void Main(string[] args) {
// ASP specific Tag query
var typesWithAttribute = (
from type in Assembly.GetEntryAssembly().GetTypes()
where type.GetCustomAttribute<SomeAttribute>() != null
select type
).ToList();
// create instance of this type
PrintObj(Activator.CreateInstance(typesWithAttribute.First()));
Console.ReadLine();
}
```
#subsubsection("Anonymous types")
```cs
// no name
var v = new { Amount = 108, Message = "Hello" };
Console.WriteLine(v.Amount + v.Message);
```
#subsubsection("Class extensions")
```cs
string s = "Hello Extension Methods";
int i = s.WordCount();
// this exists already
public static class MyExtensions {
// new function added to parameter
// e.g. this -> string
// hence on the type of variable str, we will add a new function
public static int WordCount(this string str) {
return str.Split(new char[] { ' ', '.', '?' }).Length;
}
}
// note, you can't access private variables from the class here!
```
These tags can also be read with *reflection*.
#subsection("Convention")
ASP does not do much configurability
- uses typical conventions instead
- idea is to not need to think about how to setup things
- framework does this instead
- on certain actions, ASP will automatically create a success or failure URL -> no
need to define it your own
- pain when this is not what you want/need
- For users who aren't familiar with all convention rules, behavior might seem
random.
#subsection("Thread Pool")
- ASP.NET provides its own thread pool
- size is configurable
- ASP chooses a thread for each request
- this thread is blocked until request processing is done
- premature return possible
- NOTE: don't create static data for controller and services
- ASP creates a new controller for each request -> aka won't work!
- if you want static data, you need to provide custom datastructure that is thread
safe!
#subsection("MVVM (Model-View-Viewmodel) in ASP")
#align(
center,
[#image("../../Screenshots/2023_12_08_06_11_45.png", width: 70%)],
)
#subsection("Middlewares")
- each middleware can end the request or pass it to the next one
- example middlewares:
- logging
- mvc
- authorization
- error handling
#align(
center,
[#image("../../Screenshots/2023_12_08_06_13_17.png", width: 60%)],
)
#subsection("Example Application")
Setup Code\
```cs
var builder = WebApplication.CreateBuilder(args);
// Dependency Injection
builder.Services.AddSingleton<TodoService, TodoService>();
var app = builder.Build();
// Register Middleware
app.Use(async (context, next) => { /* … */ });
app.Run();
``` Configuration ```json
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7250",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
```
Register New Middlewares on entire application
```cs
app.Use(async (context, next) => {
System.Diagnostics.Debug.WriteLine("Handling request");
await next.Invoke();
System.Diagnostics.Debug.WriteLine("Finished handling request.");
});
```
Register middleware on an existing path and fork into middleware
```cs
app.Map("/logging", builder => {
// builder creates fork
// middleware executed inside fork
builder.Run(async (context) => {
await context.Response.WriteAsync("Hello World!");
});
});
```
Register End middleware
```cs
// this middleware ends the request -> no next called, and no fork called
app.Run(async (context) => {
await context.Response.WriteAsync("Hello World!");
});
```
Register Middleware as generic class parameter
```cs
app.UseMiddleware<RequestLoggerMiddleware>();
public class RequestLoggerMiddleware {
private readonly RequestDelegate _next;
private readonly ILogger _logger;
// next variable is the next middleware
// further parameters are handled by the dependency container -> injection
public RequestLoggerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) {
_next = next;
_logger = loggerFactory.CreateLogger<RequestLoggerMiddleware>();
}
public async Task Invoke(HttpContext context) {
_logger.LogInformation("Handling request: " + context.Request.Path);
await _next.Invoke(context);
_logger.LogInformation("Finished handling request.");
}
}
```
#subsection("Dependency Injection")
- Idea
- define interfaces that must be implemented
- a resolver searches for a class inside the container that fits these interfaces
- if no class is found, throw error
- differences between dependency injection containers
- different default behavior
- registration can me manual or automatic
- some resolvers throw exceptions when the result isn't clear
#subsubsection("Example")
```cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddTransient<IUserService, UserService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseMiddleware<UserMiddleware>();
app.Run();
// use the injection
public class UserMiddleware {
private readonly RequestDelegate _next;
// so called captive dependency
public UserMiddleware(RequestDelegate next, IUserService userService) {
// problem is that the requestdelegate variable would not live as long as the class variable
// Hence we keep the service alive for longer by keeping the reference, however this does not mean the service is still active!
_next = next;
}
public async Task Invoke(HttpContext context, IUserService userService) {
// no captive dependency -> e.g. no references set
await context.Response.WriteAsync(string.Join(", ", userService.Users));
}
}
```
Lifetimes:
- Transient: temporary -> function(new Someting()) -> Something is transient, e.g.
best for small, stateless services that are created each time
- created once per usage
- Scoped: local variable with a regular scope
- created once per request
- Singleton: creation can be lazy, after that: as long as the app runs
- created once per app
#text(
red,
)[Important:
- DBContext is not multi threading safe!
- Only use services in combination with same level services or longer living
services
]
#align(
center,
[#image("../../Screenshots/2023_12_08_06_40_23.png", width: 100%)],
)
- T: transient service
- S: singleton service
A singleton may NOT use a transient service -> transient lives shorter\
A transient may use a singleton service -> singleton lives longer
#subsection("Project Structure")
- templates with different features
- wwwroot
- everything needed for a website
- appsettings.json
- settings for website and connection for db
- Program.cs
- entry point for program
- middleware and dependency injection configuration
#subsection("Pages")
Pages in ASP are created using a special templating engine -> htmx similar
```asp
<!-- With the @ you can use Csharp code inside the template! -->
<!-- Single statement blocks -->
@{ var total = 7; }
@{ var myMessage = "Hello World"; }
<!-- Inline expressions -->
<p>The value of your account is: @total </p>
<p>The value of myMessage is: @myMessage</p>
<!-- Multi-statement block -->
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Today is: " + weekDay;
<!-- Note, you can also just use html here again! Compiler will know it's html
-->
}
<p>The greeting is: @greetingMessage</p>
```
- Good for web applications with "page" focus
- no router needs to be defined
- best practices for server side rendering
- can be combined with MVC
- provides static pages
- REST-API with mvc
#align(
center,
[#image("../../Screenshots/2023_12_08_07_17_32.png", width: 100%)],
)
#subsubsection("Page composition")
Pages have 2 files, the Csharp code and the view code: ```cs
// Csharp
public class HelloWorldModel : PageModel {
public string HelloWorld { get; set; }
public void OnGet() {
HelloWorld = "Hi World!";
}
}
```
```asp
@page
@model HelloWorldModel
@{
ViewData["Title"] = "HelloWorld";
}
<h1>@Model.HelloWorld</h1>
```
\@Model -> this will bind the following variable to Model\
E.g. you can use the variable HelloWorld inside the HelloWorldModel class with
\@Mode.HelloWorld
#subsubsection("OnPost/OnGet")
```cs
public void OnPost(string echoText, long times) {
EchoText = echoText;
Times = times;
}
public void OnPost(EchoModel data) {
Data = data;
}
```
#subsubsection("Bind Property")
With bind property, you can ommit the onPost and instead use the data on the
class immediately:
```cs
// like ngModel in Angular
// or useState in React
public class PostModel : PageModel {
[BindProperty]
public string EchoText { get; set; }
[BindProperty]
public long Times { get; set; }
}
```
#subsubsection("@Page")
```cs
public class RoutingModel : PageModel {
public int Id { get; set; }
[BindProperty(SupportsGet = true, Name = "Id")]
public int Id2 { get; set; }
public void OnGet(int id) {
Id = id;
}
}
```
```asp
@page "/test/{id:int?}"
@model Examples.Pages.Page.RoutingModel
@{
ViewData["Title"] = "Routing";
}
<h1>Routing</h1>
@RouteData.Values["id"]
```
With the page directive, you can also define a custom URL alongside possible
parameters like above.
#subsection("Razor")
#subsubsection("_layout.cshtml")
includes the structure of the website \@RenderBody()\
The place where all the content page will be rendered:\
```asp
<div class="container">
@RenderBody()
</div>
```
\@RenderSection()\
defines the section, in which the content page can place its content\
```asp
<div class="container">
<a class="navbar-brand" asp-area="" asp-page="/Index">Home</a>
@RenderSection("Nav", false)
</div>
@section Nav{
<a class="navbar-brand" asp-area="" asp-page="./ViewData">ViewData</a>
<a class="navbar-brand" asp-area="" asp-page="./TempData">TempData</a>
}
```
#subsubsection("_ViewStart.cshtml")
- hierarchical
- includes code which will be run before the razor-files
- defines the layout for all pages
```asp
@{
Layout = "_Layout";
}
```
#subsection("AJAX")
- Handler functions should have the following naming scheme: On[Method][Name]
- these can be used via: [Method]/[Page]?handler=[HandlerName]
```cs
public class AjaxModel : PageModel {
public IActionResult OnPostEcho(string echoText) {
return this.Content(echoText);
}
public IActionResult OnGetAutocomplete(string text) {
return new JsonResult(_citiesService.GetCities(text));
}
}
```
Example use:
- POST /Ajax?handler=echo\
- GET /Ajax?handler=autocomplete\
#subsubsection("Return Types")
Return values of the functions with IActionResult can be the following:
- ContentResult
- StringResult
- JsonResult
- EmptyResult
- Status
- NotFoundResult
- StatusCodeResult
- Redirects
- RedirectToPage
- RedirectToPagePermanent
- Hilfsmethoden
- Page() und Partial()
- Content()
- ViewComponent()
#subsubsection("Bigger example")
```cs
// Ajax.cshtml.cs
public IActionResult OnPostEcho(string echoText){
return this.Content(echoText);
}
```
AjaxFetch.cshtml: ```asp
<form asp-page="Ajax" asp-page-handler="Echo" id="echoForm">
<input name="echoText"/>
<input type="submit"/>
</form>
<div id="echoOutput"></div>
@section Scripts{
<script>
const echo = document.getElementById("echoOutput");
document.getElementById("echoForm").addEventListener("submit",
async (args) => {
args.preventDefault();
const formData = new FormData(args.target);
const result = await fetch(args.target.action, { method: "post", body: formData
});
echo.innerText = await result.text();
});
</script>
}
```
#subsubsection("Form without javascript")
```asp
<form asp-page="Ajax" asp-page-handler="Echo" id="echoForm" data-ajax="true"
data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#echoOutput">
<input name="echoText"/>
<input type="submit"/>
</form>
<div id="echoOutput"></div>
@section Scripts{
<script
src="https://cdn.jsdelivr.net/npm/jquery-ajax-
[email protected]/dist/jquery.unobtrusive-ajax.min.js"
integrity="<KEY>
crossorigin="anonymous"></script>
}
```
#align(
center,
[#image("../../Screenshots/2023_12_08_07_40_44.png", width: 50%)],
)
#subsection("Data")
#subsubsection("EF Entity Framework (OR Mapper)")
#align(
center,
[#image("../../Screenshots/2023_12_08_07_59_02.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_12_08_07_53_36.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_12_08_07_53_50.png", width: 100%)],
)
#subsubsubsection("Providers")
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.SQLite
- Microsoft.EntityFrameworkCore.InMemory
- no migration
- for testing
#subsubsubsection("Entity")
```cs
public class Order {
public long Id { get; set; }
[Required]
public string Name { get; set; }
public DateTime Date { get; set; }
public OrderState State { get; set; }
public virtual ApplicationUser Customer { get; set; }
[Required]
public string CustomerId { get; set; }
public Order() {
Date = DateTime.Now;
}
}
```
#subsubsubsection("Conventions")
- public [long/string] Id {get;set;}
- recgonized as the primary key of the entity
- public virtual ApplicationUser Customer { get; set; }
- recognized as navigation property
- public [long/string] CustomerId { get; set; }
- recognized as the foreign key for the customer entity
#subsubsubsection("Important Attributes")
- [Required]
- constraint for the database -> NOTNULL
- also possible for navigation properties
- used for the differentiation between aggregation and association
- [NotMapped]
- not used in DB
- [Key]
- defines the primary key for the entity
- [MaxLength(10)]
- influences the allocation size of the property
#subsubsubsection("Migration")
Migration can't be done automatically(fully):
- dotnet ef migrations –help
- dotnet ef migrations add Init
- requires function in code, see below
- dotnet ef migrations script
- dotnet ef database update
- this can be automated
```cs
public partial class Init : Migration {
protected override void Up(MigrationBuilder migrationBuilder) {
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new {
Id = table.Column<long>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Date = table.Column<DateTime>(nullable: false),
Name = table.Column<string>(nullable: true),
State = table.Column<int>(nullable: false)
},
constraints: table => {
table.PrimaryKey("PK_Orders", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder) {
migrationBuilder.DropTable(name: "Orders");
}
}
```
You can migrate with 3 different options:
- dotnet ef database update
- execute script
- migrate in code\
```cs
app.ApplicationServices.GetRequiredService<ApplicationDbContext>().Database.Migrate();
```
|
|
https://github.com/MikoBie/typst_template | https://raw.githubusercontent.com/MikoBie/typst_template/main/themes/iss.typ | typst | // This theme contains ideas from the former "bristol" theme, contributed by
// https://github.com/MarkBlyth
#import "@preview/polylux:0.3.1": *
#import "@preview/cetz:0.2.2"
#let iss-left-footer = state("iss-left-footer", [])
#let iss-short-title = state("iss-short-title", none)
#let iss-color = state("iss-color", blue)
#let iss-logo = state("iss-logo", image("png/uw.png"))
#let m-cell = block.with(
width: 100%,
height: 100%,
above: 0pt,
below: 0pt,
breakable: false
)
#let iss-theme(
aspect-ratio: "16-9",
short-title: none,
left-footer: [],
logo: image("png/uw.png"),
color: blue,
body
) = {
set page(
paper: "presentation-" + aspect-ratio,
margin: 0em,
header: none,
footer: none,
)
set text(size: 25pt)
show footnote.entry: set text(size: .6em)
iss-left-footer.update(left-footer)
iss-color.update(color)
iss-short-title.update(short-title)
iss-logo.update(logo)
body
}
#let title-slide(
title: none,
subtitle: none,
authors: (),
date: none,
secondlogo: none,
funding: none,
) = {
let content = locate( loc => {
let color = iss-color.at(loc)
let logo = iss-logo.at(loc)
let authors = if type(authors) in ("string", "content") {
( authors, )
} else {
authors
}
v(5%)
align(center + horizon)[
#grid(columns: (5%, 1fr, 5%),
[],
{
block(
stroke: ( y: 1mm + color, x: 1mm + color ),
inset: 1em,
breakable: false,
fill: color,
radius: 8pt,
[
#text(fill: white, 1.3em)[*#title*] \
#{
if subtitle != none {
parbreak()
text(fill: white, .9em)[#subtitle]
}
}
]
)
},
[]
)
#v(5%)
#set text(size: .8em)
#grid(
columns: (1fr,) * calc.min(authors.len(), 3),
column-gutter: 1em,
row-gutter: 1em,
block(..authors, width: 70%)
)
#if secondlogo == none{
grid(columns: (5%, 1fr, 5%),
[],
{
set align(center + horizon)
set image(height: 3em)
logo
},
[]
)
} else {
grid(columns: (5%, 1fr, 5%, 1fr, 5%),
[],
{ set align(bottom + right)
set image(height: 3em)
logo
},
[],
{ set align(bottom + left)
set image(height: 3em)
secondlogo
},
[]
)
}
#v(1em)
#date
#v(2em)
#grid(columns: (5%, 1fr,5%),
[],
[#text(size: 14pt)[
#funding
]
],
[]
)
]
})
logic.polylux-slide(content)
}
#let slide(title: none, body) = {
let header = locate( loc => {
let color = iss-color.at(loc)
set align(top)
if title != none {
show: m-cell.with(fill: color, inset: 2em)
set align(horizon)
set text(fill: white, size: 1.2em)
strong(title)
} else { [] }
})
let footer = locate( loc => {
let color = iss-color.at(loc)
let short-title = iss-short-title.at(loc)
let left-footer = iss-left-footer.at(loc)
set align(bottom)
{
set align(horizon + center)
set text(fill: white, size: .5em)
grid(columns: (15%, 1fr, 5%),
{
show: m-cell.with(fill: color.lighten(20%), inset: .5em)
left-footer
},
{
show: m-cell.with(fill: color, inset: .5em)
short-title
},
{
show: m-cell.with(fill: color.darken(20%), inset: .5em)
logic.logical-slide.display()
}
)
}
})
set page(
margin: ( top: 4em, bottom: 2em, x: 0em ),
header: header,
footer: footer,
footer-descent: 1em,
header-ascent: 1.5em,
)
let body = pad(x: .0em, y: .5em, body)
let content = {
grid(columns: (4%, 1fr, 4%),
[],
body,
[])
}
logic.polylux-slide(content)
}
#let focus-slide(background: teal, foreground: white, body) = {
set page(fill: background, margin: 2em)
set text(fill: foreground, size: 1.5em)
let content = { v(.1fr); body; v(.1fr) }
// logic.polylux-slide(align(horizon, body))
logic.polylux-slide(content)
}
#let new-section-slide(name) = {
set page(margin: 2em)
let content = locate( loc => {
let color = iss-color.at(loc)
set align(center + horizon)
show: block.with(stroke: ( bottom: 1mm + color ), inset: 1em,)
set text(size: 1.5em)
strong(name)
utils.register-section(name)
})
logic.polylux-slide(content)
}
|
|
https://github.com/typst-doc-cn/tutorial | https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/intermediate/stateful/q0.typ | typst | Apache License 2.0 |
#let curr-heading = state("curr-heading", ())
#set text(size: 8pt)
#let set-heading(content) = {
show heading.where(level: 3): it => {
show regex("[\p{hani}\s]+"): underline
it
}
show heading: it => {
show regex("KiraKira"): box("★", baseline: -20%)
show regex("FuwaFuwa"): box("✎", baseline: -20%)
it
}
set page(header: {
set text(size: 5pt);
[这是页眉]
})
content
}
#let set-text(content) = {
show regex("feat|refactor"): emph
content
}
#show: set-heading
#show: set-text
#set page(width: 120pt, height: 120pt, margin: (top: 12pt, bottom: 10pt, x: 5pt))
== 雨滴书v0.1.2
=== KiraKira 样式改进
feat: 改进了样式。
=== FuwaFuwa 脚本改进
feat: 改进了脚本。
== 雨滴书v0.1.1
refactor: 移除了LaTeX。
feat: 删除了一个多余的文件夹。
== 雨滴书v0.1.0
feat: 新建了两个文件夹。
|
https://github.com/0xPARC/0xparc-intro-book | https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/old-stuff/h-fhe.typ | typst | #import "preamble.typ":*
*WARNING*: THESE ARE NOT POLISHED AT ALL AND MAY BE NONSENSE.
= FHE intro raw notes (April 16 raw notes from lecture)
#todo[raw notes based on Aard's lecture]
*Fully homomorphic encryption* (FHE) refers to the idea that one can have some encrypted data
and do circuit operations on this encrypted data (NAND gates, etc.).
== Outline
There are six pieces that go into this:
1. LWE (learning with errors): this was the red/blue tables from the retreat.
Given a secret $arrow(a)$ and a bunch of vectors $arrow(v)$,
and the values of $angle.l arrow(a), arrow(v) angle.r + epsilon(arrow(v))$
where there are errors $epsilon(v) in {0,1}$, determine $arrow(a)$.
2. How to public key cryptosystem out of LWE
3. The _approximate eignevector trick_
4. The _flatten trick_.
After the first four items, we get *somewhat homomorphic encryption*,
which works but only up to a certain depth.
(LWE always give small errors, and the errors compound as you do more operations.)
To get from somewhat homomorphic encryption to FHE, we need:
5. Bootstrapping trick.
It turns out that LWE problems don't really care about the values of $(q,n)$.
So you can actually try to translate into a problem with smaller $(q,n)$, which is called:
6. Dimension and modulus reduction
== Learning with errors (LWE)
Pick parameters $q$ and $n$, and a "secret key" $arrow(s) in FF_q^n$.
I put secret key in quotes because we're not going to try to do cryptography just yet;
instead, I'll invite you to guess $arrow(s)$.
Here's the puzzle.
For lots of vectors $arrow(x) in FF_q^n$, I will share with you
$ ( arrow(x), arrow(x) dot arrow(s) + epsilon ) $
where the "errors" $epsilon$ are being sampled from some random distribution
(e.g. Gaussian, doesn't really matter) and bounded with $|epsilon| <= r$.
At the retreat, we had $r = 1$.
I'm happy to give you as many of these perturbed dot products as you like.
The challenge is to determine $arrow(s)$.
#footnote[
Technically, at the retreat we did a decision problem, but it's no different.
Yan has an write-up at #url("https://hackmd.io/F1vjMWzhTk-J7u-ctWQIIQ")
of the red and blue example.
]
Assume LWE is a "hard" problem, i.e. we can't easily recover $arrow(s)$ in this challenge.
(LWE might be hard even when $q=2$, if $epsilon$ is say 90% zero and 10% one.)
=== Attacks on LWE
- Brute force $epsilon$: once you have $n$ vectors, guess all $(2r+1)^n$
possibilities of $epsilon$ and invert the matrices, and see if they work with other vectors.
- Find linear dependencies among the $arrow(x)_i$.
Turns out all the naive algorithms still end up being exponential in $n$.
#remark[
Lattice-based cryptography uses "find the shortest vector in a lattice" as a hard problem,
and it turns out LWE can be reduced to this problem.
So this provides reasons to believe LWE is hard.
]
== Building a public-key system out of LWE
Here's how to build a public-key system.
The public key will consist of $m$ ordered pairs
$ arrow(x)_i, #h(1em) y_i := arrow(x)_i dot arrow(s) + epsilon_i $
where $m approx 2 n log q = 2 log(q^n)$ and $epsilon_i$ are small errors.
We'll assume roughly the size constraints $n^2 <= q <= 2^(sqrt(n))$.
Now, how can I submit a single bit?
Suppose Bob wants to send a single bit to Alice.
The idea is to take $arrow(x)$ as a "not-too-big" random linear combination, like say
$ arrow(x) := 2 arrow(x)_1 + arrow(x)_7 + arrow(x)_9 $
so that Bob can compute
$ y := 2 y_1 + y_7 + y_9 = arrow(x) dot arrow(s) + "up to 4 errors". $
Then Bob sends $arrow(x)$ and then _either_ $y + floor(q/2)$ or $y$.
Since Alice knows the true value of $arrow(x) dot arrow(s)$,
she can figure out whether $y$ or $y + floor(q/2)$ was sent.
So $m$ needs to be big enough that $arrow(x)$ could be almost anything
even with "not-too-big" coefficients, but small enough LWE is still hard.
== Building homomorphic encryption on top of this: approximate
Addition is actually just addition (as long as you don't add too many things
and cause the errors to overflow).
But multiplication needs a new idea, the approximate eigenvalue trick.
Suppose Bob has a message $mu in {0, 1} subset FF_q$.
Our goal is to construct a matrix $C$ such that $C arrow(s) approx mu arrow(s)$,
which we can send as a ciphertext.
#algorithm[
1. Use the public key to find $n$ "almost orthogonal" vectors $arrow(c)_i$,
meaning $arrow(c)_i dot arrow(s)$ is small.
2. If $mu = 0$, use $C$ as the matrix whose rows are $arrow(c_i)$.
3. If $mu = 1$, take the matrix $C$ from Step 2
and then increase its diagonal by $floor(q/2)$.
]
The NOT gate is $1 - C$.
#todo[something about subset sum?]
#todo[I think we can commit to $arrow(s)$ having first component $1$ for convenience
because the augmentation thing is terrible notation-wise]
If we can do this, then multiplication can be done by multiplying the matrices.
#todo[Use NOT, AND gates]
= FHE intro raw notes continued (April 23 raw notes from lecture)
== Recap
To paraphrase last week's setup:
- Our secret key is a vector $v = (1, ...)$ of length $n+1$.
- Our public key is about $2 log(q^n) = 2 n log q$ vectors $a$ such that $a dot v approx 0$.
#remark[
I think we don't even really care whether $q$ is prime or not,
if we work in $ZZ slash q ZZ$.
]
Our idea was that given a message $mu in {0,1}$,
we construct a matrix $C$ such that $C v approx mu v$; the matrix $C$ is the ciphertext.
And we can apply NOT by just looking at $id - C$.
Then given the equations
$
C_1 v &= mu_1 v + epsilon_1 \
C_2 v &= mu_2 v + epsilon_2
$
the multiplication goes like
$
C_1 C_2 v = mu_1 mu_2 v + (mu_2 epsilon_1 + C_1 epsilon_2).
$
In the new error term, $mu_2 epsilon_1$ is still small,
but $C_1 epsilon_2$ is not obviously bounded,
because we don't have constraints on the entries of $C_1$.
== Flatten
So our goal is to modify our scheme so that:
#goal[
We want to change our protocol so that $C$ only has zero-one entries.
]
To do this, we are going to demand our secret key $v$ has a specific form: it must be
$ v = (& 1, 2, 4, ...., 2^ell, \
& a_1, 2a_1, 4a_1, ..., 2^ell a_1, \
& a_2, 2a_2, 4a_2, ..., 2^ell a_2, \
& ..., \
& a_p, 2a_p, 4a_p, ..., 2^ell a_p ) $
where $ell approx log(q)$, where $p := n / ell - 1$.
(This means we really have security parameters $(p,q)$ rather than $(n,q)$.)
#todo[
I think it's better to use $n$ and $N$ instead of $p$ and $n$.
Also, maybe we should just always use $arrow(s)$ for the secret key vector?
$v$ feels too generic for something that never changes lol.
]
#proposition[
There exists a map $Flatten : FF_q^n -> FF_q^n$
taking row vectors of length $n$ such that:
- $Flatten(r)$ has all entries either $0$ or $1$
- $Flatten(r) dot v = r dot v$ for any $v$ in nice binary form.
]
We can then extend $Flatten$ to work on $n times n$ matrices,
by just flattening each of the rows.
When we add this additional assumption, we have a natural map
$ C |-> Flatten(C) $
on matrices that forces them to have $0$/$1$.
#example[
For concreteness, let's write out an example $ell = 3$ and $p = 2$, so
$ v = (1,2,4,8, a_1, 2a_1, 4a_1, 8a_1, a_2, 2a_2, 4a_2, 8a_2). $
Let $q = 13$ for concreteness.
Suppose the first row of $C$ is
$ r := (3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8). $
Then, we compute the dot product
$ r dot v = 29 + 79 a_1 + 95 a_2 = 3 + 11 a_1 + 4 a_2 pmod(13). $
Now, how can we get a 0-1 vector? The answer is to just use binary: we can use
$ Flatten(r) = (1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0) $
because
$ Flatten(r) dot v = (1+2) + (1+2+8) a_1 + 4 a_2. $
Repeating this for however many rows of the matrix you need
]
So, we can flatten any ciphertexts $C$ we get.
Now if $C_1$ and $C_2$ are flattened already, if we multiply $C_1$ and $C_2$,
we don't get a zero-one matrix; but we can just use $Flatten(C_1 C_2)$ instead.
== Going from somewhat homomorphic encryption to fully homomorphic encryption
After a while, our errors are getting big enough that we have trouble.
So we show how to go from somewhat homomorphic encryption to FHE.
This is the jankiest thing ever:
- So, suppose we're stuck at $Enc_(pk)(x)$.
- Generate another pair $(pk', sk')$.
- Send $Enc_(pk')(sk)$.
- We could compute $Enc_(pk')(Enc_(pk)(x))$.
- The decryption is itself a circuit of absolute constant length.
If we picked $(pk, pk')$ well, we should be able to get $Enc_(pk')(x)$.
So we need a way to convert $Enc_(pk')(x)$ back to $Enc_(pk)(x)$.
Let's assume for now $q = q'$.
So let's say we have a secret key $v in FF_q^n$ and $v' in FF_q^(n')$.
Our goal is to provide an almost linear map
$ F = F_(v,v') : FF_q^n -> FF_q^(n') $
that given an arbitrary vector $a in FF_q^n$, gives $F(a) in FF_q^(n')$ such that
$ F(a) dot v' approx a dot v. $
#todo[Something seems fishy here: we were about to provide $F$ at all values
of $(0, ..., 0 2^i, 0 ..., 0)$, but this seems like too much information.
Defer to next meeting.]
In the case where $q' != q$, modulus reduction is done by
$ (F(a) dot v') / q' approx (a dot v) / q. $
= Ring SHE raw notes (May 2 raw notes from lecture)
This is how to set up a somewhat-homomorphic-encryption scheme using rings.
== A non-working scheme over $ZZ$
Here is a non-working example (in the sense that it is obviously insecure).
We're going to have a small modulus, say $t = 2$, and a big odd modulus $q$ coprime to $t$.
The "ciphertexts" will be elements of $ZZ$,
but we'll think of them as elements of $ZZ slash q ZZ$.
Messages will be elements of a $ZZ / t ZZ$.
So to encrypt a bit $m in {0,1}$, we'll choose a small-ish integer $c_0 equiv m mod t$
with $|c_0| << q$.
Then the ciphertext will be an integer $c$ with $c equiv c_0 mod q$.
There's no security here yet: if you see $c$, you can get $c_0$ by just computing $c mod q$.
But that's just because it's easy to take integers modulo $q$.
Now imagine $q$ is a secret key and the public key is integers $q_1$ and $q_2$ with
$gcd(q_1, q_2) = q$.
So again, to encrypt $c_0$, then we just add on random multiples of $q_1$ and $q_2$.
This still isn't secure because we have Euclidean algorithm.
But the idea is that instead of using $ZZ$, we can use a number field.
In a general number field, we might _not_ have the Euclidean algorithm anymore.
That's the trick that makes this scheme go from trivially breakable to hard-to-break.
== Gaussian integers
For concreteness, for example, let's take the Gaussian integers $ZZ[i]$
and the ideal $(6+i)$.
The ideal $(6+i)$ is this lattice generated by $6+i$ and $i(6+i) = -1+6i$.
We'll have $6+i$ take the role of $q$;
we could imagine taking a fundamental domain of this,
so there is a canonical representation of each Gaussian integer.
To encrypt a message, you pick an element of the fundamental domain that's even or odd
(say, by taking modulo $1+i$), and then add a multiple of $q$.
Like before, $q$ is the secret key;
the public key is instead two Gaussian integers $q_1$ and $q_2$.
We'll actually require
$
q_1 &in ZZ \
q_2 &in ZZ + i
$
which you can do using elimination:
starting with the basis vectors $10+7i$ and $-7+10i$,
you take some linear combination of these that gets you the part you want, say
$ 10(10+7i) - 7(-7+10i) &= 149 \
2(10+7i) - 3(-7+10i) &= 41 + i. $
Well, computing the GCD of two Gaussian integers is still pretty easy.
But it gets harder quickly in the degree of the number field, _really quickly_.
== General procedure
To show how to do this for larger degree number fields,
let's take $zeta$ to be a primitive $8$th root of unity.
Hence we're working in the ring
$ ZZ[zeta] / (zeta^4 + 1) $
and the resulting ring of integers is a rank four $ZZ$-module.
We choose something like $q = 1 + 3 zeta + 3 zeta^2 + 7 zeta^3$, for example.
And then we find the smallest integers $n_0$, $n_1$, $n_2$, $n_3$ such that the four numbers
$ angle.l n_0, n_1 + zeta, n_2 + zeta^2, n_3 + zeta^3 angle.r $
are multiples of $q$, hence with gcd $q$.
You don't need all four actually.
Just two is enough.
e.g. if you have $179$ and $zeta - 82$, then $n_2$ will be $82^2 mod 179$ or something like this.
== Relation to LWE
$ angle.l 179, zeta - 82, zeta^2 - 17, zeta^3 - 33 angle.r $
looks a lot like LWE:
$ 82a + 17b + 33c = d mod 179 $
with $a,b,c,d$ small. Kind of? Need to think more about how to make this fleshed out.
== Somewhat homomorphic
Just add and multiply directly, lol.
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/valkyrie/0.1.0/src/types/logical.typ | typst | Apache License 2.0 | #import "../base-type.typ": base-type, assert-base-type
#import "../context.typ": context
/// Valkyrie schema generator for objects that can be any of multiple types.
///
/// - ..options (schema): Variadic position arguments for possible types. *MUST* have at least `1` positional argument. Schemas *SHOULD* be given in order of "preference".
/// -> schema
#let either( ..options ) = {
let options = options.pos()
assert( options.len() > 0 , message: "z.either requires 1 or more arguments.")
for option in options {
assert-base-type(option, scope: ("arguments",))
}
let name = "[" + options.map(it=>it.name).join( ", ", last: " or ") + "]"
return (:..base-type(),
name: name,
validate: (self, it, ctx: context(), scope: ()) => {
for option in options {
let ret = (option.validate)(option, it, ctx: context(ctx, soft-error: true), scope: scope)
if ( ret != none ){ return ret }
}
// Somehow handle error? Not sure how to retrieve from ctx
return (self.fail-validation)(self, it, ctx: ctx, scope: scope,
message: "Type failed to match any of possible options: " + options.map(it=>it.name).join(", ", last: " or "))
}
)
} |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz-plot/0.1.0/src/plot/line.typ | typst | Apache License 2.0 | #import "/src/cetz.typ": draw
#import "util.typ"
#import "sample.typ"
// Transform points
//
// - data (array): Data points
// - line (str,dictionary): Line line
#let transform-lines(data, line) = {
let hvh-data(t) = {
if type(t) == ratio {
t = t / 1%
}
t = calc.max(0, calc.min(t, 1))
let pts = ()
let len = data.len()
for i in range(0, len) {
pts.push(data.at(i))
if i < len - 1 {
let (a, b) = (data.at(i), data.at(i+1))
if t == 0 {
pts.push((a.at(0), b.at(1)))
} else if t == 1 {
pts.push((b.at(0), a.at(1)))
} else {
let x = a.at(0) + (b.at(0) - a.at(0)) * t
pts.push((x, a.at(1)))
pts.push((x, b.at(1)))
}
}
}
return pts
}
if type(line) == str {
line = (type: line)
}
let line-type = line.at("type", default: "raw")
assert(line-type in ("raw", "linear", "spline", "vh", "hv", "hvh"))
// Transform data into line-data
let line-data = if line-type == "linear" {
return util.linearized-data(data, line.at("epsilon", default: 0))
} else if line-type == "spline" {
return util.sampled-spline-data(data,
line.at("tension", default: .5),
line.at("samples", default: 15))
} else if line-type == "vh" {
return hvh-data(0)
} else if line-type == "hv" {
return hvh-data(1)
} else if line-type == "hvh" {
return hvh-data(line.at("mid", default: .5))
} else {
return data
}
}
// Fill a plot by generating a fill path to y value `to`
#let fill-segments-to(segments, to) = {
for s in segments {
let low = calc.min(..s.map(v => v.at(0)))
let high = calc.max(..s.map(v => v.at(0)))
let origin = (low, to)
let target = (high, to)
draw.line(origin, ..s, target, stroke: none)
}
}
// Fill a shape by generating a fill path for each segment
#let fill-shape(paths) = {
for p in paths {
draw.line(..p, stroke: none)
}
}
// Prepare line data
#let _prepare(self, ctx) = {
let (x, y) = (ctx.x, ctx.y)
// Generate stroke paths
self.stroke-paths = util.compute-stroke-paths(self.line-data, x, y)
// Compute fill paths if filling is requested
self.hypograph = self.at("hypograph", default: false)
self.epigraph = self.at("epigraph", default: false)
self.fill = self.at("fill", default: false)
if self.hypograph or self.epigraph or self.fill {
self.fill-paths = util.compute-fill-paths(self.line-data, x, y)
}
return self
}
// Stroke line data
#let _stroke(self, ctx) = {
let (x, y) = (ctx.x, ctx.y)
for p in self.stroke-paths {
draw.line(..p, fill: none)
}
}
// Fill line data
#let _fill(self, ctx) = {
let (x, y) = (ctx.x, ctx.y)
if self.hypograph {
fill-segments-to(self.fill-paths, y.min)
}
if self.epigraph {
fill-segments-to(self.fill-paths, y.max)
}
if self.fill {
if self.at("fill-type", default: "axis") == "shape" {
fill-shape(self.fill-paths)
} else {
fill-segments-to(self.fill-paths,
calc.max(calc.min(y.max, 0), y.min))
}
}
}
/// Add data to a plot environment.
///
/// Note: You can use this for scatter plots by setting
/// the stroke style to `none`: `add(..., style: (stroke: none))`.
///
/// Must be called from the body of a `plot(..)` command.
///
/// - domain (domain): Domain of `data`, if `data` is a function. Has no effect
/// if `data` is not a function.
/// - hypograph (bool): Fill hypograph; uses the `hypograph` style key for
/// drawing
/// - epigraph (bool): Fill epigraph; uses the `epigraph` style key for
/// drawing
/// - fill (bool): Fill the shape of the plot
/// - fill-type (string): Fill type:
/// / `"axis"`: Fill the shape to y = 0
/// / `"shape"`: Fill the complete shape
/// - samples (int): Number of times the `data` function gets called for
/// sampling y-values. Only used if `data` is of type function. This parameter gets
/// passed onto `sample-fn`.
/// - sample-at (array): Array of x-values the function gets sampled at in addition
/// to the default sampling. This parameter gets passed to `sample-fn`.
/// - line (string, dictionary): Line type to use. The following types are
/// supported:
/// / `"raw"`: Plot raw data
/// / `"linear"`: Linearize data
/// / `"spline"`: Calculate a Catmull-Rom curve through all points
/// / `"vh"`: Move vertical and then horizontal
/// / `"hv"`: Move horizontal and then vertical
/// / `"hvh"`: Add a vertical step in the middle
///
/// If the value is a dictionary, the type must be
/// supplied via the `type` key. The following extra
/// attributes are supported:
/// / `"samples" <int>`: Samples of splines
/// / `"tension" <float>`: Tension of splines
/// / `"mid" <float>`: Mid-Point of hvh lines (0 to 1)
/// / `"epsilon" <float>`: Linearization slope epsilon for
/// use with `"linear"`, defaults to 0.
///
/// #example(```
/// let points(offset: 0) = ((0,0), (1,1), (2,0), (3,1), (4,0)).map(((x,y)) => {
/// (x,y + offset * 1.5)
/// })
/// plot.plot(size: (12, 3), axis-style: none, {
/// plot.add(points(offset: 5), line: (type: "hvh", mid: .1))
/// plot.add(points(offset: 4), line: "hvh")
/// plot.add(points(offset: 3), line: "hv")
/// plot.add(points(offset: 2), line: "vh")
/// plot.add(points(offset: 1), line: "spline")
/// plot.add(points(offset: 0), line: "linear")
/// })
/// ```, vertical: true)
///
/// - style (style): Style to use, can be used with a `palette` function
/// - axes (axes): Name of the axes to use for plotting. Reversing the axes
/// means rotating the plot by 90 degrees.
/// - mark (string): Mark symbol to place at each distinct value of the
/// graph. Uses the `mark` style key of `style` for drawing.
/// - mark-size (float): Mark size in cavas units
/// - data (array,function): Array of 2D data points (numeric) or a function
/// of the form `x => y`, where `x` is a value in `domain`
/// and `y` must be numeric or a 2D vector (for parametric functions).
/// #example(```
/// plot.plot(size: (2, 2), axis-style: none, {
/// // Using an array of points:
/// plot.add(((0,0), (calc.pi/2,1),
/// (1.5*calc.pi,-1), (2*calc.pi,0)))
/// // Sampling a function:
/// plot.add(domain: (0, 2*calc.pi), calc.sin)
/// })
/// ```)
/// - label (none,content): Legend label to show for this plot.
#let add(domain: auto,
hypograph: false,
epigraph: false,
fill: false,
fill-type: "axis",
style: (:),
mark: none,
mark-size: .2,
mark-style: (:),
samples: 50,
sample-at: (),
line: "raw",
axes: ("x", "y"),
label: none,
data
) = {
// If data is of type function, sample it
if type(data) == function {
data = sample.sample-fn(data, domain, samples, sample-at: sample-at)
}
// Transform data
let line-data = transform-lines(data, line)
// Get x-domain
let x-domain = (
calc.min(..line-data.map(t => t.at(0))),
calc.max(..line-data.map(t => t.at(0)))
)
// Get y-domain
let y-domain = if line-data != none {(
calc.min(..line-data.map(t => t.at(1))),
calc.max(..line-data.map(t => t.at(1)))
)}
((
type: "line",
label: label,
data: data, /* Raw data */
line-data: line-data, /* Transformed data */
axes: axes,
x-domain: x-domain,
y-domain: y-domain,
epigraph: epigraph,
hypograph: hypograph,
fill: fill,
fill-type: fill-type,
style: style,
mark: mark,
mark-size: mark-size,
mark-style: mark-style,
plot-prepare: _prepare,
plot-stroke: _stroke,
plot-fill: _fill,
plot-legend-preview: self => {
if self.fill or self.epigraph or self.hypograph {
draw.rect((0,0), (1,1), ..self.style)
} else {
draw.line((0,.5), (1,.5), ..self.style)
}
}
),)
}
/// Add horizontal lines at one or more y-values. Every lines start and end points
/// are at their axis bounds.
///
/// #example(```
/// plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
/// plot.add(domain: (0, 4*calc.pi), calc.sin)
/// // Add 3 horizontal lines
/// plot.add-hline(-.5, 0, .5)
/// })
/// ```)
///
/// - ..y (float): Y axis value(s) to add a line at
/// - min (auto,float): X axis minimum value or auto to take the axis minimum
/// - max (auto,float): X axis maximum value or auto to take the axis maximum
/// - axes (array): Name of the axes to use for plotting
/// - style (style): Style to use, can be used with a palette function
/// - label (none,content): Legend label to show for this plot.
#let add-hline(..y,
min: auto,
max: auto,
axes: ("x", "y"),
style: (:),
label: none,
) = {
assert(y.pos().len() >= 1,
message: "Specify at least one y value")
assert(y.named().len() == 0)
let prepare(self, ctx) = {
let (x-min, x-max) = (ctx.x.min, ctx.x.max)
let (y-min, y-max) = (ctx.y.min, ctx.y.max)
let x-min = if min == auto { x-min } else { min }
let x-max = if max == auto { x-max } else { max }
self.lines = self.y.filter(y => y >= y-min and y <= y-max)
.map(y => ((x-min, y), (x-max, y)))
return self
}
let stroke(self, ctx) = {
for (a, b) in self.lines {
draw.line(a, b, fill: none)
}
}
let x-min = if min == auto { none } else { min }
let x-max = if max == auto { none } else { max }
((
type: "hline",
label: label,
y: y.pos(),
x-domain: (x-min, x-max),
y-domain: (calc.min(..y.pos()), calc.max(..y.pos())),
axes: axes,
style: style,
plot-prepare: prepare,
plot-stroke: stroke,
),)
}
/// Add vertical lines at one or more x-values. Every lines start and end points
/// are at their axis bounds.
///
/// #example(```
/// plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
/// plot.add(domain: (0, 2*calc.pi), calc.sin)
/// // Add 3 vertical lines
/// plot.add-vline(calc.pi/2, calc.pi, 3*calc.pi/2)
/// })
/// ```)
///
/// - ..x (float): X axis values to add a line at
/// - min (auto,float): Y axis minimum value or auto to take the axis minimum
/// - max (auto,float): Y axis maximum value or auto to take the axis maximum
/// - axes (array): Name of the axes to use for plotting, note that not all
/// plot styles are able to display a custom axis!
/// - style (style): Style to use, can be used with a palette function
/// - label (none,content): Legend label to show for this plot.
#let add-vline(..x,
min: auto,
max: auto,
axes: ("x", "y"),
style: (:),
label: none,
) = {
assert(x.pos().len() >= 1,
message: "Specify at least one x value")
assert(x.named().len() == 0)
let prepare(self, ctx) = {
let (x-min, x-max) = (ctx.x.min, ctx.x.max)
let (y-min, y-max) = (ctx.y.min, ctx.y.max)
let y-min = if min == auto { y-min } else { min }
let y-max = if max == auto { y-max } else { max }
self.lines = self.x.filter(x => x >= x-min and x <= x-max)
.map(x => ((x, y-min), (x, y-max)))
return self
}
let stroke(self, ctx) = {
for (a, b) in self.lines {
draw.line(a, b, fill: none)
}
}
let y-min = if min == auto { none } else { min }
let y-max = if max == auto { none } else { max }
((
type: "vline",
label: label,
x: x.pos(),
x-domain: (calc.min(..x.pos()), calc.max(..x.pos())),
y-domain: (y-min, y-max),
axes: axes,
style: style,
plot-prepare: prepare,
plot-stroke: stroke
),)
}
/// Fill the area between two graphs. This behaves same as `add` but takes
/// a pair of data instead of a single data array/function.
/// The area between both function plots gets filled. For a more detailed
/// explanation of the arguments, see @@add().
///
/// This can be used to display an error-band of a function.
///
/// #example(```
/// plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
/// plot.add-fill-between(domain: (0, 2*calc.pi),
/// calc.sin, // First function/data
/// calc.cos) // Second function/data
/// })
/// ```)
///
/// - domain (domain): Domain of both `data-a` and `data-b`. The domain is used for
/// sampling functions only and has no effect on data arrays.
/// - samples (int): Number of times the `data-a` and `data-b` function gets called for
/// sampling y-values. Only used if `data-a` or `data-b` is of
/// type function.
/// - sample-at (array): Array of x-values the function(s) get sampled at in addition
/// to the default sampling.
/// - line (string, dictionary): Line type to use, see @@add().
/// - style (style): Style to use, can be used with a palette function.
/// - label (none,content): Legend label to show for this plot.
/// - axes (array): Name of the axes to use for plotting.
/// - data-a (array,function): Data of the first plot, see @@add().
/// - data-b (array,function): Data of the second plot, see @@add().
#let add-fill-between(data-a,
data-b,
domain: auto,
samples: 50,
sample-at: (),
line: "raw",
axes: ("x", "y"),
label: none,
style: (:)) = {
// If data is of type function, sample it
if type(data-a) == function {
data-a = sample.sample-fn(data-a, domain, samples, sample-at: sample-at)
}
if type(data-b) == function {
data-b = sample.sample-fn(data-b, domain, samples, sample-at: sample-at)
}
// Transform data
let line-a-data = transform-lines(data-a, line)
let line-b-data = transform-lines(data-b, line)
// Get x-domain
let x-domain = (
calc.min(..line-a-data.map(t => t.at(0)),
..line-b-data.map(t => t.at(0))),
calc.max(..line-a-data.map(t => t.at(0)),
..line-b-data.map(t => t.at(0)))
)
// Get y-domain
let y-domain = if line-a-data != none and line-b-data != none {(
calc.min(..line-a-data.map(t => t.at(1)),
..line-b-data.map(t => t.at(1))),
calc.max(..line-a-data.map(t => t.at(1)),
..line-b-data.map(t => t.at(1)))
)}
let prepare(self, ctx) = {
let (x, y) = (ctx.x, ctx.y)
// Generate stroke paths
self.stroke-paths = (
a: util.compute-stroke-paths(self.line-data.a, x, y),
b: util.compute-stroke-paths(self.line-data.b, x, y),
)
// Generate fill paths
self.fill-paths = util.compute-fill-paths(self.line-data.a + self.line-data.b.rev(), x, y)
return self
}
let stroke(self, ctx) = {
for p in self.stroke-paths.a {
draw.line(..p, fill: none)
}
for p in self.stroke-paths.b {
draw.line(..p, fill: none)
}
}
let fill(self, ctx) = {
fill-shape(self.fill-paths)
}
((
type: "fill-between",
label: label,
axes: axes,
line-data: (a: line-a-data, b: line-b-data),
x-domain: x-domain,
y-domain: y-domain,
style: style,
plot-prepare: prepare,
plot-stroke: stroke,
plot-fill: fill,
plot-legend-preview: self => {
draw.rect((0,0), (1,1), ..self.style)
}
),)
}
|
https://github.com/Tengs-Fan/Tengs-Penkwe | https://raw.githubusercontent.com/Tengs-Fan/Tengs-Penkwe/master/letter.typ | typst | #import "./template.typ": *
#show: layout
#set text(size: 12pt) //set global font size
#letterHeader(
myAddress: [1690 Western Parkway \ V6T 1V3, Vancouver, British Columbia],
recipientName: [Safe Software],
recipientAddress: [Vancouver, BC],
date: [#datetime.today().display()],
subject: "Subject: Job Application for C++ Software Developer Co-op"
)
Dear Hiring Manager,
I am drawn to Safe Software's commitment to unleashing the power of data through FME. The diverse applications of FME, including handling sensors, maps, building models, imagery, databases, social media, web services, and more, resonate with my academic and project experience, particularly in Remote Sensing and GIS.
As a Computer Science student at UBC, I am passionate about programming and have experience in C++, making me eager to contribute to the FME Desktop/Engine development group at Safe Software.
My specific experience includes:
- Spatial Data Processing & Analysis: My experience in processing and analyzing spatial data includes using GIS techniques and tools, This expertise aligns with Safe Software's focus on supporting spatial data and will allow me to contribute to the development of new data formats and capabilities within the FME platform.
- Back-end Development with C++: I have developed image processing software using C++ and implemented algorithms for efficient processing and analysis of Remote Sensing (RS) images.
- Front-end Development with C++ and Qt: My hands-on experience with C++ and my quick adaptability to new technologies will enable me to pick up Qt and contribute to the front-end development tasks.
- Build and Test Tools: I have been using Linux for five years, and I am familiar with Git, Makefile, and Docker, which align with the tools used at Safe Software.
- Databases: My projects have exposed me to the use and management of relational databases, including SQLite3, which will allow me to work with databases mentioned in the job description.
- Team Collaboration: My work on course projects such as UBCInsight Software Project showcases my ability to collaborate within a team, apply software engineering principles, and conduct iterative development and efficient project management.
Eager to contribute, learn, and make an impact, I thank you for considering my application. I look forward to discussing how my skills align with your needs.
Sincerely,
#letterSignature("/assets/signature.png")
#letterFooter()
|
|
https://github.com/Dr00gy/Typst-thesis-template-for-VSB | https://raw.githubusercontent.com/Dr00gy/Typst-thesis-template-for-VSB/main/thesis_template/misc.typ | typst | // Heading for the assignment
#let assignmentHeading = context(
heading(
level: 1,
outlined: false,
if text.lang == "cs" [Zadání kvalifikační práce] else [Thesis assignment]
)
)
#let headerChapters(body, headerHeadingPage: true) = {
let headerHeading(text) = {
align(center)[
#block(
width: 100%,
stroke: (bottom: 1pt + luma(120)),
inset: (bottom: 2.5pt)
)[
#emph(text)
]
]
}
set page(header: context {
let headingBefore = query(
selector(heading.where(level: 1)).before(here()),
).last()
let headingAfter = query(
selector(heading.where(level: 1)).after(here()),
).first()
// Checks if the heading on the next page is the same as on the current page
if headingAfter.location().page() == here().page() {
if headerHeadingPage {headerHeading(headingAfter.body)}
} else {
headerHeading(headingBefore.body)
}
})
body
}
|
|
https://github.com/mem-courses/linear-algebra | https://raw.githubusercontent.com/mem-courses/linear-algebra/main/homework/linear-algebra-quiz3.typ | typst | #import "../template.typ": *
#show: project.with(
title: "Linear Algebra Quiz #3",
authors: (
(name: "memset0", email: "<EMAIL>", phone: ""),
),
date: "December 18, 2023",
)
#note[2023-2024 学年秋冬学期周一第九节小测(汤数元班)试题回忆版.]
#let alpha = math.bold(math.alpha)
#let beta = math.bold(math.beta)
= T1
#prob[求基 $alpha_1,1/2alpha_2,1/3alpha_3$ 到基 $alpha_1+alpha_2,alpha_2+alpha_3,alpha_3+alpha_1$ 的过渡矩阵.]
= T2
#prob[在线性空间 $PP[x]_n$ 中,令 $f_i = (x - a_1)(x - a_2) dots.c (x-a_(i-1)) (x-a_(i+1)) dots.c (x-a_n) sp (i=1,2,dots.c,n)$,其中 $a_i$ 两两不同.证明 $seqn(f,n)$ 是线性空间的一组基.]
= T3
#prob[
在线性空间 $PP^n$ 中,向量组 $seqn(alpha,s)$ 可被 $seqn(beta,t)$ 线性表示,且 $seqn(alpha,s)$ 线性无关.求证 $s<=t$.
]
= T4
#prob[
设二阶对称矩阵构成 $PP^(2 times 2)$ 的一个子空间 $W$,给定:
$
bold(A)_1 = mat(1,-2;-2,1) quad
bold(A)_2 = mat(2,1;1,3) quad
bold(A)_3 = mat(-4,1;1,-5) quad
$
求证 $bold(A)_1,bold(A)_2,bold(A)_3$ 是 $W$ 的一组基.并对其正交化.
#warn[具体系数可能有误.]
]
= T5
#prob[在 $n$ 维线性空间中,$seqn(alpha,n-1)$ 是一组线性无关的向量组,且与向量 $beta_1,beta_2$ 正交.求证:$beta_1,beta_2$ 线性相关.] |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-11080.typ | typst | Apache License 2.0 | #let data = (
("KAITHI SIGN CANDRABINDU", "Mn", 0),
("KAITHI SIGN ANUSVARA", "Mn", 0),
("KAITHI SIGN VISARGA", "Mc", 0),
("KAITHI LETTER A", "Lo", 0),
("KAITHI LETTER AA", "Lo", 0),
("KAITHI LETTER I", "Lo", 0),
("KAITHI LETTER II", "Lo", 0),
("KAITHI LETTER U", "Lo", 0),
("KAITHI LETTER UU", "Lo", 0),
("KAITHI LETTER E", "Lo", 0),
("KAITHI LETTER AI", "Lo", 0),
("KAITHI LETTER O", "Lo", 0),
("KAITHI LETTER AU", "Lo", 0),
("KAITHI LETTER KA", "Lo", 0),
("KAITHI LETTER KHA", "Lo", 0),
("KAITHI LETTER GA", "Lo", 0),
("KAITHI LETTER GHA", "Lo", 0),
("KAITHI LETTER NGA", "Lo", 0),
("KAITHI LETTER CA", "Lo", 0),
("KAITHI LETTER CHA", "Lo", 0),
("KAITHI LETTER JA", "Lo", 0),
("KAITHI LETTER JHA", "Lo", 0),
("KAITHI LETTER NYA", "Lo", 0),
("KAITHI LETTER TTA", "Lo", 0),
("KAITHI LETTER TTHA", "Lo", 0),
("KAITHI LETTER DDA", "Lo", 0),
("KAITHI LETTER DDDHA", "Lo", 0),
("KAITHI LETTER DDHA", "Lo", 0),
("KAITHI LETTER RHA", "Lo", 0),
("KAITHI LETTER NNA", "Lo", 0),
("KAITHI LETTER TA", "Lo", 0),
("KAITHI LETTER THA", "Lo", 0),
("KAITHI LETTER DA", "Lo", 0),
("KAITHI LETTER DHA", "Lo", 0),
("KAITHI LETTER NA", "Lo", 0),
("KAITHI LETTER PA", "Lo", 0),
("KAITHI LETTER PHA", "Lo", 0),
("KAITHI LETTER BA", "Lo", 0),
("KAITHI LETTER BHA", "Lo", 0),
("KAITHI LETTER MA", "Lo", 0),
("KAITHI LETTER YA", "Lo", 0),
("KAITHI LETTER RA", "Lo", 0),
("KAITHI LETTER LA", "Lo", 0),
("KAITHI LETTER VA", "Lo", 0),
("KAITHI LETTER SHA", "Lo", 0),
("KAITHI LETTER SSA", "Lo", 0),
("KAITHI LETTER SA", "Lo", 0),
("KAITHI LETTER HA", "Lo", 0),
("KAITHI VOWEL SIGN AA", "Mc", 0),
("KAITHI VOWEL SIGN I", "Mc", 0),
("KAITHI VOWEL SIGN II", "Mc", 0),
("KAITHI VOWEL SIGN U", "Mn", 0),
("KAITHI VOWEL SIGN UU", "Mn", 0),
("KAITHI VOWEL SIGN E", "Mn", 0),
("KAITHI VOWEL SIGN AI", "Mn", 0),
("KAITHI VOWEL SIGN O", "Mc", 0),
("KAITHI VOWEL SIGN AU", "Mc", 0),
("KAITHI SIGN VIRAMA", "Mn", 9),
("KAITHI SIGN NUKTA", "Mn", 7),
("KAITHI ABBREVIATION SIGN", "Po", 0),
("KAITHI ENUMERATION SIGN", "Po", 0),
("KAITHI NUMBER SIGN", "Cf", 0),
("KAITHI SECTION MARK", "Po", 0),
("KAITHI DOUBLE SECTION MARK", "Po", 0),
("KAITHI DANDA", "Po", 0),
("KAITHI DOUBLE DANDA", "Po", 0),
("KAITHI VOWEL SIGN VOCALIC R", "Mn", 0),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
("KAITHI NUMBER SIGN ABOVE", "Cf", 0),
)
|
https://github.com/cwreed/cv | https://raw.githubusercontent.com/cwreed/cv/main/src/template.typ | typst | /* Packages */
#import "metadata.typ": *
#import "utils.typ": *
#import "@preview/fontawesome:0.2.0": *
#let accentColor = {
if type(choiceColor) == color {
colorName
} else {
colors.at(choiceColor)
}
}
#let cvHeader(align: left, hasPhoto: true, quote: str) = {
let makeHeaderInfo() = {
let personalInfoIcons = (
phone: fa-phone(),
email: fa-envelope(),
linkedin: fa-linkedin(),
homepage: fa-pager(),
github: fa-square-github(),
gitlab: fa-gitlab(),
orcid: fa-orcid(),
researchgate: fa-researchgate(),
location: fa-location-dot(),
googleScholar: fa-graduation-cap(),
extraInfo: "",
)
let n = 1
for (k, v) in personalInfo {
// A dirty trick to add linebreaks with "linebreak" as key in personalInfo
if k == "linebreak" {
n = 0
linebreak()
continue
}
if k.contains("custom") {
// example value (icon: fa-graduation-cap(), text: "PhD", link: "https://www.example.com")
let icon = v.at("icon", default: "")
let text = v.at("text", default: "")
let link_value = v.at("link", default: "")
box({
icon
h(5pt)
link(link_value)[#text]
})
} else if v != "" {
box({
// Adds icons
personalInfoIcons.at(k) + h(5pt)
// Adds hyperlinks
if k == "email" {
link("mailto:" + v)[#v]
} else if k == "linkedin" {
link("https://www.linkedin.com/in/" + v)[#v]
} else if k == "github" {
link("https://github.com/" + v)[#v]
} else if k == "gitlab" {
link("https://gitlab.com/" + v)[#v]
} else if k == "homepage" {
link("https://" + v)[#v]
} else if k == "orcid" {
link("https://orcid.org/" + v)[#v]
} else if k == "researchgate" {
link("https://www.researchgate.net/profile/" + v)[#v]
} else {
v
}
})
}
// Adds hBar
if n != personalInfo.len() {
hBar()
}
n = n + 1
}
}
let makeHeaderNameSection() = table(
columns: 1fr,
inset: 0pt,
stroke: none,
row-gutter: 6mm,
[#headerFirstNameStyle(firstName) #h(5pt) #headerLastNameStyle(lastName)],
[#headerInfoStyle(makeHeaderInfo(), accentColor)],
[#headerQuoteStyle(quote, accentColor)],
)
let makeHeader(leftComp, rightComp, columns, align) = table(
columns: columns,
inset: 0pt,
stroke: none,
column-gutter: 15pt,
align: align + horizon,
{ leftComp },
{ rightComp },
)
show link: set text(fill: accentColor)
makeHeader(makeHeaderNameSection(), v(2.75cm), (auto, 0%), align)
}
#let cvSection(title, highlighted: true, letters: 3) = {
let highlightText = title.slice(0, letters)
let normalText = title.slice(letters)
v(beforeSectionSkip)
sectionTitleStyle(title, color: black)
h(2pt)
box(width: 1fr, line(stroke: 0.9pt, length: 100%))
}
#let cvEntry(
title: "Title",
institution: "Society",
date: "Date",
location: "Location",
description: "",
logo: "",
tags: (),
) = {
let ifSocietyFirst(condition, field1, field2) = {
return if condition { field1 } else { field2 }
}
let ifLogo(path, ifTrue, ifFalse) = {
return if varDisplayLogo {
if path == "" { ifFalse } else { ifTrue }
} else { ifFalse }
}
let setLogoLength(path) = {
return if path == "" { 0% } else { 4% }
}
let setLogoContent(path) = {
return if logo == "" [] else { image(path, width: 100%) }
}
v(beforeEntrySkip)
table(
columns: (ifLogo(logo, 4%, 0%), 1fr),
inset: 0pt,
stroke: none,
align: horizon,
column-gutter: ifLogo(logo, 4pt, 0pt),
setLogoContent(logo),
table(
columns: (1fr, auto),
inset: 0pt,
stroke: none,
row-gutter: 6pt,
align: auto,
{ entryA1Style(ifSocietyFirst(varEntrySocietyFirst, institution, title)) },
{
entryA2Style(ifSocietyFirst(varEntrySocietyFirst, location, date), accentColor)
},
{
entryB1Style(ifSocietyFirst(varEntrySocietyFirst, title, institution), accentColor)
},
{ entryB2Style(ifSocietyFirst(varEntrySocietyFirst, date, location)) },
),
)
entryDescriptionStyle(description)
entryTagListStyle(tags)
}
#let cvSkill(type: "Type", info: "Info") = {
table(
columns: (13%, 1fr),
inset: 0pt,
column-gutter: 10pt,
stroke: none,
align: (right, left),
skillTypeStyle(type),
skillInfoStyle(info),
)
v(-6pt)
}
#let cvHonor(date: "1990", title: "Title", issuer: "", url: "", location: "") = {
table(
columns: (auto, 1fr),
inset: 0pt,
column-gutter: 10pt,
row-gutter: 5pt,
align: horizon,
stroke: none,
honorDateStyle(date),
if issuer == "" {
honorTitleStyle(title)
} else if url != "" {
[
#honorTitleStyle(link(url)[#title]), #honorIssuerStyle(issuer)
]
} else {
[
#honorTitleStyle(title), #honorIssuerStyle(issuer)
]
},
honorLocationStyle(location, accentColor),
)
v(-6pt)
}
#let cvPublication(bibPath: "", keyList: list(), refStyle: "apa", refFull: true) = {
show bibliography: it => publicationStyle(it, firstName, lastName)
bibliography(bibPath, title: none, style: refStyle, full: refFull)
}
#let cvFooter(pageNumbers: bool) = {
let today = datetime.today(offset: auto)
let left = [#firstName #lastName]
if pageNumbers {
left = left + [, page #counter(page).display("1/1", both: true)]
}
table(
columns: (1fr, auto),
inset: 0pt,
stroke: none,
footerStyle(left),
footerStyle([Compiled #today.display()]),
)
}
#let letterHeader(
myAddress: "Your Address Here",
recipientName: "<NAME> Here",
recipientAddress: "Company Address Here",
date: "Today's Date",
subject: "Subject: Hey!",
) = {
letterHeaderNameStyle(firstName + " " + lastName, accentColor)
v(1pt)
letterHeaderAddressStyle(myAddress)
v(1pt)
align(right, letterHeaderNameStyle(recipientName))
v(1pt)
align(right, letterHeaderAddressStyle(recipientAddress))
v(1pt)
letterDateStyle(date)
v(1pt)
letterSubjectStyle(subject, accentColor)
linebreak(); linebreak()
}
#let letterSignature(path) = {
linebreak()
place(right, dx: -5%, dy: 0%, image(path, width: 25%))
}
#let letterFooter() = {
place(bottom, table(
columns: (1fr, auto),
inset: 0pt,
stroke: none,
footerStyle([#firstName #lastName]),
footerStyle(languageSwitch(letterFooterInternational)),
))
}
#let layout(doc) = {
set text(font: fontList, weight: "regular", size: 9pt)
set align(left)
set page(
paper: "a4",
margin: (left: 1.4cm, right: 1.4cm, top: .8cm, bottom: .8cm),
)
show link: set text(fill: colors.sky)
doc
} |
|
https://github.com/lyzynec/orr-go-brr | https://raw.githubusercontent.com/lyzynec/orr-go-brr/main/12/main.typ | typst | #import "../lib.typ": *
#knowledge[
#question(name: [Explain how the peak in the sensitivity and complementary
sensitivity functions relate to gain and phase margins.])[
$
alpha_min = 1 / norm(S(s))_oo
$
$
"GM" &= 1/(1-alpha_1), &"PM" &= 2 arcsin(alpha_2/2)\
"GM" &>= M_S / (M_S -1), &"PM" &>= 2 arcsin(1/(2 M_S))
$
]
#question(name: [Explain the concept of a _bandwidth_. Shall we define it
using the sensitivity or the complementary sensitivity functions?])[
- Using $T$, bandwidth is the frequency from which the gain starts
rolling off.
- Using $S$, bandwidth is the frequency up to which the gain is
small.
Usually, the difference is small, but for some cases it could be
significant.
]
#question(name: [Give the two "waterbed effect" integral formulas. You do
not have to remember the formulas exactly but at least the essence.])[
Waterbed effect states that one can not have small gain for all
frequencies, if there is unstable pole involved.
]
#question(name: [Give the SISO version of interpolation conditions of
internal stability. Namely, assuming that the transfer function of the
system vanishes at $z$ in the right half plane of the complex plane, it must
hold that $S(z) = 1$. Similarly, for an unstable pole p of the system, it
must hold that $T(p) = 1$.])[
$S(z) = 1$ and $T(p) = 1$
]
#question(name: [Give the lower bound on the peaks in the weighted
sensitivity function in presence of poles and/or zeros in the right half
plane.])[
$
norm(S)_oo > c\
norm(T)_oo > c\
c = (|z + p|)/(|z - p|)
$
]
#question(name: [How does the time delay in the system affects the
achievable bandwidth?])[
As ideal delay transfer function is
$
T(s) = e^(- theta s)
$
its sensitivity function would be
$
S(s) = 1 - e^(- theta s) approx theta s
$
As such gain 1 would be achieved at $omega_c = 1/theta$
$
omega_c < 1/theta
$
]
#question(name: [How does the presence of disturbance affect the achievable
bandwidth?])[
$
omega_B > omega_d
$
where
$
|G_d (j omega_d)| = 1
$
]
#question(name: [What conditions on system transfer function(s) are imposed
by the saturation of actuators? More accurately, under which conditions is
it guaranteed that the actuators do not saturate?])[
Actuators do not saturate if
$
|G^(-1) (j omega) G_d (j omega)| < 1, forall omega
$
]
#question(name: [Explain the concept of directionality in MIMO systems.])[]
#question(name: [Explain the condition number of the matrix of transfer
functions. How can it be computed? Perhaps only approximately.])[
$
gamma(G) = (overline(sigma)(G))/(underline(sigma)(G))
$
System is ill--conditioned for $gamma(G) > 10$.
Depends on scaling.
$
gamma^* (G) = min_(D_1, D_2) gamma(D_1 G D_2)
$
It can be difficult to compute.
Good approximation comes from Relative Gain Array (RGA)
$
Lambda(G) = G circle.small (G^(-1))^T
$
$circle.small$ is called Hadamard product, in Matlab it is denoted `.*`.
Sum of absolute values of elements is close to $gamma^*$.
]
#question(name: [How does the presence of input multiplicative uncertainty
affect the achievable behaviour of the closed--loop transfer functions?])[]
]
#skills[
#question(name: [Analyze the provided linear model of dynamics of the system
to be controlled in order to learn the limitations on achievable performance
such as bandwidth, resonant peak, steady-state regulation error etc.])[]
]
|
|
https://github.com/MrToWy/Bachelorarbeit | https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Code/facultyPrisma.typ | typst | ```prisma
model Faculty {
id Int @id @default(autoincrement())
name TranslationKey? @relation(fields: [nameId], references: [id])
nameId Int?
...
``` |
|
https://github.com/Isaac-Duan/ousr_typst_templates | https://raw.githubusercontent.com/Isaac-Duan/ousr_typst_templates/main/README.md | markdown | MIT License | # ousr_typst_templates
各种常用文档排版模板
|
https://github.com/Mufanc/hnuslides-typst | https://raw.githubusercontent.com/Mufanc/hnuslides-typst/master/utils/background.typ | typst | #import "/configs.typ"
#let bg(content) = context {
let (x, y) = here().position()
place(
center,
pad(top: -y, box(width: configs.slide.width, height: configs.slide.height, content))
)
}
#let bgimage(src) = context {
bg(image(width: configs.slide.width, height: configs.slide.height, src))
}
|
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/02-concepts/pipeline.typ | typst | Other | #import "/lib/draw.typ": *
#import "/template/theme.typ": theme, choose
#import "/lib/glossary.typ": tr
#let start = (0, 0)
#let end = (1000, 1100)
#let graph = with-unit((ux, uy) => {
// mesh(start, end, (100, 100), stroke: 1 * ux + gray)
let bubble-stroke = 3 * ux + theme.main
let bubble-stroke-dashed = stroke(
paint: theme.main,
thickness: 3 * ux,
dash: "dashed",
)
let bubble = (body, dash: false) => block(
inset: 20 * ux,
spacing: 0pt,
radius: 40 * ux,
stroke: if dash { bubble-stroke-dashed } else { bubble-stroke },
fill: choose(rgb("ededed"), rgb("343434")),
align(center, text(size: 50 * ux, body)),
)
let arrow = arrow.with(stroke: bubble-stroke, head-scale: 4)
txt(["Hello world"], (300, 1000), size: 50 * ux, anchor: "cb")
txt(align(center)[
13pt 粗意大利体\
Noto Serif\
小型大写字母
], (740, 900),size: 50 * ux, anchor: "cb")
txt(bubble[
Unicode\ 处理
], (300, 720), anchor: "cb")
arrow((300, 980), (300, 890))
txt(bubble[
字体管理
], (740, 750), anchor: "cb")
arrow((740, 880), (740, 830))
txt(bubble[
文本#tr[shaping]
], (500, 600), anchor: "cb")
arrow((300, 720), (470, 678))
arrow((740, 750), (540, 678))
txt(bubble(dash: true)[
语言处理
], (500, 450), anchor: "cb")
arrow((500, 600), (500, 525))
txt(bubble(dash: true)[
断行
], (500, 320), anchor: "cb")
arrow((500, 450), (500, 400))
txt(bubble(dash: true)[
连字号
], (700, 410), anchor: "lc")
arrow((570, 370), (700, 410))
arrow((700, 410), (570, 370))
txt(bubble(dash: true)[
对齐
], (700, 300), anchor: "lc")
arrow((570, 350), (700, 300))
arrow((700, 300), (570, 350))
txt(bubble[
渲染
], (500, 190), anchor: "cb")
arrow((500, 320), (500, 265))
txt(bubble(dash: true)[
#tr[hinting]\ 处理
], (300, 290), anchor: "rc")
arrow((430, 240), (300, 260))
arrow((300, 260), (430, 240))
txt(bubble(dash: true)[
#tr[rasterization]
], (300, 150), anchor: "rc")
arrow((432, 210), (300, 150))
arrow((300, 150), (432, 210))
txt(text(
font: ("Noto Serif",),
style: "italic",
weight: "bold",
features: ("smcp",),
)[
Hello world
], (500, 70), size: 50 * ux, anchor: "ct")
arrow((500, 190), (500, 120))
})
#canvas(end, start: start, width: 70%, graph)
|
https://github.com/pank-su/report_3 | https://raw.githubusercontent.com/pank-su/report_3/master/templates/toc.typ | typst | #import "escd.typ": outlineFrame
#let toc() = {
show heading: set text(size: 14pt)
show heading: set align(center)
//counter(page).update(3)
set page(background:
outlineFrame(),
margin: (left: 30mm, right: 15mm, top: 20mm, bottom: 25mm),
paper: "a4"
)
set text(size: 14pt, font: "Times New Roman")
outline(depth: 3, indent: true, title: align(center)[#upper("Содержание")])
} |
|
https://github.com/SillyFreak/typst-prequery | https://raw.githubusercontent.com/SillyFreak/typst-prequery/main/docs/template.typ | typst | MIT License | // adapted from https://github.com/Mc-Zen/tidy/blob/98612b847da41ffb0d1dc26fa250df5c17d50054/docs/template.typ
// licensed under the MIT license
#import "@preview/tidy:0.3.0"
#import "@preview/codly:1.0.0"
#import "@preview/crudo:0.1.1"
#import "man-style.typ"
// The manual 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 manual(
title: "",
subtitle: "",
authors: (),
abstract: [],
url: none,
version: none,
date: none,
) = body => {
// Set the document's basic properties.
set document(author: authors, title: title, date: date)
set page(numbering: "1", number-align: center)
set text(font: "Libertinus Serif", lang: "en")
show heading.where(level: 1): it => block(smallcaps(it), below: 1em)
// set heading(numbering: (..args) => if args.pos().len() == 1 { numbering("I", ..args) })
set heading(numbering: "I.a")
show list: pad.with(x: 5%)
// show link: set text(fill: purple.darken(30%))
show link: set text(fill: rgb("#1e8f6f"))
show link: underline
v(4em)
// Title row.
align(center, {
block(text(weight: 700, 1.75em, title))
block(text(1.0em, subtitle))
v(4em, weak: true)
if date == none [
v#version
] else [
v#version
#h(1.2cm)
#date.display("[month repr:long] [day], [year]")
]
block(link(url))
v(1.5em, weak: true)
})
// Author information.
pad(
top: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center, strong(author))),
),
)
v(3cm, weak: true)
// Abstract.
pad(
x: 3.8em,
top: 1em,
bottom: 1.1em,
align(center)[
#heading(
outlined: false,
numbering: none,
text(0.85em, smallcaps[Abstract]),
)
#abstract
],
)
set par(justify: true)
show raw.where(block: true): set par(justify: false)
v(10em)
// Outline.
pad(x: 10%, outline(depth: 1))
pagebreak()
// Main body.
show: codly.codly-init
show raw.where(block: true): set text(size: .9em)
show raw.where(block: true): pad.with(x: 4%)
body
}
#let module(
code,
name: none,
label-prefix: auto,
scope: (:),
preamble: "",
..args,
) = {
let (name, label-prefix) = (name, label-prefix)
if label-prefix == auto and name != none {
label-prefix = name + "."
} else if type(label-prefix) == str {
label-prefix += "."
} else {
assert(label-prefix == none or name == none)
label-prefix = ""
}
if name != none {
name = raw(name)
}
let module = tidy.parse-module(
code,
name: name,
label-prefix: label-prefix,
scope: scope,
preamble: preamble,
)
tidy.show-module(
module,
show-module-name: name != none,
sort-functions: none,
style: man-style,
..args,
)
}
#let ref-fn(name) = link(label(name), man-style.mono(name))
#let file-code(filename, code) = pad(x: 4%, block(
width: 100%,
fill: rgb("#239DAE").lighten(80%),
inset: 1pt,
stroke: rgb("#239DAE") + 1pt,
radius: 3pt,
{
block(align(right, text(raw(filename))), width: 100%, inset: 5pt)
v(1pt, weak: true)
move(dx: -1pt, line(length: 100% + 2pt, stroke: 1pt + rgb("#239DAE")))
v(1pt, weak: true)
pad(x: -4.3%, code)
}
))
#let preview-block(body, ..args) = {
show: figure
man-style.preview-block(
radius: man-style.preview-radius * 3,
..args,
{
set heading(numbering: none, outlined: false)
set text(size: .8em)
show: box.with(
width: 80%,
inset: 20pt,
)
show: align.with(left)
block(breakable: false, body)
}
)
}
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/scripting/tips.md | markdown | MIT License | # Tips
There are lots of elements in Typst scripting that are not obvious, but important. All the book is designated to show them, but some of them
## Equality
Equality doesn't mean objects are really the same, like in many other objects:
```typ
#let a = 7
#let b = 7.0
#(a == b)
#(type(a) == type(b))
```
That may be less obvious for dictionaries. In dictionaries **the order may matter**, so equality doesn't mean they behave exactly the same way:
```typ
#let a = (x: 1, y: 2)
#let b = (y: 2, x: 1)
#(a == b)
#(a.pairs() == b.pairs())
```
## Check key is in dictionary
Use the keyword `in`, like in `Python`:
```typ
#let dict = (a: 1, b: 2)
#("a" in dict)
// gives the same as
#(dict.keys().contains("a"))
```
Note it works for lists too:
```typ
#("a" in ("b", "c", "a"))
#(("b", "c", "a").contains("a"))
``` |
https://github.com/ivaquero/cetz-control | https://raw.githubusercontent.com/ivaquero/cetz-control/main/README.md | markdown | # CeTZ-Control
Draw Control Block using [fletcher](https://github.com/Jollywatt/typst-fletcher) and [CeTZ](https://github.com/cetz-package/cetz).
## Usage
### Clone Official Repository
To compile, please refer to the guide on [typst-packages](https://github.com/typst/packages) and clone this repository in the following path:
- Linux:
- `$XDG_DATA_HOME/typst`
- `~/.local/share/typst`
- macOS:`~/Library/Application Support/typst`
- Windows:`%APPDATA%/typst`
### Import the Template
Clone the [cetz-control](https://github.com/ivaquero/cetz-control) repository in the above path, and then import it in the document
```typst
#import "@local/cetz-control:0.1.0": *
```
|
|
https://github.com/SnO2WMaN/incompleteness.txt | https://raw.githubusercontent.com/SnO2WMaN/incompleteness.txt/main/README.md | markdown | Creative Commons Zero v1.0 Universal | # [Incompleteness.txt](https://sno2wman.github.io/incompleteness.txt/main.pdf)
## Description
不完全性定理についての様々な話題についてのメモ書きです.
### Sections
現在企んでいる章としては以下のものがあります.
- 可証性述語の構成まで正確に記述したGödelの不完全性定理の証明
- Löbの定理
- Robinson算術についての第2不完全性定理
- Boolosの不完全性定理
- 証明可能性論理
- Chaitinの不完全性定理
- 抜き打ちテストのパラドクスの形式化
- Grzegorczykの連結の理論
最新のPDFをいつでも[ここ](https://sno2wman.github.io/incompleteness.txt/main.pdf)から閲覧することが出来ます.
### Technical Details
この文書は[Typst](https://typst.app/)という組版システムで書かれています.
またリポジトリに更新が入る度にGitHub Actions上で文書がコンパイルされ,生成されたPDFファイルはGitHub Pagesにデプロイされます.そのためコンパイルに失敗していなければ,常に最新の文書が閲覧可能になっているはずです.
## Status
[](https://github.com/SnO2WMaN/incompleteness.txt/actions/workflows/gh-pages.yml)
## LICENSE
[](https://github.com/SnO2WMaN/incompleteness.txt/blob/main/LICENSE)
|
https://github.com/0x6e66/hbrs-typst | https://raw.githubusercontent.com/0x6e66/hbrs-typst/main/ads/acronyms.typ | typst | // Dictionary with acronyms
#let acronyms = (
API: "Application programmable interface",
DLR: "Deutsches Zentrum für Luft- und Raumfahrt",
IOCCC: [#[*I*]nternational #[*O*]bfuscated #[*C*] #[*C*]ode #[*C*]ontest],
)
|
|
https://github.com/orkhasnat/resume | https://raw.githubusercontent.com/orkhasnat/resume/master/modern-big/resume.typ | typst | #import "resume-lib.typ": *
#show: resume.with(
author: (
firstname: "Tasnimul",
lastname: "Hasnat",
email: "<EMAIL>",
phone: "+880-1731969827",
github: "orkhasnat",
linkedin: "tasnimul-hasnat-37515025a",
),
)
= About Me
//I'm a final semester undergraduate student with a keen interest in open-source projects. I actively seek out opportunities to learn and grow, specially within collaborative team environments where I can contribute to technological innovations. Adept at bug hunting and vulnerability detection, I excel at performing under tight deadlines and pressure.
I'm a recent graduate with a passion for technology and a strong interest in open-source development. I flourish in collaborative environments, actively seeking opportunities to learn and grow while excelling under pressure and tight deadlines. Eager to apply my skills and enthusiasm to contribute meaningfully to innovative projects aimed at the betterment of society.
= Education
#resume-entry(
title: "Islamic University of Technology",
location: "B.Sc in Computer Science & Engineering",
date: "Jan 2020 - Present",
description: "CGPA: "+text(fill:color-darkgray)[3.77]+" out of 4.00" // | Position: "+text(fill:color-darkgray)[19#super("th")]
)
#resume-entry(
title: "Dhaka Residential Model College",
location: "Higher Secondary Certificate",
date: "2017 - 2019",
description: "GPA: "+text(fill:color-darkgray)[5.00]+" out of 5.00"
)
#resume-entry(
title: "Dhaka Residential Model College",
location: "Secondary School Certificate",
date: "2015 - 2017",
description: "GPA: "+text(fill:color-darkgray)[5.00]+" out of 5.00"
)
= Research Experience
#resume-entry(
title: "Binary Function Clone Detection Using MBA Simplification",
location: "Ongoing",
date: "",
description:[
- Proposed a novel approach to binary function clone detection utilizing MBA (Mathematical Boolean Arithmetic) simplification.
- Trying to employ dynamic symbolic execution to coalesce assembly instructions into mathematical expressions.
- Conducting benchmark study against other methods of binary clone detection to evaluate the performance of the proposed model.
]
)
= Work Experience
#resume-entry(
title: "Beetles Cyber Security Ltd.",
location: "PenTest Intern",
date: "",
description:[
Became familiarized with vulnerability assessment and malware development.
]
)
= Projects
#resume-project(
title: "Abaash",
location: github-link("orkhasnat/Abaash"),
stack: "EJS, ExpressJs, MariaDB, Bulma"
)
#resume-item[
A web-based platform that simplifies the process of finding and renting flats for non-residential IUT students. It offers a user-friendly interface for flat owners and tenants, while providing students with a one-stop solution for accommodation and dining needs, including the management of cafeteria coupons.
]
#resume-project(
title: "Broke_No_More",
location: github-link("orkhasnat/Broke_No_More"),
stack: "Python, Keras, Pandas"
)
#resume-item[
Developed a deep learning model to forecast stock price movements in the Dhaka Stock Exchange, enhancing investment decision-making with accurate predictions. Employed a comprehensive methodology, encompassing data acquisition, pre-processing techniques, and proposed a RNN-LSTM forecasting model.
]
#resume-project(
title: "Fox's Tale",
location: github-link("orkhasnat/Foxs-Tale"),
stack: "C++, SFML"
)
#resume-item[
A modern tribute to the classic Rapid Roll game, created using the SFML library. It adds new features such as updated graphics, sound effects, obstacles, power-ups, and achievements to the original game. Nostalgic fan or a new player, it provides an engaging gaming experience that tests your reflexes, agility, and strategic thinking.
]
#resume-project(
title: "Outbreak",
location: github-link("orkhasnat/Outbreak"),
stack: "C++, SFML"
)
#resume-item[
Outbreak is a viral simulator developed in C++ and SFML. It models the spread of viruses based on parameters such as transmission rate, mortality rate, and incubation period. Users can manipulate these parameters to see how they affect the spread of the virus.
]
#pagebreak()
#resume-project(
title: "Sanctuary",
location: github-link("orkhasnat/Sanctuary"),
stack: "Java, JavaFX, FXML, MariaDB"
)
#resume-item[
A user-friendly application built with JavaFX, designed to simplify the process of finding and renting flats for IUT students. It offers students the ability to find flats based on their preferences, and allows flat owners to easily manage their properties and tenants.
]
#resume-project(
title: "ISC-BD",
location: github-link("orkhasnat/ISC-BD"),
stack: "Astro, TypeScript, Tailwind"
)
#resume-item[
// #set text(hyphenate: false)
Developed a comprehensive full-stack portfolio website for a non-profit NGO. Managed the entire development lifecycle, from initial conceptualization to deployment.
]
= Skills
#resume-skill-item("Programming Languages", ("C","C++", "Java", "Go", "Python", "JavaScript","SQL","x86 Assembly"))
#resume-skill-item("Libraries & Frameworks", ("Astro","React","Tailwind","SFML","ExpressJS","Pandas","Keras"))
#resume-skill-item("Other Tools", ("Git","Bash","Linux","Docker","Excel","Burp Suite","UML","LaTeX"))
#resume-skill-item("Database",("Oracle","MySQL","MariaDB"))
= Co-Curriculars
#v(padf*4)
#resume-cocurr[
- Member of #link("https://ctftime.org/team/175924")[_IUT Genesis_], team ranked #text(weight:"bold")[1#super("st")] in #link("https://ctftime.org/stats/2023/BD")[_CTFtime_] in Bangladesh (2023).
- Organizer and Problem Setter of IUT 11#super("th") National ICT Fest 2024.
- Problem Setter at KnightCTF 2023.
- Organizer and Problem Setter of Intra IUT Coderush Competition 2023.
- Volunteer at Intra IUT Hackathon Competition 2023.
- Instructor at IUT CTF Club.
- Participated in various national and international CTF (Capture the Flag) competitions since 2022.
]
= Achievements
#v(padf*4)
#resume-achievement[
#let t = text.with(weight:"black")
- #t[BUET CSE Fest CTF 2023]
- *Champion* among 100+ teams.
- #t[DU Cefalo ITVerse CTF 2023]
- *4#super[th]* among 60+ teams.
- #t[RITSEC International CTF 2023]
- *7#super[th]* among 710+ _international_ teams.
- #t[SUST SWE Technovent CTF 2023]
- *6#super[th]* among 40+ teams.
- #t[RIOT Flaghunt CTF 2022]
- *8#super[th]* among 80+ teams.
- #t[Awarded IUT-OIC Partial Scholarship]
- Ranked *195#super[th]* amongst 4200+ participants.
- Scholarship awarded for 3 Years equivalent to *\$13500*.
]
// #resume-achievement2[
// BUET CSE Fest CTF 2023][
// *Champion* among 100+ teams.]
// #resume-achievement2[DU Cefalo ITVerse CTF 2023][*4#super[th]* among 60+ teams.]
// #resume-achievement2[RITSEC International CTF 2023][*7#super[th]* among 710+ _international_ teams.]
// #resume-achievement2[SUST SWE Technovent CTF 2023][*6#super[th]* among 40+ teams.]
// #resume-achievement2[RIOT Flaghunt CTF 2022][*8#super[th]* among 80+ teams.]
// #resume-achievement2[Awarded IUT-OIC Partial Scholarship][
// // Ranked *195#super[th]* amongst 4200+ participants. \
// Scholarship awarded for 3 Years equivalent to *\$13500*.]
= Reference
// #resume-ref-iut("Dr. <NAME>","Assistant Professor","<EMAIL>")
// #resume-ref-iut("<NAME>","Lecturer","<EMAIL>")
#resume-ref("Dr. <NAME>","Assistant Professor",[Computer Science and Engineering Department\ Islamic University and Technology],"+8801618054411","<EMAIL>")
#resume-ref("<NAME>","Lecturer",[Computer Science and Engineering Department\ Islamic University and Technology],"+8801838929161","<EMAIL>")
|
|
https://github.com/mst2k/HSOS-PTP-Typst-Template | https://raw.githubusercontent.com/mst2k/HSOS-PTP-Typst-Template/main/templates/acronyms.typ | typst | // Acrostiche package for Typst
// Author: Grizzly
#let acros = state("acronyms",none)
#let init-acronyms(acronyms) = {
acros.update(acronyms)
}
#let reset-acronym(term) = {
// Reset a specific acronym. It will be expanded on next use.
state("acronym-state-" + term, false).update(false)
}
#let reset-all-acronyms() = {
// Reset all acronyms. They will all be expanded on the next use.
state("acronyms",none).display(acronyms=>
for acr in acronyms.keys() {
state("acronym-state-" + acr, false).update(false)
})
}
#let display-def(plural: false, acr) = {
//
if plural{
state("acronyms",none).display(acronyms=>{
if acr in acronyms{
let defs = acronyms.at(acr)
if type(defs) == "string"{ // If user forgot the trailing comma the type is string
defs
}else if type(defs)== "array"{
if acronyms.at(acr).len() == 0{panic("No definitions found for acronym "+acr+". Make sure it is defined in the dictionary passed to #init-acronyms(dict)")
}else if acronyms.at(acr).len() == 1{
acronyms.at(acr).at(0)+"s"
}else{
acronyms.at(acr).at(1)
}
}else{
panic("Definitions should be arrays of one or two strings. Definition of "+acr+ " is: "+type(defs))
}
}else{
panic(acr+" is not a key in the acronyms dictionary.")
}
})
}else{
state("acronyms",none).display(acronyms=>{
if acr in acronyms{
let defs = acronyms.at(acr)
if type(defs) == "string"{ // If user forgot the trailing comma the type is string
defs
}else if type(defs)== "array"{
if acronyms.at(acr).len() == 0{panic("No definitions found for acronym "+acr+". Make sure it is defined in the dictionary passed to #init-acronyms(dict)")
}else{
acronyms.at(acr).at(0)
}
}else{
panic("Definitions should be arrays of one or two strings. Definition of "+acr+ " is: "+type(defs))
}
}else{
panic(acr+" is not a key in the acronyms dictionary.")
}
})
}
}
#let acr(acr) = {
// Display an acronym in the singular form. Expands it if used for the first time.
// Generate the key associated with this acronym
let state-key = "acronym-state-" + acr
// Create a state to keep track of the expansion of this acronym
state(state-key,false).display(seen => {if seen{acr}else{[#display-def(plural: false, acr) (#acr)]}})
state(state-key,false).update(true)
}
#let acrpl(acr) = {
// Display an acronym in the plural form. Expands it if used for the first time.
// Generate the key associated with this acronym
let state-key = "acronym-state-" + acr
// Create a state to keep track of the expansion of this acronym
state(state-key,false).display(seen => {if seen{acr+"s"}else{[#display-def(plural: true, acr) (#acr\s)]}})
state(state-key,false).update(true)
}
#let print-index(level: 1, outlined: false, sorted:"", title:"Acronyms Index", delimiter:":", numbering: none) = {
//Print an index of all the acronyms and their definitions.
// Args:
// level: level of the heading. Default to 1.
// outlined: make the index section outlined. Default to false
// sorted: define if and how to sort the acronyms: "up" for alphabetical order, "down" for reverse alphabetical order, "" for no sort (print in the order they are defined). If anything else, sort as "up". Default to ""
// title: set the title of the heading. Default to "Acronyms Index". Passing an empty string will result in removing the heading.
// delimiter: String to place after the acronym in the list. Defaults to ":"
// numbering: decide numbering of the header
// assert on input values to avoid cryptic error messages
assert(sorted in ("","up","down"), message:"Sorted must be a string either \"\", \"up\" or \"down\"")
if title != ""{
heading(level: level, outlined: outlined, numbering: numbering)[#title]
}
state("acronyms",none).display(acronyms=>{
// Build acronym list
let acr-list = acronyms.keys()
// order list depending on the sorted argument
if sorted!="down"{
acr-list = acr-list.sorted()
}else{
acr-list = acr-list.sorted().rev()
}
set block(above: 3em, below: 14pt)
// print the acronyms
for acr in acr-list{
table(
columns: (20%,80%),
stroke:none,
inset: 0pt,
[*#acr#delimiter*], [#acronyms.at(acr).at(0)\ ]
)
}
})
}
|
|
https://github.com/nafkhanzam/typst-common | https://raw.githubusercontent.com/nafkhanzam/typst-common/main/src/touying-themes/touying.typ | typst | #import "@preview/touying:0.5.3": *
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10FB0.typ | typst | Apache License 2.0 | #let data = (
("CHORASMIAN LETTER ALEPH", "Lo", 0),
("CHORASMIAN LETTER SMALL ALEPH", "Lo", 0),
("CHORASMIAN LETTER BETH", "Lo", 0),
("CHORASMIAN LETTER GIMEL", "Lo", 0),
("CHORASMIAN LETTER DALETH", "Lo", 0),
("CHORASMIAN LETTER HE", "Lo", 0),
("CHORASMIAN LETTER WAW", "Lo", 0),
("CHORASMIAN LETTER CURLED WAW", "Lo", 0),
("CHORASMIAN LETTER ZAYIN", "Lo", 0),
("CHORASMIAN LETTER HETH", "Lo", 0),
("CHORASMIAN LETTER YODH", "Lo", 0),
("CHORASMIAN LETTER KAPH", "Lo", 0),
("CHORASMIAN LETTER LAMEDH", "Lo", 0),
("CHORASMIAN LETTER MEM", "Lo", 0),
("CHORASMIAN LETTER NUN", "Lo", 0),
("CHORASMIAN LETTER SAMEKH", "Lo", 0),
("CHORASMIAN LETTER AYIN", "Lo", 0),
("CHORASMIAN LETTER PE", "Lo", 0),
("CHORASMIAN LETTER RESH", "Lo", 0),
("CHORASMIAN LETTER SHIN", "Lo", 0),
("CHORASMIAN LETTER TAW", "Lo", 0),
("CHORASMIAN NUMBER ONE", "No", 0),
("CHORASMIAN NUMBER TWO", "No", 0),
("CHORASMIAN NUMBER THREE", "No", 0),
("CHORASMIAN NUMBER FOUR", "No", 0),
("CHORASMIAN NUMBER TEN", "No", 0),
("CHORASMIAN NUMBER TWENTY", "No", 0),
("CHORASMIAN NUMBER ONE HUNDRED", "No", 0),
)
|
https://github.com/ohmycloud/computer-science-notes | https://raw.githubusercontent.com/ohmycloud/computer-science-notes/main/Rust/impl-trait.typ | typst | == `impl Trait` in type aliases
```rs
type Odd = impl Iterator<Item = u32>;
fn odd(start: u32, stop: u32) -> Odd {
(start..=stop).filter(|i| i % 2 == 0)
}
```
`impl Trait` provides ways to specify unnamed but concrete types that implement a specific trait.It
can appear in two sorts of places: argument position(where it can act as an anonymous type parameter to functions), and
return position(where it can act as an abstract return type).
```rs
trait Trait {}
// argument position: anonymous type parameter
fn foo(arg: impl Trait) {}
// return position: abstract return type
fn bar() -> impl Trait {}
```
== `impl Trait` in return types
```rs
// return position: abstract return type
fn odd(start: u32, stop: u32) -> impl Iterator<Item = u32> {
(start ..= stop).filter(|i| i % 2 != 0)
}
```
== `impl Trait` in argument types
When you use an `impl Trait` in the type of a function argument, that is generally equivalent to adding a generic parameter to
the function. So this function:
```rs
// argument position: anonymous type parameter
fn sum(nums: impl Iterator<Item = u32>) -> u32 {
nums.sum()
}
```
is roughly equivalent to the following generic function:
```rs
fn sum<T>(nums: T) -> u32
where
T: Iterator<Item = u32>,
{
nums.sum()
}
```
Intuitively, a function that has an argument of type `impl Iterator` is saying "you can give me any sort of iterator that you like".
== Return types in trait definitions and impls
When you use `impl Trait` as the return type for a function *within a trait* or *trait impl*,
the intent is the same: impls that implement this trait return "some type that implements `Trait`", and
users of the trait can only rely on that. However, the desugaring to achieve that effect looks somewhat different than other cases
of impl trait in return position. This is because we cannot desugar to a type alias in the surrounding module;
We need to desugar to an associated type(effectively, a type alias *in the trait*).
Consider the following trait:
```rs
trait IntoIntIterator {
fn into_int_iter(self) -> impl Iterator<Item = u32>;
}
```
The semantics of this are analogous to introducing a new *associated type* within the surrounding trait;
```rs
trait IntoIntIterator { // desugared
type IntoIntIter: Iterator<Item = u32>;
fn into_int_iter(self) -> Self::IntoIntIter;
}
```
This associated type is introduced by the compiler and cannot be named by users.
The impl for a trait like `IntoIntIterator` must also use `impl Trait` in return position:
```rs
impl IntoIntIterator for Vec<u32> {
fn into_int_iter(self) -> impl Iterator<Item = u32> {
self.into_iter()
}
}
```
This is equivalent to specify the value of the associated type as an `impl Trait`:
```rs
#![feature(impl_trait_in_assoc_type)]
impl IntoIntIterator for Vec<u32> {
type IntoIntIter = impl Iterator<Item = u32>;
fn into_int_iter(self) -> Self::IntoIntIter {
self.into_iter()
}
}
```
|
|
https://github.com/0xPARC/0xparc-intro-book | https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/src/ec.typ | typst | #import "preamble.typ":*
Before we talk about SNARKs (specifically, PLONK), it helps to separate out an
ingredient that underlies much of programmable cryptography, which is the idea
of a _polynomial commitment_. Specifically, we will talk about the KZG
polynomial commitment, which plays an important role in PLONK (and many other
protocols). For a higher-resolution understanding of KZG, it helps to
understand _elliptic curves_ (especially in the context of _pairings_), which
are ubiquitous in cryptography. If you are uninterested (or experienced) in
mathematical details, you can and should skip elliptic curves and jump to
@kzg. If you are comfortable with black-boxing @kzg, you can even jump
straight to SNARKs into the next chapter.
The roadmap goes roughly as follows:
- In @ec we will define _elliptic curves_ and describe one standard elliptic
curve $E$, the _BN254 curve_,
that will be used in these notes.
- In @discretelog we describe the _discrete logarithm assumption_ (@ddh),
which we need to make to provide security to our protocols. As an example, in
@eddsa we describe how @ddh
can be used to construct a signature scheme, namely
#cite("https://en.wikipedia.org/wiki/EdDSA", "EdDSA").
- The EdDSA idea will later grow up to be the KZG commitment scheme in @kzg.
= Elliptic curves <ec>
Every modern cryptosystem rests on a hard problem
-- a computationally infeasible challenge
whose difficulty makes the protocol secure.
The best-known example is
#cite("https://en.wikipedia.org/wiki/RSA_(cryptosystem)", "RSA"),
which is secure because
it is hard to factor a composite number (like $6887$)
into prime factors ($6887 = 71 dot 97$).
Our SNARK protocol will be based on a different hard problem:
the "discrete logarithm problem"
(@discretelog) on elliptic curves.
But before we get to the problem,
we need to introduce some of the math behind elliptic curves.
An _elliptic curve_ is a set of points with a group operation.
The set of points is the set of solutions $(x, y)$
to an equation in two variables;
the group operation is a rule for "adding" two of the points
to get a third point.
Our first task will be to understand what all this means. Rather than set up a general definition of elliptic curve,
for these notes we will be satisfied to describe one specific elliptic curve
that can be used for all the protocols we describe later.
The curve we choose for these notes is the _BN254 curve_.
The BN254 specification fixes a specific#footnote[
If you must know, the values in the specification are given exactly by
$
x &:= &&4965661367192848881 \
p &:= &&36x^4 + 36x^3 + 24x^2 + 6x + 1 \
&= && 218882428718392752222464057452572750886 \
& && 96311157297823662689037894645226208583 \
q &:= && 36x^4 + 36x^3 + 18x^2 + 6x + 1 \
&= && 218882428718392752222464057452572750885 \
& && 48364400416034343698204186575808495617.
$
]
large prime $p approx 2^(254)$
(and a second large prime $q approx 2^(254)$ that we define later)
which has been specifically engineered to have certain properties
(<NAME> has a #cite("https://hackmd.io/@jpw/bn254", "blog post")
about the properties of this curve).
The name BN stands for Barreto-Naehrig, two mathematicians who
#cite("https://link.springer.com/content/pdf/10.1007/11693383_22.pdf",
"proposed a family of such curves in 2006").
#definition[
The _BN254 curve_ is the elliptic curve
#eqn[$ E(FF_p) : Y^2 = X^3 + 3 $ <bn254eqn>]
defined over $FF_p$, where $p approx 2^(254)$
is the prime from the BN254 specification.
]
So each point on $E(FF_p)$ is an ordered pair $(X,Y) in FF_p^2$ satisfying @bn254eqn.
Okay, actually, that's a white lie: conventionally,
there is one additional point $O = (0, oo)$ called the "point at infinity"
added in (whose purpose we describe in the next section).
The constants $p$ and $q$ are contrived so that the following holds:
#theorem[BN254 has prime order][
Let $E$ be the BN254 curve.
The number of points in $E(FF_p)$,
including the point at infinity $O$, is a prime $q approx 2^(254)$.
]
#definition[
This prime $q approx 2^(254)$ is affectionately called the _Baby Jubjub prime_
(a reference to #cite("https://en.wikipedia.org/wiki/The_Hunting_of_the_Snark", "The Hunting of the Snark")).
It will usually be denoted by $q$ in these notes.
]
So at this point, we have a bag of $q$ points denoted $E(FF_p)$.
However, right now it only has the structure of a set.
The beauty of elliptic curves
is that it's possible to define an *addition* operation on the curve;
this is called the #cite("https://en.wikipedia.org/wiki/Elliptic_curve#The_group_law", "group law on the elliptic curve").
This addition will make $E(FF_p)$ into an abelian group whose identity element
is the point at infinity $O$. This addition can be formalized as a _group law_, which is an equation that points on the curve must follow.
This group law involves some kind of heavy algebra.
It's not important to understand exactly how it works.
All you really need to take away from this section is that there is some group law,
and we can program a computer to compute it. We provide details below for the interested reader.
#gray[
So, let's get started.
The equation of $E$ is cubic -- the highest-degree terms have degree $3$.
This means that (in general) if you take a line $y = m x + b$ and intersect it with $E$,
the line will meet $E$ in exactly three points.
The basic idea behind the group law is:
If $P, Q, R$ are the three intersection points of a line (any line)
with the curve $E$, then the group-law addition of the three points is
$
P + Q + R = O.
$
(You might be wondering how we can do geometry
when the coordinates $x$ and $y$ are in a finite field.
It turns out that all the geometric operations we're describing --
like finding the intersection of a curve with a line --
can be translated into algebra.
And then you just do the algebra in your finite field.
But we'll come back to this.)
Why three points?
Algebraically, if you take the equations $Y^2 = X^3 + 3$ and $Y = m X + b$
and try to solve them,
you get
$
(m X + b)^2 = X^3 + 3,
$
which is a degree-3 polynomial in $X$,
so it has (at most) 3 roots.
And in fact if it has 2 roots, it's guaranteed to have a third
(because you can factor out the first two roots, and then you're left with a linear factor).
OK, so given two points $P$ and $Q$, how do we find their sum $P+Q$?
We can draw the line through the two points.
That line -- like any line -- will intersect $E$ in three points:
$P$, $Q$, and a third point $R$.
Now since $P + Q + R = 0$, we know that
$
- R = P + Q.
$
So now the question is just: how to find $-R$?
Well, it turns out that if $R = (x_R, y_R)$, then
$
- R = (x_R, -y_R).
$
Why is this?
If you take the vertical line $X = x_R$,
and try to intersect it with the curve,
it looks like there are only two intersection points.
After all, we're solving
$
Y^2 = x_R^3 + 3,
$
and since $x_R$ is fixed now, this equation is quadratic.
The two roots are $Y = plus.minus y_R$.
OK, there are only two intersection points, but
we say that the third intersection point is "the point at infinity" $O$.
(The reason for this lies in projective geometry, but we won't get into it.)
So the group law here tells us
$
(x_R, y_R) + (x_R, -y_R) + O = O.
$
And since $O$ is the identity, we get
$
-R = (x_R, -y_R).
$
So:
- Given a point $P = (x_P, y_P)$, its negative is just $-P = (x_P, -y_P)$.
- To add two points $P$ and $Q$, compute the line through the two points,
let $R$ be the third intersection of that line with $E$,
and set
$
P + Q = -R.
$
We just described the group law as a geometric thing,
but there are algebraic formulas to compute it as well.
They are kind of a mess, but here goes.
If $P = (x_P, y_P)$ and $Q = (x_Q, y_Q)$, then the line between the two points is
$Y = m X + b$, where
$
m = (y_Q - y_P) / (x_Q - x_P)
$
and
$
b = y_P - m x_P.
$
The third intersection is $R = (x_R, y_R)$, where
$
x_R = m^2 - x_P - x_Q
$
and
$
y_R = m x_R + b.
$
There are separate formulas to deal with various special cases
(if $P = Q$, you need to compute the tangent line to $E$ at $P$, for example),
but we won't get into it.
]
In summary we have endowed the set of points $E(FF_p)$ with the additional
structure of an abelian group, which happens to have exactly $q$ elements.
However, an abelian group with prime order is necessarily cyclic.
In other words:
#theorem[The group BN254 is isomorphic to $ZZ slash q ZZ$][
Let $E$ be the BN254 curve.
We have the isomorphism of abelian groups
$ E(FF_p) tilde.equiv ZZ slash q ZZ. $
]
In these notes, this isomorphism will basically be a standing assumption.
Moving forward we'll abuse notation slightly
and just write $E$ instead of $E(FF_p)$.
In fancy language, $E$ will be a one-dimensional vector space over $FF_q$.
In less fancy language, we'll be working with points on $E$ as black boxes.
We'll be able to add them, subtract them,
and multiply them by arbitrary scalars from $FF_q$.
Consequently --- and this is important ---
*one should think of $FF_q$ as the base field
for all our cryptographic primitives*
(despite the fact that the coordinates of our points are in $FF_p$).
#remark[
Whenever we talk about protocols, and there are any sorts of
"numbers" or "scalars" in the protocol,
*these scalars are always going to be elements of $FF_q$*.
Since $q approx 2^(254)$,
that means we are doing something like $256$-bit integer arithmetic.
This is why the baby Jubjub prime $q$ gets a special name,
while the prime $p$ is unnamed and doesn't get any screen-time later.
]
= Discrete logarithm <discretelog>
For our systems to be useful, rather than relying on factoring,
we will rely on the so-called _discrete logarithm_ assumption.
#assumption[Discrete logarithm assumption][
Let $E$ be the BN254 curve (or another standardized curve).
Given arbitrary nonzero $g, g' in E$,
the _discrete logarithm problem_ asks you
to find an integer $n$ such that $n dot g = g'$.
Experience suggests that the discrete logarithm problem is hard:
in general, we don't know a fast algorithm to solve it.
The _discrete logarithm assumption_
says that no such algorithm exists.
] <ddh>
In other words, if one only
sees $g in E$ and $n dot g in E$, one cannot find $n$.
For cryptography, we generally assume $g$ has order $q$,
so we will talk about $n in NN$ and $n in FF_q$ interchangeably.
In other words, $n$ will generally be thought of as being up to about $2^(254)$ in size.
#remark[The name "discrete log"][
This problem is called discrete log because if one used multiplicative notation
for the group operation, it looks like solving $g^n = g'$ instead.
We will never use this multiplicative notation in these notes.
]
On the other hand, given $g in E$,
one can compute $n dot g$ in just $O(log n)$ operations,
by #cite("https://en.wikipedia.org/wiki/Exponentiation_by_squaring", "repeated squaring").
For example, to compute $400g$, one only needs to do $10$ additions,
rather than $400$: one starts with
$
2g &= g + g \
4g &= 2g + 2g \
8g &= 4g + 4g \
16g &= 8g + 8g \
32g &= 16g + 16g \
64g &= 32g + 32g \
128g &= 64g + 64g \
256g &= 128g + 128g \
$
and then computes
$ 400g = 256g + 128g + 16g. $
Because we think of $n$ as up to $q approx 2^(254)$-ish in size,
we consider $O(log n)$ operations like this to be quite tolerable.
== Curves other than BN254
We comment briefly on how the previous definitions adapt to other curves,
although readers could get away with always assuming $E$ is BN254 if they prefer.
In general, we could have chosen for $E$ any equation of the form
$Y^2 = X^3 + a X + b$ and chosen any prime $p >= 5$
such that a nondegeneracy constraint $4a^3 + 27b^2 equiv.not 0 mod p$ holds.
In such a situation, $E(FF_p)$ will indeed be an abelian group
once the identity element $O = (0, oo)$ is added in.
How large is $E(FF_p)$?
There is a theorem called
#cite("https://en.wikipedia.org/wiki/Hasse's_theorem_on_elliptic_curves", "Hasse's theorem") that states
the number of points in $E(FF_p)$ is between $p+1-2sqrt(p)$ and $p+1+2sqrt(p)$.
But there is no promise that $E(FF_p)$ will be _prime_;
consequently, it may not be a cyclic group either.
So among many other considerations,
the choice of constants in BN254 is engineered to get a prime order.
There are other curves used in practice for which $E(FF_p)$
is not a prime, but rather a small multiple of a prime.
The popular #cite("https://en.wikipedia.org/wiki/Curve25519", "Curve25519") is such a curve
that is also believed to satisfy @ddh.
Curve25519 is defined as $ Y^2 = X^3 + 486662X^2 + X $ over $FF_p$
for the prime $p := 2^(255)-19$.
Its order is $8$ times a large prime
$ q' := 2^(252) + 27742317777372353535851937790883648493. $
In that case, to generate a random point on Curve25519 with order $q'$,
one will usually take a random point on the curve and multiply it by $8$.
BN254 is also engineered to have a property called _pairing-friendly_,
which is defined in @pairing-friendly when we need it later.
(In contrast, Curve25519 does not have this property.)
== Example application: EdDSA signature scheme <eddsa>
We'll show how @ddh can be used to construct a signature scheme that replaces RSA.
This scheme is called #cite("https://en.wikipedia.org/wiki/EdDSA", "EdDSA"),
and it's used quite frequently (e.g. in OpenSSH and GnuPG).
One advantage it has over RSA is that its key size is much smaller:
both the public and private key are 256 bits.
(In contrast, RSA needs 2048-4096 bit keys for comparable security.)
#definition[
Let $E$ be an elliptic curve and let $g in E$
be a fixed point on it of prime order $q approx 2^(254)$.
For $n in ZZ$ (equivalently $n in FF_q$) we define
$ [n] := n dot g in E. $
] <armor>
The hardness of discrete logarithm means that, given $[n]$, we cannot get $n$.
You can almost think of the notation as an "armor" on the integer $n$:
it conceals the integer, but still allows us to perform (armored) addition:
$ [a+b] = [a] + [b]. $
In other words, $n |-> [n]$ viewed as a map $FF_q -> E$ is $FF_q$-linear.
So now suppose Alice wants to set up a signature scheme.
#algorithm[EdDSA public and secret key][
1. Alice picks a random integer $d in FF_q$ as her _secret key_ (a piece of information that she needs to keep private for the security of the protocol).
2. Alice publishes $[d] in E$ as her _public key_ (a piece of information which, even when obtained by adversaries, does not challenge the security of the protocol).
]
Now suppose Alice wants to prove to Bob that she approves the message $msg$,
given her published public key $[d]$.
#algorithm[EdDSA signature generation][
Suppose Alice wants to sign a message $msg$.
1. Alice picks a random scalar $r in FF_q$ (keeping this secret)
and publishes $[r] in E$.
2. Alice generates a number $n in FF_q$ by hashing $msg$ with all public information,
say $ n := hash([r], msg, [d]). $
3. Alice publishes the integer $ s := (r + d n) mod q. $
In other words, the signature is the ordered pair $([r], s)$.
]
#algorithm[EdDSA signature verification][
For Bob to verify a signature $([r], s)$ for $msg$:
1. Bob recomputes $n$ (by also performing the hash) and computes $[s] in E$.
2. Bob verifies that $[r] + n dot [d] = [s]$.
]
An adversary cannot forge the signature even if they know $r$ and $n$.
Indeed, such an adversary can compute what the point $[s] = [r] + n [d]$
should be, but without knowledge of $d$ they cannot get the integer $s$,
due to @ddh.
The number $r$ is called a _blinding factor_ because
its use prevents Bob from stealing Alice's secret key $d$ from the published $s$.
It's therefore imperative that $r$ isn't known to Bob
nor reused between signatures, and so on.
One way to do this would be to pick $r = hash(d, msg)$; this has the
bonus that it's deterministic as a function of the message and signer.
In @kzg we will use ideas quite similar to this to
build the KZG commitment scheme.
== Example application: Pedersen commitments <pedersen>
A _commitment scheme_ is a protocol where Alice wants to commit some value $x$ to Bob that is later revealed. Typically Alice gives Bob some "commitment" $Com(x)$ and later reveals $x$. What we want is that this protocol is both _binding_ (Alice cannot change her mind about $x$ depending on Bob's later actions) and _hiding_ (Bob does not get any information about $x$ from $Com(x)$). The KZG scheme we are building towards will be a commitment scheme for polynomials, but we can already use elliptic curves to commit *numbers* with something called a Pedersen commitment, which we will now describe.
A multivariable generalization of @ddh is that if $g_1, ..., g_n in E$
are a bunch of randomly chosen points of $E$ with order $q$,
then it's computationally infeasible to find
$(a_1, ..., a_n) != (b_1, ..., b_n) in FF_q^n$ such that
$ a_1 g_1 + ... + a_n g_n = b_1 g_1 + ... + b_n g_n. $
(Remember that $q approx 2^(256)$ is very large.)
#definition[
In these notes, if there's a globally known elliptic curve $E$
and points $g_1, ..., g_n$ have order $q$ and no known nontrivial
linear dependencies between them,
we'll say they're a _computational basis over $FF_q$_.
] <comp_basis>
#remark[
This may horrify pure mathematicians because we're pretending the map
$ FF_q^n -> FF_q " by " (a_1, ..., a_n) |-> sum_1^n a_i g_i $
is injective,
even though the domain is an $n$-dimensional $FF_q$-vector space
and the codomain is one-dimensional.
This can feel weird because our instincts from linear algebra in pure math
are wrong now. This map, while not injective in theory,
ends up being injective *in practice* (because we can't find collisions).
And this is a critical standing assumption for this entire framework!
]
This injectivity gives us a sort of hash function on vectors
(with "linearly independent" now being phrased as "we can't find a collision").
To spell this out:
#definition[
Let $g_1, ..., g_n in E$ be a computational basis over $FF_q$.
Given a vector
$ arrow(a) = angle.l a_1, ..., a_n angle.r in FF_q^n $ of scalars,
the group element
$ sum a_i g_i = a_1 g_1 + ... + a_n g_n in E $
is called the _Pedersen commitment_ to our vector $arrow(a)$.
]
The Pedersen commitment is thus a sort of hash function:
given the group element above,
one cannot recover any of the $a_i$;
but given the entire vector $arrow(a)$
one can compute the Pedersen commitment easily.
We won't use Pedersen commitments in this book,
but they will be closely related to KZG.
|
|
https://github.com/smorad/um_cisc_7026 | https://raw.githubusercontent.com/smorad/um_cisc_7026/main/lecture_4_backpropagation.typ | typst | #import "@preview/polylux:0.3.1": *
#import themes.university: *
#import "@preview/cetz:0.2.2": canvas, draw, plot
#import "common.typ": *
#import "@preview/algorithmic:0.1.0"
#import algorithmic: algorithm
// TODO: Should talk more about forward/backward pass
// TODO: Add break
// TODO: Use different brackets for gradient_theta (f(theta)) to differentiate between products and input/arguments to grad function
#set math.vec(delim: "[")
#set math.mat(delim: "[")
#let ag = (
[Review],
[Quiz],
[Optimization],
[Calculus review],
[Deriving linear regression],
[Gradient descent],
[Backpropagation],
[Coding]
)
#let local_optima_plot = canvas(length: 1cm, {
plot.plot(size: (8, 6),
x-tick-step: 2,
y-tick-step: 30,
{
plot.add(
domain: (-2, 2),
x => - 2 * calc.pow(x, 3) - 2 * calc.pow(x, 4) + calc.pow(x, 5) + calc.pow(x, 6),
)
plot.add(((-1.4,0), (1.2,-2)),
mark: "o",
mark-style: (stroke: none, fill: black),
style: (stroke: none))
})
})
#show: university-theme.with(
aspect-ratio: "16-9",
short-title: "CISC 7026: Introduction to Deep Learning",
short-author: "<NAME>",
short-date: "Lecture 1: Introduction"
)
#title-slide(
title: [Optimization],
subtitle: "CISC 7026: Introduction to Deep Learning",
institution-name: "University of Macau",
//logo: image("logo.jpg", width: 25%)
)
#slide(title: [Admin])[
Quiz 1 grades are on moodle (mean 2.75 / 4) #pause
When I have a function called $g$ that maps some inputs $a in A, b in B, c in C$ to outputs $d in D, e in E$ I would write
$ g: A times B times C |-> D times E $
or
$ g: A, B, C |-> D, E $ #pause
In my code, I would write
$ d, e = g(a, b, c) $
]
#slide(title: [Admin])[
$bb(R)$ is the set of real numbers #pause
$5, pi, e, -3.2, 3 / 2, 1.3333...$ are all real numbers #pause
Unless the number is $sqrt(-1)$, it is probably a real number #pause
When I write $bb(R)^(d_x)$, this corresponds to $d_x$ real numbers #pause
So $f: bb(R)^(d_x) |-> bb(R)^(d_y)$ is a function that maps $d_x$ numbers to $d_y$ numbers
]
#slide(title: [Admin])[
Assignment one should be graded next week #pause
Today's lecture will be very theoretical, but I must teach it #pause
I understand the homework might be difficult for some #pause
Assignment 2 is *optional* (it is *not* required) #pause
I will give $n$ assignments and you will receive the highest $n - 1$ grades #pause
E.g., $"asg1" = 60, #redm[$"asg2" = 90$], #redm[$"asg3" = 70$]$, $"total score" = 160 / 200$ #pause
E.g., $#redm[$"asg1" = 60$], "asg2" = 0, #redm[$"asg3" = 70$]$, $"total score" = 130 / 200$
]
/*
#sslide[
I have two types of students in this class #pause
+ Computer/information science MS and PhD students #pause
+ Students from other departments #pause
Many computer science students take this course to prepare for PhD research #pause
They must understand theory to do good research #pause
Maybe other students care more about application than theory #pause
It is challenging to teach both groups at once #pause
I can only change the course if you give me feedback
]
*/
// 4:00
#aslide(ag, none)
#aslide(ag, 0)
#sslide[
In lecture 1, we assumed a single-input system #pause
Years of education: $X in bb(R)$ #pause
But sometimes we want to consider multiple input dimensions #pause
Years of education, BMI, GDP: $X in bb(R)^3$ #pause
We can solve these problems using linear regression too
]
#sslide[
For multivariate problems, we will define the input dimension as $d_x$ #pause
$ bold(x) in X; quad X in bb(R)^(d_x) $ #pause
We will write the vectors as
$ bold(x)_[i] = vec(
x_([i], 1),
x_([i], 2),
dots.v,
x_([i], d_x)
) $
]
#sslide[
The design matrix for a *multivariate* linear system is
$ bold(X)_D = mat(
x_([1], d_x), x_([1], d_x - 1), dots, x_([1], 1), 1;
x_([2], d_x), x_([2], d_x - 1), dots, x_([2], 1), 1;
dots.v, dots.v, dots.down, dots.v;
x_([n], d_x), x_([n], d_x - 1), dots, x_([n], 1), 1
) $ #pause
The solution is the same as before
$ bold(theta) = (bold(X)_D^top bold(X)_D )^(-1) bold(X)_D^top bold(y) $
]
#sslide[
We combined *polynomial* and *multivariate* design matrices: #pause
#side-by-side[
One-dimensional polynomial functions
$ bold(X)_D = mat(
x_[1]^m, x_[1]^(m-1), dots, x_[1], 1;
x_[2]^m, x_[2]^(m-1), dots, x_[2], 1;
dots.v, dots.v, dots.down;
x_[n]^m, x_[n]^(m-1), dots, x_[n], 1
) $ #pause][
Multi-dimensional linear functions
$ bold(X)_D = mat(
x_([1], d_x), x_([1], d_x - 1), dots, 1;
x_([2], d_x), x_([2], d_x - 1), dots, 1;
dots.v, dots.v, dots.down, dots.v;
x_([n], d_x), x_([n], d_x - 1), dots, 1
) $
]
]
#sslide[
$ bold(X)_D = mat(bold(x)_(D, [1]), dots, bold(x)_(D, [n]))^top $ #pause
$ &bold(x)_(D, [i]) = \ &mat(
underbrace(x_([i], d_x)^m x_([i], d_x - 1)^m dots x_([i], 1)^m, (d_x => 1, x^m)),
underbrace(x_([i], d_x)^m x_([i], d_x - 1)^m dots x_([i], 2)^m, (d_x => 2, x^m)),
dots,
underbrace(x_([i], d_x)^(m-1) x_([i], d_x - 1)^(m-1) dots x_([i], 1)^m, (d_x => 1, x^(m-1))),
dots,
)
$ #pause
The resulting design matrix is too large to solve #pause
We introduced neural networks because they scale to larger problems
]
#sslide[
Brains and neural networks rely on *neurons* #pause
*Brain:* Biological neurons $->$ Biological neural network #pause
*Computer:* Artificial neurons $->$ Artificial neural network
]
#sslide[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
Neurons send messages based on messages received from other neurons
]
#sslide[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
Incoming electrical signals travel along dendrites
]
#sslide[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
Electrical charges collect in the Soma (cell body)
]
#sslide[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
The axon outputs an electrical signal to other neurons
]
#sslide[
How does a neuron decide to send an impulse ("fire")? #pause
Dendrites form a parallel circuit #pause
In a parallel circuit, we can sum voltages together #pause
#side-by-side[Incoming impulses (via dendrites) change the electric potential of the neuron][ #cimage("figures/lecture_3/bio_neuron_activation.png", height: 50%)] #pause
Many active dendrites will add together and trigger an impulse
]
#sslide[
We model the neuron "firing" using an activation function $sigma$ #pause
Last time, we used the heaviside step function as the activation function
$ sigma(x) = H(x) = cases(0 "if" x <= 0, 1 "if" x > 0) $ #pause
#cimage("figures/lecture_4/heaviside.svg", height: 50%)
]
#sslide[
We modeled a neuron mathematically, creating an artificial neuron #pause
$ f(bold(x), bold(theta)) = sigma(bold(theta)^top overline(bold(x))); quad overline(bold(x)) = vec(1, bold(x)) $ #pause
$ f(bold(x), vec(b, bold(w))) = sigma(b + bold(w)^top bold(x)) $ #pause
An artificial neuron is a linear model with an activation function $sigma$ #pause
$ f(bold(x), bold(theta)) = sigma( underbrace(theta_0 1 + theta_1 x_1 + dots + theta_(d_x) x_(d_x), "Linear model") ) $
]
#sslide[
We can represent AND and OR boolean operators using a neuron #pause
But a neuron cannot represent many other functions #pause
So we take many neurons and create a neural network #pause
We discussed *wide* neural networks and *deep* neural networks
]
#sslide[
How do we express a *wide* neural network mathematically? #pause
A single neuron:
$ f: bb(R)^(d_x) times Theta |-> bb(R) $
$ Theta in bb(R)^(d_x + 1) $ #pause
$d_y$ neurons (wide):
$ f: bb(R)^(d_x) times Theta |-> bb(R)^(d_y) $
$ Theta in bb(R)^((d_x + 1) times d_y) $
]
#sslide[
// Must be m by n (m rows, n cols)
#text(size: 24pt)[
For a wide network (also called a layer):
$ f(vec(x_1, x_2, dots.v, x_(d_x)), mat(theta_(0,1), theta_(0,2), dots, theta_(0,d_y); theta_(1,1), theta_(1,2), dots, theta_(1, d_y); dots.v, dots.v, dots.down, dots.v; theta_(d_x, 1), theta_(d_x, 2), dots, theta_(d_x, d_y)) ) = vec(
sigma(sum_(i=0)^(d_x) theta_(i,1) overline(x)_i ),
sigma(sum_(i=0)^(d_x) theta_(i,2) overline(x)_i ),
dots.v,
sigma(sum_(i=0)^(d_x) theta_(i,d_y) overline(x)_i ),
)
$
$ f(bold(x), bold(theta)) =
sigma(bold(theta)^top overline(bold(x))); quad bold(theta) in bb(R)^( (d_x + 1) times d_y )
$ #pause
$
f(bold(x), vec(bold(b), bold(W))) = sigma( bold(b) + bold(W)^top bold(x) ); quad bold(b) in bb(R)^(d_y), bold(W) in bb(R)^( d_x times d_y )
$
]
]
#sslide[
A *wide* neural network is also called a *layer* #pause
A layer is a linear operation and an activation function
$ f(bold(x), vec(bold(b), bold(W))) = sigma(bold(b) + bold(W)^top bold(x)) $
#side-by-side[Many layers makes a deep neural network][
#text(size: 22pt)[
$ bold(z)_1 &= f(bold(x), vec(bold(b)_1, bold(W)_1)) \
bold(z)_2 &= f(bold(z)_1, vec(bold(b)_2, bold(W)_2)) \ quad bold(y) &= f(bold(z)_2, vec(bold(b)_2, bold(W)_2)) $
]
]
]
// 18:00
#aslide(ag, 0)
#aslide(ag, 1)
#sslide[
Put away your phones and laptops #pause
Take out a paper and pen, write your name and student ID #pause
I will take away your quiz, give zero points, and refer you to the Dean if: #pause
- Your phone or laptop is open during the quiz #pause
- You talk to your neighbor #pause
- You look at your neighbor's quiz #pause
After I explain the questions, you will have 15 minutes to finish the quiz
]
#aslide(ag, 1)
#aslide(ag, 2)
#sslide[
We previously introduced neural networks as universal function approximators #pause
A deep neural network $f$ can approximate *any* continuous function $g$ to infinite precision #pause
$ f(x, bold(theta)) = g(x) + epsilon; quad epsilon -> 0 $ #pause
$g$ can be a mapping from pictures to text, English to Chinese, etc #pause
But how do we find the $bold(theta)$ that makes $f(x, bold(theta)) = g(x) + epsilon$? #pause
We said this $bold(theta)$ exists, but never said how to find it #pause
*Goal:* Find the parameters $bold(theta)$ a neural network
]
#sslide[
When we search for $bold(theta)$, we call it *optimization* or *training* #pause
We optimize a loss function by computing
$ argmin_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) $ #pause
This expression looks very simple, but it can be very hard to evaluate
]
#sslide[
#cimage("figures/lecture_1/timeline.svg", height: 60%)
Neural networks were discovered in 1943, but we could not train them until 1982! #pause
This is why theory is important
]
#sslide[
Recall how we found $bold(theta)$ in the linear regression problem #pause
We define the square error loss function #pause
$ argmin_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) = argmin_bold(theta) sum_(i=1)^n ( f(bold(x)_[i], bold(theta)) - bold(y)_[i] )^2 $ #pause
Then, I gave you a magical solution to this optimization problem #pause
$ bold(theta) = (bold(X)_D^top bold(X)_D )^(-1) bold(X)_D^top bold(Y) $ #pause
Where does this solution come from? Can we do the same for neural networks?
]
//22:00 + 15:00 quiz = 37:00
#sslide[
The solution for linear regression and neural networks comes from *calculus* #pause
The solution for neural networks also comes from calculus #pause
Let us review basic calculus concepts
]
#aslide(ag, 2)
#aslide(ag, 3)
#sslide[
We write the *derivative* of a function $f$ with respect to an input $x$ as
$ f'(x) = d / (d x) f = (d f) / (d x) = lim_(h -> 0) (f(x + h) - f(x)) / h $ #pause
The derivative is the slope of a function #pause
#cimage("figures/lecture_4/slope.svg", height: 30%) #pause
$ f(x), #redm[$f'(x=a)$] $
]
//26:00 + 15 == 41:00
#sslide[
It is easiest if you treat the derivative as a *function of functions* #pause
$ "derivative"(f) = f' $ #pause
$ d / (d x): f |-> f' $ #pause
The derivative takes a function $f$ and outputs a new function $f'$ #pause
$ d / (d x): [f: X |-> Y] |-> [f': X |-> Y] $
]
#sslide[
There are formulas for computing the derivative of various operations #pause
#side-by-side(align: left + horizon)[Constant][$ d / (d x) c = 0 $] #pause
#side-by-side(align: left + horizon)[Power][$ d / (d x) x^n = n x^(n-1) $]
]
#sslide[
#side-by-side(align: left + horizon)[Sum/Difference][$ d / (d x) [f(x) + g(x)] = f'(x) + g'(x) $] #pause
#side-by-side(align: left + horizon)[Product][$ d / (d x) [f(x) g(x)] = f'(x) g(x) + g'(x) f(x) $] #pause
#side-by-side(align: left + horizon)[Chain][$ d / (d x) [f (g (x))] = f'(g(x)) g'(x) $]
]
#sslide[
For example, consider the function
$ f(x) = x^2 - 3x $ #pause
We can write the derivative as
$ d / (d x) [f(x)] = 2x - 3 $ #pause
We can evaluate the derivative at specific points #pause
$ d / (d x) [f] (1) = 2 dot 1 - 3 = -1 $
]
#sslide[
#side-by-side[#cimage("figures/lecture_4/quadratic.png", height: 35%)][$ f(x) = x^2 - 3x $] #pause
#side-by-side[#cimage("figures/lecture_4/quadratic_with_derivative.png", height: 35%)][$ (d f) / (d x) = 2x - 3 $] #pause
$ 0 = 2x - 3 quad => quad x = 3 / 2 $
]
#sslide[
We can expand the definition of derivative to multivariate functions. We call this the *gradient*
$ gradient_(bold(x)) f(mat(x_1, x_2, dots, x_n)^top) = mat((partial f) / (partial x_1), (partial f) / (partial x_2), dots, (partial f) / (partial x_n))^top $ #pause
Partial derivatives behave similarly to standard derivatives #pause
$ (partial) / (partial x_1) f(x_1, dots, x_n) approx d / (d x_1) f(x_1, dots, x_n) $ #pause
When computing $partial / (partial x_i) f(x_1, dots, x_n)$, we treat $x_1, dots, x_(i-1), x_(i+1), dots, x_n$ as constant
]
#sslide[
For example, consider the function
$ f(x_1, x_2) = x_1^2 - 3 x_1 x_2 $ #pause
We can write the gradient as
$ gradient_bold(x) f(bold(x)) =
gradient_(x_1, x_2) f(vec(x_1, x_2)) =
vec(
partial / (partial x_1) f(x_1, x_2),
partial / (partial x_2) f(x_1, x_2)
) = vec(
2 x_1 - 3 x_2,
-3 x_1
) $
]
#sslide[
$ gradient_bold(x) f(bold(x)) =
gradient_(x_1, x_2) f(vec(x_1, x_2)) =
vec(
partial / (partial x_1) f(x_1, x_2),
partial / (partial x_2) f(x_1, x_2)
) = vec(
2 x_1 - 3 x_2,
-3 x_1
) $ #pause
We can evaluate the gradient at specific points #pause
$ gradient_bold(x) f(vec(1, 0)) =
gradient_(x_1, x_2) f(vec(1, 0)) =
vec(
partial / (partial x_1) f(1, 0),
partial / (partial x_2) f(1, 0)
) = vec(
2 dot 1 - 3 dot 0,
-3 dot 1
) = vec(-1, -3) $
]
// 54:00 with quiz
#sslide[
In calculus, we can find the local extrema of a function $f(x)$ by finding where the derivative is zero
$ f'(x) = d / (d x) f (x)= 0 $ #pause
With a multivariate function, the extrema lies where the gradient is zero
//In multivariable calculus, we use the gradient instead
$ gradient_bold(x) f(bold(x)) = mat((partial f) / (partial x_1), (partial f) / (partial x_2), dots, (partial f) / (partial x_n))^top = mat(0, 0, dots, 0)^top $
]
#aslide(ag, 3)
#aslide(ag, 4)
#sslide[
Now that we remember calculus, let us revisit linear regression #pause
If we can derive the solution for linear regression, maybe we can apply it to deep neural networks
]
#sslide[
In linear regression, our loss function is
$ cal(L)(bold(X), bold(Y), bold(theta)) = sum_(i=1)^n ( f(bold(x)_[i], bold(theta)) - bold(y)_[i] )^2 $ #pause
We can write the square error loss in matrix form as
$ cal(L)(bold(X), bold(Y), bold(theta)) = ( bold(Y) - bold(X)_D bold(theta) )^top ( bold(Y) - bold(X)_D bold(theta) ) $ #pause
$ cal(L)(bold(X), bold(Y), bold(theta)) =
underbrace(underbrace(( bold(Y) - bold(X)_D bold(theta) )^top, "Linear function of " theta quad)
underbrace(( bold(Y) - bold(X)_D bold(theta) ), "Linear function of " theta), "Quadratic function of " theta) $
]
#sslide[
$ cal(L)(bold(X), bold(Y), bold(theta)) =
underbrace(underbrace(( bold(Y) - bold(X)_D bold(theta) )^top, "Linear function of " theta quad)
underbrace(( bold(Y) - bold(X)_D bold(theta) ), "Linear function of " theta), "Quadratic function of " theta) $ #pause
#side-by-side[A quadratic function has a single minima! The minima must be at $gradient_bold(theta) cal(L) = 0$][#cimage("figures/lecture_4/quadratic_parameter_space.png", height: 65%)]
]
#sslide[
Therefore, we know that the $bold(theta)$ that solves
$ gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) = 0 $ #pause
Also solves
$ argmin_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) $
]
#sslide[
Using calculus, let us derive the solution to linear regression #pause
$ cal(L)(bold(X), bold(Y), bold(theta)) = ( bold(Y) - bold(X)_D bold(theta) )^top ( bold(Y) - bold(X)_D bold(theta) ) $ #pause
$ gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) = gradient_bold(theta) [( bold(Y) - bold(X)_D bold(theta) )^top ( bold(Y) - bold(X)_D bold(theta) )] $ #pause
$ = gradient_bold(theta) [bold(Y)^top bold(Y) - bold(Y)^top bold(X)_D bold(theta) - (bold(X)_D bold(theta))^top bold(Y) + (bold(X)_D bold(theta))^top bold(X)_D bold(theta)] $ #pause
$ = bold(0) - bold(Y)^top bold(X)_D bold(I) - (bold(X)_D bold(I))^top bold(Y) + (bold(X)_D bold(I))^top bold(X)_D bold(theta) + (bold(X)_D bold(theta))^top bold(X)_D bold(I) $
]
#sslide[
$ = bold(0) - bold(Y)^top bold(X)_D bold(I) - (bold(X)_D bold(I))^top bold(Y) + (bold(X)_D bold(I))^top bold(X)_D bold(theta) + (bold(X)_D bold(theta))^top bold(X)_D bold(I) $ #pause
$ = - bold(Y)^top bold(X)_D - bold(X)_D^top bold(Y) + bold(X)_D^top bold(X)_D bold(theta) + (bold(X)_D bold(theta))^top bold(X)_D $ #pause
Remember, $(bold(A B))^top = bold(B)^top bold(A)^top$, and so $bold(Y)^top bold(X)_D = bold(Y)^top (bold(X)_D^top)^top = bold(X)_D^top bold(Y)$ #pause
$ = - bold(Y)^top bold(X)_D - bold(Y)^top bold(X)_D + bold(X)_D^top bold(X)_D bold(theta) + bold(X)_D^top bold(X)_D bold(theta) $ #pause
$ = - 2 bold(X)_D^top bold(Y) + 2 bold(X)_D^top bold(X theta) $ #pause
And so, the gradient of the loss is
$ gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) = - 2 bold(X)_D^top bold(Y) + 2 bold(X)_D^top bold(X)_D bold(theta) $
]
#sslide[
$ gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) = - 2 bold(X)_D^top bold(Y) + 2 bold(X)_D^top bold(X)_D bold(theta) $ #pause
We want to find the $bold(theta)$ that makes the gradient of the loss zero #pause
$ bold(0) = - 2 bold(X)_D^top bold(Y) + 2 bold(X)_D^top bold(X)_D bold(theta) $ #pause
$ 2 bold(X)_D^top bold(Y) = 2 bold(X)_D^top bold(X)_D bold(theta) $ #pause
$ bold(X)_D^top bold(Y) = bold(X)_D^top bold(X theta) $ #pause
$ (bold(X)_D^top bold(X)_D)^(-1) bold(X)_D^top bold(Y) = bold(theta) $
]
#sslide[
$ (bold(X)_D^top bold(X)_D)^(-1) bold(X)_D^top bold(Y) = bold(theta) $ #pause
This was the "magic" solution I gave you for linear regression #pause
$ bold(theta) = (bold(X)_D^top bold(X)_D)^(-1) bold(X)_D^top bold(Y) $
]
// 68:00 with quiz
#sslide[
Great! We derived the solution to linear regression #pause
Now, we will do the same approach for neural networks #pause
To make it simple, we assume $d_x = 1, d_y = 1, n = 1$ #pause
One input dimension, one output dimension, one datapoint #pause
*Step 1*: Write the loss function for a neural network
]
#sslide[
Like linear regression, we can use square error for a neural network #pause
$ cal(L)(x, y, bold(theta)) = (f(x, bold(theta)) - y)^2 $ #pause
All that changes is the model $f$ #pause
#side-by-side[Linear regression:][$ f(x, y, bold(theta)) = theta_0 + theta_1 x $] #pause
#side-by-side[Perceptron:][$ f(x, y, bold(theta)) = sigma(theta_0 + theta_1 x) $]
]
#sslide[
#side-by-side[$ cal(L)(x, y, bold(theta)) = (f(x, bold(theta)) - y)^2 $][Loss function] #pause
#side-by-side[$ f(x, bold(theta)) = sigma(theta_0 + theta_1 x) $][Neural network model] #pause
Now, we plug the model $f$ into the loss function #pause
$ cal(L)(x, y, bold(theta)) = (sigma(theta_0 + theta_1 x) - y)^2 $ #pause
Rewrite #pause
$ cal(L)(x, y, bold(theta)) =
underbrace((sigma(theta_0 + theta_1 x) - y), "Nonlinear function of" theta)
underbrace((sigma(theta_0 + theta_1 x) - y), "Nonlinear function of" theta) $
]
// 70:00
#sslide[
#side-by-side[Linear regression loss function was quadratic with one minima][#cimage("figures/lecture_4/quadratic_parameter_space.png", height: 35%)] #pause
With a neural network, this is our loss function
$ cal(L)(x, y, bold(theta)) =
underbrace((sigma(theta_0 + theta_1 x) - y), "Nonlinear function of" theta)
underbrace((sigma(theta_0 + theta_1 x) - y), "Nonlinear function of" theta) $ #pause
*Question:* How many minima does this function have? #pause
*Answer:* We do not know
]
#sslide[
The nonlinearity/activation function $sigma$ in the neural network means we cannot find an analytical solution #pause
$ f(x, bold(theta)) = sigma(theta_0 + theta_1 x) $ #pause
*Question:* Can we remove the activation function $sigma$? #pause
*Answer:* Yes, but the result is linear regression #pause
$ f(x, bold(theta)) = theta_0 + theta_1 x $ #pause
Activation functions make the neural network powerful
]
#sslide[
Linear regression: analytical solution for $bold(theta)$ #pause
Neural network: no analytical solution for $bold(theta)$ #pause
So how to find $bold(theta)$ for a neural network?
]
#aslide(ag, 4)
#aslide(ag, 5)
#sslide[
To find $bold(theta)$ for a neural network, we use *gradient descent* #pause
Gradient descent optimizes *differentiable* functions #pause
We must be able to take the derivative or gradient of the loss function to use gradient descent #pause
How does gradient descent work?
]
#sslide[
#side-by-side[A differentiable loss function produces a manifold][#cimage("figures/lecture_4/parameter_space.png", height: 70%)] #pause
Our goal is to find the lowest point on this manifold #pause
The lowest point solves $argmin_bold(theta) cal(L)(bold(X), bold(Y), bold(theta))$
]
#sslide[
*Note:* Gradient descent provides a *local* optima, not necessarily a *global* optima #pause
#align(center, local_optima_plot) #pause
In practice, a local optima provides a good enough model
]
#focus-slide[Relax]
#sslide[
Let us define gradient descent without math #pause
You are on the top of a mountain and there is lightning storm #pause
#cimage("figures/lecture_4/lightning.jpg", height: 60%) #pause
For safety, you should walk down the mountain to escape the lightning
]
#sslide[
But you do not know the path down! #pause
#cimage("figures/lecture_4/hiking_slope.jpg", height: 70%)
You see this, which way do you walk next?
]
#sslide[
#cimage("figures/lecture_4/hiking_slope.jpg", height: 80%)
This is gradient descent
]
#sslide[
In gradient descent, we look at the *slope* of the loss function #pause
And we walk in the steepest direction #pause
#cimage("figures/lecture_4/gradient_descent_3d.png", height: 60%) #pause
And then we repeat
]
#sslide[
#cimage("figures/lecture_4/gradient_descent_3d.png", height: 70%) #pause
We find the gradient $gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta))$ #pause
And update $bold(theta)$ in the steepest direction
]
#sslide[
#cimage("figures/lecture_4/gradient_descent_3d.png", height: 70%)
Eventually, we arrive at the bottom
]
#sslide[
With gradient descent, the loss function must be differentiable #pause
If we cannot compute the derivative/gradient, then we do not know which way to walk!
]
#sslide[
The gradient descent algorithm:
#algorithm({
import algorithmic: *
Function("Gradient Descent", args: ($bold(X)$, $bold(Y)$, $cal(L)$, $t$, $alpha$), {
Cmt[Randomly initialize parameters]
Assign[$bold(theta)$][$cal(N)(0, 1)$]
For(cond: $i in 1 dots t$, {
Cmt[Compute the gradient of the loss]
Assign[$bold(J)$][$gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta))$]
Cmt[Update the parameters using the negative gradient]
Assign[$bold(theta)$][$bold(theta) - alpha bold(J)$]
})
Return[$bold(theta)$]
})
})
]
// 84:00
#sslide[
#cimage("figures/lecture_4/parameter_space.png", height: 100%)
]
#sslide[
Two main steps in gradient descent: #pause
Step 1: Compute the gradient of the loss #pause
Step 2: Update the parameters using the gradient #pause
Let us start with step 1
]
#aslide(ag, 5)
#aslide(ag, 6)
#sslide[
*Goal:* Compute the gradient of the loss $gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta))$ #pause
We call this process *backpropagation* #pause
We propagate errors from the loss function *backward* through each layer of the neural network #pause
#cimage("figures/lecture_1/optimizer_nn.png")
//Let us propagate errors through a deep neural network
]
#sslide[
Forward propagation
#cimage("figures/lecture_4/forward.svg", height: 80%)
]
#sslide[
Backward propagation
#cimage("figures/lecture_4/backward.svg", height: 80%)
]
#sslide[
Finding the gradient is necessary to use gradient descent! #pause
First, we will find the gradient of a neural network layer #pause
Then, we will find the gradient of a deep neural network #pause
Finally, we will find the gradient of the loss function
]
#sslide[
Start with the equation of a neural network layer
$ f(bold(x), bold(theta)) = sigma( bold(theta)^top overline(bold(x)) ) $ #pause
Take the gradient of both sides
$ gradient_bold(theta) f(bold(x), bold(theta)) = gradient_bold(theta) sigma( bold(theta)^top overline(bold(x)) ) $ #pause
$ "Chain: " d / (d x) f(g(x)) = f'(g(x)) dot g'(x) $ #pause
$ gradient_(bold(theta)) f(bold(x), bold(theta)) = gradient_bold(theta) [sigma] (bold(theta)^top overline(bold(x))) dot gradient_(bold(theta)) (bold(theta)^top overline(bold(x))) $
]
#sslide[
$ gradient_(bold(theta)) f(bold(x), bold(theta)) = gradient_bold(theta) [sigma] (bold(theta)^top overline(bold(x))) dot gradient_(bold(theta)) (bold(theta)^top overline(bold(x))) $
$ "What is " gradient_bold(theta) sigma "?" $ #pause
#cimage("figures/lecture_4/heaviside.svg") #pause
Derivative is zero everywhere and infinity at $x=0$, so the derivative for a layer is either infinity or zero
]
#sslide[
We use a differentiable approximation of the heaviside step function #pause
$ sigma(z) = 1 / (1 + e^(-z)) $ #pause
We call this approximation the *sigmoid function* #pause
#side-by-side[#cimage("figures/lecture_4/heaviside.svg")][#cimage("figures/lecture_4/sigmoid.svg")]
The sigmoid function has finite and nonzero derivative everywhere
]
#sslide[
#side-by-side[#cimage("figures/lecture_4/heaviside.svg")][#cimage("figures/lecture_4/sigmoid.svg")][ $ sigma(z) = 1 / (1 + e^(-z)) $]
The derivative of the sigmoid function is
$ d / (d z) sigma(z) = sigma(z) dot (1 - sigma(z)) $ #pause
$ gradient_bold(z) sigma(bold(z)) = sigma(bold(z)) dot.circle (1 - sigma(bold(z))) $
]
// 97:00
#sslide[
Back to our layer #pause
$ gradient_(bold(theta)) f(bold(x), bold(theta)) = gradient_bold(theta) [sigma] (bold(theta)^top overline(bold(x))) dot gradient_(bold(theta)) (bold(theta)^top overline(bold(x))) $ #pause
Plug in the gradient of our new activation function
$ gradient_bold(z) sigma(bold(z)) = sigma(bold(z)) dot.circle (1 - sigma(bold(z))) $ #pause
$ gradient_(bold(theta)) f(bold(x), bold(theta)) = (sigma(bold(theta)^top overline(bold(x))) dot.circle (1 - sigma(bold(theta)^top overline(bold(x))))) gradient_(bold(theta)) (bold(theta)^top overline(bold(x))) $ #pause
Evalute the final term #pause
$ gradient_(bold(theta)) f(bold(x), bold(theta)) = (sigma(bold(theta)^top overline(bold(x))) dot.circle (1 - sigma(bold(theta)^top overline(bold(x))))) overline(bold(x))^top $
]
#sslide[
$ gradient_(bold(theta)) f(bold(x), bold(theta)) = (sigma(bold(theta)^top overline(bold(x))) dot.circle (1 - sigma(bold(theta)^top overline(bold(x))))) overline(bold(x))^top $ #pause
This is the gradient for the layer of a neural network! #pause
We will use this to compute the gradient of a deep neural network
]
#sslide[
Recall the deep neural network has many layers
$ f_1(bold(x), bold(phi)) = sigma(bold(phi)^top overline(bold(x))) quad
f_2(bold(x), bold(psi)) = sigma(bold(psi)^top overline(bold(x))) quad
dots quad
f_(ell)(bold(x), bold(xi)) = sigma(bold(xi)^top overline(bold(x))) $ #pause
And that we call them in series
$ bold(z)_1 &= f_1(bold(x), bold(phi)) \
bold(z)_2 &= f_2(bold(z)_1, bold(psi)) \
dots.v \
bold(z)_(ell) &= f_(ell)(bold(z)_(ell - 1), bold(xi))
$ #pause
//$ f(bold(x), bold(theta)) = f_(ell) (dots f_2(f_1(bold(x), bold(phi)), bold(psi)) dots bold(xi) ) $
]
#sslide[
#side-by-side[Take the gradient of both sides][
$ gradient_(bold(phi), bold(psi), dots, bold(xi)) bold(z)_1 &= gradient_(bold(phi), bold(psi), bold(xi)) f_1(bold(x), bold(phi)) \
gradient_(bold(phi), bold(psi), dots, bold(xi)) bold(z)_2 &= gradient_(bold(phi), bold(psi), bold(xi)) f_2(bold(z)_1, bold(psi)) \
dots.v \
gradient_(bold(phi), bold(psi), dots, bold(xi)) bold(z)_(ell) &= gradient_(bold(phi), bold(psi), bold(xi)) f_(ell)(bold(z)_(ell - 1), bold(xi))
$] #pause
#v(1em)
#side-by-side[Each layer only uses one set of parameters][
$ gradient_(bold(phi)) bold(z)_1 &= gradient_(bold(phi)) f_1(bold(x), bold(phi)) \
gradient_(bold(psi)) bold(z)_2 &= gradient_(bold(psi)) f_2(bold(z)_1, bold(psi)) \
dots.v \
gradient_(bold(xi)) bold(z)_(ell) &= gradient_(bold(xi)) f_(ell)(bold(z)_(ell - 1), bold(xi))
$] #pause
]
#sslide[
The gradient of a deep neural network is
$
gradient_(bold(theta)) f(bold(x), bold(theta)) = gradient_(bold(phi), bold(psi), dots, bold(xi)) f(bold(x), mat(bold(phi), bold(psi), dots, bold(xi))^top) = vec(
gradient_bold(phi) f_1(bold(x), bold(phi)),
gradient_(bold(psi)) f_2(bold(z)_1, bold(psi)),
dots.v,
gradient_(bold(xi)) f_(ell)(bold(z)_(ell - 1), bold(xi))
)
$ #pause
Where each layer gradient is
$ gradient_(bold(xi)) f_ell (bold(z)_(ell - 1), bold(xi)) = (sigma(bold(xi)^top overline(bold(z))_(ell - 1)) dot.circle (1 - sigma(bold(xi)^top overline(bold(z))_(ell - 1)))) overline(bold(z))_(ell - 1)^top $
]
#sslide[
We computed the gradient of a neural network layer #pause
We computed the gradient of the neural network #pause
Now, we must compute gradient of the loss function #pause
]
#sslide[
$ cal(L)(bold(X), bold(Y), bold(theta)) = sum_(i = 1)^n (f(bold(x)_[i], bold(theta)) - bold(y)_[i])^2 $
$ gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) = gradient_bold(theta) sum_(i = 1)^n (f(bold(x)_[i], bold(theta)) - bold(y)_[i])^2 $ #pause
//Use the sum rule $d / (d x) (f(x) + g(x)) = f'(x) + g'(x)$
$ gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) = sum_(i = 1)^n gradient_bold(theta) ( f(bold(x)_[i], bold(theta)) - bold(y)_[i] )^2 $ #pause
$ gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) = sum_(i = 1)^n 2 ( f(bold(x)_[i], bold(theta)) - bold(y)_[i]) gradient_bold(theta) f(bold(x)_[i], bold(theta)) $
]
#sslide[
To summarize: #pause
$ gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) = sum_(i = 1)^n 2 ( f(bold(x)_[i], bold(theta)) - bold(y)_[i]) #redm[$gradient_bold(theta) f(bold(x)_[i], bold(theta))$]
$ #pause
$
#redm[$gradient_(bold(theta)) f(bold(x), bold(theta))$] = gradient_(bold(phi), bold(psi), dots, bold(xi)) f(bold(x), mat(bold(phi), bold(psi), dots, bold(xi))^top) = vec(
gradient_bold(phi) f_1(bold(x), bold(phi)),
gradient_(bold(psi)) f_2(bold(z)_1, bold(psi)),
dots.v,
#redm[$gradient_(bold(xi)) f_(ell)(bold(z)_(ell - 1), bold(xi))$]
)
$ #pause
$ #redm[$gradient_(bold(xi)) f_ell (bold(z)_(ell - 1), bold(xi))$] = (sigma(bold(xi)^top overline(bold(z))_(ell - 1)) dot.circle (1 - sigma(bold(xi)^top overline(bold(z))_(ell - 1)))) overline(bold(z))_(ell - 1)^top $
]
#sslide[
*Question:* Why did we spend all this time deriving gradients? #pause
*Answer:* The gradient is necessary for gradient descent #pause
#algorithm({
import algorithmic: *
For(cond: $i in 1 dots t$, {
Cmt[Compute the gradient of the loss]
Assign[$bold(J)$][$gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta))$]
Cmt[Update the parameters using the negative gradient]
Assign[$bold(theta)$][$bold(theta) - alpha bold(J)$]
})
}) #pause
$ bold(theta)_(t + 1) = bold(theta)_t - alpha gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)_t) $
]
#aslide(ag, 6)
#aslide(ag, 7)
#slide[
How do gradients work in `jax` or `torch`? #pause
The libraries compute the gradients using *autograd* #pause
Autograd differentiates nested functions using the chain rule #pause
$ gradient_bold(theta) f(g(h(x, bold(theta)))) = f'(g(h(x, bold(theta)))) dot g'(h(x, bold(theta))) dot h'(x, bold(theta)) $ #pause
Engineers derived gradients for hundreds of functions $f, g, h, dots$ #pause
Researchers derive their own analytical gradients like we did today #pause
Now, let us look at `jax` and `torch` optimization code
]
#slide[
```python
import jax
def L(theta, X, Y):
...
# Create a new function that is the gradient of L
# Then compute gradient of L for given inputs
J = jax.grad(L)(X, Y, theta)
# Update parameters
alpha = 0.0001
theta = theta - alpha * J
```
]
#slide[
```python
import torch
optimizer = torch.optim.SGD(lr=0.0001)
def L(model, X, Y):
...
# Pytorch will record a graph of all operations
# Everytime you do theta @ x, it stores inputs and outputs
loss = L(X, Y, model) # compute gradient
# Traverse the graph backward and compute the gradient
loss.backward() # Sets .grad attribute on each parameter
optimizer.step() # Update the parameters using .grad
optimizer.zero_grad() # Set .grad to zero, DO NOT FORGET!!
```
]
#slide[
Time for some interactive coding
https://colab.research.google.com/drive/1W8WVZ8n_9yJCcOqkPVURp_wJUx3EQc5w
] |
|
https://github.com/jneug/typst-ccicons | https://raw.githubusercontent.com/jneug/typst-ccicons/main/src/utils.typ | typst | MIT License |
#let _typst-link = link
#let _ccicon-formats = (
icon: (
"by",
"cc",
"logo",
"nc",
"nceu",
"ncjp",
"nd",
"pd",
"remix",
"sa",
"sampling",
"sampling.plus",
"share",
"zero",
),
shield: (
"cc-by-nc-nd",
"cc-by-nc-sa",
"cc-by-nc",
"cc-by-nd",
"cc-by-sa",
"cc-by",
"cc-pd",
"cc-zero",
),
badge: (
"cc-by-nc-nd",
"cc-by-nc-sa",
"cc-by-nc",
"cc-by-nceu",
"cc-by-nceu-nd",
"cc-by-nceu-sa",
"cc-by-nd",
"cc-by-sa",
"cc-by",
"cc-pd",
"cc-zero",
),
)
#let _ccicon-aliases = (
cc-logo: "logo",
cc-by-nc-sa-eu: "cc-by-nceu-sa",
cc-by-nc-sa-jp: "cc-by-ncjp-sa",
cc-by-nc-nd-eu: "cc-by-nceu-sa",
cc-by-nc-nd-jp: "cc-by-ncjp-sa",
publicdomain: "pd",
public-domain: "pd",
ccbysa: "cc-by-sa",
ccbynd: "cc-by-nd",
ccbync: "cc-by-nc",
ccbyncsa: "cc-by-nc-sa",
ccbyncnd: "cc-by-nc-nd",
ccbynceusa: "cc-by-nceu-sa",
ccbyncjpsa: "cc-by-ncjp-sa",
ccbyncsaeu: "cc-by-nceu-sa",
ccbyncsajp: "cc-by-ncjp-sa",
ccbynceund: "cc-by-nceu-nd",
ccbyncjpnd: "cc-by-ncjp-nd",
ccbyncndeu: "cc-by-nceu-nd",
ccbyncndjp: "cc-by-ncjp-nd",
)
#let _ccicon-all-keys = _ccicon-formats.icon + _ccicon-formats.shield + _ccicon-formats.badge
_ccicon-all-keys = _ccicon-all-keys.dedup()
#let _cc-colorize(icon-file, fill: black, ..args) = {
let svg-data = read(icon-file)
svg-data = svg-data.replace("<path", "<path style=\"fill:" + fill.to-hex() + "\"").replace(
"<polygon",
"<polygon style=\"fill:" + fill.to-hex() + "\"",
)
return image.decode(..args.named(), svg-data)
}
#let _cc-resolve-name(name) = {
let parts = name.split("/")
let resolved = (
parts.first(),
"icon",
if parts.len() > 1 {
parts.slice(1).join("/")
} else {
""
},
)
parts = resolved.first().split("-")
if parts.last() in ("shield", "badge") {
resolved.at(1) = parts.pop()
resolved.at(0) = parts.join("-")
}
resolved.at(0) = _ccicon-aliases.at(resolved.at(0), default: resolved.at(0))
return resolved
}
#let _cc-parse(name) = {
let cc-info = (
license: "",
parts: (),
version: "4.0",
lang: "en",
format: "icon",
)
let (name, format, version) = _cc-resolve-name(name)
cc-info.license = name
cc-info.parts = name.split("-")
cc-info.format = format
let parts = version.split("/")
while parts.len() > 1 {
if parts.last().position(regex("\d\.\d")) != none {
cc-info.version = parts.pop()
} else {
cc-info.lang = parts.pop()
}
}
return cc-info
}
#let cc-is-valid(name) = {
let (name, fmt, _) = _cc-resolve-name(name)
if fmt == "icon" {
return name in _ccicon-all-keys
} else {
return name in _ccicon-formats.at(fmt)
}
}
#let cc-url(name) = {
let base = "https://creativecommons.org/licenses/"
let cc-info = _cc-parse(name)
if cc-info.parts.first() == "cc" {
let _ = cc-info.parts.remove(0)
}
let url = base + cc-info.parts.join("-") + "/" + cc-info.version
if cc-info.lang not in (auto, "en") {
url += "/deed." + cc-info.lang
}
return url
}
#let cc-icon(name, scale: 1.0, baseline: 5%, format: auto, link: false, fill: auto) = {
let cc-info = _cc-parse(name)
if format in ("icon", "badge", "shield") {
cc-info.format = format
}
let icon
if cc-info.format == "icon" {
icon = cc-info.parts.map(name => box(context _cc-colorize(
height: .75em * scale,
"assets/svg/icon/" + name + ".svg",
fill: if fill == auto {
text.fill
} else {
fill
},
))).join(
h(1.5pt),
)
} else {
if not cc-info.license.starts-with("cc") {
cc-info.license = "cc-" + cc-info.license
}
icon = image(height: .75em * scale, "assets/svg/" + cc-info.format + "/" + cc-info.license + ".svg")
}
// TODO: Only generate links, if a license page is available
if link != false {
_typst-link(cc-url(name), box(baseline: baseline, icon))
} else {
box(baseline: baseline, icon)
}
}
#let ccicon = cc-icon
|
https://github.com/N4tus/types-for-typst | https://raw.githubusercontent.com/N4tus/types-for-typst/main/README.md | markdown | MIT License | # types-for-typst
A small library for building and checking types in typst.
# Documention
## Check function
- `t_assert(type, value)` panics if the given value is not of the specified type. Returns nothing.
- `t_check(type, value)` checks if the given value if of the specified type and returns `true` if it is
- `t_require(type, value)` panics if the given value is not of the specified type. Returns the value if no panic.
## Primitive Types
- `TBoolean` primtive type
- `TInteger` primtive type
- `TFloat` primtive type
- `TLength` primtive type
- `TAngle` primtive type
- `TRatio` primtive type
- `TRelativeLength` primtive type
- `TFraction` primtive type
- `TColor` primtive type
- `TSymbol` primtive type
- `TString` primtive type
- `TContent` primtive type
- `TFunction` primtive type
## Other predifined Types
- `TAny` allows everything
- `TNone` none literal
- `TNumber` or combination of `TInteger` and `TFloat`
- `TLit(lit)` literal type. Allowes only the given literal as type.
- `TMap(values)` generic map from string to `value`
- `TDict(..fields)` generic dictionary with the given fields. Only named fields are allowed
- `TArray(values)` generic array with zero or more values of one type
- `TTuple(..elemn)` generic tuple of exact size. Only positional fields are allowed
## Other functions
- `t_or(..types)` constructs a union type of all given types
- `optional(type)` used to make a dictionary field optional
# Example
```typ
#import "types_for_typst.typ": *
#t_assert(TInteger, 7)
#t_assert(TNumber, 4.2)
#t_assert(TArray(TString), ())
#t_assert(TArray(TString), ("Test",))
#t_check(TArray(TNumber), (4.7, 1, "Test"))
#t_check(TArray(TString), ("Test", 8))
#t_check(TDict(test: TNumber, name: TString, sym: optional(TSymbol)), (test: "d", name: [OK], extra: 42))
#t_assert(TTuple(TNumber, TString, TDict(r: TRatio, num: TNumber)), (42, "LUL", (r: 50%, num: 8)))
#t_check(TMap(t_or(TString, TContent)), (l: "OK", b: [sdf], c: 8))
#t_assert(t_or(TLit("mon"), TLit("two"), TLit("three"), TLit(42)), 42)
```
|
https://github.com/pride7/Typst-callout | https://raw.githubusercontent.com/pride7/Typst-callout/main/callout.typ | typst | #import "configure.typ": configure
#let callout(
type: "note",
title: none,
icon: true,
width: 100%,
height: auto,
body
) = {
let (logo, box-color, title-color) = (
configure.at(type).logo,
configure.at(type).box-color,
configure.at(type).title-color
)
block(
width: width,
height: height,
fill: box-color,
inset: 8pt,
radius: 4pt,
stroke: (left: 0.2em+title-color)
)[
#if title != none {
if icon == true {
grid(
columns: 2,
column-gutter: 1.4em,
rows: 1,
place(
center+horizon,
dx: 0.5em,
image(logo, width: 1.3em),
),
text(
fill: title-color,
weight: "bold",
size: 1.3em
)[#title]
)} else {
grid(
columns: 1,
text(
fill: title-color,
weight: "bold",
size: 1.3em
)[#title]
)
}
}
#body
]
}
#callout[#lorem(50)]
|
|
https://github.com/Chwiggy/thesis_bachelor | https://raw.githubusercontent.com/Chwiggy/thesis_bachelor/main/src/appendices/01_aknowledgements.typ | typst | #import "../preamble.typ": *
= Aknowledgements
Thanks to the people at HeiGIT gGmbh for supporting this thesis, specifically <NAME> and <NAME> for guiding me through this project and asking valuable questions. This thanks also extends to the provison of computing resources.
Thanks as well to my life partners Aada and Lillian for invaluable coding advice and a shoulder to cry on.
Part of the resources and ideas for this thesis where gathered at an industry summer school financed by the _Verband Deutscher Verkehrsunternehmen_ (VDV) a lobby group of german public transport companies. This includes accommodations and food in the order of 2000 €
But also free access to resources like VDV training material like @pieper_kreislauf_2021.
<end_of_chapter>
#locate(loc => bib_state.at(query(<end_of_chapter>, loc).first().location())) |
|
https://github.com/EunTilofy/NumComputationalMethods | https://raw.githubusercontent.com/EunTilofy/NumComputationalMethods/main/Chapter8/Chapter8-1.typ | typst | #import "../template.typ": *
#show: project.with(
course: "Computing Method",
title: "Computing Method - Chapter8-1",
date: "2024.5.13",
authors: "<NAME>, 3210106357",
has_cover: false
)
*Problems:1,2,4,5*
#HWProb(name: "1")[
用 Jacobi 迭代法,Gauss-Seidel 迭代法和取 $omega = 1.46$ 的超松弛迭代法解方程组(误差为 $0.5 times 10^(-4)$)
$
cases(
2x_1 - x_2 = 1\
-x_1+2x_2-x_3 = 0\
-x_2+2x_3-x_4 = 1\
-x_3+2x_4=0
)
$
并写出相应的迭代矩阵。若取最优松弛因子计算,结果如何?
]
#solution[
$
A = bmatrix(2,-1,0,0;-1,2,-1,0;0,-1,2,-1;0,0,-1,2).
$
#set enum(numbering :"(1)")
+ Jacobi 迭代法:
$
T_j = -bmatrix(0,-1/2,0,0;-1/2,0,-1/2,0;0,-1/2,0,-1/2;0,0,-1/2,0), cm = [1/2,0,1/2,0]^T,xm^((0))=[0,0,0,0]^T,xm^((k+1))=T_j xm^((k))+cm,k in bb(N)^+
$
```python
import numpy as np
eps = 5e-5
def iter(x0, T, c):
x1 = T @ x0 + c
k = 1
while np.linalg.norm(x0 - x1, ord=np.inf) > eps:
x0 = x1
x1 = T @ x0 + c
k = k + 1
print("k = ", k)
return x1
Tj = - np.array([[0,-1/2,0,0],[-1/2,0,-1/2,0],[0,-1/2,0,-1/2],[0,0,-1/2,0]])
c = np.array([1/2,0,1/2,0])
x0 = np.array([0,0,0,0])
c = c.transpose()
x0 = x0.transpose()
print(iter(x0, Tj, c))
```
求解结果为:$xm^((46)) = [1.19993889 1.39992001 1.59990113 0.79995056]^T$。
+ Gauss-Seidel 迭代法:
```python
D_L = np.array([[2,0,0,0],[-1,2,0,0],[0,-1,2,0],[0,0,-1,2]])
U = -np.array([[0,-1,0,0],[0,0,-1,0],[0,0,0,-1],[0,0,0,0]])
T = np.linalg.inv(D_L) @ U
print ("T = ", T)
c = np.linalg.inv(D_L) @ np.array([1,0,1,0])
print("x = ", iter(x0, T, c))
```
$
T_(G S) = -bmatrix(0, 0.5, 0, 0;
0, 0.25, 0.5, 0;
0, 0.125, 0.25, 0.5;
0, 0.0625, 0.125, 0.25), cm = [0.5,0.25,0.625,0.3125]^T,xm^((0))=[0,0,0,0]^T,xm^((k+1))=T_j xm^((k))+cm,k in bb(N)^+
$
求解结果为:$xm^((24)) = [1.19994696 1.39993057 1.59994383 0.79997191]^T$。
+ SOR 迭代法:
```python
U = -np.array([[0,-1,0,0],[0,0,-1,0],[0,0,0,-1],[0,0,0,0]])
L = -np.array([[0,0,0,0],[-1,0,0,0],[0,-1,0,0],[0,0,-1,0]])
D = np.array([[2,0,0,0],[0,2,0,0],[0,0,2,0],[0,0,0,2]])
b = np.array([1,0,1,0])
x0 = np.array([0,0,0,0])
w = 1.46
T = np.linalg.inv(D - w*L) @ (w * U + (1-w) * D)
c = w * np.linalg.inv(D - w * L) @ b
print ("T = ", T)
print ("c = ", c)
print("x = ", iter(x0, T, c))
```
$
T_(S O R) = bmatrix(-0.46, 0.73, 0, 0; -0.3358,0.0729,0.73,0; -0.245134,0.053217,0.0729,0.73;-0.17894782,0.03884841,0.053217,0.0729), c = [0.73 , 0.5329 , 1.119017 ,0.81688241]^T
$
最优松弛因子:$omega_(o p t) = 2/(1+sqrt(1- rho(T_j)^2)) approx 1.25961618$。\
取 $omega = 1.46$ 时,求解结果为:$xm^(15) = [1.19999113, 1.40000495, 1.60000927, 0.80000289]^T$;\
取 $omega = 1.26$ (最优松弛因子)时,求解结果为:$xm^(11) = [1.19998703,1.39998917,1.59999415,0.79999811]^T$
]
#HWProb(name:"2")[
设有系数矩阵
$
A = bmatrix(1,2,-2;1,1,1;2,2,1), B = bmatrix(2,-1,1;1,1,1;1,1,-2)
$
证明:(1) 对系数矩阵 $A$,Jacobi 迭代法收敛,而 Gauss-Seidel 迭代法不收敛。\
(2) 对系数矩阵 $B$,Jacobi 迭代法不熟练,而 Gauss-Seidel 迭代法收敛。
]
#Proof[
通过以下代码计算 $A, B$ 两个系数矩阵的谱半径:
```python
def getLDU(A, n):
L = np.zeros(np.shape(A))
D = np.zeros(np.shape(A))
U = np.zeros(np.shape(A))
for i in range(0, n):
for j in range(0, n):
if(i < j):
U[i][j] = -A[i][j]
if(i > j):
L[i][j] = -A[i][j]
if(i == j):
D[i][j] = A[i][j]
return [L,D,U]
def rho(A):
return np.max(np.abs(np.linalg.eigvals(A)))
def Tj(A, n):
[L, D, U] = getLDU(A, n)
return np.linalg.inv(D) @ (L + U)
def TGS(A, n):
[L, D, U] = getLDU(A, n)
return np.linalg.inv(D - L) @ U
A = np.array([[1,2,-2],[1,1,1],[2,2,1]])
B = np.array([[2,-1,1],[1,1,1],[1,1,-2]])
print("rho(Tj(A)) = ", rho(Tj(A, 3)), ", rho(TGS(A)) = ", rho(TGS(A, 3)))
print("rho(Tj(B)) = ", rho(Tj(B, 3)), ", rho(TGS(B)) = ", rho(TGS(B, 3)))
```
输出:
```plain
rho(Tj(A)) = 3.759933925918774e-06 , rho(TGS(A)) = 2.0
rho(Tj(B)) = 1.1180339887498942 , rho(TGS(B)) = 0.5
```
#set enum(numbering : "(1)")
+ 对于 $A$,Jacobi 迭代矩阵的谱半径小于 1,而 GS 迭代矩阵的谱半径大于 1;
+ 对于 $B$,Jacobi 迭代矩阵的谱半径大于 1,而 GS 迭代矩阵的谱半径小于 1;
根据定理8.1,可以得到结论。
]
#HWProb(name:"4")[
设有系数矩阵
$
A = bmatrix(a,1,3;1,a,2;-3,2,a)
$
问:$a$ 取什么值时,Jacobi 迭代法收敛? $a$ 取什么值时,Gauss-Seidel 迭代法收敛?$a=3$ 时又怎样?并比较谱半径。
]
#solution[
$
T_j = 1/a bmatrix(0, 1, 3;1,0,2;-3,2,0) arrow.double lambda_(1,2,3) = 0, pm 2/a
$
所以 $abs(a) > 2$ 时,Jacobi 迭代法收敛。
$
T_(G S) = bmatrix(0, -1/a, -3/a; 0, 1/a^2, 3/a^2 - 2/a; 0, -3/a^2-2/a^3, -5/a^2-6/a^3)
$
当 $a in (-1.817, 2.862)$ 时,GS 迭代法收敛。
$a = 3$ 时,使用 $vb("2")$ 的代码计算得到两种迭代方法的谱半径分别为 0.6667 和 0.9107。
]
#HWProb(name:"5")[
设 $A in R^(n times n)$,对称正定,其最小特征值和最大特征值分别是 $lambda_n, lambda_1$。试证迭代法
$
x^(k+1) = x^(k) + alpha (b - A x^(k))
$
收敛的充分必要条件是 $0 < alpha < 2 \/ lambda_1$。
又问参数取何值时迭代矩阵的谱半径最小?
]
#Proof[\
迭代矩阵a 为 $I - alpha A$,所以迭代矩阵的谱半径为 $max (abs(1 - alpha lambda_1), abs(1 - alpha lambda_n))$。令其小于 1,得到 $0 < alpha < 2\/lambda_1$。由图像得,
当 $1 - alpha lambda_n = alpha lambda_1 - 1$,即 $alpha = 2/(lambda_1 + lambda_n)$ 时,迭代矩阵的谱半径最小。
] |
|
https://github.com/devraza/warehouse | https://raw.githubusercontent.com/devraza/warehouse/main/blog/setting-up-zola-nixos.typ | typst | MIT License | #import "template.typ": conf
#show: doc => conf(
title: [ Setting up Zola on NixOS ],
doc,
)
= Introduction
#link("https://getzola.org")[Zola] is a static site generator
\(similarly to the infamous #link("https://gohugo.io")[Hugo];, which you
may have already heard of) and is written in Rust. It also happens to be
the framework that this site is built on!
This blog post is a guide on setting up the site engine on NixOS
specifically.
= Installation
== Installing the package
`zola` is packaged in the nix package repository, so you just
declaratively add the package to your configuration as usual: For the
purposes of this guide, zola can be installed either as a system or user
package.
As a system package:
```nix
{ pkgs, ... }: {
# ...
environment.systemPackages = with pkgs; [
zola # Append the package name to the list
];
# ...
}
```
As a user package (with home-manager):
```nix
{ pkgs, ... }: {
# ...
home.packages = with pkgs; [
zola # Append the package name to the list
];
# ...
}
```
Now that `zola` itself is installed, we can move on setting up the pages
it serves - continue reading…
== Setting up a theme
Zola actually has a section of its website showcasing several
community-made themes which you can choose from to be the theme for your
static site #link("https://getzola.org/themes/")[here];.
Simply choose a theme that you like \(demos are usually available for
each theme listed) and follow its appropriate documentation to set it up - this site uses a version of the #link("https://www.getzola.org/themes/serene/")[serene theme] with my custom colours.
You can also make your own theme if
that better suits you \(I recommend giving the
#link("https://getzola.org/documentation")[documentation] a read if so).
== Setting up NGINX
After selecting a theme \(or making your own) you should now have a
directory somewhere on your server containing your static site. For the
following snippet, we’ll assume this is at `/var/lib/blog`.
#link("https://nginx.com")[NGINX] is a popular webserver which we’re
going to use for the purposes of hosting and serving our site. To do so,
append the following somewhere in your configuration:
```nix
# ...
{
# ...
services.nginx = {
enable = true;
virtualHosts = {
"blog" = {
forceSSL = true;
serverName = "blog.devraza.duckdns.org";
root = "/var/lib/blog/public";
};
};
};
# ...
}
```
Obviously, you'll want to change any of the values to better accomodate your needs.
= Finishing up
You should now have your own static site built with Zola! You can use
this for a bunch of things, like:
- Your personal blog (as I’ve done)
- A way to showcase your projects #link("https://blog.devraza.duckdns.org/projects")[(as I’ve also done)]
- Hosting documentation (check out #link("https://www.getzola.org/themes/adidoks/")[this Zola theme])
=== Help, my changes aren't sticking!
When you make new markdown files \(or any other changes to the structure of your
site), remember to run `zola build` in your site directory
\(`/var/lib/blog`) for the changes to #emph[build] into the actual site.
|
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/common-tools/router_table.typ | typst | #import "/meta-environments/env-features.typ": *
= Router Table
The router table can be used to profile an edge of a workpiece, or cut a channel in the face of a board.
== Notes
=== Safety
Always pass the workpiece across the bit from the right to the left.
#safety_hazard_box([DO NOT let the workpiece pass between the fence and the bit.
If the workpiece passes between the fence and the bit, the workpiece is likely to catch on the bit and be kicked violently off of the table into the shop, possibly causing injury or damage.
])
// === Care
== Parts of the Router Table
=== Full View
#figure(
image("images/router_table-full_view-annotated.png", width: 100%),
caption: [
An annotated full view of the router table.
],
)
=== Lift Assembly
#figure(
image("images/router_table-height_adjust-annotated.png", width: 100%),
caption: [
The router table lift assembly, with lifting arm inserted.
],
)<router-table-height-adjust>
=== On/Off Switch
Use the *green button* to turn on the machine.
Use the *red paddle* to turn off the machine.
The red paddle acts as the emergency stop button on the router table.
=== Throat Plate
The through plate sits in the router opening in table, and supports the material as it gets close to the bit.
There are several throat plates available in the Router Table Kit that work with router bits of varying sizes.
Use a throat plate that is as close to the size of the router bit as possible while allowing the router bit to freely turn within the throat plate.
=== Lifting Arm
Use the router lifting arm for large adjustments in the height of the router.
The lifting arm is keyed to the lifting assembly within the table.
See @adjusting-router_bit_height for instructions on using the lifting arm.
=== Fine Height Adjustment Dial
The fine height adjustment dial raises and lowers the router very slowly.
Use the fine adjustment tool to dial in the router bit height for fine work.
=== Collet
The collet accepts the shaft of the bit.
Tightening the collet will lock the bit into place.
Always tighten the collet *very firmly* before turning on the router.
=== Bit
The bit spins against the workpiece to remove material.
There are many kinds and shapes of bits for treating edges: bits are available to chamfer or round edges, cut rabbets, make ogee cuts, or even complicated geometries for sash work.
Router bits are also available to cut channels (straight, sliding dovetails, etc.).
A set of various router bits is available at the front desk for member use.
=== Bearing
Some bits have a bearing at the top of the bit.
The bearing acts as a stop, and limits the depth of cut.
Test the bit with scrap material to make sure that the workpiece properly engages with the bearing.
=== Fence
The fence can be set as a reference surface on the router table.
The fence can be set in line with the bit to limit the depth of cut when using bits that do not have a bearing.
The fence can also be set to precisely cut a channel in a workpiece.
=== Shop Vac
The router table has a dedicated shop vac for dust collection.
In normal use, the shop vac hose is connected to the port on the back of the fence.
The hose can be removed to help pick up chips and dust on the floor around the router table.
Always reattach the shop vac hose to the router fence after cleaning the area.
== Basic Operation
=== Setting Up
Checkout the Router Table Kit from the front desk.
If you do not have your own router bits, checkout the router bit set from the front desk.
Lift the router to its highest position:
// Kudos to <NAME>. for assistance in puzzling this one out! -PGM
+ Stand in front of the router table. \
_ Face the side of the table that has the power switch._
+ Insert lifting arm.\
_The lifting arm is stored in a tube attached to the top of the Router Table Kit._
+ Rotate the lifting arm so that the black rubber handle is parallel to the track, pointing to the left, as shown in @router-table-height-adjust.
+ Push down the lifting arm to engage it with the lifter.
+ Rotate the lifting arm 90° clockwise, so that the black rubber handle is pointing away from you.
+ Pull up on the lifting arm to raise the router to its highest position. \
_The router may already be in its highest position._
Secure the bit in the router:
+ Attach an appropriate collet (1/4" or 1/2") for the bit in use. \
_Both collets should be in the Router Table Kit._
+ Place bit in collet.\
_If any coatings are present on the bit, ensure that the collet is not in contact with the coating. The collet should be making firm contact with only the metal shaft of the bit._
// ??? Illustrate this?
+ Tighten the collet.\
_Use the wrenches in the Router Table Kit._
Insert the throat plate:
+ Lower the router using the lift arm.
+ Insert the appropriate throat plate for the bit in use.\
_Various throat plates are available in the Router Table Kit._
+ Raise the router such that the router bit is at an appropriate cutting height.\
_Make sure there is clearance between the router bit and the throat plate._
Release the lifting arm:
+ Rotate the lifting arm 90° counter-clockwise to release the lifting arm.
+ Remove the lifting arm from the router table.
Set up and clear the table:
- If using the fence to register your workpiece, securely lock the fence in place to make sure it does not move during a cut.
- Clear away any setup tools (lifting arm, Allen wrench, collet wrenches) off of the table and put them back in the kit.
=== Adjusting the Bit Height
<adjusting-router_bit_height>
// Illustrate these things?
The lifting arm can be used for large adjustments of the bit height:
+ Stand in front of the router table. \
_ Face the side of the table that has the power switch._
+ Insert lifting arm.\
_The lifting arm is stored in a tube attached to the top of the Router Table Kit._
+ Rotate the lifting arm so that the black rubber handle is parallel to the track, pointing to the left, as shown in @router-table-height-adjust.
+ Push down the lifting arm to engage it with the lifter.
+ Rotate the lifting arm 90° clockwise, so that the black rubber handle is pointing away from you.
+ Pull up or push down on the lifting arm to change the router position. \
_This takes a good amount of force._
+ Rotate the lifting arm 90° counter-clockwise to release the lifting arm.
+ Remove the lifting arm from the router table.
Make fine adjustments to the bit height with the fine adjustment dial:
+ Unlock the fine adjustment dial.\
_The appropriate Allen wrench is included in the Router Table Kit._
+ Adjust the bit height.
+ Lock the fine adjustment dial.
=== Workholding
The workpiece must be held down firmly against the table at all times.
The workpiece is held against the fence or a bearing on the bit.
Make sure the fence is firmly held down against the table.
Test fit the workpiece (or appropriate scrap) to make sure the workpiece will properly register against the bearing or the fence.
#warning([DO NOT let the workpiece pass between the fence and the bit. The workpiece may catch on the bit and be violently ejected from the router table.])
=== Making the Cut
+ Attach the shop vac to the router table fence, if needed.
+ Turn on the shop vac.
+ Make sure the router table is free of any loose materials: cut offs, tools, etc.
+ Using push pads to keep your hands clear of the bit, pass the workpiece across the bit, moving the workpiece from right to left.
- If you are profiling an edge, keep the working edge pressed firmly against either the bit bearing or the fence during the pass.
- If you are making a channel cut, keep the workpiece pressed firmly against the fence during the pass.
+ Depending on the material and the depth of cut, adjust pressure and speed for a clean cut. \
_Cutoffs and other waste scraps are good for testing router setups with specific materials._
When finished cutting, turn off the router and the shop vac.
=== Cleaning Up
+ Unplug the router table.
+ Remove throat plate and return it to the Router Table Box.
+ Raise the router to its highest position.
+ Loosen the collet with the wrenches in the Router Table Kit.
+ Return the wrenches to the Router Table Kit.
+ Remove the bit from the collet. \
_If you are using a shop bit, return the bit to its case._
+ Put the collet in the Router Table Kit.
+ Sweep up any dust and chips. \
_Disconnect the shop vac to pickup floor sweepings and clean out the track and the fence. Reconnect the shop vac to the fence when finished._
+ Return the Router Table Kit to the front desk.\
_If you borrowed shop router bits, bring them back, too!_
|
|
https://github.com/rabotaem-incorporated/probability-theory-notes | https://raw.githubusercontent.com/rabotaem-incorporated/probability-theory-notes/master/sections/03-characteristic-functions/02-convergence-in-distribution.typ | typst | #import "../../utils/core.typ": *
== Сходимость по распределению
#remind[
$xi_1$, $xi_2$, ... --- сходится по распеределению к $xi$, если
$
lim F_(xi_n) (x) = F_xi (x)
$
во всех точках непрерывности $F_xi$.
]
#notice[
Если $xi$ и $eta$ назависимы, $eta$ непрерывна, то $xi + eta$ --- непрерывная случайная величина.
]
#proof[
$P(xi + eta = x) = P_(xi + eta) ({x}) = integral_RR underbrace(P_eta ({x - y}), =0) dif P_xi (y) = 0$.
]
#lemma[
Если $F_n$ и $F$ --- функции распределения такие, что для любых $a, b in RR$,
$
lim (F_n (b) - F_n (a)) = F(b) - F(a)
$
то $lim F_n (x) = F(x)$ для любого $x in RR$.
]
#proof[
Сущесвуют $a, b$ такие, что $F(a) < eps, F(b) > 1 - eps$. Тогда при больших $n$, $|(F_n (b) - F_n (a)) - (F(b) - F(a))| < eps ==> F_n (b) - F_n (a) > 1 - 3eps ==> F_n (a) < 3eps$.
Возьмем $x in RR$:
$
abs(F_n (x) - F(x)) <= abs((F_n (x) - F_n (a)) - (F (x) - F (a))) + abs(F_n (a)) + abs(F(a)) newline(<) underbrace(abs((F_n (x) - F_n (a)) - (F(x) - F(a))), <eps) + 3 eps + eps.
$
Значит по определению есть предел.
]
#def[
$B$ --- _регулярное множество_ для меры $P_xi$, если $P_xi (Cl B without Int B) = 0$.
]
#th[
$xi$, $xi_1$, $xi_2$, ... --- случайные величины, $F$, $F_1$, $F_2$, ... --- их функции распределения. $phi$, $phi_1$, $phi_2$, ... --- характеристические функции.
Следующие условия равносильны:
1. $xi_n$ сходится к $xi$ по распределению.
2. для любого $U subset RR$ открытого, $liminf P(xi_n in U) >= P(xi in U)$.
3. для любого $A subset RR$ замкнутого, $limsup P(xi_n in A) <= P(xi in A)$.
4. для любого $B subset RR$ регурярного борелевского, $lim P(xi_n in B) = P(xi in B)$.
5. для любого $B subset RR$ регурярного борелевского, $lim E bb(1)_B (xi_n) = E bb(1)_B (xi)$.
6. для любой $f in C(RR)$ непрерывной ограниченной $lim E f(xi_n) = E f(xi)$.
7. $phi_n$ сходится к $phi$ поточечно.
]
#proof[
"Ну тут 3 стрелки содержательные, остальные тривиальщина" --- Храбров.
- "$2 <==> 3$": Пусть $A := RR without U$. Тогда $P(eta in A) = 1 - P(eta in U)$ и
$
limsup P(xi_n in A) = limsup (1 - P(xi_n in U)) = 1 - liminf P(xi_n in U).
$
В 2 и 3 мы знаем, что все выражения в этих равенствах не больше $P(xi in A) = 1 - P(xi in U)$. Понятно, что они следуют друг из друга.
- "$2+3 ==> 4$": Пусть $U = Int B$, $A = Cl B$. Тогда $P(xi in B) = P(xi in U)$ так как
$
P(xi in B) - P(xi in U) = P(xi in B without U) = P_xi (B without U) <= P_xi (A without U) = 0.
$
Тогда
$
P(xi in B) = P(xi in U) <=
liminf P(xi_n in U) <=
liminf P(xi_n in B) <=
limsup P(xi_n in B) newline(<=)
limsup P(xi_n in A) <=
P(xi in A) = P(xi in B).
$
- "$4<==>5$": $E bb(1)_B (eta) = P(bb(1)_B (eta) = 1) = P(eta in B)$, поэтому
$
lim P(xi_n in B) = lim E bb(1)_B (xi_n) = E bb(1)_B (xi) = P(xi in B).
$
- "$6 ==> 7$":
$
phi_n (t) =
E e^(i t xi_n) =
E (cos(t xi_n) + i sin (t xi_n)) =
E cos(t xi_n) + i E sin(t xi_n) --> \
E cos(t xi) + i E sin (t xi) =
E (cos(t xi) + i sin (t xi)) =
E e^(i t xi) =
phi(t).
$
- "$1 ==> 2$": возьмем $U$ открытое. Рассмотрим $U = usb_(k=1)^oo (a_k, b_k]$. Разбить так множество можно: в начале возьмем ячейки $(k, k + 1]$, $k in ZZ$, и возьмем все, что влезли с замыканием. Потом поделим пополам все, что влезли частично, и возьмем их половики. Потом поделим еще раз, снова возьмем все что влезло с замыканием, и так далее. Едиснтвенное, мы потребуем еще одно условие: $P(xi = a_k) = P(xi = b_k) = 0$. К счастью, в любой окрестности любой границы отрезка найдется точка, где вероятность равна 0. Вот возьмем ее: то есть будем отклоняться от каждой границы на $1/4$ длины отрезка, из которого вы выбираем середину, чтобы всегда брать точки, где распределение непрерывно.
Тогда
$
P(xi_n in U) = P(xi_n in usb_(k=1)^oo (a_k, b_k]) >= P(xi_n in usb_(k = 1)^m (a_k, b_k]) = sum_(k=1)^m P(xi_n in (a_k, b_k]) newline(=)
sum_(k=1)^m (F_n (b_k) - F_n (a_k)) newline(==>)
liminf P(xi_n in U) >= liminf sum_(k=1)^m (F_n (b_k) - F_n (a_k)) = sum_(k=1)^m (F(b_k) - F(a_k)) newline(=) P(xi in usb_(k = 1)^m (a_k, b_k]) -->_(m-->oo) P (xi in usb_(k=1)^oo (a_k, b_k]) = P (xi in U).
$
- "$5==>6$":
Пусть
$
D := {x: P(f(xi) = x) > 0} =
{x: P(xi in f^(-1) (x)) > 0}.
$
Это не более чем счетное множество. Рассмотрим $M$ такое, что $abs(f) <= M$, $plus.minus M in.not D$. Разобьем $(-M, M]$ на ячейки $(t_(j - 1), t_j]$ с мелкостью дробления меньше $eps$ так, что $t_j in.not D$ для любого $j$. Рассмотрим $B_j := {x in RR: t_(j - 1) < f(x) <= t_j}$. Тогда
$
B_j supset U_j := {x in RR: t_(j - 1) < f(x) < t_j}
$
--- открытое. Более того, $B_j subset A_j := {x in RR : t_(j - 1) <= f(x) <= t_j}$ --- замкнутое. Более того, $Cl B_j without Int B_j subset A_j without U_j$. Тогда
$
P_xi (Cl B_j without Int B_j) <= P_xi (A_j without U_j) = P_xi (f^(-1) (t_(j - 1)) union f^(-1) (t_j)) = 0.
$
Значит $B_j$ регулярное. Тогда по пункту 5 $E bb(1)_(B_j) (xi_n) --> E bb(1)_B_j (xi)$.
Рассмотрим $g(x) := sum_(j = 1)^m t_(j - 1) bb(1)_B_j (x)$. Тогда $E g(xi_n) --> E g(xi)$, так как это просто линейная комбинация индикаторов. А еще мы знаем $0 < f(x) - g(x) < eps$. Ну тогда $E abs(g(eta) - f(xi)) < eps$. Добиваем:
$
abs(E f(xi_n) - E f(xi)) =
abs(E f(xi_n) - E g(xi_n) + E g(xi_n) - E g(xi) + E g(xi) - E f(xi))
newline(<=)
abs(E (f(xi_n) - g(xi_n))) +
abs(E (g(xi_n) - g(xi))) +
abs(E (g(xi) - f(xi)))
newline(<=)
underbrace(E abs(f(xi_n) - g(xi_n)), < eps) +
underbrace(abs(E g(xi_n) - g(xi)), --> 0\, "значит" < eps\ "при больших" n) +
underbrace(E abs(g(xi) - f(xi)), <eps) < 3eps
$
при больших $n$.
Значит
$
lim E f(xi_n) = E f(xi).
$
- "$7 ==> 1$":
$
P(xi_n in [a, b]) = lim_(T-->+oo) 1/(2pi) integral_(-T)^T (e^(-i a t) - e^(-i b t))/(i t) phi_n (t) dif t.
$
Возьмем случайную величину $eta_sigma sim Nn(0, sigma^2)$, независящую от $xi$, $xi_1$, $xi_2$, .... Положим
$
psi_n (t) := phi_(xi_n + eta_sigma) (t) = phi_n (t) dot phi_(eta_sigma) (t) = phi_n (t) e^(-sigma^2 t^2/2) --> phi(t) e^(-sigma^2 t^2/2) = phi_(xi + eta_sigma) (t) =: psi(t).
$
Тогда
$
P(xi_n + eta_sigma in [a, b]) = 1/(2pi) integral_RR (e^(-i a t) - e^(-i b t))/(i t) phi_n (t) e^(-sigma^2 t^2/2) dif t.
$
Под интегралом все ограничено: дробь константой, $phi_n$ единицей, поэтому есть суммируемая мажоранта и можно переходить к пределу:
$
P(xi_n + eta_sigma in [a, b]) --> 1/(2pi) integral_RR (e^(-i a t) - e^(-i b t))/(i t) phi(t) e^(-sigma^2 t^2/2) dif t = P(xi + eta_sigma in [a, b]).
$
Все бы хорошо, только мы чтобы избавиться от интеграла по главному значению, поменяли нашу случайную величину. Давайте объяснять, что это сильно ничего не испортило:
$
G_(n sigma) (x) := F_(xi_n + eta_sigma) (x), space G_sigma (x) := F_(xi + eta_sigma) (x).
$
Тогда
$
G_(n sigma) (b) - G_(n sigma) (a) --> G_sigma (b) - G_sigma (a) space (forall a, b in RR) ==> G_(n sigma) --> G_sigma "поточечно".
$
Возьмем $delta > 0$, тогда
$
{xi_n + eta_sigma <= x - delta} without {abs(eta_sigma) > delta} subset {xi_n <= x} subset {xi_n + eta_sigma <= x + delta} union {abs(eta_sigma) >= delta}.
$
Можно написать неравенства на вероятности:
$
P(xi_n + eta_sigma <= x - delta) - P(abs(eta_sigma) >= delta) <= P(xi_n <= x) <= P(xi_n + eta_sigma <= x + delta) + P(abs(eta_sigma) >= delta).
$
Распишем через функции распределения где можем:
$
G_(n sigma) (x - delta) - P(abs(eta_sigma) >= delta) <= F_n (x) <= G_(n sigma) (x + delta) + P(abs(eta_sigma) >= delta).
$
Оцениваем вероятность:
$
P(abs(eta_sigma) >= delta) <=^"Чебышев" (D eta_sigma)/delta^2 = sigma^2/delta^2.
$
Тогда
$
G_(n sigma) (x - delta) - sigma^2/delta^2 <=^(A(x)) F_n (x) <=^(B(x)) G_(n sigma) (x + delta) + sigma^2/delta^2.
$
Да, я только что обозначил неравенста за $A(x)$ и $B(x)$.
Переходим к пределу:
$
F(x - 2delta) - 2sigma^2/delta^2 <=^(B(x-2 delta))
G_sigma (x - delta) - sigma^2/delta^2 =
liminf (G_(n sigma) (x - delta) - sigma^2/delta^2) <=^(A(x))
liminf F_n (x) newline(<=)
limsup F_n (x) <=^(B(x))
limsup (G_(n sigma) (x + delta) + sigma^2/delta^2) =
G_sigma (x + delta) + sigma^2/delta^2 <=^(A(x + 2delta)) F(x + 2 delta) + 2 sigma^2/delta^2.
$
Устремляем $sigma$ к нулю, а потом устремляем $delta$ к нулю в точках непрерывности $F$, Получаем
$
F(x) <= liminf F_n (x) <= limsup F_n (x) <= F(x)
$
*mic drop.*
]
#th[
$F_n$, $F$: $RR --> [0, 1]$ --- функции распределения, $F in C(RR)$ и $F_n$ поточечно сходится к $F$. Тогда $F_n arrows F$.
]
#proof[
Пусть $m in NN$, и $t_k$ такие, что $F(t_k) = k/m$ для $k = 1, 2, ..., m - 1$. Пусть $t_0 = -oo$, $t_m = +oo$. Такие точки найдутся из-за непрерывности. Возьмем $eps >= 0$ и $N$ такое, что для любого $k$, $forall n >= N space abs(F_n (t_k) - F(t_k)) < eps$. Рассмотрим $t in RR$ и возьмем $t_k <= t < t_(k + 1)$. Оцениваем:
$
F_n (t) &<= F_n (t_(k + 1)) < F (t_(k + 1)) + eps = (k + 1)/m + eps = k/m + 1/m + eps = F(t_k) + 1/m + eps <= F(t) + 1/m + eps, \
F_n (t) &>= F_n (t_k) > F (t_k) - eps = k/m - eps = (k + 1)/m - 1/m - eps = F(t_(k + 1)) - 1/m - eps >= F(t) - 1/m - eps.
$
Тогда $F(t) - 1/m - eps < F_n (t) < F(t) + 1/m + eps$. Значит начиная с какого-то номера для любого $t$ разность $F$ и $F_n$ небольшая. Это и есть равномерная сходимость.
]
|
|
https://github.com/PgBiel/typst-tablex | https://raw.githubusercontent.com/PgBiel/typst-tablex/main/README.md | markdown | MIT License | # typst-tablex (v0.0.8)
**More powerful and customizable tables in Typst.**
**NOTE: Please open an issue if you find a bug with tablex** and I'll get to it as soon as I can. **(PRs are also welcome!)**
## Sponsors ❤️
If you'd like to appear here, [consider sponsoring the project!](https://github.com/sponsors/PgBiel)
<!-- manual -->
<p align="center">
<a href="https://github.com/felipeacsi"><img src="https://github.com/felipeacsi.png" width="50px" alt="felipeacsi" /></a>
<a href="https://github.com/Fabioni"><img src="https://github.com/Fabioni.png" width="50px" alt="Fabioni" /></a>
</p>
<!-- manual -->
<!-- sponsors -->
<!-- sponsors -->
## Important note regarding Typst 0.11.0 and Tablex
A large amount of tablex's features have successfully been upstreamed by this package's author to Typst's built-in `table` and `grid` elements (see the new Tables Guide, at https://typst.app/docs/guides/table-guide/, and the `table` element's reference, at https://typst.app/docs/reference/model/table/, for more information).
This means that, starting with Typst 0.11.0, **many advanced table features can now be used with Typst grids and tables without tablex!** This includes:
- Per-cell customization (through `table.cell(inset: ..., align: ..., fill: ...)[body]`, and `#show table.cell: it => ...` instead of `map-cells`);
- Merging cells (colspans and rowspans, through `table.cell(colspan: 2, rowspan: 2)[body]`);
- Line customization (you can control the `stroke` parameter of `table.cell` to control the lines around it, and you can use `table.hline` and `table.vline` which work similarly to their tablex counterparts - the equivalent of `map-hlines` and `map-vlines` is `table(stroke: (x, y) => (left: ..., right: ..., top: ..., bottom: ...))`);
- Repeatable table headers (through `table.header(... cells ...)`);
- The features above are available within `grid` as well by replacing `table` with `grid` where applicable (e.g. `grid.cell` instead of `table.cell`).
Additionally, built-in Typst tables have support for features which weren't previously available within tablex, such as **repeatable table footers** (through `table.footer` and `grid.footer`).
Therefore, **for the vast majority of use cases, you will no longer need to use this library.** However:
1. **Tablex will still receive updates over time** with extra features. In the next version (tablex 0.1.0), there will be **support for CeTZ integration**, which will allow you to easily annotate your tables using CeTZ (e.g. draw arrows between cells). If you're interested in such features, then tablex might still be useful for you!
2. **Not _all_ tablex features are present in built-in tables, at least yet.** Therefore, you might still have to use tablex depending on your use case. It is expected, however, that built-in tables will eventually have support for most of the missing features in future Typst releases. Here's a non-exhaustive list of them:
1. Built-in tables do not yet have the ability to expand table lines by some arbitrary length.
2. The tablex `fit-spans` option, through which colspans and rowspans don't cause `auto`-sized columns and/or rows to expand, is not yet supported in built-in tables.
3. Built-in repeatable table headers currently always repeat in all pages, whereas you can define in which pages a tablex header should be repeated.
3. **Regarding sponsorships:** The tablex author, [@PgBiel](https://github.com/PgBiel), has also been responsible for upstreaming the various tablex features to built-in tables. Therefore, any future sponsorships will go not only towards extended maintenance of tablex, but also towards future work on built-in tables and other general contributions to the Typst ecosystem! More information here: https://github.com/sponsors/PgBiel/
If there any questions, feel free to open a thread in the `Discussions` page of this repository, or ping the author on Discord. Thanks to everyone who supported me throughout tablex's development and the upstreaming process. I hope you enjoy the new update, and have fun with tables! 😄
And make sure to keep an eye for future tablex updates. 😉
## Table of Contents
* [Usage](#usage)
* [Features](#features)
* [_Almost_ drop-in replacement for `#table`](#almost-drop-in-replacement-for-table)
* [colspanx/rowspanx](#colspanxrowspanx)
* [Repeat header rows](#repeat-header-rows)
* [Customize every single line](#customize-every-single-line)
* [Customize every single cell](#customize-every-single-cell)
* [Known Issues](#known-issues)
* [Reference](#reference)
* [Basic types and functions](#basic-types-and-functions)
* [Gridx and Tablex](#gridx-and-tablex)
* [Changelog](#changelog)
* [v0.0.8](#v008)
* [v0.0.7](#v007)
* [v0.0.6](#v006)
* [v0.0.5](#v005)
* [v0.0.4](#v004)
* [v0.0.3](#v003)
* [v0.0.2](#v002)
* [v0.0.1](#v001)
* [0.1.0 Roadmap](#010-roadmap)
* [License](#license)
## Usage
To use this library through the Typst package manager **(for Typst v0.6.0+)**, write for example `#import "@preview/tablex:0.0.8": tablex, cellx` at the top of your Typst file (you may also add whichever other functions you use from the library to that import list!).
For older Typst versions, download the file `tablex.typ` from the latest release (or directly from the main branch, for the 'bleeding edge') at the tablex repository (https://github.com/PgBiel/typst-tablex) and place it on the same folder as your own Typst file. Then, at the top of your file, write for example `#import "tablex.typ": tablex, cellx` (plus whichever other functions you use from the library).
This library should be compatible with Typst v0.2.0, v0.3.0, v0.4.0, v0.5.0, v0.6.0, v0.7.0, v0.8.0, v0.9.0 and v0.10.0.
**Using the latest Typst version is always recommended** in order to make use of the latest optimizations and features available.
Here's an example of what `tablex` can do:

Here's the code for that table:
```typ
#import "@preview/tablex:0.0.8": tablex, rowspanx, colspanx
#tablex(
columns: 4,
align: center + horizon,
auto-vlines: false,
// indicate the first two rows are the header
// (in case we need to eventually
// enable repeating the header across pages)
header-rows: 2,
// color the last column's cells
// based on the written number
map-cells: cell => {
if cell.x == 3 and cell.y > 1 {
cell.content = {
let value = int(cell.content.text)
let text-color = if value < 10 {
red.lighten(30%)
} else if value < 15 {
yellow.darken(13%)
} else {
green
}
set text(text-color)
strong(cell.content)
}
}
cell
},
/* --- header --- */
rowspanx(2)[*Username*], colspanx(2)[*Data*], (), rowspanx(2)[*Score*],
(), [*Location*], [*Height*], (),
/* -------------- */
[John], [Second St.], [180 cm], [5],
[Wally], [Third Av.], [160 cm], [10],
[Jason], [Some St.], [150 cm], [15],
[Robert], [123 Av.], [190 cm], [20],
[Other], [Unknown St.], [170 cm], [25],
)
```
## Features
### _Almost_ drop-in replacement for `#table`
(**Update:** tablex's syntax was designed to be compatible with Typst tables created **up to Typst v0.10.0**. The new table features introduced in Typst v0.11.0 use syntax which isn't compatible with tablex, so it won't be a drop-in replacement in that case. However, tablex does have its own syntax for those features, as will be explained below!)
In most cases, you should be able to replace `#table` with `#tablex` and be good to go for a start - it should look _very_ similar (if not identical). Indeed, the syntax is very similar for the basics:
```typ
#import "@preview/tablex:0.0.8": tablex
#tablex(
columns: (auto, 1em, 1fr, 1fr), // 4 columns
rows: auto, // at least 1 row of auto size
fill: red,
align: center + horizon,
stroke: green,
[a], [b], [c], [d],
[e], [f], [g], [h],
[i], [j], [k], [l]
)
```

There are still a few oddities in the library (see [Known Issues](#known-issues) for more info), but, for the vast majority of cases, replacing `#tablex` by `#table` should work just fine. (Sometimes you can even replace `#grid` by `#gridx` - see the line customization section for more -, but not always, as the behavior is a bit different.)
This is mostly a word of caution in case anything I haven't anticipated happens, but, based on my tests (and after tons of bug-fixing commits), the vast majority of tables (that don't face one of the listed known issues) should work just fine under the library.
**Note:** If your document is written in a right-to-left (RTL) script, you may wish to enable `rtl: true` for your tables so that the order of cells and lines properly follows your text direction (when combined with `set text(dir: rtl)`). This is necessary because tablex cannot detect that setting automatically at the moment (while the native Typst table can and flips itself horizontally automatically). See the tablex option reference for more information.
### colspanx/rowspanx
Your cells can now span more than one column and/or row at once, with `colspanx` / `rowspanx`:
```typ
#import "@preview/tablex:0.0.8": tablex, colspanx, rowspanx
#tablex(
columns: 3,
colspanx(2)[a], (), [b],
[c], rowspanx(2)[d], [ed],
[f], (), [g]
)
```

Note that the empty parentheses there are just for organization, and are ignored (unless they come before the first cell - more on that later). They're useful to help us keep track of which cell positions are being used up by the spans, because, if we try to add an actual cell at these spots, it will just push the others forward, which might seem unexpected.
Use `colspanx(2, rowspanx(2)[d])` to colspan and rowspan at the same time. Be careful not to attempt to overwrite other cells' spans, as you will get a nasty error.
**Note (since tablex v0.0.8):** By default, colspans and rowspans can cause spanned `auto` columns and rows to expand to fit their contents (only the last spanned track - column or row - can expand). If you'd like colspans to not affect column sizes at all (and thus "fit" within their spanned columns), you may specify `fit-spans: (x: true)` to the table. Similarly, you can specify `fit-spans: (y: true)` to have rowspans not affect row sizes at all. To apply both effects, use either `fit-spans: true` or `fit-spans: (x: true, y: true)`. You can also apply this to a single colspan (for example) with `colspanx(2, fit-spans: (x: true))[a]`, as this option is available not only for the whole table but also for each cell. See the reference section for more information.
### Repeat header rows
You can now ensure the first row (or, rather, the rows covered by the first rowspan) in your table repeats across pages. Just use `repeat-header: true` (default is `false`).
Note that you may wish to customize this. Use `repeat-header: 6` to repeat for 6 more pages. Use `repeat-header: (2, 4)` to repeat only on the 2nd and the 4th page (where the 1st page is the one the table starts in). Additionally, use `header-rows: 5` to ensure the first (e.g.) 5 rows are part of the header (by default, this is 1 - more rows will be repeated where necessary if rowspans are used).
Also, note that, by default, the horizontal lines below the header are transported to other pages, which may be an annoyance if you customize lines too much (see below). Use `header-hlines-have-priority: false` to ensure that the first row in each page will dictate the appearance of the horizontal lines above it (and not the header).
**Note:** Depending on the size of your document, repeatable headers might not behave properly due to certain limitations in Typst's introspection system (as observed in https://github.com/PgBiel/typst-tablex/issues/43).
Example:
```typ
#import "@preview/tablex:0.0.8": tablex, hlinex, vlinex, colspanx, rowspanx
#pagebreak()
#v(80%)
#tablex(
columns: 4,
align: center + horizon,
auto-vlines: false,
repeat-header: true,
/* --- header --- */
rowspanx(2)[*Names*], colspanx(2)[*Properties*], (), rowspanx(2)[*Creators*],
(), [*Type*], [*Size*], (),
/* -------------- */
[Machine], [Steel], [5 $"cm"^3$], [John p& Kate],
[Frog], [Animal], [6 $"cm"^3$], [Robert],
[Frog], [Animal], [6 $"cm"^3$], [Robert],
[Frog], [Animal], [6 $"cm"^3$], [Robert],
[Frog], [Animal], [6 $"cm"^3$], [Robert],
[Frog], [Animal], [6 $"cm"^3$], [Robert],
[Frog], [Animal], [6 $"cm"^3$], [Robert],
[Frog], [Animal], [6 $"cm"^3$], [Rodbert],
)
```

### Customize every single line
Every single line in the table is either a `hlinex` (horizontal) or `vlinex` (vertical) instance. By default, there is one between every column and between every row - unless you specify a custom line for some column or row, in which case the automatic line for it will be removed (to allow you to freely customize it). To disable this behavior, use `auto-lines: false`, which will remove _all_ automatic lines. You may also remove only automatic horizontal lines with `auto-hlines: false`, and only vertical with `auto-vlines: false`.
**Note:** `gridx` is an alias for `tablex` with `auto-lines: false`.
For your custom lines, write `hlinex()` at any position and it will add a horizontal line below the current cell row (or at the top, if before any cell). You can use `hlinex(start: a, end: b)` to control the cells which that line spans (`a` is the first column number and `b` is the last column number). You can also specify its stroke (color/thickness) with `hlinex(stroke: red + 5pt)` for example. To position it at an arbitrary row, use `hlinex(y: 6)` or similar. (Columns and rows are indexed starting from 0.)
Something similar occurs for `vlinex()`, which has `start`, `end` (first row and last row it spans), and also `stroke`. They will, by default, be placed to the right of the current cell, and will span the entire table (top to bottom). To override the default placement, use `vlinex(x: 2)` or similar.
**Note:** Only one hline or vline with the same span (same start/end) can be placed at once.
**Note:** You can also place vlines before the first cell, in which case _they will be placed consecutively, each after the last `vlinex()`_. That is, if you place several of them in a row (*before the first cell* only), then it will not place all of them at one location (which is normally what happens if you try to place multiple vlines at once), but rather one after the other. With this behavior, you can also specify `()` between each vline to _skip_ certain positions (again, only before the first cell - afterwards, all `()` are ignored). Note that you can also just ignore this entirely and use `vlinex(x: 0)`, `vlinex(x: 1)`, ..., `vlinex(x: columns.len())` for full control.
Here's some sample usage:
```typ
#import "@preview/tablex:0.0.8": tablex, gridx, hlinex, vlinex, colspanx, rowspanx
#tablex(
columns: 4,
auto-lines: false,
// skip a column here vv
vlinex(), vlinex(), vlinex(), (), vlinex(),
colspanx(2)[a], (), [b], [J],
[c], rowspanx(2)[d], [e], [K],
[f], (), [g], [L],
// ^^ '()' after the first cell are 100% ignored
)
#tablex(
columns: 4,
auto-vlines: false,
colspanx(2)[a], (), [b], [J],
[c], rowspanx(2)[d], [e], [K],
[f], (), [g], [L],
)
#gridx(
columns: 4,
(), (), vlinex(end: 2),
hlinex(stroke: yellow + 2pt),
colspanx(2)[a], (), [b], [J],
hlinex(start: 0, end: 1, stroke: yellow + 2pt),
hlinex(start: 1, end: 2, stroke: green + 2pt),
hlinex(start: 2, end: 3, stroke: red + 2pt),
hlinex(start: 3, end: 4, stroke: blue.lighten(50%) + 2pt),
[c], rowspanx(2)[d], [e], [K],
hlinex(start: 2),
[f], (), [g], [L],
)
```

#### Bulk line customization
You can also *bulk-customize lines* by specifying `map-hlines: h => new_hline` and `map-vlines: v => new_vline`. This includes any automatically generated lines. For example:
```typ
#import "@preview/tablex:0.0.8": tablex, colspanx, rowspanx
#tablex(
columns: 3,
map-hlines: h => (..h, stroke: blue),
map-vlines: v => (..v, stroke: green + 2pt),
colspanx(2)[a], (), [b],
[c], rowspanx(2)[d], [ed],
[f], (), [g]
)
```

### Customize every single cell
Cells can be customized entirely. Instead of specifying content (e.g. `[text]`) as a table item, you can specify `cellx(property: a, property: b, ...)[text]`, which allows you to customize properties, such as:
- `colspan: 2` (same as using `colspanx(2, ...)[...]`)
- `rowspan: 3` (same as using `rowspanx(3, ...)[...]`)
- `align: center` (override whole-table alignment for this cell)
- `fill: blue` (fill just this cell with that color)
- `inset: 0pt` (override inset/internal padding for this cell - note that this can look off unless you use auto columns and rows)
- `x: 5` (arbitrarily place the cell at the given column, beginning at 0 - may error if conflicts occur)
- `y: 6` (arbitrarily place the cell at the given row, beginning at 0 - may error if conflicts occur)
Additionally, instead of specifying content to the cell, you can specify a function `(column, row) => content`, allowing each cell to be aware of where it's positioned. (Note that positions are recorded in the cell's `.x` and `.y` attributes, and start as `auto` unless you specify otherwise.)
For example:
```typ
#import "@preview/tablex:0.0.8": tablex, cellx, colspanx, rowspanx
#tablex(
columns: 3,
fill: red,
align: right,
colspanx(2)[a], (), [beeee],
[c], rowspanx(2)[d], cellx(fill: blue, align: left)[e],
[f], (), [g],
// place this cell at the first column, seventh row
cellx(colspan: 3, align: center, x: 0, y: 6)[hi I'm down here]
)
```

#### Bulk customization of cells
To customize multiple cells at once, you have a few options:
1. `map-cells: cell => cell` (given a cell, returns a new cell). You can use this to customize the cell's attributes, but also to change its positions (however, avoid doing that as it can easily generate conflicts). You can access the cell's position with `cell.x` and `cell.y`. All other attributes are also accessible and changeable (see the `Reference` further below for a list). Return something like `(..cell, fill: blue)`, for example, to ensure the other properties (including the cell type marker) are kept. (Calling `cellx` here is not necessary. If overriding the cell's content, use `content: [whatever]`). This is useful if you want to, for example, customize a cell's fill color based on its contents, or add some content to every cell, or something similar.
2. `map-rows: (row_index, cells) => cells` (given a row index and all cells in it, return a new array of cells). Allows customizing entire rows, but note that the cells in the `cells` parameter can be `none` if they're some position occupied by a colspan or rowspan of another cell. Ensure you return the cells in the order you were given, including the `none`s, for best results. Also, you cannot move cells here to another row. You can change the cells' columns (by changing their `x` property), but that will certainly generate conflicts if any col/rowspans are involved (in general, you cannot bulk-change col/rowspans without `map-cells`).
3. `map-cols: (col_index, cells) => cells` (given a column index and all cells in it, return a new array of cells). Similar to `map-rows`, but for customizing columns. You cannot change the column of any cell here. (To do that, `map-cells` is required.) You can, however, change its row (with `y`, but do that sparingly), and, of course, all other properties.
**Note:** Execution order is `map-cells` => `map-rows` => `map-cols`.
Example:
```typ
#import "@preview/tablex:0.0.8": tablex, colspanx, rowspanx
#tablex(
columns: 4,
auto-vlines: true,
// make all cells italicized
map-cells: cell => {
(..cell, content: emph(cell.content))
},
// add some arbitrary content to entire rows
map-rows: (row, cells) => cells.map(c =>
if c == none {
c // keeping 'none' is important
} else {
(..c, content: [#c.content\ *R#row*])
}
),
// color cells based on their columns
// (using 'fill: (column, row) => color' also works
// for this particular purpose)
map-cols: (col, cells) => cells.map(c =>
if c == none {
c
} else {
(..c, fill: if col < 2 { blue } else { yellow })
}
),
colspanx(2)[a], (), [b], [J],
[c], rowspanx(2)[dd], [e], [K],
[f], (), [g], [L],
)
```

Another example (summing columns):
```typ
#gridx(
columns: 3,
rows: 6,
fill: (col, row) => (blue, red, green).at(calc.rem(row + col - 1, 3)),
map-cols: (col, cells) => {
let last = cells.last()
last.content = [
#cells.slice(0, cells.len() - 1).fold(0, (acc, c) => if c != none { acc + eval(c.content.text) } else { acc })
]
last.fill = aqua
cells.last() = last
cells
},
[0], [5], [10],
[1], [6], [11],
[2], [7], [12],
[3], [8], [13],
[4], [9], [14],
[s], [s], [s]
)
```

## Known Issues
- Filled cells will partially overlap with horizontal lines above them (see https://github.com/PgBiel/typst-tablex/issues/4).
- To be fixed in a future rework of the table drawing process.
- Table lines don't play very well with column and row gutter when a colspan or rowspan is used. They may be missing or be cut off by gutters.
- Repeatable table headers might not behave properly depending on the size of your document or other factors (https://github.com/PgBiel/typst-tablex/issues/43).
- Using tablex (especially when using repeatable header rows) may cause a warning, "layout did not converge within 5 attempts", to appear on recent Typst versions (https://github.com/PgBiel/typst-tablex/issues/38). This warning is due to how tablex works internally **and is not your fault** (in principle), so don't worry too much about it (unless you're sure it's not tablex that is causing this).
- Rows with fractional height (such as `2fr`) have zero height if the table spans more than one page. This is because fractional row heights are calculated on the available height of the first page of the table, which is something that the default `#table` can circumvent using internal code. This won't be fixed for now. (Columns with fractional width work fine, provided all pages the table is in have the same width, **and the page width isn't `auto`** (which forces fractional columns to be 0pt, even in the default `#table`).)
- Rotation (via Typst's `#rotate`) of text only affects the visual appearance of the text on the page, but does not change its dimensions as they factor into the layout.
This leads to certain visual issues, such as rotated text potentially overflowing the cell height without being hyphenated or, inversely, being hyphenated even though there is enough space vertically (https://github.com/PgBiel/typst-tablex/issues/59).
This is a [known issue](https://github.com/typst/typst/issues/528) with Typst (perhaps, in the future, `#rotate` [may](https://github.com/typst/typst/issues/528#issuecomment-1494123195) get a setting to affect layout).
As a workaround for the text hyphenation problem, the content can be boxed (and thus grouped together) with `#box` (e.g., `rowspanx(7, box(rotate(-90deg, [*donothyphenatethis*])))`), or hyphenation can be prevented by setting `#text(hyphenate: false, ...)` (e.g., `colspanx(2, text(hyphenate: false, rotate(-90deg, [*donothyphenatethis*])))`), as also discussed in https://github.com/PgBiel/typst-tablex/issues/59;
another alternative is to use `#place`, e.g. aligning to `center + horizon`: `cellx(place(center + horizon, rotate(-90deg, [*donothyphenatethis*])))`, which probably allows the most control over the in-cell layout, since it simply draws the rotated content without having it occupy any space (letting you define that by yourself, e.g. using `box(width: 1em, height: 2em, place(...))`).
- Alternatively, you may attempt to use the solution proposed at https://github.com/typst/typst/issues/528#issuecomment-1494318510 to define a `rotatex` function which produces a rotated element with the appropriate sizes, such that tablex may recognize its size accordingly and avoid visual glitches.
- `tablex` can potentially be slower and/or take longer to compile than the default `table` (especially when the table spans a lot of pages). **Please use the latest Typst version to reduce this problem** (each version has been bringing further improvements in this sense). Still, we are looking for ways to better optimize the library (see more discussion at https://github.com/PgBiel/typst-tablex/issues/5 - feel free to give some input!). However, re-compilation is usually fine thanks to Typst's built-in memoization.
- The internals of the library still aren't very well documented; I plan on adding more info about this eventually.
- **Please open a GitHub issue for anything weird you come across** (make sure others haven't reported it first).
## Reference
### Basic types and functions
1. `cellx`: Represents a table cell, and is initialized as follows:
```typ
#let cellx(content,
x: auto, y: auto,
rowspan: 1, colspan: 1,
fill: auto, align: auto,
inset: auto,
fit-spans: auto
) = (
tablex-dict-type: "cell",
content: content,
rowspan: rowspan,
colspan: colspan,
align: align,
fill: fill,
inset: inset,
fit-spans: fit-spans,
x: x,
y: y,
)
```
where:
- `tablex-dict-type` is the type marker
- `content` is the cell's content (either `content` or a function with `(col, row) => content`)
- `rowspan` is how many rows this cell spans (default 1)
- `colspan` is how many columns this cell spans (default 1)
- `align` is this cell's align override, such as "center" (default `auto` to follow the rest of the table)
- `fill` is this cell's fill override, such as "blue" (default `auto` to follow the rest of the table)
- `inset` is this cell's inset override, such as `5pt` (default `auto` to follow the rest of the table)
- `fit-spans` allows overriding the table-wide `fit-spans` setting for this specific cell (e.g. if this cell has a `colspan` greater than 1, `fit-spans: (x: true)` will cause it to not affect the sizes of `auto` columns).
- `x` is the cell's column index (0..len-1) - `auto` indicates it wasn't assigned yet
- `y` is the cell's row index (0..len-1) - `auto` indicates it wasn't assigned yet
2. `hlinex`: represents a horizontal line:
```typ
#let hlinex(
start: 0, end: auto, y: auto,
stroke: auto,
stop-pre-gutter: auto, gutter-restrict: none,
stroke-expand: true,
expand: none
) = (
tablex-dict-type: "hline",
start: start,
end: end,
y: y,
stroke: stroke,
stop-pre-gutter: stop-pre-gutter,
gutter-restrict: gutter-restrict,
stroke-expand: stroke-expand,
expand: expand,
parent: none,
)
```
where:
- `tablex-dict-type` is the type marker
- `start` is the column index where the hline starts from (default `0`, a.k.a. the beginning)
- `end` is the last column the hline touches (default `auto`, a.k.a. all the way to the end)
- Note that hlines will *not* be drawn over cells with `colspan` larger than 1, even if their spans (`start`-`end`) include that cell.
- `y` is the index of the row at the top of which the hline is drawn. (Defaults to `auto`, a.k.a. depends on where you placed the `hline` among the table items - it's always on the top of the row below the current one.)
- `stroke` is the hline's stroke override (defaults to `auto`, a.k.a. follow the rest of the table).
- `stop-pre-gutter`: When `true`, the hline will not be drawn over gutter (which is the default behavior of tables). Defaults to `auto` which is essentially `false` (draw over gutter).
- `gutter-restrict`: Either `top`, `bottom`, or `none`. Has no effect if `row-gutter` is set to `none`. Otherwise, defines if this `hline` should be drawn only on the top of the row gutter (`top`); on the bottom (`bottom`); or on both the top and the bottom (`none`, the default). Note that `top` and `bottom` are alignment values (not strings).
- `stroke-expand`: When `true`, the hline will be extended as necessary to cover the stroke of the vlines going through either end of the line. Defaults to `true`.
- `expand`: Optionally extend the hline by an arbitrary length. When `none`, it is not expanded. When a length (such as `5pt`), it is expanded by that length on both ends. When an array of two lengths (such as `(5pt, 10pt)`), it is expanded to the left by the first length (in this case, `5pt`) and to the right by the second (in this case, `10pt`). Defaults to `none`.
- `parent`: An internal attribute determined when splitting lines among cells. (It should always be `none` on user-facing interfaces.)
3. `vlinex`: represents a vertical line:
```typ
#let vlinex(
start: 0, end: auto, x: auto,
stroke: auto,
stop-pre-gutter: auto, gutter-restrict: none,
stroke-expand: true,
expand: none
) = (
tablex-dict-type: "vline",
start: start,
end: end,
x: x,
stroke: stroke,
stop-pre-gutter: stop-pre-gutter,
gutter-restrict: gutter-restrict,
stroke-expand: stroke-expand,
expand: expand,
parent: none,
)
```
where:
- `tablex-dict-type` is the type marker
- `start` is the row index where the vline starts from (default `0`, a.k.a. the top)
- `end` is the last row the vline touches (default `auto`, a.k.a. all the way to the bottom)
- Note that vlines will *not* be drawn over cells with `rowspan` larger than 1, even if their spans (`start`-`end`) include that cell.
- `x` is the index of the column to the left of which the vline is drawn. (Defaults to `auto`, a.k.a. depends on where you placed the `vline` among the table items.)
- For a `vline` to be placed after all columns, its `x` value will be equal to the amount of columns (which isn't a valid column index, but it's what is used here).
- `stroke` is the vline's stroke override (defaults to `auto`, a.k.a. follow the rest of the table).
- `stop-pre-gutter`: When `true`, the vline will not be drawn over gutter (which is the default behavior of tables). Defaults to `auto` which is essentially `false` (draw over gutter).
- `gutter-restrict`: Either `left`, `right`, or `none`. Has no effect if `column-gutter` is set to `none`. Otherwise, defines if this `vline` should be drawn only to the left of the column gutter (`left`); to the right (`right`); or on both the left and the right (`none`, the default). Note that `left` and `right` are alignment values (not strings).
- `stroke-expand`: When `true`, the vline will be extended as necessary to cover the stroke of the hlines going through either end of the line. Defaults to `true`.
- `expand`: Optionally extend the vline by an arbitrary length. When `none`, it is not expanded. When a length (such as `5pt`), it is expanded by that length on both ends. When an array of two lengths (such as `(5pt, 10pt)`), it is expanded towards the top by the first length (in this case, `5pt`) and towards the bottom by the second (in this case, `10pt`). Defaults to `none`.
- `parent`: An internal attribute determined when splitting lines among cells. (It should always be `none` on user-facing interfaces.)
4. The `occupied` type is an internal type used to represent cell positions occupied by cells with `colspan` or `rowspan` greater than 1.
5. Use `is-tablex-cell`, `is-tablex-hline`, `is-tablex-vline` and `is-tablex-occupied` to check if a particular object has the corresponding type marker.
6. `colspanx` and `rowspanx` are shorthands for setting the `colspan` and `rowspan` attributes of `cellx`. They can also be nested (one given as an argument to the other) to combine their properties (e.g., `colspanx(2)(rowspanx(3)[a])`). They accept all other cell properties with named arguments. For example, `colspanx(2, align: center)[b]` is equivalent to `cellx(colspan: 2, align: center)[b]`.
### Gridx and Tablex
1. `gridx` is equivalent to `tablex` with `auto-lines: false`; see below.
2. `tablex:` The main function for creating a table with this library:
```typ
#let tablex(
columns: auto, rows: auto,
inset: 5pt,
align: auto,
fill: none,
stroke: auto,
column-gutter: auto, row-gutter: auto,
gutter: none,
repeat-header: false,
header-rows: 1,
header-hlines-have-priority: true,
auto-lines: true,
auto-hlines: auto,
auto-vlines: auto,
map-cells: none,
map-hlines: none,
map-vlines: none,
map-rows: none,
map-cols: none,
..items
) = {
// ...
}
```
**Parameters:**
- `columns`: The sizes (widths) of each column. They work just like regular `table`'s columns, and can be:
- an array of lengths (`1pt`, `2em`, `100%`, ...), including fractional (`2fr`), to specify the width of each column
- For instance, `columns: (2pt, 3em)` will give you two columns: one with a width of `2pt` and another with the width of `3em` (3 times the font size).
- Note that percentages, such as `49%`, **are considered fixed widths** as they are **always multiplied by the full page width** (minus margins) for columns. Thus, a column with a size of `100%` would span your whole page (even if there are other columns).
- `auto` may be specified to automatically resize the column based on the largest width of its contents, if possible - **this is the most common column width choice,** as it just delegates the column sizing job to tablex!
- For example, if your `auto`-sized column contains two cells with `Hello world!` and `Bye!` as contents, tablex will try to make the column large enough for `Hello world!` (the cell with largest _potential_ width) to fit in a single line.
- However, note that often enough that's not possible, as increasing the column's size too much would result in the table going over the page's margin - perhaps even beyond the document's total width. Therefore, **tablex will automatically reduce the size of your `auto` columns** when they would otherwise cause the table to overrun the page's normal width (i.e. the width between the page's lateral margins).
- Fixed width columns (such as `2pt`, `3em` or `49%`) are not subject to this size reduction; thus, if you specify all columns' widths with fixed lengths, your table _could_ become larger than the page's width! (In such a case, **`auto` columns would be reduced to a size of zero,** as there would be no available space anymore!)
- when specifying fractional widths (`1fr`, `2fr`...) for columns, the available space (remaining page width, after calculating all other columns' sizes) is divided between them, weighted on the fraction value of each column.
- For example, with `(1fr, 2fr)`, the available space will be divided by 3 (1 + 2), and the first column will have 1/3 of the space, while the second will have 2/3.
- `(1fr, 1fr)` would cause both columns to have equal length (1/2 and 1/2 of the available space).
- This is useful when you want some columns to just occupy all the remaining horizontal space in the page.
- **Note:** If only one column has a fractional width (e.g. a single column with `1fr`), it will occupy the entire available space.
- **Warning:** fractional columns in tablex (much like in Typst's default tables) **will not work properly in pages with `auto` width** (the columns will have width zero) - this is because those pages theoretically have infinite width (they can expand indefinitely), so having columns spanning the entire available width is then impossible!
- a single length like above, to indicate the width of a single column (equivalent to just placing it inside a unit array)
- For instance, `columns: 2pt` is equivalent to `columns: (2pt,)`, which translates to a single column of width `2pt`.
- an integer (such as `4`), as a shorthand for `(auto,) * 4` (that many `auto` columns)
- Useful if you just want to quickly set the amount of columns without worrying about their sizes (`columns: 4` will give you four `auto` columns).
- `rows`: The sizes (heights) of each row. They follow the exact same format as `columns`, except that the "available space" is infinite (auto rows can expand as much as is needed, as the table can add rows over multiple pages).
- **Note:** For rows, percentages (such as `49%`) are fixed width lengths, like in `columns`; however, here, they are **multiplied by the page's full height** (minus margins), and not width.
- **Note:** If more rows than specified are added, the height for the **last row** will be the one assigned to all extra rows. (If the last row is `auto`, the extra ones will also be `auto`, for example.)
- Your table can have more rows than expected by simply having more cells than `(# columns)` multipled by `(# rows)`. In this case, you will have an extra row for each `(# columns)` cells after the limit. In other words, **the amount of columns is always fixed** (determined by the amount of widths in the array given to `columns`), but the amount of rows can vary depending on your input of cells to the table.
- Adding a cell at an arbitrary `y` coordinate can also cause your table to have extra rows (enough rows to reach the cell at that coordinate).
- **Warning:** support for fractional sizes for rows is still rudimentary - they only work properly on the table's first page; on the second page and onwards, they will not behave properly, differently from the default `#table`.
- `inset`: Inset/internal padding to give to each cell. Can be either a length (same inset from the top, bottom, left and right of the cell), or a dictionary (e.g. `(left: 5pt, right: 10pt, bottom: 2pt, top: 4pt)`, or even `(left: 5pt, rest: 10pt)` to apply the same value to the remaining sides). Defaults to `5pt` (the `#table` default).
- `align`: How to align text in the cells. Defaults to `auto`, which inherits alignment from the outer context. Must be either `auto`, an `alignment` (such as `left` or `top`), a `2d alignment` (such as `left + top`), an `array` of alignment/2d alignment (one for each column in the table - if there are more columns than alignment values, they will alternate); or a function `(column, row) => alignment/2d alignment` (to customize for each individual cell).
- `fill`: Color with which to fill cells' backgrounds. Defaults to `none`, or no fill. Must be either a `color`, such as `blue`; an `array` of colors (one for each column in the table - if there are more columns than colors, they will alternate); or a function `(column, row) => color` (to customize for each individual cell).
- `stroke`: Indicates how to draw the table lines. Defaults to the current line styles in the document. For example: `5pt + red` to change the color and the thickness.
- `column-gutter`: optional separation (length) between columns (such as `5pt`). Defaults to `none` (disable). At the moment, looks a bit ugly if your table has a `hline` attempting to cross a `colspan`.
- `row-gutter`: optional separation (length) between rows. Defaults to `none` (disable). At the moment, looks a bit ugly if your table has a `vline` attempting to cross a `rowspan`.
- `gutter`: Sets a length to both `column-` and `row-gutter` at the same time (overridable by each).
- `repeat-header`: Controls header repetition. If set to `true`, the first row (or the amount of rows specified in `header-rows`), including its rowspans, is repeated across all pages this table spans. If set to `false` (default), the aforementioned header row is not repeated in any page. If set to an integer (such as `4`), repeats for that many pages after the first, then stops. If set to an array of integers (such as `(3, 4)`), repeats only on those pages _relative to the table's first page_ (page 1 here is where the table is, so adding `1` to said array has no effect).
- `header-rows`: minimum amount of rows for the repeatable
header. 1 by default. Automatically increases if
one of the cells is a rowspan that would go beyond the
given amount of rows. For example, if 3 is given,
then at least the first 3 rows will repeat.
- `header-hlines-have-priority`: if `true`, the horizontal
lines below the header being repeated take priority
over the rows they appear atop of on further pages.
If `false`, they draw their own horizontal lines.
Defaults to `true`.
- For example, if your header has a blue hline under it, that blue hline will display on all pages it is repeated on if this option is `true`. If this option is `false`, the header will repeat, but the blue hline will not.
- `rtl`: if true, the table is horizontally flipped. That is, cells and lines are placed in the opposite order (starting from the right), and horizontal lines are flipped.
This is meant to simulate the behavior of default Typst tables when `set text(dir: rtl)` is used,
and is useful when writing in a language with a RTL (right-to-left) script.
Defaults to `false`.
- `auto-lines`: Shorthand to apply a boolean to both `auto-hlines` and `auto-vlines` at the same time (overridable by each). Defaults to `true`.
- `auto-hlines`: If `true`, draw a horizontal line on every line where you did not manually draw one; if `false`, no hlines other than the ones you specify (via `hlinex`) are drawn. Defaults to `auto` (follows `auto-lines`, which in turn defaults to `true`).
- `auto-vlines`: If `true`, draw a vertical line on every line where you did not manually draw one; if `false`, no vlines other than the ones you specify (via `vlinex`) are drawn. Defaults to `auto` (follows `auto-lines`, which in turn defaults to `true`).
- `map-cells`: A function which takes a single `cellx` and returns another `cellx`, or a `content` which is converted to `cellx` by `cellx[#content]`. You can customize the cell in pretty much any way using this function; just take care to avoid conflicting with already-placed cells if you move it.
- `map-hlines`: A function which takes each horizontal line object (`hlinex`) and returns another, optionally modifying its properties. You may also change its row position (`y`). Note that this is also applied to lines generated by `auto-hlines`.
- `map-vlines`: A function which takes each horizontal line object (`vlinex`) and returns another, optionally modifying its properties. You may also change its column position (`x`). Note that this is also applied to lines generated by `auto-vlines`.
- `map-rows`: A function mapping each row of cells to new values or modified properties.
Takes `(row_num, cell_array)` and returns
the modified `cell_array`. Note that, with your function, they
cannot be sent to another row. Also, please preserve the order of the cells. This is especially important given that cells may be `none` if they're actually a position taken by another cell with colspan/rowspan. Make sure the `none` values are in the same indexes when the array is returned.
- `map-cols`: A function mapping each column of cells to new values or modified properties.
Takes `(col_num, cell_array)` and returns
the modified `cell_array`. Note that, with your function, they
cannot be sent to another column. Also, please preserve the order of the cells. This is especially important given that cells may be `none` if they're actually a position taken by another cell with colspan/rowspan. Make sure the `none` values are in the same indexes when the array is returned.
- `fit-spans`: either a dictionary `(x: bool, y: bool)` or just `bool` (e.g. just `true` is converted to `(x: true, y: true)`). When given `(x: true)`, colspans won't affect the sizes of `auto` columns. When given `(y: true)`, rowspans won't affect the sizes of `auto` rows. By default, this is equal to `(x: false, y: false)` (equivalent to just `false`), which means that colspans will cause the last spanned `auto` column to expand (depending on the contents of the cell) and rowspans will cause the last spanned `auto` row to expand similarly.
- This is usually used as `(x: true)` to prevent unexpected expansion of `auto` columns after using a colspan, which can happen when a colspan spans both a fractional-size column (e.g. `1fr`) and an `auto`-sized column. Can be applied to rows too through `(y: true)` or `(x: true, y: true)`, if needed, however.
- The point of this option is to have colspans and rowspans not affect the size of the table at all, and just "fit" within the columns and rows they span. Therefore, this option does not have any effect upon colspans and rowspans which don't span columns or rows with automatic size.
## Changelog
### v0.0.8
- Added `fit-spans` option to `tablex` and `cellx` (https://github.com/PgBiel/typst-tablex/pull/111)
- Accepts `(x: bool, y: bool)`. When set to `(x: true)`, colspans won't affect the sizes of `auto` columns. When set to `(y: true)`, rowspans won't affect the sizes of `auto` rows.
- Defaults to `false`, equivalent to `(x: false, y: false)`, that is, colspans and rowspans affect the sizes of `auto` tracks (columns and rows) by default (expanding the last spanned track if the colspan/rowspan is too large).
- Useful when you want merged cells (or a specific merged cell) to "fit" within their spanned columns and rows. May help when adding a colspan or rowspan causes an `auto`-sized track to inadvertently expand.
- `auto` column sizing received multiple improvements and bug fixes. Tables should now have more natural column widths. (https://github.com/PgBiel/typst-tablex/pull/109, https://github.com/PgBiel/typst-tablex/pull/116)
- Fixes some problems with overflowing cells (https://github.com/PgBiel/typst-tablex/issues/48, https://github.com/PgBiel/typst-tablex/issues/75)
- Fixes `auto` columns being needlessly expanded in some cases (https://github.com/PgBiel/typst-tablex/issues/56, https://github.com/PgBiel/typst-tablex/issues/78)
- For similar problems not fixed by this, please use the new `fit-spans` option as needed, or use fixed-size columns instead.
- Several performance optimizations and other internal code improvements were made (https://github.com/PgBiel/typst-tablex/pull/113, https://github.com/PgBiel/typst-tablex/pull/114, https://github.com/PgBiel/typst-tablex/pull/115).
- Documents with lots of `tablex` tables might now become **up to 20% faster** to cold compile. Give it a shot!
- Fixed extra fixed-height rows appearing to have `auto` height (https://github.com/PgBiel/typst-tablex/pull/108).
- Fixed rows without any visible cells being drawn with zero height (https://github.com/PgBiel/typst-tablex/pull/107).
- Fixes some rowspans causing cells to overlap (https://github.com/PgBiel/typst-tablex/issues/82, https://github.com/PgBiel/typst-tablex/issues/105).
### v0.0.7
I have begun [work on bringing many tablex improvements to built-in Typst tables](https://github.com/PgBiel/typst-improv-tables-planning)! In that regard, [you can now sponsor my work on tablex and improving Typst tables via GitHub Sponsors! Consider taking a look :)](https://github.com/sponsors/PgBiel)
- Allow gradients and patterns in fills (https://github.com/PgBiel/typst-tablex/pull/87)
- Fixed a critical bug where `line` in tablex cells would misbehave (https://github.com/PgBiel/typst-tablex/issues/80)
- CeTZ and drawing in general should now work properly within tablex cells (see https://github.com/johannes-wolf/cetz/issues/345).
- Also fixes a problem with nested tables (https://github.com/PgBiel/typst-tablex/issues/34)
- Fixed negative line expansion within a single cell (https://github.com/PgBiel/typst-tablex/pull/84)
- Negative line expansion across multiple cells isn't yet supported.
- Thanks GitHub user @dixslyf for the great work on fixing and testing this!
- Made internal length calculation procedures more robust (https://github.com/PgBiel/typst-tablex/issues/92, https://github.com/PgBiel/typst-tablex/issues/94)
- Fixes a potential incompatibility with (currently unreleased) Typst 0.11.0
- Added missing support for boolean types in Typst 0.8.0+ (https://github.com/PgBiel/typst-tablex/issues/73)
- Added some keywords to tablex's `typst.toml` for better discoverability (https://github.com/PgBiel/typst-tablex/issues/91)
### v0.0.6
- Added support for RTL tables with `rtl: true` (https://github.com/PgBiel/typst-tablex/issues/58).
- Default Typst tables are automatically flipped horizontally when using `set text(dir: rtl)`, however we can't detect that setting from tablex at this moment (it isn't currently possible to fetch set rules in Typst).
- Therefore, as a way around that, you can now specify `#tablex(rtl: true, ...)` to flip your table horizontally if you're writing a document in RTL (right-to-left) script. (You can use e.g. `#let old-tablex = tablex` followed by `#let tablex(..args) = old-tablex(rtl: true, ..args)` to not have to repeat the `rtl` parameter every time.)
- Added support for `box`'s dictionary inset syntax on tablex (https://github.com/PgBiel/typst-tablex/issues/54).
- For instance, you can now do `#tablex(inset: (left: 5pt, top: 10pt, rest: 2pt), ...)`.
- Fixed errors when using floating point strokes or other more complex strokes (https://github.com/PgBiel/typst-tablex/issues/55).
- Added full compatibility with the new Typst 0.8.0 type system (https://github.com/PgBiel/typst-tablex/issues/69).
- Added info about `#rotate` problems to "Known Issues" in the README (https://github.com/PgBiel/typst-tablex/pull/60).
- Improved docs for tablex options `columns` and `rows` (https://github.com/PgBiel/typst-tablex/issues/53).
### v0.0.5
- ⚠️ **Minimum Typst version raised to v0.2.0**
- Improved calculation of page/container dimensions by using the `layout()` function.
- Fixes tables with fractional columns not displaying properly in blocks with `auto` width (https://github.com/PgBiel/typst-tablex/issues/44; https://github.com/PgBiel/typst-tablex/issues/39)
- Fixes some nested tables overflowing the page width (https://github.com/PgBiel/typst-tablex/issues/41)
- Fixes bad interaction between tables with fractional columns and nested tables (https://github.com/PgBiel/typst-tablex/issues/28)
- Fixes table rotation messing up table size calculation (https://github.com/PgBiel/typst-tablex/issues/52)
- Probably fixes other issues not listed here as well.
- Added some guards for infinite lengths and `auto`-sized pages (https://github.com/PgBiel/typst-tablex/issues/47).
- Fixed tablex crashes/improper behavior with `em` strokes and other types of strokes (https://github.com/PgBiel/typst-tablex/issues/49).
- Added the tablex version number as a comment in the source file (as requested in https://github.com/PgBiel/typst-tablex/issues/25).
### v0.0.4
- Added `typst.toml` to support Typst v0.6.0's soon-to-be-released package manager (see https://github.com/PgBiel/typst-tablex/issues/22).
- Fixed a division by zero regression from v0.0.3 (https://github.com/PgBiel/typst-tablex/issues/19).
- Fixed a bug where cells placed in arbitrary positions could force an extra empty row to appear (https://github.com/PgBiel/typst-tablex/issues/16).
- Fixed `hlinex(gutter-restrict: top)` causing the hline to just disappear (https://github.com/PgBiel/typst-tablex/issues/20).
- Fixed certain `gutter-restrict` lines disappearing when there's no gutter (https://github.com/PgBiel/typst-tablex/issues/21).
- Fixed row gutter lines not properly splitting across pages (https://github.com/PgBiel/typst-tablex/issues/23).
### v0.0.3
- Added support for Typst v0.4.0 and v0.5.0.
- The tablex options `fill:` and `align:` now accept arrays of values for each column (https://github.com/PgBiel/typst-tablex/issues/13).
- For example, `fill: (red, blue)` would fill the first column with red, the second column with blue, and any further columns would alternate between the two fill colors.
- Fixed the calculation of the size of `auto` rows and columns when a rowspan or colspan was used (https://github.com/PgBiel/typst-tablex/issues/11).
- Fixed the calculation of the size of the last `auto` column when it was too long (https://github.com/PgBiel/typst-tablex/issues/6).
### v0.0.2
- Added support for Typst v0.3.0.
- Fixed strokes - now lines will expand to not look weird when strokes are larger.
- You can disable this behavior by setting `stroke-expand: false` on your lines.
- You can now arbitrarily change your lines' sizes at either end with the option `expand: (length, length)`; e.g. `expand: (5pt, 10pt)` will increase your horizontal line 5pt to the left and 10pt to the right (or, for a vertical line, 5pt to the top and 10pt to the bottom).
- Support for negative expand lengths is limited (so far, only reduces length in the first cell the line spans).
- Added some gutter fixes (not all gutter issues were fixed yet).
### v0.0.1
Initial release.
- Added types `tablex`, `cellx`, `hlinex`, `vlinex`
- Added type aliases `gridx`, `rowspanx`, `colspanx`
## 0.1.0 Roadmap
- [ ] General
- [X] More docs
- [ ] Code cleanup
- [ ] Table drawing rework
- [ ] `#table` parity
- [X] `columns:`, `rows:`
- [X] Basic support
- [X] Accept a single size to mean a single column
- [X] Adjust `auto` columns and rows
- [X] Accept integers to mean multiple `auto`
- [X] Basic unit conversion (em -> pt, etc.)
- [X] Ratio unit conversion (100% -> page width...)
- [X] Fractional unit conversion based on available space (1fr, 2fr -> 1/3, 2/3)
- [X] Shrink `auto` columns based on available space
- [X] `fill`
- [X] Basic support (`color` for general fill)
- [X] Accept a function (`(column, row) => color`)
- [X] Accept an array of colors (one for each column)
- [X] `align`
- [X] Basic support (`alignment` and `2d alignment` apply to all cells)
- [X] Accept a function (`(column, row) => alignment/2d alignment`)
- [X] Accept an array of alignment values (one for each column)
- [X] `inset`
- [ ] `gutter`
- [X] Basic support
- [X] `column-gutter`
- [X] `row-gutter`
- [ ] Hline, vline adaptations
- [X] `stop-pre-gutter`: Makes the hline/vline not transpose gutter boundaries
- [X] `gutter-restrict`: Makes the hline/vline not draw on both sides of a gutter boundary, and instead pick one (top/bottom; left/right)
- [ ] Properly work with gutters after colspanxs/rowspanxs
- [X] `stroke`
- [X] Basic support (change all lines, vline or hline, without override)
- [X] `none` for no stroke
- [X] Default to lines on every row and column
- [ ] New features for `#tablex`
- [X] Basic types (`cellx`, `hlinex`, `vlinex`)
- [X] `hlinex`, `vlinex`
- [X] Auto-positioning when placed among cells
- [X] Arbitrary positioning
- [X] Allow customizing `stroke`
- [X] `colspanx`, `rowspanx`
- [X] Interrupt `hlinex` and `vlinex` with `end: auto`
- [X] Support simultaneous col/rowspan with `cellx(colspanx:, rowspanx:)`
- [X] Support nesting colspan/rowspan (`colspanx(rowspanx())`)
- [X] Support cell attributes (e.g. `colspanx(2, align: left)[a]`)
- [X] Reliably detect conflicts
- [ ] Repeating headers
- [X] Basic support (first row group repeats on every page)
- [ ] Work with different page sizes
- [X] `repeat-header`: Control header repetition
- [X] `true`: Repeat on all pages
- [X] integer: Repeat for the next 'n' pages
- [X] array of integers: Repeat on those (relative) pages
- [X] `false` (default): Do not repeat
- [X] `header-rows`: Indicate what to consider as a "header"
- [X] integer: At least first 'n' rows are a header (plus whatever rowspanxs show up there)
- [X] Defaults to 1
- [X] `none` or `0`: no header (disables header repetition regardless of `repeat-header`)
- [X] `cellx`
- [X] Auto-positioning based on order and columns
- [X] Place empty cells when there are too many
- [X] Allow arbitrary positioning with `cellx(x:, y:)`
- [X] Allow `align` override
- [X] Allow `fill` override
- [X] Allow `inset` override
- [X] Works properly only with `auto` cols/rows
- [X] Dynamic content (maybe shortcut for `map-cells` on a single cell)
- [X] Auto-lines
- [X] `auto-hlines` - `true` to place on all lines without hlines, `false` otherwise
- [X] `auto-vlines` - similar
- [X] `auto-lines` - controls both simultaneously (defaults to `true`)
- [X] Iteration attributes
- [X] `map-cells` - Customize every single cell
- [X] `map-hlines` - Customize each horizontal line
- [X] `map-vlines` - Customize each vertical line
- [X] `map-rows` - Customize entire rows of cells
- [X] `map-cols` - Customize entire columns of cells
## License
MIT license (see the `LICENSE` file).
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/commute/0.1.0/README.md | markdown | Apache License 2.0 | # Commute
Proof-of-concept commutative diagrams library for [typst](https://typst.app/home)
# Example
```
#import "@preview/commute:0.1.0": node, arr, commutative-diagram
#align(center)[#commutative-diagram(
node((0, 0), [$X$]),
node((0, 1), [$Y$]),
node((1, 0), [$X \/ "ker"(f)$]),
arr((0, 0), (0, 1), [$f$]),
arr((1, 0), (0, 1), [$tilde(f)$], label-pos: -1em, "dashed", "inj"),
arr((0, 0), (1, 0), [$pi$]),
)]
```

For more usage examples look at `example.typ`
# Usage
The library provides 3 functions: `node`, `arr`, and `commutative-diagram`.
You can clone this repo and import `lib.typ`:
```
#import "path/to/commute/lib.typ": node, arr, commutative-diagram
```
Or directly use the builtin package manager:
```
#import "@preview/commute:0.1.0": node, arr, commutative-diagram
```
## `commutative-diagram`
```
commutative-diagram(
node-padding: (70pt, 70pt),
arr-clearance: 0.7em,
padding: 1.5em,
debug: false,
..entities
)
```
`commutative-diagram` returns a rectangular region containing the
nodes and arrows.
All the unnamed arguments passed to `commutative-diagram` are treated as
nodes or arrows of the diagram. These can be constructed using the
`node` and `arr` functions explained below.
The other arguments are as follows:
- `node-padding`: `(length, length)`. The space to leave between adjacent nodes. It's a
tuple, `(h, v)`, containing the horizontal and vertical spacing respectively.
- `arr-clearance`: `length`. The default space between arrows' base/tip and the diagram's nodes.
- `padding`: `length`. The padding around the whole diagram
- `debug`: `bool`. Whether or not to display debug information.
## `node`
```
node(
pos,
label,
)
```
Creates a new diagram node. Has the following positional arguments:
- `pos`: `(integer, integer)`. The position of the node in `(row, column)` format.
Must be integers, but can be negative, the only thing that counts is the
difference between the coordinares of the variuos nodes in the diagram.
- `label`: `content`. The node's label.
## `arr`
```
arr(
start,
end,
label,
start-space: none,
end-space: none,
label-pos: 1em,
curve: 0deg,
stroke: 0.45pt,
..options
)
```
Creates an arrow. Has the following arguments:
- `start`: `(integer, integer)`. The position of the node from which the arrow starts,
in `(row, column)` format.
- `end`: `(integer, integer)`. The position of the node where the arrow ends,
in `(row, column)` format.
- `label`: `content`. The label to put on the arrow.
- `start-space`: `length`. The space between the start node and the beginning of the arrow.
You can pass `none` to leave a sensible default, customizable using the
`arr-clearance` parameter of the `commutative-diagram` function.
- `end-space`: `length`. Similar to the above.
- `label-pos`: `length`. Where to position the arrow's label relative to the arrow.
A positive length means that, when looking towards the tip of the arrow,
the label is on the "left". If set to `0` (`0` the number, which is different from `0pt` or `0em`)
then the label is placed on top of the arrow, with a white background to help
with legibility.
- `curve`: `angle`. The difference in orientation between the start and the end of the arrow.
If positive, the arrow curves to the right, when looking towards the tip.
- `stroke`: `stroke`. The thickness and color of the arrows. The default should probably be fine.
- `options`: `string`s. After the mandatory positional arguments `start`, `end` and `label`,
any remaining unnamed argument is treated as an extra option. Recognized options are:
- `"inj"`, gives the arrow a hook at the start, used for injective functions
- `"surj"`, gives the arrow a double tip, used for surjective functions
- `"bij"`, gives the arrow a tip also at the start, used for bijective functions
- `"def"`, gives the arrow a bar at the start, used for function definitions
- `"dashed"`, the arrow becomes dashed
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas5/4_Stvrtok.typ | typst | #let V = (
"HV": (
("","Rádujsja póstnikom","Vsjú prošédše zémľu, vsíjaste božéstvennaja učénija, slóvo tóčiju jáko svíščnik i bohátstvo vsé, učenicý Hospódni nosjášče, ímže carí že i mučíteli posramíste, i ľubomudrecém i vitíjam ľútosť jáko paučínnaja razdráste pleténija, vsích k rázumu prizyvájušče ziždíteľa, i sújetnaja služénija bisóvskaja otémľušče. Ťímže moľú, bezslovésnych izbáviti mjá strastéj molítvami vášimi."),
("","","Matéža iskušénij, i ľútyja lží bezčéstnych jereséj, bisóvskaho zlosovítija, i čelovík hórkaho soobščénija i búri vseblažénniji, ohňá nesvitímaho, i víčnujuščaho čérvija, skréžeta zubnáho, i vsjákija inýja múki, k Bóhu moľbámi izbávite vsích nás, i sehó umolíte, vozderžánija rádi i trudóv, dobroďítelej vozdajánij polučíti, nasľídija že nebésnaho cárstvija, i véliju mílosť."),
("","","Vsjú svítlosť jásno vosprijémľušče, tróičnyj svít vtorýj neizrečénnaho smotrénija, jáko móščno voístinnu čelovíčeskomu jestestvú, vsechváľnaja desjatíca so dvóiceju, pokazásja soveršénňi voďášči jedinorevníteľnyj sobór, sedmídesjatich i dvú imúšči s ními, i vsjá prosviščájušče míra koncý, omračájuščyjasja ťmóju zlomúdrennych jereséj, Christá moľášče, podajúščaho mírovi véliju mílosť."),
("","Rádujsja póstnikom","Rádujsja svjáščénnaja hlavó, čístoje dobroďítelej obítelišče, božéstvennoje neporóčnaho svjaščénstva právilo, pástyrju velíkij jávstvennyj, svítloje pobídy nosjá íma, moľáščymsja mílostivnyj prikloníteľu, prekloňájasja k nemoščných moľbám, izbáviteľ hotóvyj, pribížišče spasíteľnoje vsím, víroju čtúščym prísno slávnuju tvojú pámať, Christá molí, nizposláti nám véliju mílosť."),
("","","Rádujsja svjaščénňijšij úme, Tróicy čístoje žilíšče, stólpe cerkóvnyj, vírnych utverždénije, ozlóblennym pomóščniče, zvizdá íže blistáňmi blahoprijátnych molítv, razorjája napásti že i skórbi ťmú vsehdá, svjatíteľu Nikólaje: pristánišče tíchoje, v néže pribihájušče trevolnéniji žitijá napástvujemiji spasájutsja. Christá molí, nizposláti dušám nášym véliju mílosť."),
("","","Rádujsja vo svjatítelech právilo, božéstvennych čudés neisčerpájemaja pučíno, krasotó cerkóvnaja, svítlaja zvizdó, svjaščénnymi tvojími blažénne blistáňmi, nás ozarjája kojehóždo svjaťíjšij, presvítlymi mólnijami prosviščájem: stólpe neoborímyj, stepéňu víry, čéstnúju tvojú pámjať ľubóviju soveršájuščym, Christá molí, dušám nášym darováti véliju mílosť."),
("Bohoródičen","","Rádujsja proróčeskaja pečáte, i Bohohlásnych apóstol propovídanije: Bóha bo voístinnu súščaho voploščénna, páče umá i slóva rodilá jesí, čístaja: ímže pérvoje vospriímše blahoródije, i rájskija píšči naslaždájuščesja, tebé chodátaicu takovýja svítlosti, i molítvennicu blahoprijátnu, písňmi počitájem. Tobóju prečístaja obohatívšesja, prisnosúščnyja spodobľájemsja žízni Sýna tvojehó, podajúščaho bohátno véliju mílosť."),
),
"S": (
("","","Učenicý Spásovy táin samovídcy bývše, nevídimaho i načála ne imúščaho propovídaste, hlahóľušče: v načáľi bí slóvo. Ne sózdani býste préžde ánhel, ni naučístesja ot čelovík, no ot výšnija premúdrosti. Ťímže derznovénije imúšče, molítesja o dušách nášich."),
("","","Apóstoly Hospódni sohlásno písňmi pochválim, oblékšesja bo v kréstnoje orúžije, ídoľskuju prélesť uprazdníša, i pobidonósniji javíšasja vinéčnicy: íchže molítvami i vsích svjatých, Bóže, pomíluj nás."),
("Múčeničen","","Nesýtnoju ľubóviju duší, Christá ne otverhóstesja svjatíji múčenicy, íže razlíčnyja rány strastéj preterpívše, mučítelej dérzosť nizložíste, nepreklónnu i nevredímu víru sochráňše, na nebesá prestávistesja. Ťímže i derznovénije imúšče k nemú, prosíte darováti nám véliju mílosť."),
("Bohoródičen","","Blažím ťá Bohoródice Ďívo, i slávim ťá vírniji po dólhu, hrád nepokolebímyj, sťínu neoborímuju, tvérduju predstáteľnicu, i pribížišče dúš nášich."),
),
)
#let P = (
"1": (
("","","Spasíteľu Bóhu, v móri ľúdi nemókrymi nohámi nastávľšemu i faraóna so vsevóinstvom potópľšemu, tomú jedínomu poím, jáko proslávisja."),
("","","Svitonósnaja skínije carjá Christá, ozarí mojú mýsľ omračénnuju léstiju borcá, i ťmóju osľiplénnuju prehrišénij mojích."),
("","","Pomyšlénij lukávych smirénnuju mojú dúšu Bohorodíteľnice svobodí, i žilíšče Bóhu sijú soďílaj, da po dólhu ťá slávľu vsehdá."),
("","","Jehdá poveľínijem Bóžijim, ot vrémennyja žízni otití choščú prečístaja, bisóvskija rukí pokaží mja výšša, ánhely podajúšči spútniki mňí."),
("","","Vskúju, o dušé! vo unýniji mnózi vsé žitijé iždíla jesí? Potščísja úbo próčeje, i vozopíj Hospódni Máteri: očísti i spasí mja, Bohorodíteľnice."),
),
"3": (
("","","Síloju krestá tvojehó Christé, utverdí mojé pomyšlénije, vo jéže píti i sláviti tridnévnoje tvojé voskresénije."),
("","","Iz róva strastéj i mučénij vozvedí mja, nesumňínno pojúšča ťá, Bohoródice vseblažénnaja."),
("","","Vrétišče mojé rastórhni bezmírnych prehrišénij mojích, i vesélijem opojáši dobroďítelej, Bohoblahodátnaja."),
("","","Kápľu mí čístaja sléz podážď, jáko da otženú sérdca mojehó nedoumínije, i priľížno vospojú ťa."),
("","","Nizloží preneporóčnaja vráh bezplótnych šatánije, i ťích tomlénija vskóri svobodí mja."),
),
"4": (
("","","Uslýšach slúch síly krestá, jáko ráj otvérzesja ím, i vozopích: sláva síľi tvojéj Hóspodi."),
("","","Vskúju upodóbilasja jesí dušé, neplódňij smokóvnici, nikákože bojáščisja posičénija i plámene víčnaho? Uskorí úbo préžde koncá, i vozníkni."),
("","","Kíj jazýk izrečét soďíjannych mojích zól bezmírnoje móre, i hlubinú prehrišénij? Spasí mja, Ďívo preneporóčnaja, otčájannaho."),
("","","Sebé pláču, jehdá vo úm prijidú mnóhich mojích prehrišénij, i ohňá nehasímaho: i moľú ťa, dáti mí vrémja pokajánija, čístaja."),
("","","Da ne voschítit jáko lév stroptívyj vráh okajánnuju mojú dúšu: no tvojéju síloju dušetľínnyja sokruší zúby jehó, blahája."),
),
"5": (
("","","Útreňujušče vopijém tí Hóspodi, spasí ny: tý bo jesí Bóh náš, rázvi bo tebé inóho ne znájem."),
("","","Prízri i uslýši Vladýčice, hlás mój, i izbávi mjá, moľúsja, víčnaho osuždénija."),
("","","Ujazvíchsja hrichá strilámi, i vopijú ti: uvračúj, prečístaja, sérdca mojehó jázvy."),
("","","Pomíluj mjá jedíne čelovikoľúbče ščédryj, molítvami róždšija ťá: tý bo mí jesí Bóh i Hospóď."),
("","","Pomíluj mjá jedína vsepítaja, moľú tvojú bláhosť, i mílosti spodóbi."),
),
"6": (
("","","Obýde mjá bézdna, hrób mňí kít býsť, áz že vozopích k tebí čelovikoľúbcu, i spasé mja desníca tvojá Hóspodi."),
("","","Jáko lév rykája ľstívyj íščet mjá rastórhnuti, i pokazáti sňíď svojéj zlóbi, čístaja: no sehó vréda svobodí mja."),
("","","Očísti čelovikoľúbče, molítvami čísto róždšija ťá, i izbávi mír tvój ot vsjákija skórbi, i víčnyja slávy spodóbi."),
("","","Obýde mjá bézdna prehrišénij, vo hlubinú nizvédši otčájanija, moľúsja, čístaja, vozvedí ot preispódňaho áda, tebé slávjaščaho."),
("","","Žitijé mojé ispólnisja prehrišénij, i vsjákija ľínosti: ťímže k pokajániju préžde končíny mojejá čístaja, obratí, i spasí mja prepítaja."),
),
"S": (
("","Sobeznačáľnoje Slóvo","Rádujsja, sťinó, tvérdaja Bohopobídnaja, rádujsja, padénije várvarov vsevojevánnoje, rádujsja, vozvedénije vírnych pravoslávnych ľudéj, Bohoródice, voístinnu upovájuščich na ťá, molítvami tvojími izbavľájušči nás ot bíd vsjáčeskich, i ot bezbóžnych vráh."),
),
"7": (
("","","V peščí óhnenňij pisnoslóvcy spasýj ótroki, blahoslovén Bóh otéc nášich."),
("","","Nevóľnych zól i vóľnych, proščénije tvojéju bláhostiju Vladýčice, podážď mí."),
("","","Iznemohájet mój úm, prilóhi nečéstija lukávych pómysl: pomozí mi, blahája."),
("","","Dušévnych mojích strastéj rány, Bohoródice, tvojích molítv ľičbámi nýňi iscilí."),
("","","Sokrušénnu dúšu, i pómysl smirén, podážď mí blahája: jáko da slávľu ťá."),
),
"8": (
("","","Iz Otcá préžde vík roždénnaho Sýna i Bóha, i v posľídňaja ľíta voploščénnaho ot Ďívy Mátere, svjaščénnicy pójte, ľúdije prevoznosíte vo vsjá víki."),
("","","V ľínosti žitijé skončáv okajánnyj, i priblíživsja k koncú životá mojehó, vzyváju tí Bohoródice: soprotívnych ischití sitéj smirénnuju mojú dúšu."),
("","","Ťilésnych boľíznej, rán ľútych dušévnych, i strastéj nastojánija isťazújemu, tvojehó cárstvija sílu mí podážď, jáko jedína mílostiva."),
("","","V pučíňi žitijá oburevájema, i bisóvskimi volnámi pohružájema, spasí čístaja, i božéstvennomu ustremléniju, k blahouhódnomu žitijú vvedí mja, otrokovíce."),
("","","Jáko v nevístnyj čertóh vchoďá Ďívo, Havrijíl póslan, rádujsja vozopí, hlahóľa: preslávnaja paláto vsích carjá Christá, v ňúže vséľsja, zemnýja vsjá oboží."),
),
"9": (
("","","Ťá páče umá i slovesé Máter Bóžiju, v ľíto bezľítnaho neizrečénno róždšuju, vírniji jedinomúdrenno veličájem."),
("","","Ťá júže Bóha neskazánno róždšuju, zastúpnicu sťažáchom, i sťínu nedvížimu, i dušám spasénije, i čudesém istóčnik."),
("","","Mílostiv búdi mí, Slóve ístinnaho Bóha, v déň sudá, moľbámi róždšija ťá: i súščym odesnúju tebé sočetáj."),
("","","Izbávi mjá čístaja, ohňá víčnujuščaho, i neusypájuščaho čérvija, i vsjákija múki, na ťá nadéždu vozlóžšaho."),
("","","Jehdá chóščet dušá mojá razlučítisja ot okajánnaho mojehó ťilesé, nevídimych vráh tomíteľstva izbávi mjá Bohonevístnaja."),
),
)
#let U = (
"S1": (
("","","Jáko samovídcy i sluhí Slóva, premúdryja apóstoly pochválim, písňmi duchóvnymi i píňmi vsí zemníji: tíji bo Christá priľížno móľat o nás, pojúščich svjaščénnuju ích pámjať, i kláňajuščichsja moščém ích."),
("","","Apóstoly sohlásno voschválim, jáko samovídcy Slóva, i božéstvennyja propovídniki, i jazýkov duchóvnyja ulovíteli, jáko jávi privedóša nás k poznániju Christá, izbávľše ot prélesti ród čelovíčeskij, i cárstvija spodóbiša."),
("Bohoródičen","","Osuždén jésm sudóm sóvisti, i préžde sudá súd pomyšľája, trepéšču okajánnyj, pominája zól mojích mnóžestvo. No k tebí neoborímij umilénijem vopijú, i predstátelnici, i pokróvu: ónaho studá izbávi mjá, i spasí molítvami tvojími."),
),
"S2": (
("","","Apóstoly sohlásno pochválim, jáko propovídaša vsím pravoslávnoje Hospódne učénije, i prohnávšyja jeretíčeskuju mhlú, i prosviščénije duchóvno vozsijávšyja v míri, blahodáti učénijem: i móľatsja spastísja nám."),
("","","Apóstoly sohlásno pochválim, jáko propovídaša vsím pravoslávnoje Hospódne učénije, i prohnávšyja jeretíčeskuju mhlú, i prosviščénije duchóvno vozsijávšyja v míri, blahodáti učénijem: i móľatsja spastísja nám."),
("Múčeničen","","Svjatých múčenik ispravlénijem nebésnyja síly preudivíšasja: káko v ťíľi mértvenňim dóbri podvíhšesja, bezplótnaho vrahá síloju krestnoju nevídimo pobidíša: i móľatsja Hóspodevi, pomílovatisja dušám nášym."),
("Bohoródičen","","Ťá pristánišče, i sťínu, i pribížišče, i nadéždu, i pokróv, i zastuplénije téploje obrítše vírniji, k tebí pritekájem, i vopijém priľížno, i zovém vírno: pomíluj Bohoródice upovájuščich na ťá, i ot prehrišénij izbávi."),
),
"S3": (
("","Sobeznačáľnoje Slóvo","Učenicý Spásovy, božéstvenniji apóstoli, íže slóvo spasíteľnoje vsíjavše v koncý zemlí, i ozarívše vo ťmí i síni siďáščyja, mojú prosvitíte dúšu omračénnuju strastéj čérnostiju, moľbámi vášimi vsechváľniji."),
("","","Hóspodi, neizrečénnoje táinstvo tvojehó voploščénija propovídavše nemúdriji, filosófov posramíša, rítorov rýbarije zaustíša, i býša jazýkov premúdriji učítelije, prosvitívše koncý svítom božéstvennaho rázuma: ťími podážď nám véliju mílosť."),
("Bohoródičen","","Íže upovánije na ťá Ďívo prečístaja, nepotknovénnoje imúščym, pokróv súšči ot razlíčnych napástej i obstojánij, i bíd ľútych svobodí nás, moľášči Sýna tvojehó, so apóstoly jehó, i spasí vsích vospivájuščich ťá."),
),
"K": (
"P1": (
"1": (
("","","Koňá i vsádnika v móre čermnóje, sokrušájaj bráni mýšceju vysókoju, Christós istrjasé: Izráiľa že spasé, pobídnuju písň pojúšča."),
("","","Sijánijem pervodátnaho svitodánija, plótiju besídovati čelovíkom spodóbivšahosja, obohatívšesja slávniji, duší mojejá razrušíte vsják mrák, božéstvenniji apóstoli."),
("","","Sijánijem pervodátnaho svitodánija, plótiju besídovati čelovíkom spodóbivšahosja, obohatívšesja slávniji, duší mojejá razrušíte vsják mrák, božéstvenniji apóstoli."),
("","","Naprjáh božéstvennyj lúk, jákože stríly vás vo vés mír poslá apóstoli, stríly sokrušájuščyja zlokóznennaho vsjá, i isciľájuščyja vírnych jázvy."),
("","","Imúšče premúdrosť sámuju učíteľa, umudríste apóstoli vsjá koncý. Ťímže mjá umudríte, vrážije vsjáko zloďíjstvo othoňáti."),
("Bohoródičen","","Jedí<NAME>oslovénnaja, Bohorádovannaja, blahoslovéňmi čelovíčeskij ród obrádovavši, Christá molí s božéstvennymi, prečístaja, apóstoly, pomílovatisja nám."),
),
"2": (
("","","Koňá i vsádnika v móre čermnóje, sokrušájaj bráni mýšceju vysókoju, Christós istrjasé: Izráiľa že spasé, pobídnuju písň pojúšča."),
("","","Víroju i ľubóviju, ótče, prisvóivsja Bóhovi, vsesvjatája sehó ispólnil jesí choťínija: ímže po vsemú svját býl jesí, svjatíteľu múdre Nikólaje."),
("","","Imúšče ťá predstáteľa k ščédromu, íže napásťmi i pečáľmi oderžímiji, k tebí pribihájem: dáruj rúku spasájuščuju nás ot vsjákija ťisnotý."),
("","","Mírjanom svjatíteľa Christós pomáza ťá, blahovónijem čudés nás oblahouchájušča. Ťímže mólim ťá Nikólaje, zlovónija hrichóvnaho izbáviti nás."),
("Bohoródičen","","Drévle proróčeskij ťá lík pronarečé hóru božéstvennuju Ďívo, i dvér neprochodímuju. Ťímže mólimsja tí: pokajánija dvéri božéstvennyja, otrokovíce, otvérzi nám."),
),
),
"P3": (
"1": (
("","","Vodruzívyj na ničesómže zémľu poveľínijem tvojím, i povísivyj neoderžímo ťahoťíjuščuju, na nedvížimim Christé, kámeni zápovidej tvojích, cérkov tvojú utverdí, jedíne bláže i čelovikoľúbče."),
("","","Íže plótiju obniščávyj, premnóhij bláhostiju, jehó rádi obniščávšyja, obohatí vás slávniji apóstoli, darováňmi vsjákimi, obohaščájuščja koncý božéstvennymi i čestnými rázumy."),
("","","Íže plótiju obniščávyj, premnóhij bláhostiju, jehó rádi obniščávšyja, obohatí vás slávniji apóstoli, darováňmi vsjákimi, obohaščájuščja koncý božéstvennymi i čestnými rázumy."),
("","","Ujazvíchsja jadovítym zmíja uhryzénijem, ujázveno sérdce sťažách. Ťímže tí vopijú Christé, mené rádi ujazvívšemusja: apóstol tvojích moľbámi iscilí, i spasí mja, moľúsja."),
("","","Mréžeju molítv vášich vseblažénniji, ot hlubiný zlóbnyja boríteľa, i ot trevolnénija pomyšlénij, i ot strastéj smertonósnych vozvédše mjá, privedíte Bóhu vsích spasájema."),
("Bohoródičen","","Jáže dóžď prijémšaja nebésnyj, so apóstoly tohó molí: ustáviti potóki mojích strastéj, pučínu izsušájušči hrichá mojehó, i spastí mja, čísto tebé slávjaščaho."),
),
"2": (
("","","Vodruzívyj na ničesómže zémľu poveľínijem tvojím, i povísivyj neoderžímo ťahoťíjuščuju, na nedvížimim Christé, kámeni zápovidej tvojích, cérkov tvojú utverdí, jedíne bláže i čelovikoľúbče."),
("","","Stríly lukávaho pritupíl jesí prepodóbne, protivlénijem božéstvennych tvojích trudóv: no tvojími molítvami premúdre, ot tohó zloďíjstvija i nasílija sobľudí nevreždénny, tebé vospivájuščyja, velíkij Nikólaje."),
("","","Žitijé ánheľskoje na zemlí pokazáv, nýňi so ánhely prísno predstoíši prestólu Tróičeskomu, svjaščénne, nášich sohrišénij i napástej razrišénija prosjá, ótče pervosvjatíteľu Nikólaje."),
("","","Umá mojehó omračénije vsé otžení Nikólaje, tvojími svitonósnymi molítvami, utíši búrju strastéj, uprávi mjá ótče, k bezstrástija pristánišču, moľúsja, jáko da vo chvaléniji slávľu ťá."),
("Bohoródičen","","Predstojášči odesnúju Christá, jáko caríca, rjásny zlatými Bohoobrádovannaja oďíjana voístinnu, nám cárstvije nebésnoje molítvami tvojími otrokovíce, ischodátaj vseneporóčnaja."),
),
),
"P4": (
"1": (
("","","Božéstvennoje tvojé razumív istoščánije, prozorlívo Avvakúm, Christé, so trépetom vopijáše tebí: vo spasénije ľudéj tvojích spastí pomázannyja tvojá prišél jesí."),
("","","Dvér sýj Iisús Bóh náš i Hospóď, otvérzl svojé apóstolom poznánije, vsém jazýkom dvér otvérze ťích učéňmi."),
("","","Dvér sýj Iisús Bóh náš i Hospóď, otvérzl svojé apóstolom poznánije, vsém jazýkom dvér otvérze ťích učéňmi."),
("","","Sýne Bóžij, sýny po pričástiju nebésnaho Otcá tvojehó apóstoly javíl jesí: molénijem ích sýny svíta vsích nás sotvorí."),
("","","Íže na prestóľich dvojunádesjatich, so sudijéju i carém choťášče preslávno sísti, strášnaho i užásnaho mjá apóstoli, izbávite sudá."),
("Bohoródičen","","Božéstvennaho svjaščénija kovčéže, osvjatí mojú dúšu, pomyšlénije prosvití, vsehdá moľášči Christá so apóstoly, da spasét mjá."),
),
"2": (
("","","Božéstvennoje tvojé razumív istoščánije, prozorlívo Avvakúm, Christé, so trépetom vopijáše tebí: vo spasénije ľudéj tvojích spastí pomázannyja tvojá prišél jesí."),
("","","Mimotekúščimi izminíl jesí búduščaja, íchže pričástniki i nás svjatými tvojími molítvami sotvorí Nikólaje, i iskušénija vsjákaho izbavľája žitéjskaho."),
("","","Mírjanom pervoprestóľnik býv Nikólaje, vsjá čúvstvija sérdca mojehó mírom oblahoucháj svjáte, i strásti zlosmrádnyja ot sehó, molítvami tvojími othoňáj vsehdá."),
("","","Sokruší vrážija kózni vídimyja, i nevídimyja, Nikólaje, vsehdá borjúščyja ný náša vrahí v bezkonéčnuju páhubu poslí."),
("Bohoródičen","","Svjatája Bohoródice, pomozí mi, sládosťmi výnu potopľájemu ťilésnymi, i na odrí unýnija prísno sležášču i steňášču."),
),
),
"P5": (
"1": (
("","","Oďijájsja svítom jáko rízoju, k tebí útreňuju, i tebí zovú: dúšu mojú prosvití omračénnuju Christé, jáko jedín blahoutróben."),
("","","Duchóvniji vitíji, čestníji apóstoli, na hórnicie, vo óhnenňi víďi Dúcha svjatáho k ním prišédša, strášno prijáša."),
("","","Duchóvniji vitíji, čestníji apóstoli, na hórnicie, vo óhnenňi víďi Dúcha svjatáho k ním prišédša, strášno prijáša."),
("","","Sokrušájušče nečéstija, sokrušénuju prehrišéňmi mojú mýsľ, rosóju iscilénija apóstoli iscilíte."),
("","","Stríly izbránnyja vás Christós poslá apóstoli, sokrušájuščyja stríly lukávstvija: ťímže mjá iscilíte ujázvennaho vrážijimi strilámi."),
("Bohoródičen","","Ne osudí mené, ni otvérži mené ot licá tvojehó, mnohomílostive: mólit ťá čísto róždšaja, i apóstoľskij sobór."),
),
"2": (
("","","Oďijájsja svítom jáko rízoju, k tebí útreňuju, i tebí zovú: dúšu mojú prosvití omračénnuju Christé, jáko jedín blahoutróben."),
("","","Kumíry sokrušíl jesí ídoľskija svjáte, i sovíty bezďíľny jeretíčestvujuščich pokazál jesí Nikólaje, i vedómyja na smérť izbávil jesí."),
("","","Útrenevav ko Hóspodu izmláda prepodóbne, i támo súščimi svitolítiji vés prosvitílsja jesí. Ťímže moľúsja: duší mojejá óblaki razžení."),
("","","Tebé mólim, ótče Nikólaje, v čás séj posreďí búdi vsích prizyvájuščich ťá, i jáže ko spaséniju dáruj nám prošénija."),
("Bohoródičen","","Nepostížimyj umóm, Bohoblahodátnaja, obderžánije ťá, plotonósec býv, priját čelovíki, izbavľája ot oderžáščich skorbéj."),
),
),
"P6": (
"1": (
("","","Neístovstvujuščejesja búreju dušetľínnoju, Vladýko Christé, strastéj móre ukrotí, i ot tlí vozvedí mja, jáko blahoutróben."),
("","","Rasprostraňájuščejesja ustávil jesí zlóby sohnítije, jazýkov dúši, čelovikoľúbče, sóliju učénija svjaščénnych učeník tvojích."),
("","","Rasprostraňájuščejesja ustávil jesí zlóby sohnítije, jazýkov dúši, čelovikoľúbče, sóliju učénija svjaščénnych učeník tvojích."),
("","","Hlubinú vési zól mojích Vladýko Christé, dážď mí rúku, i spasí mja čelovikoľúbče, moľbámi svjaščénnych apóstol tvojích."),
("","","Sudijé pravedňijšij, v déň sudá strášnaho, trépetnaho mjá izbávi osuždénija, blahoslávnych apóstol tvojích moľbámi."),
("Bohoródičen","","Otčájannaho mjá ot mnóžestva bezzakónij, spasénija Hóspodi spodóbi, učeník i Mátere tvojejá moľbámi."),
),
"2": (
("","","Neístovstvujuščejesja búreju dušetľínnoju, Vladýko Christé, strastéj móre ukrotí, i ot tlí vozvedí mja, jáko blahoutróben."),
("","","Mílostiva soďílaj Vladýku, tvojími molítvami, vsím čtúščym ťá Nikólaje, jáko da nášich prehrišénij razrišénije dárujet."),
("","","Nedúh izbávi i soblázn žitéjskich, napástej že i skorbéj Nikólaje, ťá molítvennika ko Hóspodu sťažávšich."),
("","","Vračá ťá izjáščna Vladýka pokazá Christós: ťímže nedúhi iscilí, blahočéstno k tebí pristupájuščich, Nikólaje."),
("Bohoródičen","","Rodíteľnica bezmúžnaja, Bohomáti bylá jesí, čístaja. Sehó rádi víroju moľú ťá: duší mojejá unýnija razžení."),
),
),
"P7": (
"1": (
("","","Prevoznosímyj otcév Hospóď, plámeň uhasí, ótroki orosí sohlásno pojúščyja: Bóže, blahoslovén jesí."),
("","","Prevoznosímyj otcév Hospóď, vás prevoznesé, vsjú nizvérže vrážiju sílu, učenicý Christóvy bohovídcy."),
("","","Skvérnu sérdca mojehó strujámi umilénija, vášimi moľbámi, apóstoli, omýjte, učášče vzyváti: Bóže, blahoslovén jesí."),
("","","Ohném božéstvennaho Dúcha véšč popalíste vsjákaho sújetstva: ťímže paľáščija mjá izbávite hejénny, učenicý Bóha Slóva."),
("Bohoródičen","","Jáže padénija Adámova ispravlénije, vozdvíhni pádšaho mjá v própasť zlóbnuju, molítvami tvojími Ďívo, i božéstvennych apóstol."),
),
"2": (
("","","Prevoznosímyj otcév Hospóď, plámeň uhasí, ótroki orosí sohlásno pojúščyja: Bóže, blahoslovén jesí."),
("","","Vés vozložívsja Bóhu Nikólaje, vsehó mja spasí, žitéjskimi strasťmí okajánno vsehdá vpádajušča, Bohomúdre."),
("","","Svitílo Bohozárňijšeje, umá mojehó ozarí, strastéj mrákom prísno pomračájema, i daváj blahoobrázno chodíti v žitijí."),
("","","Vsjákaja otverzájemaja na mjá Nikólaje, ustá lukávaja, tvojími molítvami zahradí: i izbávi mjá vídimych vráh i nevídimych."),
("Bohoródičen","","Iz tebé nám vozsijá nevečérneje sólnce, óblače vsesvítlyj, Christós Bóh náš, prosviščája íže vo ťmí nevíďinija Bohoródice."),
),
),
"P8": (
"1": (
("","","Tebí vseďíteľu, v peščí ótrocy, vsemírnyj lík splétše pojáchu: ďilá vsjákaja Hóspoda pójte. i prevoznosíte vo vsjá víki."),
("","","Tý mýslennyja óblaki, apóstoly Slóve rasprostérl jesí, kropjáščyja na ný dóžď premúdrych i božéstvennych učénij, i napojájuščyja nás vo vsjá víki."),
("","","Preudóbrenniji stolpí cerkóvniji, íže sijú deržáščiji víry učéňmi, sohnívšujusja duší mojejá chráminu, božéstvennym chitroďíjstvijem utverdíte, bohovídcy."),
("","","Stení dušé, i sléz potóki ot vsehó sérdca prinesí Hóspodevi, zovúšči: jedíne ščédryj, spasí i očísti mjá, vseslávnych apóstol molítvami blahoprijátnymi."),
("Bohoródičen","","Sijóne izbránnyj, cárkskij hráde, výšňaho mjá hráda hraždanína sotvorí, s božéstvennymi učenikí moľášči prečístaja Ďívo, bezľítnaho Sýna tvojehó."),
),
"2": (
("","","Tebí vseďíteľu, v peščí ótrocy, vsemírnyj lík splétše pojáchu: ďilá vsjákaja Hóspoda pójte. i prevoznosíte vo vsjá víki."),
("","","V Mírich pervosvjatíteľ býv velíkij, duší mojejá Nikólaje, čúvstvija mírom oblahoucháj: jáko da izbíhnu strastéj zlovónija, i Uťíšitelevu prijimú blahodáť."),
("","","Ustávil jesí premúdre tvojehó svjatáho jazýka strujámi, strují Árijevy chúľnyja. Ťímže vopijú ti: tóki strastéj mojích izsuší molítvami tvojími, Nikólaje vseblažénne."),
("","","Izbávi nás sohrišénij molítvami tvojími, démonskaho ozloblénija, jazýčeskaho pľinénija, i vsích čelovík lukávňijšaho zláho vréda, da ťá jáko izbáviteľa nášeho voschvaľájem."),
("Tróičen","","Íže Tróičeski jedinonačálije neprestánno víroju slávjašče, vozopijím: Ótče, i Slóve, i vsesvjatýj Dúše, pisnoslóvim ťá vo vsjá víki."),
("Bohoródičen","","V plóť nás rádi iz tebé Bóh obléksja, čístuju tebé vseneporóčnuju, vsemú ródu nášemu božéstvennuju pokazá Ďívo predstáteľnicu. Ťímže ťá vírniji velehlásno vospivájem."),
),
),
"P9": (
"1": (
("","","Isáije likúj, Ďíva imí vo čréve, i rodí Sýna Jemmanújila, Bóha že i čelovíka, Vostók ímja jemú: jehóže veličájušče, Ďívu ublažájem."),
("","","Nebesá uzvízdeny svítlosťmí božéstvennych dobroďítelej úmno javístesja, posreďí, Christá, jáko sólnce imúšče, i zemnýja koncý premúdriji obnovíste: sehó rádi blažími jesté."),
("","","Christóvy jázvy na božéstvenňim ťilesí vášem, jáko útvar vseblahoľípnu nosjášče premúdriji, ujázvlenuju mojú dúšu démonskimi strilámi, jáže ko Hóspodu chodátajstvy iscilíte."),
("","","V róvi preispódňim mjá hrichá sležášča, Christé, i ľínosti ľútyja snóm dúšu oťahčívšaho, tvojími Slóve, učenikí, jákože Lázarja vozdvíhnuvyj, spasí Hóspodi."),
("Bohoródičen","","Duší mojejá naprávi šéstvija Slóve Bóžij, k stezjám zápovidej tvojích nezablúdnych, imíja moľáščujusja róždšuju ťá prečístuju Ďívu, i premúdryja apóstoly tvojá mnohomílostive."),
),
"2": (
("","","Isáije likúj, Ďíva imí vo čréve, i rodí Sýna Jemmanújila, Bóha že i čelovíka, Vostók ímja jemú: jehóže veličájušče, Ďívu ublažájem."),
("","","Svjatíteľ božéstven býv, vsjá zápovidi sochraníl jesí Christóvy: ťímže vírnym chraníteľ božéstvennyj býl jesí, ótče Nikólaje, sobľudáj ťích ot vsjákich napástej i ozloblénija."),
("","","Jákože inohdá prepitál jesí hrád tvój iznemohájušč hládom, jáko dóbr pástyr, prepodóbne: tákožde i nýňi prepitáj dúšu mojú chľíbom razúmnym, ótče Nikólaje, ťá zastúpnika bláha sťažávšaho."),
("","","Ťá velíkoje sólnce, na vysoťí ležáščeje prísno cérkve Christóvy, prepodóbne pástyrju, vírno mólim ťá: svitonósnymi blistáňmi svíta, hlubókuju ťmú otžení hrichá dúš nášich."),
("","","Priblížisja, jákože píšetsja, déň strášnyj prišéstvija Christóva. Podvíhnisja dušé, otríni ľínosť, i usérdno Christú vozopíj: spasí mja Hóspodi, Nikolája tvojehó molénijem."),
("Bohoródičen","","Svíteľ ťá svíščnik prorók províďaše prečístaja, sviščú razúmnuju, nosjáščuju Christá, ímže prosvitíchomsja, íže vo ťmí ležáščiji i strastéch, ťá ublažájem Bohoródice prisnoďívo."),
),
),
),
"CH": (
("","","Učenicý Spásovy, tájnym samovídcy bývše, nevídimaho i načála neimúščaho propovídaste, hlahóľušče: v načáľi bí Slóvo, ne sózdani býste préžde ánhel, nižé naučístesja ot čelovík, no ot výšnija premúdrosti. Ťímže derznovénije imúšče, molíte o dušách nášich."),
("","","Apóstoly Hospódni sohlásno v písnech pochválim, obólkšesja bo v krestnoje vseorúžije, ídoľskuju lésť uprazdníša, i pobidonósniji javíšasja vinéčnicy: íchže molítvami i vsích svjatých, Bóže pomíluj nás."),
("Múčeničen","","V múkach súšče svjatíji, rádujuščesja, vopijáchu: kúpľa nám súť sijá ko Vladýci: vmísto bo byvájuščich rán na ťilesích, svítlo oďijánije vo voskresénije procvitét nám: vmísto bezčéstija, vincý: za úzy temníčnyja, ráj: i za jéže so zloďíji osuždénije so ánhely žitijé. Íchže molítvami Hóspodi, spasí dúšy náša."),
("Bohoródičen","","Blažím ťá Bohoródice Ďívo, jáko iz tebé vozsijá sólnce právednoje Christós, imíjaj véliju mílosť."),
),
)
#let L = (
"B": (
("","","Razbójnik na kresťí, Bóha ťá býti vírovav Christé ispovída ťá čísťi ot sérdca: pomjaní mja Hóspodi, vopijá, vo cárstviji tvojém."),
("","","Jákože óblacy svítliji zémľu proidóste božéstvenniji učenicý, vódu živótnuju okropľájušče, i serdcá istájavšaja prehrišéniji bohátno napojájete."),
("","","Jákože lučý tájnyja, sólnca vozsijávšaho ot Ďívy čístyja, prosvitíli jesté súščyja vo ťmí nevíďinija siďáščyja, božéstvenniji učenicý Christá Bóha nášeho."),
("Múčeničen","","Razžžénija ľútych mučénij, premúdriji preterpívše usérdnoju dušéju, popalíste ídoľskuju lésť, i k božéstvennomu uťišéniju preidóste svjatíji."),
("","","Da dráchmu vo hlubiňí prehrišénija pohrebénuju Christé, vzém ko Otcú prineséši, apóstoly propovídniki sotvoríl jesí božéstvennym Dúchom."),
("Tróičen","","Prebožéstvennaja Tróice, Ótče prebeznačáľne, sobeznačáľne Sýne, i Dúše svjatýj: jedíno Božestvó, vsích propovídnik molítvami cérkov tvojú sochraní."),
("Bohoródičen","","Apóstolov udobrénije Bohoobrádovannaja súšči, omračéna mjá slasťmí žitéjskimi, pokajánija prosvití, zarjámi, jáko da veličáju ťá."),
),
)
|
|
https://github.com/DarrenKwonDev/resume | https://raw.githubusercontent.com/DarrenKwonDev/resume/master/권수훈_cv_kor.typ | typst |
////////////////////////////
// global settings
////////////////////////////
#let default_font_size = 10pt
#let name_size = 12pt
#let personal_info_size = 10pt
// https://typst.app/docs/reference/layout/page/
#set page(
paper: "a4",
margin: 1cm,
numbering: "1 / 1",
)
// english version
#set text(
font: "Times New Roman",
size: default_font_size,
cjk-latin-spacing: none,
)
// korean version
#set text(
font: "Apple SD Gothic Neo",
size: default_font_size
)
#set heading(level: 1, supplement: none)
#set heading(level: 2, supplement: none)
#let sectionHeader = (title) => [
#align(left)[
#set text(size: section_size)
== #title
#v(-0.2cm)
#line(length: 100%, stroke: 1pt + black)
]
]
#let boxText = (txt) => [
#box(
stroke: 1pt + rgb("#F3F4F6"),
fill: rgb("#F3F4F6"),
outset: 3pt,
radius: 3pt,
)[
#text(weight: "bold")[
#text(txt)
]
]
]
////////////////////////////
// top of cv
////////////////////////////
#align(center)[
#set text(size: name_size)
= SUHUN KWON
]
#v(0cm)
#align(center)[
#set text(size: personal_info_size)
]
#v(0.2cm)
#align(center)[
#set text(size: personal_info_size)
#boxText(link("https://darrenkwondev.github.io/")[darrenkwondev.github.io])
#text(" | ")
#boxText(
link("https://github.com/DarrenKwonDev")[github.com/darrenkwondev]
)
#v(0.02cm)
#boxText("Seoul, South Korea")
#text(" | ")
#boxText("+82 10-6707-4624")
#text(" | ")
#boxText("<EMAIL>")
]
////////////////////////////
// intro (optional)
////////////////////////////
#set quote(block: true)
#quote[
Mainly focus on server, infra
#linebreak()
focus on low-level details to avoid pitfalls of leaky abstraction.
]
////////////////////////////
// sections related helpers
////////////////////////////
#let section_size = 11pt
#let sectionHeader = (title) => [
#align(left)[
#set text(size: section_size)
== #title
#v(-0.2cm)
#line(length: 100%, stroke: 1pt + black)
]
]
// justify-content: space-between 와 같은 기능은 없음.
// 양쪽 정렬을 위해서 grid의 왼쪽은 align left로, 오른쪽은 align right로 설정하는게 최선.
// grid : https://typst.app/docs/reference/layout/grid
#let educationEntity = (title, subtitle, where, when) => [
#grid(columns: (2.5fr, 1.5fr),
align(left)[
*#title*
#linebreak()
#subtitle
],
align(right)[
#where
#linebreak()
#when
]
)
]
#let careerHeader = (title, subtitle, department, when) => [
#grid(columns: (2.5fr, 1fr),
align(left)[
*#title*
#linebreak()
#subtitle
],
align(right)[
#department
#linebreak()
#when
]
)
]
////////////////////////////
// sections
////////////////////////////
#sectionHeader[Technical Skills]
- PL
- C/C++ : MFC, algorithm
- CPython : ruff, poetry, fastapi, uvloop, sqlalchemy, mypy, isort
- javascript/typescript : node.js runtime, express, react, redux, gulp, webpack
- Infra
- Database : postgresql, mongodb, sqlite, redis
- server components : nginx, let's encrpyt
- cloud native, ops : kubernetes, terraform, github-actions
- aws : VPC, NAT, ec2, s3, cloudfront, route53, lambda
- gcp : Network, NAT, compute engine, GKE, cloud run
- etc
- shell script : bash
- mark up language: latex, typst, html
- git, git hook, pre-commit, husky, lint-staged
- pine script(TradingView), fast expression(WroldQuant)
////////////////////////////
// Career Experience
////////////////////////////
#sectionHeader[Career Experience]
#careerHeader(
"RTG",
"Software Engineer",
"development dept",
"2024.02-Present")
- system trading
#careerHeader(
"Business Canvas",
"Software Engineer",
"development dept",
"2021.09-2023.02")
- Server, Infra
- clickstream data 수집을 위한 중계 서버 운영
- node.js multi connection relay server
- data processing 및 business metric 연산용 서버 아키텍쳐링 및 운영
- MQL(Marketing Qualified Lead), SQL(Sales Qualified Lead) 집계
- Web Programming
- 레거시 번들 코드(neutrino)를 제거하고 webpack으로 재작성. 개발 편의성 향상
- typescript을 점진적 마이그레이션하여 80% 정도의 코드를 교체
- storybook, rollup, svgr을 활용하여 design system 개발 및 배포 (#link("https://www.npmjs.com/package/typed-design-system")[npm link])
- 웹 개발 일반 (화면 구성, API 연동, 기능 추가 등)
#careerHeader(
"Freelancer",
"",
"",
"")
- TIPS(민간투자주도형 기술창업지원) 컨설팅 및 장표 작성 (합격)
////////////////////////////
// Education
////////////////////////////
#sectionHeader[Posts]
- #link("https://darrenkwondev.github.io/posts/2023-12-28_kernel_study_03.md/")[Inside the Kernel - How Load Average is Calculated]
#v(0.2cm)
- #link("https://darrenkwondev.github.io/posts/2024-01-06-cheap_k8s/")[
GCP에서 저렴하게 교육용 쿠버네티스를 운용하는 방법
]
#v(3.5cm)
////////////////////////////
// Education
////////////////////////////
#sectionHeader[Education]
#educationEntity(
"Naver Connect Foundation",
"boostcamp AI Tech, Recommender System",
"Seoul, South Korea",
"2023.03-2023.08"
)
#educationEntity(
"Seoul National University",
"B.S in Venture Business Management & Korean literature",
"Seoul, South Korea",
"2014.03-2022.09 (+ 2 year of military service)"
)
////////////////////////////
// Personal Projects
////////////////////////////
#let projectBox = (contents) => [
#box(
stroke: 1pt + rgb("#F3F4F6"),
inset: 4pt,
radius: 4pt,
width: 95%, // 차지할 수 있는 영역의 95%만. 100%면 상자끼리 딱 맞아 떨어져버림
)[
#text(contents)
]
]
#sectionHeader[Personal Projects]
#grid(columns: (1fr, 1fr),
align(left)[
#projectBox()[
*2d game engine* : ECS pattern based event driven game engine core
- C++, SDL2, lua(binding), game loop
- #link("https://github.com/DarrenKwonDev/simple_2d_game_engine")
]
#projectBox()[
*ko-fuzzy* : korean consonant matching, and fuzzy search
- korean regex, tsup, typescript
- #link("https://github.com/DarrenKwonDev/ko-fuzzy")
]
#projectBox()[
*style-journey* : personalize fashion recommendation service
- fastapi, docker, airflow, nginx, postgresql, s3
- #link("https://github.com/Lv2-Recsys-01/styl-backend")
]
],
align(left)[
#projectBox()[
*redis-like server* : redis-like server implementation
- C/C++, poll multiplexing base event loop
- #link("https://github.com/DarrenKwonDev/redis-like")
]
#projectBox()[
*other trivial projects*
- naver-vod-dl : transport stream merger and downloader
- bash
- fuze : one on one english tutor matching service
- react, react-spring, s3
- cineps : cinephiles web community
- nginx, express, mongodb, logrotate, Next.js
- edu-popkorn : korean learning app by video clips
- flutter
]
]
)
////////////////////////////
// OSS Contributions
////////////////////////////
// #sectionHeader[OSS Contributions]
////////////////////////////
// Other Experiences
////////////////////////////
#sectionHeader[Other Experiences]
#grid(columns: (1fr, 1fr),
align(left)[
- 한국벤처협회 PSWC 엑셀러레이팅 프로그램 수료
- 예비창업패키지 우수 등급 수료
],
align(left)[
- SQLD
]
) |
|
https://github.com/Mouwrice/thesis-typst | https://raw.githubusercontent.com/Mouwrice/thesis-typst/main/preface.typ | typst | I would like to thank prof. <NAME> for his enthusiasm for the drum application and his guidance during the project. I would also like to thank my parents for their support during my studies. Finally, I would like to thank my friends for their encouragement and support.
#v(16pt)
_The author gives permission to make this master dissertation available for
consultation and to copy parts of this master dissertation for personal use.
In all cases of other use, the copyright terms have to be respected, in particular with
regard to the obligation to state explicitly the source when quoting results from this
master dissertation._
29/05/2024
#v(16pt)
_This master's dissertation is part of an exam. Any comments formulated by the
assessment committee during the oral presentation of the master's dissertation are
not included in this text._
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/space-05.typ | typst | Other | // Test that space at start of non-backslash-linebreak line isn't trimmed.
A#"\n" B
|
https://github.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024/master/entries/summer/cad.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/templates/entries.typ": *
#import "/templates/headers.typ": *
#import "/templates/text.typ": *
#create_footerless_page(
title: [Computer Aided Design],
date: [Summer Break],
content: [
#box_header(
title: [Introduction],
color: purple.lighten(60%)
) \
#entry_text()
Computer-aided design, commonly referred to as _CAD_ is the process of creating a design with computer software. This allows an engineer to visualize and simulate their design without spending resources to build a prototype. Last year, we did not utilize CAD in our design process, which often meant that many of our designs never worked, causing a lot of delays. This year however, Jin decided to take the initiative and learned how to design a robot using Onshape, a popular web-based CAD platform.
#box_header(
title: [Learning CAD],
color: yellow.lighten(60%)
) \
#entry_text()
A new rule was implemented this season: *All teams must have a fully completed CAD of their functioning robot.* Last year, teams were blindly building their robots without any plan. The consequence was teams having to completely disassemble their robots because of an error. With the addition of the new rule, we hope to catch these mistakes ahead of time.
#entry_header(title: [Onshape])
Our team used onshape, a CAD software platform that allows engineers, designers, and other professionals to create, edit, and collaborate on 3D models and design projects. onshape is known for its innovative approach to CAD, as it differs from traditional CAD software.
\ #image("/assets/onshape.png") \
Onshape is also widely used in industries such as manufacturing, product design, architecture, and engineering for creating 3D models, assemblies, and drawings. Its collaborative and cloud-based nature simplifies the design process, reduces the need for extensive local hardware and software, and fosters more efficient design workflows.
]
)
#create_headerless_page(
design: [Jin],
witness: [Deb],
content: [
#entry_header(title: [Drive Train])
#entry_text()
Here is the initial CAD of our drive train. It has 6 motors, which we decided to use instead of instead of 4 so that we could have more speed and power. It is also fairly compact, with the central cross bars only being 20 holes long.
#image("/assets/drive_cad.png")
]
) |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/001%20-%20Magic%202013/003_Chronomaton.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Chronomaton",
set_name: "Magic 2013",
story_date: datetime(day: 11, month: 07, year: 2012),
author: "<NAME>",
doc
)
#figure(image("003_Chronomaton/01.jpg", height: 40%), caption: [], supplement: none, numbering: none)
Bazzle woke with a start. He heard a cry of alarm and the sounds of boots rushing outside. He sat up with some effort and listened to the chimes and ticks of the two hundred twelve clocks around him. It was a comforting noise, so much so that the cry for help had to register a second time in his mind before he realized what had probably happened.
#emph[It got out again. My creation continues to defy my wishes!]
He cast his eyes on the creature's bronze shell, completely covered in filigree lines and a slight patina of rust that somehow made it look stately. He had done all the work himself, of course, and with his one good hand. He had lost his left arm to the creeping plague that had been his constant companion for the past six years—the plague turned the strange clockmaker into the village pariah. He was certain that, were it not for his rare skills, he would have been cast out into the snow-covered forest and forgotten long ago.
#emph[Probably would have been better off... no, that's just self pity. Poor form, old man.]
He had abandoned his dreams of a wife, children, and even mentoring his own apprentice. He poured himself into his work. None of the villagers understood why everyone else touched by the creeping plague had died, while this strange tinkerer lived on. When the clock orders inevitably ceased altogether, he carried on nonetheless, turning out one masterfully crafted clock after another. His workspace began to look like an overgrown tomb in a forest of silver and bronze, clicking, clacking, and chiming all around him. He imagined they were colorful birds.
But this—this was the pinnacle of his work. He had nearly gone blind cutting the thousands of gears the legs required. The chest cage was the most difficult by far and required two huge keys—front and back—to wind its springs. Working with only one arm, he had come up with a way to turn the keys simultaneously: twist the front one enough and the clockwork arm sprung to life and turned the one in the back. It had taken him a year to figure that out, and another year to get the movements to align precisely. The memory made him smile.
#figure(image("003_Chronomaton/02.jpg", width: 100%), caption: [Chronomaton | Art by Vincent Proce], supplement: none, numbering: none)
Yes, this was by far his greatest creation. One that would be his lasting legacy to a world that had shunned him. But now it seemed that even it preferred the company of others and went out on its own at night to terrify the villagers down the lane. He hid the keys, chained the thing up, and tied boulders to it, but nothing seemed to suffice.
#emph[You can't blame the thing. You would go out on your own too, if you could.]
Sometimes he would awake to find strange things in his shop—objects that had no business being there. A guard's helmet, the stirrups from a saddle, even a pair of wooden teeth. Mostly, he found strange keys, hundreds of them, filling small burlap sacks and stacked near the door. He never bothered to return them, since their original owners would never touch them now that he had. He merely pushed them into one of the few corners of his shop that wasn't covered in parts, tools, or shavings and forgot about them. They were brass, after all, and no use to him.
This morning, he looked warily at his surroundings to see if he would be surprised again. He awkwardly ambled over to his workbench, nearly knocking over his favorite sitting chair, and stopped in his tracks, letting out a pathetic yelp. There, resting on the boarhide desk cover, lay a crude clockwork arm.
#emph[You have really gone down the well, old man. Now you're making things you don't even remember making.]
He approached it cautiously, slowly reaching out his good hand as if he expected the thing to jump to life and grab him. He winced as he touched it, but the thing didn't move at all. Something was just not right about this artifact. Something that tugged at the back of Bazzle's mind.
#figure(image("003_Chronomaton/03.jpg", width: 100%), caption: [Wild Guess | Art by <NAME>], supplement: none, numbering: none)
He pulled the leather headband that held his reading crystals in place from the owl clock next to his desk and put it on. Swinging the thickest of the crystals over his eye, he began to scrutinize the work in front of him.
No filigree, no smoothing of the rough-cut corners, and hammered pins! And was that trace of gray mineral... zinc? This was brass! Bazzle refused to use brass, since it cheapened the end result of his hard labors—at least in his estimation.
#emph[You didn't do this. Nobody else could have.]
His paradoxical line of thinking was interrupted when he noticed something. There #emph[were] lines on the arm after all, but they seemed to make a haphazard kind of sense; clearly intentional but lacking any artistic logic. That's when he saw the angular teeth and the looped handles.
#emph[Keys. This is made of melted keys.]
He compared it to the creature's arm, the one #emph[he] had made, and found the evidence he hoped he would not find. Its fingers were covered with brass filings, held in place by clock oil. For decades, he had scrubbed a similar mixture from his own hands at the end of a long day's work.
Now, it seemed, he finally had an apprentice.
Bazzle stared, wide-eyed, as the implications began to fill his brain like milk poured into water. The creature had somehow learned it creator's trade and was using it to build... what? #emph[A companion? An army?]
He frantically tugged at the thing's chest key, but he was still sleep-weak and his good arm failed him. He gritted his teeth and pulled again, this time dislodging the key and sending it clanking across the room. To his horror, the creature's arm reached around and began turning the back key, the loud cranking sound filling the sad little workshop. Before Bazzle could do anything, the hand swung back and struck him squarely in the face. The last thing he heard was the chiming of the two hundred twelve clocks. It was time for breakfast.
On the second morning, Bazzle woke up on his own, a splitting headache reminding him of the previous day's attack. He looked around frightfully, trying to remember where he had thrown the key. With it, he might regain control of his creation and dismantle it, ending this terrible endeavor and perhaps saving the old man some of his waning dignity.
#figure(image("003_Chronomaton/04.jpg", width: 100%), caption: [Captain of the Watch | Art by <NAME>], supplement: none, numbering: none)
The militia was marching outside and he could hear the hoarse shouts of the sergeant-at-arms. They were searching the farmhouses, no doubt looking for his mischievous metal child, but he knew they would not come calling today. The pitch-black skull painted on his door, the symbol of plague, was better than castle walls for keeping out invaders. He found himself looking forward to the annual visitor who would refresh the paint.
The sunlight pouring in from the hole in his thatched roof caused a sparkle in the corner of his eye. #emph[The key!] It rested under what used to be his dining table, but which was now covered in tools and metal bits, much like every surface in his shop. He stood up, groaning with pain and suddenly losing his balance. He fell toward his workbench, grasping it for stability. As he lifted himself up, his heart jumped into his throat.
He was staring at a severed head.
He swooned in shock. As his mind began to realign, he recognized the metal features he had come to know in the mysterious arm. This was a clockwork head. The guard's helmet had been fashioned into a skull, Bazzle's own reading crystals repurposed as eyes, and the stirrups and wooden teeth set in the jaw in a sad mockery of a human face. He could hear his heart beating deep and low in his ears, almost in time with the ticking that surrounded him, but not quite.
#emph[Your child has grown beyond your ability to control. You should have left well enough alone. Stupid, sad old man.]
He fell to the floor and reached out for the key, just as he heard the dreaded but familiar whirr of gears. The thing had a mind of its own and apparently no intention of going quietly. Bazzle dragged himself with his good arm toward the golden promise the key held.
#emph[Not far to go now. Just an arm's length, just a hand's-width, just fingers away.]
He felt the cold metal of the key on his fingertip just as the thing's arm connected with the back of his neck. Pain pierced through his mind and he felt the room spinning. He saw the thing reaching out for the key, heard the metal action of the mechanism as the thing slid the key into place...
On the third morning, Bazzle opened his eyes. He was momentarily oblivious to the events of the past two days—a state of mind he was soon to envy. He realized he was seated at his workbench. The pain in his neck made him want to reach up and rub it, but his arm would not heed the call of his instincts.
One look around the room told him why: his formerly good arm lay severed on the floor near his bed, and attached to his shoulder in its place was the metal arm from days before.
#emph[Isn't this what you wanted all along?]
He looked down at his creation; #emph[his] metal body. The body he had spent six years making. The body that had helped him cheat the creeping plague death. Bazzle realized all too late that the thing wasn't making a companion. It wasn't constructing an army. It had merely decided it would no longer share a body with a rotting old clockmaker.
#figure(image("003_Chronomaton/05.jpg", width: 100%), caption: [Butcher's Cleaver | Art by <NAME>], supplement: none, numbering: none)
The arms began moving again, and no matter how much Bazzle's mind screamed at them to stop, he could not control them. The hand he had made and the hand he had not served a different master now, and there was nothing he could do but watch.
The desk was strewn with chirurgeon's tools: a bloody bone saw and a huge cleaver. He watched as the arm he had made clicked into action, the springs singing their song of tension's imminent release. The metal fingers wrapped around the cleaver, raised it to neck height, and reared back.
The last thing he saw was his shop spinning roof-over-floor around him. He would not hear the final click of the head as the hand snapped it into its newly-vacated space.
Finally, his creation was complete.
|
|
https://github.com/SkiFire13/fmcps-assignment2 | https://raw.githubusercontent.com/SkiFire13/fmcps-assignment2/master/report.typ | typst | #import "automata.typ"
#import "defs.typ": *
#set par(justify: true)
#set text(size: 12pt, font: "New Computer Modern")
#set page(numbering: "1")
#align(center)[
#heading(outlined: false)[
Formal Methods for Cyberphysical Systems \
Assignment 2
]
#v(1em)
#text(size: 15pt, "<NAME>")
#text(size: 15pt, "20/01/2024")
]
=== Conventions
In this report the notation $pre{x}post$ will be used to mean the string resulting from the concatenation of the literal string $pre$, the value of the expression $x$ and the literal string $post$. For example if $x$ is $1$ then $pre{x+1}post$ will mean $pre 2 post$.
= Plant definition
== States
The two rovers are independent, so they can be represented with two different sets of plants. The yellow rover will be referred to as rover 1 and the blue rover as rover 2.
For each rover $i$ two plants have been defined: $Position{i}$ and $Battery{i}$, respectively tracking the rover's position and battery level.
=== Position
Each $Position{i}$ plant contains a state for every tile, representing the rover currently being on that tile. The states have been named $X{x}Y{y}$ where $x$ is the $X$ coordinate of the corresponding tile, ranging from 1 to 5, and $y$ is its $Y$ coordinate, ranging from 1 to 3, when viewed in a cartesian plane with the $X$ axis going right and the $Y$ axis going down.
$X1Y1$ is the initial state for rover 1 and $X4Y2$ is the initial state for rover 2. Only the initial states have been marked since those have been considered to be the "stable" states. Other possible choices considered were marking the states representing tiles with charging stations or all the states.
=== Battery
Each $Battery{i}$ plant contains a state for every battery level, representing the rover's battery currently being at that level. The states have been named $L{l}$ where $l$ is the current battery level and ranges from 0 to 6. $L6$ is the initial state since rovers start fully charged. Only $L6$ have been marked since that has been considered to be a "stable" state. Another possible choice considered was marking $L0$ too.
== Events
The following 9 events have been defined for each rover $i$:
- $left{i}$, $right{i}$, $down{i}$ and $up{i}$, the controllable events for the movements in the 4 directions of rover $i$;
- $uleft{i}, uright{i}, udown{i} "and" uup{i}$, the uncontrollable events for the movements in the 4 directions of rover $i$;
- $charge{i}$, the controllable event for charging.
The $charge{i}$ events have been defined as controllable since it is stated that:
#h(1em) _If a Rover sits on any of these tiles, then it *can* get a full charge_
Which has been interpreted to mean that a rover is not required to get the full charge and can choose not to.
== Edges
=== Position
Each $Position{i}$ plant contains an edge between two states if the corresponding tiles are adjacent. In particular they contain the following edges, excluding when the starting state is $X2Y2$:
- for all $2 <= x <= 5, 1 <= y <= 3$, an edge with event $left{i}$ from the state $X{x}Y{y}$ to the state $X{x-1}Y{y}$ of rover $i$;
- for all $1 <= x <= 4, 1 <= y <= 3$, an edge with event $right{i}$ from the state $X{x}Y{y}$ to the state $X{x+1}Y{y}$ of rover $i$;
- for all $1 <= x <= 5, 2 <= y <= 3$, an edge with event $up{i}$ from the state $X{x}Y{y}$ to the state $X{x}Y{y-1}$ of rover $i$;
- for all $1 <= x <= 5, 1 <= y <= 2$, an edge with event $down{i}$ from the state $X{x}Y{y}$ to the state $X{x}Y{y+1}$ of rover $i$.
The $X2Y2$ state represent the rover being on the red tile, where the movements are uncontrollable. Hence the following edges have been defined for that case:
- an edge with event $uleft{i}$ to the state $X1Y2$;
- an edge with event $uright{i}$ to the tile $X3Y2$;
- an edge with event $uup{i}$ to the state $X2Y1$;
- an edge with event $udown{i}$ to the state $X2Y3$.
These edges corresponds to the ones for the other states, except they use the corresponding uncontrollable events to make the movements uncontrollable by the rover.
Self-edges with event $charge{i}$ were also defined to model the charging of the rovers in the states $X1Y1$ and $X4Y2$, limiting the ability to charge the battery only on the corresponding tiles.
=== Battery
Each $Battery{i}$ plant contains an edge from every level to the previous one for every move, that is for every $1 <= l <= 6$ they contain an edge with events $left{i}$, $right{i}$, $up{i}$, $down{i}$, $uleft{i}$, $uright{i}$, $uup{i}$ and $udown{i}$ from the state $L{l}$ to the state $L{l-1}$, representing the decrease in battery level after a move. There's no such edge for the state $L0$, representing the fact that a rover can't move when its battery runs out of energy. They also contain edges for the charging, in particular for every $0 <= l <= 5$ they contain an edge with event $charge{i}$ from the state $L{l}$ to the state $L6$. It has been chosen not to add an edge with event $charge{i}$ in the state $L6$ because it doesn't make sense to charge the battery if it's already charged.
== Automata
Here are the final automata for the plants:
#figure(automata.position(1), caption: [ Plant $Position 1$ ])
#figure(automata.battery(1), caption: [ Plant $Battery 1$ ])
#figure(automata.position(2), caption: [ Plant $Position 2$ ])
#figure(automata.battery(2), caption: [ Plant $Battery 2$ ])
= Requirements
#let requirement(text) = v(0.2em) + h(1em) + [ _ #text _ ]
== Requirement 1
#requirement[ Both rovers never run our of battery on tiles that do not have a charging station. ]
The requirement can be defined by copying the $Battery{i}$ plants and updating their marking so that the state $L0$ is not marked. This way any rover that runs out of energy on a non-charging station tile will be stuck on the state $L0$ due to not being able to move or charge, which is a blocking state and will thus be prevented from happening by the supervisor synthesis.
In the case of the chosen marking $L0$ is already not marked, so this requirement is redundant.
== Requirement 2
#requirement[ Both rovers must always alternate the use of the charging stations in $(1,1)$ and $(2,4)$ regardless of which is used first. ]
Let the station in position $(1,1)$ be station 1 and the one in position $(4,2)$ be station 2. The given requirement could be translated using the following automata, once for each rover, where $I$ represent the initial state when no charging station has been used by rover $i$, and $N1$ and $N2$ represent the states where the next charging station that has to be used is respectively station 1 and 2.
#figure(automata.r2-alternate, caption: "Automaton for alternating two events.")
There's however no way to directly express the "$charge{i}$ at station $j$" edges since it's not possible to distinguish at which station the $charge{i}$ event was performed. It's thus necessary to also track in which position the rover is currently at, which can be done by creating 3 copies of the $Position{i}$ plant states, one for every state in the automaton in the figure.
More formally, for every state $S$ in $Position{i}$ three states have been defined: ${S}I$, ${S}N1$ and ${S}N2$. Given $S_i$ the initial state in $Position{i}$, ${S_i}I$ will be the new initial state. All states will be marked, since marking is not relevant for this requirement. For every edge with event different than $charge{i}$ between states ${S 1}$ and ${S 2}$ it has been defined an edge between states ${S 1}{M}$ and ${S 2}{M}$ for all $M in {I, N1, N2}$. The edges with event $charge{i}$ have been replaced with the following ones:
- an edge with event $charge{i}$ from $X1Y1 I$ to $X1Y1 N2$, representing the topmost edge in the automata above;
- an edge with event $charge{i}$ from $X4Y2 I$ to $X4Y2 N1$, representing the bottommost edge in the automata above;
- an edge with event $charge{i}$ from $X1Y1 N1$ to $X1Y1 N2$, representing the center edge in the automata above;
- an edge with event $charge{i}$ from $X4Y2 N2$ to $X4Y2 N1$, representing the rightmost edge in the automata above.
This way the $charge{i}$ edges represent exactly all the edges in the automata shown in the figure before, while all the other edges correspond to the existing movement edges.
#for i in (1, 2) {
figure(
automata.r2(i),
caption: [ Rover #i's automaton for requirement $R 2$ ]
)
}
=== Compact version
The structure of the problem can be exploited to reduce the number of states that have to be manually declared. Since there are only 2 stations, they must differ in either their $X$ or $Y$ coordinate. The requirement automata can then only track that coordinate instead of both of them, and that will be enough to distinguish at which charging station the $charge{i}$ is being performed, since there exist at most one charging station for every value of that coordinate. In this case the charging stations positions differ by both coordinates, so the one with fewer states to track has been chosen, which is Y. The automata can hence be reduced to 9 states, $Y{y}{M}$ for all $1 <= y <= 3$ and $M in { I, N1, N2 }$, and the following edges:
- for $y in {2, 3}, M in {I, N1, N2}$ an edge with events $up{i}$ and $uup{i}$ from $Y{y}M$ to $Y{y-1}M$;
- for $y in {1, 2}, M in {I, N1, N2}$ an edge with events $down{i}$ and $udown{i}$ from $Y{y}M$ to $Y{y+1}M$;
- an edge with event $charge{i}$ from $Y 1 I$ to $Y 1 N2$;
- an edge with event $charge{i}$ from $Y 2 I$ to $Y 2 N1$;
- an edge with event $charge{i}$ from $Y 1 N1$ to $Y 1 N2$;
- an edge with event $charge{i}$ from $Y 2 N2$ to $Y 2 N1$.
#for i in (1, 2) {
figure(
automata.r2-compact(i),
caption: [ Rover #i's compact automaton for requirement $R 2$ ]
)
}
== Requirement 3
#requirement[ Rovers don't collide with each other (i.e., they are never simultaneously on a same tile). ]
The given requirement could be translated by computing the synchronous product of $Position 1$ and $Position 2$ and removing all the nodes where the state from $Position 1$ and the one from $Position 2$ have the same name, that is when Rover 1 is on the same tile as Rover 2. Unfortunately this doesn't scale well, requiring the user to specify 210 states ($15 times 15 = 225$ for the syncronous product, minus $15$ for the removed ones) which are arguably too many for a human to quickly verify their correctness.
Another, more compact, approach is to track the relative position of the two rovers. There are 9 possible relative positions $x_1 - x_2$ on the $X$ axis, ranging from $-4$ to $4$ and 5 possible relative positions $y_1 - y_2$ on the $Y$ axis, ranging from $-2$ to $2$. These will be the states of 2 automata, while their edges have been defined as the following:
- for all $-3 <= d x <= 4$, an edge with events $left 1$, $uleft 1$, $right 2$ and $uright 2$ from $d x$ to $d x - 1$;
- for all $-4 <= d x <= 3$, an edge with events $right 1$, $uright 1$, $left 2$ and $uleft 2$ from $d x$ to $d x + 1$;
- for all $-1 <= d y <= 2$, an edge with events $up 1$, $uup 1$, $down 2$ and $udown 2$ from $d y$ to $d y - 1$;
- for all $-1 <= d y <= 2$, an edge with events $down 1$, $udown 1$, $up 2$ and $uup 2$ from $d y$ to $d y + 1$.
The initial states are $-3$ and $-1$, because those are differences of the initial coordinates of the rovers. All states have been marked, since marking is irrelevant for this requirement. To satisfy the requirement it's then sufficient to compute the synchronous product of the two automata and remove the state $(0, 0)$, representing the two rovers having the same $X$ and $Y$ position, hence being on the same tile.
This ends up requiring the user to specify only 44 states ($9 times 5 = 45$ for the synchronous product, minus $1$ for the removed state).
Due to the inability to use the dash character (`-`) in CIF identifiers, the relative $X$ positions have been mapped to the names $L 4$, $L 3$, $L 2$, $L 1$, $S X$, $R 1$, $R 2$, $R 3$ and $R 4$, representing rover 1 being on the left ($L{l}$), on the same $X$ ($S X$) or on the right ($R{r}$) of rover 2, and the relative $Y$ positions have been mapped to the names $U 2$, $U 1$, $S Y$, $D 1$ and $D 2$, representing rover 1 being up ($U{u}$), on the same $Y$ ($S Y$) or down ($D{d}$) compared to rover 2.
#figure(automata.r3, caption: [ Automaton for requirement 3 ])
=== Compact version
If the introduction of a new uncontrollable event $sametile$ is allowed, an even more compact requirement automaton can be created. This event will never happen, in fact it will be used to have the supervisor remove any state that can perform this event, so it won't create any new execution of the system but only remove existing ones. The way this is done is by creating an automaton with two states, an initial marked state $Valid$ and another unmarked state $Invalid$, with a single edge with event $sametile$ from $Valid$ to $Invalid$. This way if the $sametile$ event ever happens it will lead to a blocking state and thus the supervisor will have to prevent it; moreover since it is uncontrollable the supervisor won't be able to remove the edge itself but will have to remove any state that can perform it or reach it with uncontrollable events.
Then the two automata for the relative $X$ and $Y$ positions can be kept separate, and only two self-loops with event $sametile$ have to be added to the states $S X$ and $S Y$. This way if the rovers are in the same position, that is the two automata are in the states $S X$ and $S Y$, they will be able to perform the event $sametile$ and reach a blocking state, hence the supervisor will be forced to remove this state.
#figure(automata.r3-compact, caption: [ Compact automata for requirement 3 ])
|
|
https://github.com/tolstovr/typst-code-template | https://raw.githubusercontent.com/tolstovr/typst-code-template/main/example.typ | typst | #import "conf.typ": conf
#show: conf.with(
meta: (
title: "Пример использования шаблона",
author: "<NAME>",
group: 251,
city: "Саратов",
year: 2024,
)
)
= Типографика
Всё как в обычном Typst. Используется шрифт Cambria Math
= Работа с кодом
А вот это уже интереснее. Есть inline-код, например: #raw(lang: "python", "print(\"Hello, World\")") на языке Python.
Для блоков кода предусмотрены номера строк:
#raw(
block: true,
lang: "rust",
"fn main() {
println!(\"Hello, Rust!\");
}")
#quote(block: true,
attribution: "Роберт",
[Не забываем экранировать символы #raw("\"") --- а то забудете])
== Лигатуры
Да, я их выключил. Теперь будет так: #raw("=>").
= Ссылка
Да, ссылка теперь такая: #link("https://ru.w3docs.com/uchebnik-html/tablitsa-html-tegov.html")[w3docs] |
|
https://github.com/0x546974616e/typst-resume | https://raw.githubusercontent.com/0x546974616e/typst-resume/main/template/section.typ | typst | #import "./globals.typ": colors, spacing, get-lang
#import "./heading.typ": h3, h4
#let make-picture(picture) = {
block(
inset: spacing.medium,
// inset: spacing.large,
block(
clip: true,
radius: 100%,
stroke: none,
// stroke: 6pt + colors.bg2,
// stroke: 4pt + colors.bg3,
image("../" + picture),
) // block
) // block
}
#let get-fullname(profil) = (
("lastname", "firstname")
.map(info => profil.at(info, default: none))
.filter(info => info != none)
)
#let make-header(profil) = {
let items = ()
let fullname = get-fullname(profil)
if fullname.len() >= 1 {
items.push(
text(
size: 1.5em,
weight: 500,
fill: colors.fg1,
fullname.join(" ")
) // text
)
}
if "position" in profil {
items.push(
text(
size: 1.125em,
weight: 400,
fill: colors.fg3,
get-lang(profil.position),
) // text
)
}
if "description" in profil {
items.push(
text(
size: 1.0em,
weight: 400,
fill: colors.fg3,
get-lang(profil.description),
) // text
)
}
if items.len() >= 1 {
stack(
dir: ttb,
spacing: spacing.medium,
..items,
) // stack
}
}
#let make-profil(profil) = {
let details = ()
// TODO: Translate.
for info in ("phone", "email", "age", "address", "@github") {
let href = info.first() == "@"
if href { info = info.slice(1) }
if info in profil {
details.push(
stack(
dir: ttb,
spacing: 2 * spacing.medium,
h3(info),
if href { link(str(profil.at(info))) }
else { str(profil.at(info))}
) // stack
)
}
}
if details.len() >= 1 {
// TODO: TMP
let columns = if details.len() >= 4 {
(2fr, 3.25fr, 1fr)
}
else {
(1fr, 1fr, 1fr)
}
table(
columns: columns, // (auto, 1fr, auto),
// align: (left, center, left),
gutter: 2 * spacing.large,
stroke: none,
inset: 0pt,
..details,
) // table
}
}
#let make-skills(skills) = {
stack(
dir: ttb,
spacing: 2 * spacing.large,
..skills.map(
((field, skills)) => {
stack(
dir: ttb,
spacing: 2 * spacing.medium,
h3(get-lang(field), color: colors.fg4),
par(
leading: spacing.medium,
skills.map(skill => box(get-lang(skill))).join(", "),
) // par
) // stack
} // function
) // map
) // stack
}
#let make-interests(interests) = {
interests = get-lang(interests)
stack(
dir: ttb,
spacing: spacing.medium,
..interests.intersperse(",").chunks(2).map(array.join)
) // stack
}
/**
* Example:
* ```typ
* #make-table(
* config.experiences, (
* // "&" concat a field with the previous one (only for dates).
* date: ( "start", "stop", "&months" ),
* title: ( "company", "position" ),
* body: ( "description", ),
* transform: (
* months: (month) => [(#month months)],
* ),
* ),
* )
* ```
*/
#let make-table(objects, fields) = {
if objects.len() <= 0 {
return // Nothing
}
stack(
dir: ttb,
spacing: 2 * spacing.large,
..objects.map(
object => {
let header = ()
let body = ()
// 1. Date & Title
for field in (fields.date, fields.title).flatten() {
let stick = field.first() == "&"
if stick { field = field.slice(1) }
if field in object {
let item = get-lang(object.at(field));
if field in fields.transform {
item = fields.transform.at(field)(item)
}
if header.len() >= 1 and stick {
// TODO: Inefficient, check if type is array instead.
item = (header.pop(), item)
}
header.push(item)
}
}
// 2. Body
for field in fields.body {
if field in object {
let items = get-lang(object.at(field))
for item in items {
if field in fields.transform {
item = fields.transform.at(field)(item)
}
body.push(item)
}
}
}
// A. Prepare items
let items = ()
// B. Add header
if header.len() >= 2 and object.at("break", default: false) {
// TODO: Inefficient, check if type is array instead.
let last2 = (header.pop(),).flatten()
let last1 = (header.pop(),).flatten()
// B.1.
// +------------------------------------+
// | +--------------------+ +---------+ |
// | | item - item - item | | - last1 | |
// | +--------------------+ | - last2 | |
// | +---------+ |
// +------------------------------------+
items.push(
stack(
dir: ltr,
spacing: spacing.medium,
..header.intersperse(sym.dash.en).flatten().map(h4),
stack(
dir: ttb,
spacing: spacing.medium,
..(last1, last2).map(
item => stack(
dir: ltr,
spacing: spacing.medium,
h4(sym.dash.en),
..item.map(h4),
) // stack
) // map
) // stack
), // stack
)
}
else {
// B.2. Add all items on the same line.
// +----------------------------------+
// | item - item - item - item - item |
// +----------------------------------+
items.push(
stack(
dir: ltr,
spacing: spacing.medium,
..header.intersperse(sym.dash.en).flatten().map(h4),
), // stack
)
}
// C. Add body
if body.len() >= 1 {
items.push(
stack(
dir: ttb,
spacing: spacing.medium,
..body.map(par.with(leading: spacing.medium)),
) // stack
) // push
}
// Return
stack(
dir: ttb,
spacing: 2 * spacing.medium,
..items,
) // stack
} // function
) // map
) // stack
}
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.0/src/canvas.typ | typst | Apache License 2.0 | // Aliases for typst types/functions
// because we override them.
#let typst-length = length
#import "matrix.typ"
#import "vector.typ"
#import "util.typ"
#import "path-util.typ"
#import "aabb.typ"
#import "styles.typ"
#import "process.typ"
/// Sets up a canvas for drawing on.
///
/// - length (length,ratio): Used to specify what 1 coordinate unit is. If given a ratio, that ratio is relative to the containing elements width!
/// - body (none,array,element): A code block in which functions from `draw.typ` have been called.
/// - background (none,color): A color to be used for the background of the canvas.
/// - debug (bool): Shows the bounding boxes of each element when `true`.
/// -> content
#let canvas(length: 1cm, debug: false, background: none, body) = layout(ly => style(st => {
if body == none {
return []
}
assert(
type(body) == array,
message: "Incorrect type for body: " + repr(type(body)),
)
assert(type(length) in (typst-length, ratio), message: "Expected `length` to be of type length or ratio, got " + repr(length))
let length = if type(length) == ratio {
length * ly.width
} else {
measure(box(width: length, height: length), st).width
}
assert(length / 1cm != 0,
message: "Canvas length must be != 0!")
let ctx = (
typst-style: st,
length: length,
debug: debug,
// Previous element position & bbox
prev: (pt: (0, 0, 0)),
em-size: measure(box(width: 1em, height: 1em), st),
style: styles.default,
// Current transform
transform: matrix.mul-mat(
matrix.transform-shear-z(.5),
matrix.transform-scale((x: 1, y: -1, z: 1)),
),
// Nodes, stores anchors and paths
nodes: (:),
// group stack
groups: (),
)
let (ctx, bounds, drawables) = process.many(ctx, body)
if bounds == none {
return []
}
// Filter hidden drawables
drawables = drawables.filter(d => not d.hidden)
// Order draw commands by z-index
drawables = drawables.sorted(key: (cmd) => {
return cmd.at("z-index", default: 0)
})
// Final canvas size
let (width, height, ..) = vector.scale(aabb.size(bounds), length)
let relative = (orig, c) => {
return vector.sub(c, orig)
}
box(width: width, height: height, fill: background, align(top, {
for drawable in drawables {
// Typst path elements have strange bounding boxes. We need to
// offset all paths to start at (0, 0) to make gradients work.
let (x, y, _) = if drawable.type == "path" {
vector.sub(
aabb.aabb(path-util.bounds(drawable.segments)).low,
bounds.low)
} else {
(0, 0, 0)
}
place(if drawable.type == "path" {
let vertices = ()
for s in drawable.segments {
let type = s.at(0)
let coordinates = s.slice(1).map(c => {
return (
(c.at(0) - bounds.low.at(0) - x) * length,
(c.at(1) - bounds.low.at(1) - y) * length,
)
})
assert(
type in ("line", "cubic"),
message: "Path segments must be of type line, cubic",
)
if type == "cubic" {
let a = coordinates.at(0)
let b = coordinates.at(1)
let ctrla = relative(a, coordinates.at(2))
let ctrlb = relative(b, coordinates.at(3))
vertices.push((a, (0pt, 0pt), ctrla))
vertices.push((b, ctrlb, (0pt, 0pt)))
} else {
vertices += coordinates
}
}
if type(drawable.stroke) == dictionary and "thickness" in drawable.stroke and type(drawable.stroke.thickness) != typst-length {
drawable.stroke.thickness *= length
}
path(
stroke: drawable.stroke,
fill: drawable.fill,
closed: drawable.at("close", default: false),
..vertices,
)
} else if drawable.type == "content" {
let (width, height) = util.typst-measure(drawable.body, ctx.typst-style)
move(
dx: (drawable.pos.at(0) - bounds.low.at(0)) * length - width / 2,
dy: (drawable.pos.at(1) - bounds.low.at(1)) * length - height / 2,
drawable.body,
)
}, dx: x * length, dy: y * length)
}
}))
}))
|
https://github.com/benjamineeckh/kul-typst-template | https://raw.githubusercontent.com/benjamineeckh/kul-typst-template/main/src/packages.typ | typst | MIT License | #import "@preview/hydra:0.5.1": hydra |
https://github.com/wagaaa/HZAU_Typst | https://raw.githubusercontent.com/wagaaa/HZAU_Typst/main/dependents/figures.typ | typst | MIT License | #import "@preview/tablem:0.1.0": tablem
#import "@preview/tablex:0.0.6": tablex, hlinex
//设定编号为章节-序号
#let equation_num(_) = {
locate(loc => {
let chapt = counter(heading).at(loc).at(0)
let c = counter("equation-chapter" + str(chapt))
let n = c.at(loc).at(0)
"(" + str(chapt) + "-" + str(n + 1) + ")"
})
}
#let table_num(_) = {
locate(loc => {
let chapt = counter(heading).at(loc).at(0)
let c = counter("table-chapter" + str(chapt))
let n = c.at(loc).at(0)
str(chapt) + "-" + str(n + 1)
})
}
#let image_num(_) = {
locate(loc => {
let chapt = counter(heading).at(loc).at(0)
let c = counter("image-chapter" + str(chapt))
let n = c.at(loc).at(0)
str(chapt) + "-" + str(n + 1)
})
}
#set figure.caption(separator: [ ])
#set text(
font: ( "Times New Roman","Songti SC"),
size: 16pt)
#let tables=tablem.with(
render: (columns: auto, ..args) => {
tablex(
columns: columns,
auto-lines: false,
align: center + horizon,
hlinex(y: 0,stroke:2pt),
hlinex(y: 1),
..args,
hlinex(stroke:2pt),
)
}
)
#let 简单表格(表格, caption: "", cap_en: "")={
figure(
figure(
tables(表格),
caption: figure.caption(position: top)[#cap_en],
gap: 1em,
numbering: table_num,
supplement: [表],
kind: "table",
),
caption: figure.caption(position: top)[#caption],
supplement: [Table ],
numbering: table_num,
)
v(1em)
}
#let 图片(图片, caption: "", cap_en: "")={
figure(
figure(
图片,
caption: caption,
gap: 1em,
numbering: image_num,
supplement: [图],
kind: "image",
),
caption: cap_en,
supplement: [Fig. ],
numbering: table_num,
)
v(1em)
}
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Partial%20Derivative.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Partial Derivative",
authors: (
"<NAME>",
),
date: "30 Octobre, 2023",
)
#set heading(numbering: "1.1.")
= Partial Derivative
<partial-derivative>
== Definition
<definition>
In calculus, a partial derivative of a function of several variables is
the derivative of the function with respect to one of the variables,
with the others treated as constants. For example, if
$f lr((x comma y))$ is a function of two variables, then the partial
derivative of $f$ with respect to $x$ is the derivative of $f$ with
respect to $x$ while holding $y$ constant, and is denoted
$frac(diff f, diff x)$.
Partial derivatives are useful in multivariable calculus, as they allow
us to find the rates of change of a function with respect to each of its
variables independently. They are also used in the gradient vector,
which points in the direction of the greatest rate of increase of a
function at a given point.
The partial derivative of a function $f lr((x comma y))$ with respect to
$x$ is given by:
$ frac(diff f, diff x) eq lim_(h arrow.r 0) frac(f lr((x plus h comma y)) minus f lr((x comma y)), h) $
Similarly, the partial derivative of $f$ with respect to $y$ is given
by:
$ frac(diff f, diff y) eq lim_(h arrow.r 0) frac(f lr((x comma y plus h)) minus f lr((x comma y)), h) $
These expressions can be used to find the partial derivatives of a
function by directly computing the limits, or by using the rules of
calculus to simplify the expressions.
== Example
<example>
To find the partial derivatives of the function
$f lr((x comma y)) eq sin x cos y^2$, we need to use the rules of
calculus to take the derivatives with respect to $x$ and $y$ while
holding the other variable constant.
The partial derivative of $f$ with respect to $x$ is given by:
$ frac(diff f, diff x) eq frac(diff, diff x) lr((sin x cos y^2)) eq frac(diff, diff x) lr((sin x)) cos y^2 plus sin x frac(diff, diff x) lr((cos y^2)) eq cos x cos y^2 $
The partial derivative of $f$ with respect to $y$ is given by:
$ frac(diff f, diff y) eq frac(diff, diff y) lr((sin x cos y^2)) eq frac(diff, diff y) lr((sin x)) cos y^2 plus sin x frac(diff, diff y) lr((cos y^2)) eq minus 2 y sin x sin y^2 $
== Links
<links>
- #link("Derivative.pdf")[Derivative]
- #link("Maths.pdf")[Maths]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.