repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/AlexCid/CryptographieLaSalle | https://raw.githubusercontent.com/AlexCid/CryptographieLaSalle/main/cours01.typ | typst | #import "@preview/polylux:0.2.0": *
#import "@preview/tablex:0.0.4": tablex, gridx, hlinex, vlinex, colspanx, rowspanx
#import "@local/svg-emoji:0.1.0": setup-emoji, noto, github
#show: setup-emoji.with(font: noto)
#import themes.simple: *
#set text(font: "Inria Sans")
#show: simple-theme.with(
footer: [Introduction & Histoire],
)
#title-slide[
= Cryptographie
#v(2em)
Introduction & Histoire de la cryptographie
#v(2em)
<NAME> #footnote[DGA-MI, Bruz] #h(1em)
<EMAIL>
18/10/2024
]
#focus-slide[
_Crypto·graphie_
Écriture cachée
]
#title-slide[
== ATTAQUEZ A L AUBE
#uncover((2,3))[
#sym.arrow.r
]
#uncover(3)[
#h(1em)
== HDJQKLFO K M ALFY
]
]
#slide[
= Chiffres historiques
#let cell = block.with(
width: 100%,
)
#grid(
columns: (auto, auto),
rows: (auto),
gutter: 3pt,
cell(height: 80%)[
*Chiffre de substitution*
#only(1)[#image("img/CaesarDisk.jpg", width: 70%)]
#only(2)[
#pad(left:30pt,[
A #sym.arrow.r N
B #sym.arrow.r O
C #sym.arrow.r P
D #sym.arrow.r Q
...
Z #sym.arrow.r M
])
]
],
cell(height: 80%)[
*Chiffre de transposition*
#only(1)[#image("img/Skytale.png", width: 90%)]
#only(3)[
#pad(left:30pt,[
ATTAQUEZALAUBE
#pad(left:30%,[
#sym.arrow.b
])
#grid(
columns: (45%, 10%, 45%),
rows: (auto),
[
#tablex(
columns: 5,
auto-lines: false,
(), vlinex(), vlinex(),vlinex(),vlinex(), (),
[A], [T], [T], [A],[Q],
[U], [E], [Z], [A],[L],
[A], [U], [B], [E],()
)
],
[
#v(1.2em)
#sym.arrow.r],
[ #tablex(
columns: 5,
auto-lines: false,
(), vlinex(), vlinex(),vlinex(),vlinex(), (),
[T], [T], [Q], [A],[A],
[E], [Z], [L], [U],[A],
[U], [B], [], [A],[E]
)
]
)
#pad(left:30%,[
#sym.arrow.b
])
TEUTZBQLAUAAAE
])
]
],
)
]
#slide[
== Le texte c'est bien, mais à l'oral ?
#set align(center)
#image("img/navajo.jpg", width: 50%)
]
#slide[
== Et si je veux cacher l'existence du message ?
#set align(center)
#grid(
columns: (33%, 33%, 33%),
rows: (auto),
[
#image("img/pirate.png", width: 100%)
],
[
#sym.arrow.r
],
[
ATTAQUEZ A L AUBE
])
]
#focus-slide[
_Stégano·graphie_
Écriture hermétique (?)
]
#slide[
== Un peu de vocabulaire
#h(1em)
/ Texte clair: Message à transmettre
/ Texte chiffré: Transformation "incompréhensible" du message
/ Chiffrer: Transformer le texte clair en texte chiffré
/ Déchiffrer: Transformer le texte chiffré en texte clair
Remarque:
- #strike[crypter]
]
#slide[
== En images
#set align(center)
#image("img/chif-dechif.svg", width: 80%)
]
#slide[
== Un peu de notation (provisoire)
/ Alphabet: Ensemble de symboles, ici : $Sigma = {A, B, ..., Z}$
/ Message (ou texte, ou mot): Suite de symboles, i.e. élément de $Sigma^+$
(Note: $Sigma^+ = Sigma union Sigma^2 union Sigma^3 union... = union.big_(n=1)^infinity Sigma^n$)
/ Fonction de chiffrement: $f : Sigma^+ arrow.r.bar Sigma ^+$
/ Fonction de déchiffrement: $g : Sigma^+ arrow.r.bar Sigma ^+$ telle que
#h(2em)
#align(center)[
$forall x in Sigma^+, g(f(x)) = x$
]
]
#focus-slide[
Est-ce suffisant ?
#uncover(2)[_Pourquoi ?_]
]
#slide[
== Principe de Kirchhoff
_La sécurité d'un système de chiffrement ne doit reposer que sur le secret de la *clef*._
Il faut distinguer entre:
#let cell = block.with(
width: 100%,
height: 30%
)
#grid(
columns: (auto, auto),
rows: (auto),
gutter: 3pt,
cell()[
*L'algorithme général*
Ex: décaler chaque lettre dans l'alphabet
Ex: Écrire le texte dans un rectangle et lire de haut en bas
],
cell()[
et *la composante secrète*
Ex: de combien de lettres décaler
#v(1em)
Ex: la largeur du rectangle
]
)
]
#slide[
== Notation revisitée
Un système de chiffrement se compose de:
- Trois ensembles $E, F, K$
- De deux fonctions, $f : E times K arrow.bar.r F, g: F times K arrow.bar.r E$ telles que
- $forall x in E, k in K, g(f(x, k), k) = x$
- On ne doit pas pouvoir retrouver $x$ à partir de $f(x, k)$ sans connaître $k$
]
#slide[
== Exemple
Chiffre de substitution simple (dit _de Caesar_):
- $E = F = Sigma^+$
- $K = [1;25]$
- $f(x = (x_i)_i,k) = F(x_i, k)_i$ où $F(x_i, k) = x_i + k$
]
#slide[
== Exemple
Chiffre de transposition simple:
- $E = F = Sigma^+$
- $K = (n, 𝔖(n))_(n in NN)$
- $f(x = (x_i)_i,(k, sigma)) = (x_(sigma(floor(i/(n slash k))) + k*(i%n/k)))_i$ où $n$ est la longueur du message, en supposant que $n$ est un multiple de $k$
]
#focus-slide[
Un peu de pratique
#v(2em)
_Partie I du TP n°1_
]
#slide[
== _O tempora o moris_
Le chiffrement de Caesar n'est pas vraiment sûr !
#uncover((2,3))[Il n'y a que 25 transformations (= 25 clés différentes)]
#only(3)[C'est facile de toutes les essayer]
]
#slide[
== Améliorations possibles
- Considérer _toutes_ les permutations possibles:
- $26! approx 4 times 10^(26) > 25$
- Un attaquant ne peut pas toutes les essayer
#h(1em)
- Changer régulièrement de système
- Par exemple, alterner entre A #sym.arrow C et A #sym.arrow F
- Deux systèmes ne suffisent pas, mais si on en utilise plus...
- On obtient le chiffre de _Vigenère_
]
#slide[
== Chiffre de substitution généralisé
- $E = F = Sigma^+$
- $K = 𝔖(Sigma)$ l'ensemble des bijections dans $Sigma$
- $f(x = (x_i)_i,sigma) = (sigma(x_i))_i$
- $g(x = (x_i)_i,sigma) = (sigma^(-1)(x_i))_i$
]
#slide[
== Chiffre de Vigenère
- $E = F = Sigma^+$
- $K = [0;25]^m$
- $f(x = (x_i)_i,k=(k_j)_j) = F(x_i, k_(i%m))_i$ où $F(x_i, k) = x_i + k$
Exemple: clef = #text(fill:red)[M]#text(fill:teal)[O]#text(fill:green)[T]
#text(fill:red)[A]#text(fill:teal)[A]#text(fill:green)[A]#text(fill:red)[B]#text(fill:teal)[B]#text(fill:green)[B]#text(fill:red)[C]#text(fill:teal)[C]#text(fill:green)[C]#text(fill:red)[D]#text(fill:teal)[D]#text(fill:green)[D]...
#h(3em) #sym.arrow.b
#text(fill:red)[M]#text(fill:teal)[O]#text(fill:green)[T]#text(fill:red)[N]#text(fill:teal)[P]#text(fill:green)[U]#text(fill:red)[O]#text(fill:teal)[Q]#text(fill:green)[V]#text(fill:red)[P]#text(fill:teal)[R]#text(fill:green)[W]...
]
#slide[
== Un peu de cryptanalyse
#set align(center)
#image("img/chif-dechif-decrypt.svg", width: 60%)
]
#slide[
== Une histoire de fréquences
Toutes les lettres n'apparaissent pas à fréquence égale en français :
- "e" est la letter la plus courante, puis "a", "i", "s", ...
Les bigrammes ont des fréquences différentes aussi !
- l'enchaînement "nt" est beaucoup plus courant que "tn"
Une permutation unique appliquée à tout un texte *préserve les fréquences* (y compris des bigrammes)
]
#slide[
== Retrouver la permutation
Si on sait qu'un texte _français_ (suffisamment long!) a été chiffré en utilisant une _permutation_ unique :
- La lettre la plus présente correspond _probablement_ au "e"
- la deuxième la plus fréquente au "a", etc.
- on peut s'aider des fréquences de bigrammes également
#v(2em)
Contre-ex : _La Disparition_ de Georges Perec
]
#slide[
== Décrypter Vigenère
- Si on connaît la _longueur_ de la clé utilisée dans un chiffre de Vigenère, alors il "suffit" de décrypter $m$ chiffres de Caesar
- On peut retrouver cette longueur grâce aux fréquences des lettres de la langue du texte clair... (mais d'autres méthodes existent aussi !)
]
#focus-slide[
Au boulot ! A l'attaque de Vigenère...
_ Partie II du TP n°1_
]
#slide[
= Chiffres pré-modernes
#v(1em)
- Vigenère publié au XVI siècle, cassé fin du XIX siècle.
#v(1em)
- Mais plusieurs améliorations sont possibles !
]
#slide[
== Chiffrements *polygraphiques*
#v(1em)
- Dans les cryptosystèmes de César et de Vigenère, *une* lettre est transformée en *une* autre lettre...
#v(1em)
#only((2,3))[- ... et ce indépendamment lettre par lettre]
#v(1em)
#only(3)[- Et si on considérait des *groupes* de lettres plutôt ?]
]
#slide[
== Chiffrement digraphique
- $E = F = Sigma^+$
- $K = 𝔖(Sigma^2)$ l'ensemble des bijections dans $Sigma^2$
- $f(x = (x_i)_i,sigma) = (sigma(x_(2i),x_(2i+1)))_i$
- $g(x = (x_i)_i,sigma) = (sigma^(-1)(x_(2i),x_(2i+1)))_i$
]
#slide[
== Chiffre de Hill
- Une substitution générique est coûteuse à représenter
- Chiffre de Hill : ~ César mais en digraphique
- César : $y = x + a$ où $y$ chiffré, $x$ clair, $a$ décalage
- Généralisation (Hill) : $ vec(y_1, y_2) = mat(a,b;c,d) vec(x_1,x_2) = vec(a x_1 + b x_2 [26], c x_1+d x_2 [26]) $
- Pour déchiffrer : il faut inverser la matrice $mat(a,b;c,d)$ (dans $ZZ #text[/] 26ZZ$)
]
#slide[
== Cryptanalyse du chiffre de Hill
- Les fréquences de digrammes différent !
- Le chiffre de Hill est donc vulnérable à l'analyse statistique
]
#slide[
#set list(spacing: 1.1em)
== Chiffre de Hill généralisé
- Le chiffre de Hill se généralise assez bien :
- à des dimensions supérieures
- à des corps plus grands ($FF_(2^8)^n$ i.e. des chaînes d'octets)
- Le chiffrement et déchiffrement sont très rapides
- En dimension assez grande, l'analyse statistique n'est plus efficace
#only(2)[
- Cependant, il n'est plus utilisé aujourd'hui. Pourquoi d'après vous ?]
]
#slide[
= Les chiffres de la Première Guerre Mondiale
- Avec l'avènement des méthodes de communication longue distance (télégrammes), protéger ses communications devient indispensable
- Les belligérants sont capables d'intercepter les communications des autres pays
- Si la sécurité n'est pas bonne: aïe aïe aïe...
]
#slide[
== Le chiffre Ubchi
- Chiffre utilisé par *toute* l'armée allemande en 1914 lorsqu'éclate la Première Guerre Mondiale
- La même clé est utilisée pour *tous* les échanges...
- L'algorithme est une double transposition :
#grid(
columns: (20%, 5%,20%, 5%, 20%, 5%, 20%),
rows: (auto),
[
#tablex(
columns: 5,
auto-lines: false,
(), vlinex(), vlinex(),vlinex(),vlinex(), (),
[#text(fill:red)[M]], [#text(fill:teal)[A]], [#text(fill:green)[C]], [#text(fill:blue)[L]],[#text(fill:black)[E]],
hlinex(),
[#text(fill:red)[5]], [#text(fill:teal)[1]], [#text(fill:green)[2]], [#text(fill:blue)[4]],[#text(fill:black)[3]],
hlinex(),
[#text(fill:red)[A]], [#text(fill:teal)[T]], [#text(fill:green)[T]], [#text(fill:blue)[A]],[#text(fill:black)[Q]],
[#text(fill:red)[U]], [#text(fill:teal)[E]], [#text(fill:green)[Z]], [#text(fill:blue)[A]],[#text(fill:black)[L]],
[#text(fill:red)[A]], [#text(fill:teal)[U]], [#text(fill:green)[B]], [#text(fill:blue)[E]],()
)
],
[
#v(2.5em)
#sym.arrow.r],
[
#tablex(
columns: 5,
auto-lines: false,
(), vlinex(), vlinex(),vlinex(),vlinex(), (),
[#text(fill:red)[M]], [#text(fill:teal)[A]], [#text(fill:green)[C]], [#text(fill:blue)[L]],[#text(fill:black)[E]],
hlinex(),
[#text(fill:red)[5]], [#text(fill:teal)[1]], [#text(fill:green)[2]], [#text(fill:blue)[4]],[#text(fill:black)[3]],
hlinex(),
[#text(fill:teal)[T]], [#text(fill:teal)[E]], [#text(fill:teal)[U]],[#text(fill:green)[T]],[#text(fill:green)[Z]],
[#text(fill:green)[B]], [#text(fill:black)[Q]], [#text(fill:black)[L]],[#text(fill:blue)[A]], [#text(fill:blue)[A]],
[#text(fill:blue)[E]], [#text(fill:red)[A]],[#text(fill:red)[U]],[#text(fill:red)[A]], [#text(fill:black)[X]],
)],
[
#v(2.5em)
#sym.arrow.r],
[
#tablex(
columns: 5,
auto-lines: false,
(), vlinex(), vlinex(),vlinex(),vlinex(), (),
[#text(fill:red)[M]], [#text(fill:teal)[A]], [#text(fill:green)[C]], [#text(fill:blue)[L]],[#text(fill:black)[E]],
hlinex(),
[#text(fill:red)[5]], [#text(fill:teal)[1]], [#text(fill:green)[2]], [#text(fill:blue)[4]],[#text(fill:black)[3]],
hlinex(),
[E], [Q], [A], [U], [L],
[U], [Z], [A], [X], [T],
[A], [A], [T], [B], [E]
)],
[#v(2.5em)
#sym.arrow.r],
[EQAUL UZAXT AATBE],
)
]
#slide[
== Comment les français ont-il cassé Ubchi ?
Un opérateur a oublié la deuxième transposition...
#align(center)[
#image("img/laboulette.jpg", width:50%)
]
]
#slide[
== Ubchi a été décrypté !
- Tout le monde utilisait la même clef #sym.arrow.r oups !
- Maintenant, les français peuvent déchiffrer les conversations
- Comment les Français vont-il utiliser cette information ?
]
#slide[
== La réaction française
#grid(
columns: (35%,65%),
rows: (75%),
[
#image("img/lematin.jpg", width:60%)
],
[
#image("img/laboulette.jpg", width:90%)
],)
]
#slide[
== Le chiffre ABC
- La mèche est vendue, les allemands sont au courant du décryptage !
- Et du coup, la clef est changée #emoji.face.sad
- Mais les Français finissent par trouver un mode direct de décryptage ! #emoji.face.happy
- Et du coup les allemands sont obligés de changer de cryptosystème : ils utilisent le chiffre dit "ABC"
]
#slide[
== Le chiffre ABC (suite)
- Bonne nouvelle pour les Français : ce chiffre est encore moins sûr !
- Il s'agit simplement d'un chiffre Vigenère *avec une clé immuable égale à ABC*,
- suivie d'une *simple* transposition (la moitié d'Ubchi)
- pour leur défense, la clé de la transposition changeait régulièrement
- cet algorithme ne résiste pas longtemps aux spécialistes français...
]
#slide[
== Et ensuite ?
- Les Allemands changèrent de code plusieurs fois :
- KRU
- ADFGVX (substitution génériques en encodant sur deux lettres puis transposition)
- Tous deux furent décryptés !
- Un message ADFGVX décrypté fut crucial dans la victoire française : il s'agit du "Radiogramme de la victoire", permettant d'anticiper une attaque allemande à Compiègne !
]
#focus-slide[
== Puis vint la <NAME> !
]
#slide[
== Enigma
#let cell = block.with(
width: 100%,
)
#grid(
columns: (auto, auto),
rows: (auto),
gutter: 3pt,
cell(height: 75%)[
#image("img/enigma.jpg", height:90%)
],
cell(height: 75%)[
#image("img/Enigma-action.svg", height:90%)
]
)
]
#slide[
== Colossus et son créateur
#grid(
columns:(auto, 20%, auto),
rows:(60%),
[#image("img/Colossus.jpg", width:auto)],
[],
[#image("img/turing.jpg", width:auto)]
)
]
|
|
https://github.com/DieracDelta/presentations | https://raw.githubusercontent.com/DieracDelta/presentations/master/06_07_24/main.typ | typst | #import "polylux/polylux.typ": *
#import themes.metropolis: *
#import "common.typ": *
#show: metropolis-theme.with(
footer: [#logic.logical-slide.display() / #utils.last-slide-number]
)
#set text(font: font, weight: wt, size: 25pt)
#show math.equation: set text(font: "Fira Math")
#set strong(delta: 100)
#set par(justify: true)
#title-slide(
author: [<NAME>],
title: "Slides - 6/7",
)
#slide(title: "Table of contents")[
#metropolis-outline
]
#new-section-slide([High Level Idea (Review)])
#slide(title: "Pitch (Review)" )[
- Compile C to a #alert[unsafe subset] of Rust (“RustLight”)
- Run RustLight through the Rust compiler
- RustLight operational semantics serve as a "Rust Spec"
- Improve on C2Rust
]
#new-section-slide([Variadics])
#slide(title: "Refresher: Variadics in C")[
- `printf(...)` - Syntax
- `va_list` - informally pointer to info about next argument
- `typedef __builtin_va_list va_list;`
- `typedef __va_list_tag __builtin_va_list[1]`
- `va_start(va_list l, last_arg)` - `l` initialized with info about first arg
- `va_end(va_list l)` - deallocates l? Spec doesn't say.
- `t va_arg(va_list l, t)` - returns next argument
- `va_copy(va_list l, va_list l')` - copies `l` into `l'`
]
#slide(title: "va_list c99 spec")[
#image("./spec.png")
]
// TODO maybe put spec in
#slide(title: "Using Variadics")[
#set text(font: font, weight: wt, size: 18pt)
#side-by-side_dup[
#codeblock(
```C
#include <stdio.h>
void example() {
printf("Hello world %d", 5);
}
```
)
][
#set text(font: font, weight: wt, size: 16pt)
#codeblock(
```rust
extern "C" {
fn printf(
_: *const libc::c_char,
_: ...
) -> libc::c_int;
}
#[no_mangle]
pub unsafe extern "C" fn example() {
printf(
b"Hello world %d\0"
as *const u8
as *const libc::c_char,
5 as libc::c_int
);
}
```
)
]
]
#slide(title: "Variadics - Example - C")[
#set text(font: font, weight: wt, size: 14pt)
#codeblock(
```c
#include <stdarg.h>
int sum(int count, ...);
int sum(int count, ...) {
int total = 0;
va_list args;
va_start(args, count);
for (int i = 0; i < count; i++) {
total += va_arg(args, int);
}
va_end(args);
return total;
}
```
)
]
#slide(title: "Variadics - Example - Rust")[
#set text(font: font, weight: wt, size: 14pt)
#side-by-side_dup[
#codeblock(
```c
#include <stdarg.h>
int sum(int count, ...);
int sum(int count, ...) {
int total = 0;
va_list args;
va_start(args, count);
for (int i = 0; i < count; i++) {
total += va_arg(args, int);
}
va_end(args);
return total;
}
```
)
][
#codeblock(
```rust
#[no_mangle]
pub unsafe extern "C" fn sum(
mut count: libc::c_int,
mut args: ...
) -> libc::c_int {
let mut total: libc::c_int = 0
as libc::c_int;
let mut args_0: ::core::ffi::VaListImpl;
args_0 = args.clone();
let mut i: libc::c_int = 0
as libc::c_int;
while i < count {
total += args_0.arg::<libc::c_int>();
i += 1;
i;
}
return total;
}
```
)
]
]
#slide(title: "Variadics - `/VaList(Impl)?/`")[
- `'a` : how long `VaList` lives
- `'f` : how long underlying `VaListImpl` lives. Always entire function
#codeblock(
```rust
pub struct VaList<'a, 'f: 'a> {
inner: &'a mut VaListImpl<'f>,
}
```
)
]
#slide(title: "Variadics - Map")[
#set text(font: font, weight: wt, size: 18pt)
#table(
columns: 2,
[C], [Rust],
[`__va_list_tag[1]`], [`std::ffi::VaList<'a, 'f> where 'f : 'a`],
[`__va_list_tag*`], [`std::ffi::VaListImpl<'f>`],
[`va_start(l, last_arg)`], [`l.clone()`],
[`va_arg(l, t)`], [`l.arg::<T: VaArgSafe>()`],
[`va_copy(a, b)`], [`let b = a.clone()`],
[`va_end()`], [`Drop::drop()`],
)
]
#slide(title: "Variadics - Lifetimes prevent Misuse")[
#set text(font: font, weight: wt, size: 20pt)
#codeblock(
```rust
pub unsafe extern fn foo<'a>(mut ap: ...) -> VaListImpl<'a> {
// `VaListImpl` would escape
ap
}
```
// /// misuse
// fn bar<'a, 'f, 'g: 'f>(ap: &mut VaList<'a, 'f>, aq: VaList<'a, 'g>) {
// // Incompatible types
// *ap = aq;
// }
)
]
#slide(title: "Variadics - Rust Caveats")[
- Stable Rust can call variadics and link to them
- Stable Rust *cannot* generate variadic functions
- Nightly Rust (described above) come from `#![feature(c_variadic)]`
- Variadics compliant with x86_64-linux ABI, not so stable with other ABIs
- nightly feature `#![feature(c_variadic)]`
]
#new-section-slide([Forward Declaration])
#slide(title: "Forward Declarations - C")[
#set text(font: font, weight: wt, size: 18pt)
#codeblock(
```rust
// linker resolves
typedef struct ExampleS ExampleS;
typedef union ExampleU ExampleU;
struct ExampleS* createExample(ExampleU* ex);
int main() {
struct ExampleS *myExample = createExample((ExampleU*) 0x0);
return 0;
}
struct ExampleS* createExample(ExampleU* ex) {
return (struct ExampleS *) 0x0;
}
```
)
]
#slide(title: "Forward Declarations - Rust")[
#set text(font: font, weight: wt, size: 15pt)
#codeblock(
```rust
use ::libc;
extern "C" {
pub type ExampleS;
pub type ExampleU;
}
unsafe fn main_0() -> libc::c_int {
let mut myExample: *mut ExampleS = createExample(0 as *mut ExampleU);
return 0 as libc::c_int;
}
#[no_mangle]
pub unsafe extern "C" fn createExample(mut ex: *mut ExampleU) -> *mut ExampleS {
return 0 as *mut ExampleS;
}
pub fn main() {
unsafe { ::std::process::exit(main_0() as i32) }
}
```
)
]
#slide(title: "Forward Declaration - Extern Type")[
- Rust guarantees that all types have a way to obtain size.
- Static types can determine this at compile time (e.g. size_of)
- Dynamically Sized Types (DST) carry size metadata at runtime (size_of_val)
- *Not stabilized*
]
#new-section-slide([Borrow Checking])
#slide(title: "Borrow Checking Modeling and Thoughts")[
#set text(font: font, weight: wt, size: 17pt)
- RL Programs $subset$ Rust Programs
- All RL programs must be accepted by borrow checker.
- Not all accepted by borrow checker programs need to be modeled by RL.
- Model borrow checking semantics s.t. stricter than the borrow checker
- Can ignore complicated edge cases like Two Phase Borrow
- Can reduce scope significantly
- Only model `*const` `*mut`
- By definition drop edge cases
- Open question: is this enough? How to show this *actually* maps onto rust semantics (for which a spec does not exist)
- Longer term, would need to expand on this to support other pointer types. How to model `&`?
]
// disclaimer: no longer relevant to understand, really
#new-section-slide([Two Phase Borrow])
#slide(title: "Two-phase Borrow Intuition")[
- `&mut` when borrowed implicitly #emph("Reserved") until used to mutate, at which point becomes #emph("Active")
- While #emph("Reserved"), is treated as a shared (immutable) pointer
- While #emph("Active"), is treated as mutable pointer
]
#slide(title: "Two-phase Borrow (Implicit Mutable Borrow)")[
#side-by-side_dup[
✔️
```rust
let mut v = Vec::new();
v.push(v.len());
```
][
❌
```rust
let mut v = Vec::new();
let v_ptr = &mut v;
let v_len = v.len();
v_ptr.push(v_len);
```
]
// https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=394ce5a86466a3d003fe1d841464c940
]
#slide(title: "Two-phase Borrow (Implicit Mutable Borrow)")[
#set text(font: font, weight: wt, size: 15pt)
#side-by-side_dup[
Source Code:\
#codeblock(
```rust
let mut v = Vec::new();
v.push(v.len());
```
)
][
Source Code with implicit behavior made explicit:
#codeblock(
```rust
let mut v = Vec::new();
// no pointers
let temp1 = &mut v;
//temp1 treated as shared pointer to v. temp1: "Reserved"
let temp3 = &v;
// temp3 treated as shared pointer to v.
let temp2 = Vec::len(temp3);
drop(temp3);
// temp1: "Active"
Vec::push(temp1, temp2);
```
)
]
]
#slide(title: "Two-phase Borrow (Implicit Reborrow)")[
#set text(font: font, weight: wt, size: 14pt)
#side-by-side_dup[
Source Code:\
#codeblock(
```rust
let r = &mut Vec::from([0]);
std::mem::replace(
/*implicit reborrow: &mut * */ r,
vec![1, r.len()]
);
```
)
][
Source Code with implicit behavior made explicit:
#codeblock(
```rust
let mut temp_vec = Vec::from([0]); // line 1
let r = &mut temp_vec; // line 1
// r: "Active"
let temp1 = &mut *r; // line 3
// r: "Suspended", temp1: "Reserved" because implicit borrow
let temp3 = &*r; // line 4
// temp3: shared pointer
let r_len : int = Vec::len(temp3); // line 4
let temp4 = vec![1, r_len]; // line 4
// r: "Suspended", temp1: "Active" because implicit borrow
std::mem::replace(temp1, temp4);
```
)
]
]
#new-section-slide([Building bigger projects (tmux)])
#slide(title: "Compilation Information")[
- In c2rust bear/ninja/intercept-build used to determine locations of included headers
- Python used to connect files
]
#slide(title: "Headers")[
#set text(font: font, weight: wt, size: 20pt)
- General structure of file mirrors C
- Ugly
```rust
pub mod my_header {
extern "C" {
pub type ..;
pub fn ..;
}
}
// more headers
// code if C file
```
]
|
|
https://github.com/gomazarashi/Typst_describe_law_and_theorem | https://raw.githubusercontent.com/gomazarashi/Typst_describe_law_and_theorem/main/Typst_5_定理や法則の記述.typ | typst | #set text(lang: "ja") // 言語を日本語に設定
#set text(font: ("New Computer Modern", "<NAME>"), size: 10pt) // フォントを設定
#show figure.where(kind: table): set figure.caption(position: top) // 表におけるキャプションを上部に表示するよう設定
#show heading: set text(font: ("Harano Aji Gothic"), weight: 500)
#set heading(numbering: "1.1.")
#import "@preview/codelst:2.0.1": sourcecode
#import "@preview/showybox:2.0.1": showybox
#show raw: set text(font: ("DejaVu Sans Mono", "Harano Aji Gothic"))
#show math.equation: set text(size: 12pt)
// 表紙の設定
#align(center)[
#v(200pt)
#text(size: 18pt)[
Typstにおける定理・法則の記述
]
]
#pagebreak()
#set page(numbering: "1")
#counter(page).update(1)
= 微分積分学
\
#showybox(
title: text(font: ("<NAME>ji Gothic"), size: 12pt)[極限の基本性質],
title-style: (color: black, sep-thickness: 0pt, align: center, weight: 500),
frame: (
border-color: blue,
title-color: blue.lighten(50%),
body-color: blue.lighten(95%),
footer-color: blue.lighten(80%),
),
)[
$lim_(n->oo) a_n=a$、$lim_(n->oo) b_n=b$とする。
#line(length: 100%)
$ lim_(n->oo) a_n plus.minus b_n=a plus.minus b $
#line(length: 100%)
$ lim_(n->oo) a_n b_n=a b $
特に、$k$が定数のとき
$ lim_(n->oo) k a_n = k a $
#line(length: 100%)
$ lim_(n->oo) a_n / b_n = a / b quad(b_n, b!=0) $
#line(length: 100%)
$a_n <= b_n$ならば$ lim_(n->oo) a_n <= lim_(n->oo) b_n $
]
\
#showybox(
title: text(font: ("<NAME>"), size: 12pt)[合成関数の微分法],
title-style: (color: black, sep-thickness: 0pt, align: center, weight: 500),
frame: (
border-color: blue,
title-color: blue.lighten(50%),
body-color: blue.lighten(95%),
footer-color: blue.lighten(80%),
),
)[
関数$y=f(x)$が区間$I$で微分可能、その値域$f(I)$で$z=g(y)$が微分可能ならば、\
合成関数$z=g(f(x))$は$I$で微分可能で、
$ (dif z)/(dif x) = (dif z)/(dif y) (dif y)/(dif x) = g'(f(x)) f'(x) $
]
\
#showybox(
title: text(font: ("<NAME>"), size: 12pt)[基本的な関数の不定積分(抜粋)],
title-style: (color: black, sep-thickness: 0pt, align: center, weight: 500),
frame: (
border-color: blue,
title-color: blue.lighten(50%),
body-color: blue.lighten(95%),
footer-color: blue.lighten(80%),
),
)[
$ integral e^x dif x = e^x $
#line(length: 100%)
$ integral a^x dif x = a^x / (log a) $
#line(length: 100%)
$ integral 1/x dif x = log |x| $
#line(length: 100%)
$ integral x^alpha dif x = x^(alpha+1) / (alpha+1) quad (alpha != -1) $
#line(length: 100%)
$ integral (dif x)/(sqrt(a^2-x^2)) = arcsin(x/a) $
]
\
#showybox(
title: text(font: ("<NAME>"), size: 12pt)[定積分の存在],
title-style: (color: black, sep-thickness: 0pt, align: center, weight: 500),
frame: (
border-color: blue,
title-color: blue.lighten(50%),
body-color: blue.lighten(95%),
footer-color: blue.lighten(80%),
),
)[
$f(x)$が有界閉区間$[a, b]$上で連続であれば、
$ I = lim_(|Delta -> 0|) S(Delta) = lim_(|Delta -> 0|) sum_(i=1)^n f(xi_i)(x_i-x_(i-1)) $
が存在する($I$は$[a,b]$の分割の仕方、$xi_i$のとり方によらない)。
]
\
#showybox(
title: text(font: ("<NAME>"), size: 12pt)[合成関数の微分],
title-style: (color: black, sep-thickness: 0pt, align: center, weight: 500),
frame: (
border-color: blue,
title-color: blue.lighten(50%),
body-color: blue.lighten(95%),
footer-color: blue.lighten(80%),
),
)[
関数$z=f(x,y)$が全微分可能で、$x=phi(t), y=psi(t)$が$t$について微分可能ならば、合成関数$z=f(phi(t), psi(t))$は$t$について微分可能で、 次式が成り立つ。
$ (dif z)/(dif t) = (diff f)/(diff x) (dif x)/(dif t) + (diff f)/(diff y) (dif y)/(dif t) $
]
\
#showybox(
title: text(font: ("<NAME>"), size: 12pt)[ラグランジュの乗数法],
title-style: (color: black, sep-thickness: 0pt, align: center, weight: 500),
frame: (
border-color: blue,
title-color: blue.lighten(50%),
body-color: blue.lighten(95%),
footer-color: blue.lighten(80%),
),
)[
$f(x,y)$、$g(x,y)$は$C^1$級とする。条件$g(x,y)=0$のもとで関数$z=f(x,y)$が$(x,y)=(a,b)$で極値を取り、$g_x(a,b)$または$g_y(a,b)$が0でないとする。このとき、ある定数$lambda$が存在し、次式が成り立つ。
$ cases(f_x(a,b) - lambda g_x(a,b) = 0, f_y(a,b) - lambda g_y(a,b) = 0, g(a,b) = 0) $
]
\
= 線形代数学
#showybox(
title: text(font: ("<NAME>"), size: 12pt)[行列の定義],
title-style: (color: black, sep-thickness: 0pt, align: center, weight: 500),
frame: (
border-color: blue,
title-color: blue.lighten(50%),
body-color: blue.lighten(95%),
footer-color: blue.lighten(80%),
),
)[
$(m,n)$型の行列、$m times n$行列とは、$m times n$個の数の配列であり、記号で
$ mat(
delim: "[",
a_(11), a_(12), dots.h.c, a_(1 n);a_(21), a_(22), dots.h.c, a_(2 n);dots.v, dots.v, dots.down, dots.v;a_(m 1), a_(m 2), dots.h.c, a_(m n);,
) $
と表される。$a_(i j)$を行列の$(i,j)$成分という。
]
\
#showybox(
title: text(font: ("<NAME>"), size: 12pt)[ベクトルの例],
title-style: (color: black, sep-thickness: 0pt, align: center, weight: 500),
frame: (
border-color: blue,
title-color: blue.lighten(50%),
body-color: blue.lighten(95%),
footer-color: blue.lighten(80%),
),
)[
$m$次元列ベクトル:
$ bold(a) = vec(delim: "[", a_1, a_2, dots.v, a_m) $
$n$次元行ベクトル:
$ bold(b)=[b_1,b_2,dots.h.c,b_n] $
零ベクトル: 成分がすべて$0$のベクトルで、記号で$bold(0)$と表す。
]
\
#showybox(
title: text(font: ("<NAME>"), size: 12pt)[ベクトル空間],
title-style: (color: black, sep-thickness: 0pt, align: center, weight: 500),
frame: (
border-color: blue,
title-color: blue.lighten(50%),
body-color: blue.lighten(95%),
footer-color: blue.lighten(80%),
),
)[
すべての$n$次元実数ベクトル$x$の集合を$n$次元ベクトル空間といい、記号で$bold(R)^n$と表す。
]
|
|
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/design_concept.typ | typst | #import "../style.typ": *
#import "../acronyms.typ": *
#set text(..sa_text_style)
#show heading.where(level: 1): sa_heading1_show
#show heading.where(level: 2): sa_heading2_show
#show heading.where(level: 3): sa_heading3_show
#show heading.where(level: 4): sa_heading4_show
#let metadata = (
title: [VisualFP],
description: [Designing a Visual, Block-Based Environment to Create & Execute Haskell Code],
organization: [Department of Computer Science \ OST - Eastern Switzerland University of Applied Sciences \ Campus Rapperswil-Jona],
thesis: [Student Research Project],
term: [Autumn Term 2023],
authors: [<NAME>, <NAME>],
authors-short: [<NAME>, <NAME>],
advisor: [Prof. Dr. <NAME>],
partner: [IFS Institute for Software],
external-co-examiner: [],
internal-co-examiner: []
)
#sa_title_page(metadata);
#include_section("design_concept/abstract.typ")
#include_section("design_concept/mgmt_summary.typ")
#set heading(..sa_header_style)
#sa_table_of_contents()
#set page(..sa_page_style(metadata))
#include_section("design_concept/content/introduction/introduction.typ")
#include_section("design_concept/content/design/design.typ")
#include_section("design_concept/content/poc/poc.typ")
#include_section("design_concept/content/results/results.typ")
#include_section("design_concept/appendix/appendix.typ") |
|
https://github.com/sitandr/conchord | https://raw.githubusercontent.com/sitandr/conchord/main/examples/crazy.typ | typst | MIT License | #import "../lib.typ": new-chordgen
#set page(height: auto, width: auto, margin: 1em)
#let crazy-chord = new-chordgen(string-number: 3,
colors: (shadow-barre: orange,
grid: gray.darken(30%),
hold: red,
barre: purple,),
number-to-left: true
)
#set text(fill: purple)
#box(crazy-chord("320", name: "C"))
#box(crazy-chord("2,4,4,*", name: "Bm"))
#box(crazy-chord("2,2,2, *"))
#box(crazy-chord("x,3,2, !"))
#box(crazy-chord("12,12,12, !")) |
https://github.com/feil7/Cheatsheets | https://raw.githubusercontent.com/feil7/Cheatsheets/master/template.typ | typst | #let conf(
title: none,
authors: (),
abstract: none,
doc,
) = {
// Set and show rules from before.
set page(
paper: "a4",
header:
align(right + horizon,
text(size: 18pt)[#title #linebreak()]
+text(size: 12pt)[#abstract]
),
margin: (top: 60pt, left: 15pt, right: 15pt, bottom: 15pt),
)
//set par(justify: ture)
set text(
font: "CodeNewRoman Nerd Font Mono",
style: "oblique",
weight: "bold",
spacing: 3pt,
size: 11pt,
)
set align(left)
columns(2, doc)
}
#let part(section, input) = {
par(
rect(
width: 100%,
inset: 8pt,
outset: 0pt,
fill: blue,
radius: 8pt,
[#section #linebreak() #input],
))
}
#let cut(input, short) = {
rect(
width: 100%,
inset: 3pt,
outset: 0pt,
radius: 2pt,
stroke: none,
fill: gray,
[#grid(
columns: (3fr, 2fr),
rows: auto,
gutter: 0pt,
[#input],[#short])]
)
} |
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/010.%20diff.html.typ | typst | #set page(
paper: "a5",
margin: (x: 1.8cm, y: 1.5cm),
)
#set text(
font: "Liberation Serif",
size: 10pt,
hyphenate: false
)
#set par(justify: true)
#v(10pt)
= What Made Lisp Different
#v(10pt)
_December 2001 (rev. May 2002)_
_(This article came about in response to some questions on the LL1 mailing list. It is now incorporated in Revenge of the Nerds.)_
When McCarthy designed Lisp in the late 1950s, it was a radical departure from existing languages, the most important of which was Fortran.Lisp embodied nine new ideas:
#enum(
enum.item[*Conditionals*. A conditional is an if-then-else construct. We take these for granted now. They were invented by McCarthy in the course of developing Lisp. (Fortran at that time only had a conditional goto, closely based on the branch instruction in the underlying hardware.) McCarthy, who was on the Algol committee, got conditionals into Algol, whence they spread to most other languages.],
enum.item[ *A function type*. In Lisp, functions are first class objects -- they're a data type just like integers, strings, etc, and have a literal representation, can be stored in variables, can be passed as arguments, and so on.],
enum.item[*Recursion*. Recursion existed as a mathematical concept before Lisp of course, but Lisp was the first programming language to support it. (It's arguably implicit in making functions first class objects.)],
enum.item[*A new concept of variables*. In Lisp, all variables are effectively pointers. Values are what have types, not variables, and assigning or binding variables means copying pointers, not what they point to.],
enum.item[*Garbage-collection*.],
enum.item[*Programs composed of expressions*. Lisp programs are trees of expressions, each of which returns a value.(In some Lisps expressions can return multiple values.) This is in contrast to Fortran and most succeeding languages, which distinguish between expressions and statements.
It was natural to have this distinction in Fortran because (not surprisingly in a language where the input format was punched cards) the language was line-oriented. You could not nest statements. And so while you needed expressions for math to work, there was no point in making anything else return a value, because there could not be anything waiting for it.
This limitation went away with the arrival of block-structured languages, but by then it was too late. The distinction between expressions and statements was entrenched. It spread from Fortran into Algol and thence to both their descendants.
When a language is made entirely of expressions, you can compose expressions however you want. You can say either (using _Arc_ syntax)
```lisp
(if foo (= x 1) (= x 2))
```
or
```lisp
(= x (if foo 1 2))
```],
enum.item[*A symbol type*. Symbols differ from strings in that you can test equality by comparing a pointer.],
enum.item[*A notation for code* using trees of symbols.],
enum.item[*The whole language always available*. There is no real distinction between read-time, compile-time, and runtime. You can compile or run code while reading, read or run code while compiling, and read or compile code at runtime.
Running code at read-time lets users reprogram Lisp's syntax; running code at compile-time is the basis of macros; compiling at runtime is the basis of Lisp's use as an extension language in programs like Emacs; and reading at runtime enables programs to communicate using s-expressions, an idea recently reinvented as XML.],
)
When Lisp was first invented, all these ideas were far removed from ordinary programming practice, which was dictated largely by the hardware available in the late 1950s.
Over time, the default language, embodied in a succession of popular languages, has gradually evolved toward Lisp. 1-5 are now widespread. 6 is starting to appear in the mainstream. Python has a form of 7, though there doesn't seem to be any syntax for it. 8, which (with 9) is what makes Lisp macros possible, is so far still unique to Lisp, perhaps because (a) it requires those parens, or something just as bad, and (b) if you add that final increment of power, you can no longer claim to have invented a new language, but only to have designed a new dialect of Lisp ; -)
Though useful to present-day programmers, it's strange to describe Lisp in terms of its variation from the random expedients other languages adopted. That was not, probably, how McCarthy thought of it. Lisp wasn't designed to fix the mistakes in Fortran; it came about more as the byproduct of an attempt to axiomatize computation.
|
|
https://github.com/cadojo/vita | https://raw.githubusercontent.com/cadojo/vita/main/src/education.typ | typst | MIT License | #let degreeslist = state("degreeslist", ())
#let duration(start, stop) = {
text(rgb(130,130,130))[
#start #if (start != none and stop != none) { " — " } #stop
]
}
#let degree(
title, field,
school: none,
start: none,
stop: none,
notes
) = {
let content = [
#grid(
columns: (70%, 28%, 1fr),
heading(level: 2, (title, field).join(" ")),
align(right)[
#duration(start, stop)
]
)
#if school != none {
set text(rgb(100,100,100))
v(-0.75em)
heading(level: 3, school)
}
#notes
]
degreeslist.update(current => current + (content,))
}
#let degrees(header: "Education", size: 11pt) = {
locate(
loc => {
let content = degreeslist.final(loc)
if content.len() > 0 {
heading(level: 1, header)
line(length: 97%)
content.join()
}
}
)
}
|
https://github.com/saimnaveediqbal/thesis-NTNU-typst | https://raw.githubusercontent.com/saimnaveediqbal/thesis-NTNU-typst/main/template/main.typ | typst | MIT License | #import "../lib.typ": *
#let chapters-on-odd = false
#show: ntnu-thesis.with(
title: [An NTNU Thesis typst template],
short-title: [],
authors: ("<NAME>", "<NAME>"),
short-author: ("Andersen et. al."),
titlepage: true,
chapters-on-odd: chapters-on-odd,
bibliography: bibliography("thesis.bib"),
figure-index: (enabled: true, title: "Figures"),
table-index: (enabled: true, title: "Tables"),
listing-index: (enabled: true, title: "Code listings"),
abstract-en: [
The `ntnu-thesis` template is a typst port of the `ntnuthesis` LaTeX class. It can be used for theses at all levels –
bachelor, master and PhD – and is available in English (British and
American) and Norwegian (Bokmål and Nynorsk). This document is ment to
serve (i) as a description of the document class, (ii) as an example of
how to use it, and (iii) as a thesis template.
],
abstract-no: [
Malen `ntnu-thesis` er en typst-oversettelse av LaTeX-klassen `ntnuthesis`. Den er tilrettelagt for avhandlinger på alle nivåer –
bachelor, master og PhD – og er tilgjengelig på både norsk (bokmål og
nynorsk) og engelsk (britisk og amerikansk). Dette dokumentet er ment å
tjene (i) som en beskrivelse av dokumentklassen, (ii) som et eksempel på
bruken av den, og (iii) som en mal for avhandlingen.
],
)
= Introduction
<introduction>
The original `ntnuthesis` template was created by the CoPCSE #footnote[#link("https://www.ntnu.no/wiki/display/copcse/Community+of+Practice+in+Computer+Science+Education+Home")] as a template applicable for theses at all study levels.
It is closely based on the standard LaTeX `report` document class as well as previous thesis templates. This typst port aims to replicate the look of the LaTeX template in typst.
The purpose of the present document is threefold. It should serve (i) as
a description of the document class, (ii) as an example of how to use
it, and (iii) as a thesis template.
= Using the Template
<chap:usage>
== Thesis Setup
<sec:setup>
The document class is initialized by calling
```typst #show: ntnu-thesis.with()``` at the beginning of your `.typ` file. Currently it only supports english. The `ntnu-thesis` function has a number of options you can set, most of which will be described in this document. The rest will be documented in this templates repository.
The titlepage at the beginning of this document is a placeholder to be used when writing
the thesis. This should be removed before handing in the thesis, by settting `titlepage: false`.
Instead the official NTNU titlepage for the corresponding thesis type
should be added as described on Innsida.#footnote[see #link("https://innsida.ntnu.no/wiki/-/wiki/English/Finalizing+the+bachelor+and+master+thesis") for bachelor and master, and #link("https://innsida.ntnu.no/wiki/-/wiki/English/Printing+your+thesis")
for PhD.]
== Title, Author, and Date
<title-author-and-date>
The title of your thesis should be set by changing the `title` parameter of the template. The title will appear on the titlepage as well as in the running header of the even numbered pages. If the title is too long for the header, you can use `shorttitle` to set a version for the header.
The authors should be listed with full names in the `authors` parameter. This is an array, with multiple authors separated by a comma.
Use `date` to set the date of the document. It will only appear on
the temporary title page. To keep track of temporary versions, it can be
a good idea to use `date: datetime.today()` while working on the thesis.
== Page Layout
<page-layout>
The document class is designed to work with twosided printing. This
means that all chapters start on odd (right hand) pages, and that blank
pages are inserted where needed to make sure this happens. However,
since the theses are very often read on displays, the margins are kept
the same on even and odd pages in order to avoid that the page is
jumping back and forth upon reading.
By default this is turned off. You can turn it on by setting
`chapters-on-odd: false` at the top of the file.
== Structuring Elements
<structuring-elements>
The standard typst headings are supported, and are set using =.
=== This is a level 3 heading
<this-is-a-subsection>
==== This is level 4 heading
<this-is-a-subsubsection>
===== This is a level 5 heading
<this-is-a-paragraph>
Headings up to level 3 will be included in the table of
contents, whereas the lower level structuring elements will not appear
there. Don’t use too many levels of headings; how many are appropriate,
will depend on the size of the document. Also, don’t use headings too
frequently.
Make sure that the chapter and section headings are correctly
capitalised depending on the language of the thesis, e.g.,
'#emph[Correct Capitalisation of Titles in English];' vs. '#emph[Korrekt
staving av titler på norsk];'.
Simple paragraphs are the lowest structuring elements and should be used
the most. They are made by leaving one (or more) blank line(s) in the
`.typ` file. In the typeset document they will appear indented and with
no vertical space between them.
== Lists
<lists>
Numbered and unnumbered lists are used just as in regular typst, but are typeset
somewhat more densely and with other labels. Unnumbered list:
- first item
- second item
- first subitem
- second subitem
- first subsubitem
- second subsubitem
- last item
Numbered list:
+ first item
+ second item
+ first subitem
+ second subitem
+ first subsubitem
+ second subsubitem
+ last item
== Figures
<figures>
Figures are added using ```typst #figure()```. An example is shown in
#link(<fig:mapNTNU>)[2.1];. By default figures are placed in the flow, exactly where it was specified. To change this set the ```placement``` option to either `top`, `bottom`, or `auto`. To add an image, use ```typst #image()``` and set the `height` or `width` to include the graphics file. If the caption consists of a single sentence fragment (incomplete sentence), it should not be punctuated.
#figure(image("figures/kart_student.png", width: 50%),
caption: [
The map shows the three main campuses of NTNU.
]
)
<fig:mapNTNU>
For figures compsed of several sub-figures, the `subpar` module has been used. See #link(<fig:subfig>)[2.4]
with #link(<sfig:a>)[\[sfig:a\]] for an example.
#subfigure(
figure(image("figures/kart_student.png", width: 100%),
caption: [First sub-figure]), <sfig:a>,
figure(image("figures/kart_student.png", width: 100%),
caption: [Second sub-figure]), <sfig:b>,
columns: (1fr, 1fr),
caption: [A figure composed of two sub-figures. It has a long caption in order to demonstrate how that is typeset.
],
<fig:subfig>
)
== Tables
<tables>
Tables are added using ```typst #table()```, wrapped in a ```typst #figure()``` to allow referencing. An example is given in
@tab:example1. If the caption consists
of a single sentence fragment (incomplete sentence), it should not be
punctuated.
#figure(
table(
stroke: none,
columns: 2,
table.hline(),
table.header([*age*], [*IQ*],),
table.hline(),
[10], [110],
[20], [120],
[30], [145],
[40], [120],
[50], [100],
table.hline(),
), caption: [A simple, manually formatted example table]
) <tab:example1>
Tables can also be automatically generated from CSV files #footnote(link("https://typst.app/docs/reference/data-loading/csv/")).
== Listings
<listings>
Code listings are are also wrapped in a ```typst #figure()```. Code listings are defined by using three ``` `backticks` ```. The programming language can also be provided. See the typst documentation for details. The
code is set with the monospace font, and the font size is reduced to
allow for code lines up to at least 60 characters without causing line
breaks. If the caption consists of a single sentence
fragment (incomplete sentence), it should not be punctuated.
#figure(caption: "Python code in typst")[
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 1)
y = np.sin(2 * np.pi * x)
plt.plot(x, y)
plt.show()
```
]<lst:python>
#figure(caption: "C++ code in typst")[
```cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
return 0;
}
```]<lst:cpp>
== Equations
<equations>
Equations are typeset as normally in typst. It is common to consider
equations part of the surrounding sentences, and include punctuation in
the equations accordingly, e.g.,
$ f (x) = integral_1^x 1 / y thin d y = ln x thin . $ <logarithm>
For more advanced symbols like, e.g., $grad, pdv(x,y)$, the `physica` module is preloaded.
As you can see, the simple math syntax makes typst very easy to use.
== Fonts
<fonts>
Charter at 11pt with the has been selected as the main font for the thesis template. For code examples, the monospaced font should be used – for this, a scaled
version of the DejaVu Sans Mono to match the main font is preselected.
== Cross References
<sec:crossref>
Cross references are inserted using `=` in typst. For examples on usage, see @sec:crossref in @chap:usage, @tab:example1
@fig:mapNTNU, @logarithm,
@lst:cpp and #link(<app:additional>)[Appendix A];.
== Bibliography
<bibliography>
The bibliography is typeset as in standard typst. It is added in the initializing function as such: ```typst bibliography: bibliography("thesis.bib")```.
With this setup, using `@` will give a number
only~@landes1951scrutiny, and ```typst #cite(, form: "prose") ``` will give author and number like this: #cite(<landes1951scrutiny>, form: "prose");.
== Appendices
<appendices>
Additional material that does not fit in the main thesis but may still
be relevant to share, e.g., raw data from experiments and surveys, code
listings, additional plots, pre-project reports, project agreements,
contracts, logs etc., can be put in appendices. Simply issue the command
```typst #show: appendix``` in the main `.typst` file, and then the following chapters become appendices. See #link(<app:additional>)[Appendix A]
for an example.
= Thesis Structure
<thesis-structure>
The following is lifted more or less directly from the original template.
The structure of the thesis, i.e., which chapters and other document
elements that should be included, depends on several factors such as the
study level (bachelor, master, PhD), the type of project it describes
(development, research, investigation, consulting), and the diversity
(narrow, broad). Thus, there are no exact rules for how to do it, so
whatever follows should be taken as guidelines only.
A thesis, like any book or report, can typically be divided into three
parts: front matter, body matter, and back matter. Of these, the body
matter is by far the most important one, and also the one that varies
the most between thesis types.
== Front Matter
<sec:frontmatter>
The front matter is everything that comes before the main part of the
thesis. It is common to use roman page numbers for this part to indicate
this. The minimum required front matter consists of a title page,
abstract(s), and a table of contents. A more complete front matter, in a
typical order, is as follows.
/ Title page\:: #block[
The title page should, at minimum, include the thesis title, authors and
a date. A more complete title page would also include the name of the
study programme, and possibly the thesis supervisor(s). See
#link(<sec:setup>)[2.1];.
]
/ Abstracts\:: #block[
The abstract should be an extremely condensed version of the thesis.
Think one sentence with the main message from each of the chapters of
the body matter as a starting point.
#cite(<landes1951scrutiny>, form: "prose") have given some very nice
instructions on how to write a good abstract. A thesis from a Norwegian
Univeristy should contain abstracts in both Norwegian and English
irrespectively of the thesis language (typically with the thesis
language coming first).
]
/ Dedication\:: #block[
If you wish to dedicate the thesis to someone (increasingly common with
increasing study level), you may add a separate page with a dedication
here. Since a dedication is a personal statement, no template is given.
Design it according to your preference.
]
/ Acknowledgements\:: #block[
If there is someone who deserves a 'thank you', you may add
acknowledgements here. If so, make it an unnumbered chapter.
]
/ Table of contents\:: #block[
A table of contents should always be present in a document at the size
of a thesis. It is generated automatically using the `outline()`
command. The one generated by this document class also contains the
front matter and unnumbered chapters.
]
/ List of figures\:: #block[
If the thesis contains many figures that the reader might want to refer
back to, a list of figures can be included here. It is generated using
`outline()`.
]
/ List of tables\:: #block[
If the thesis contains many tables that the reader might want to refer
back to, a list of tables can be included here. It is generated using
`outline()`.
]
/ List of code listings\:: #block[
If the thesis contains many code listings that the reader might want to
refer back to, a list of code listings can be included here. It is
generated using `outline()`.
]
/ Other lists\:: #block[
If there are other list you would like to include, this would be a good
place. Examples could be lists of definitions, theorems, nomenclature,
abbreviations, glossary etc.
]
/ Preface or Foreword\:: #block[
A preface or foreword is a good place to make other personal statements
that do not fit whithin the body matter. This could be information about
the circumstances of the thesis, your motivation for choosing it, or
possibly information about an employer or an external company for which
it has been written. Add this in the initializing function of this template.
]
== Body Matter
<body-matter>
The body matter consists of the main chapters of the thesis. It starts
the Arabic page numbering with page~1. There is a great diversity in the
structure chosen for different thesis types. Common to almost all is
that the first chapter is an introduction, and that the last one is a
conclusion followed by the bibliography.
=== Development Project
<sec:development>
For many bachelor and some master projects in computer science, the main
task is to develop something, typically a software prototype, for an
'employer' (e.g., an external company or a research group). A thesis
describing such a project is typically structured as a software
development report whith more or less the following chapters:
/ Introduction\:: #block[
The introduction of the thesis should take the reader all the way from
the big picture and context of the project to the concrete task that has
been solved in the thesis. A nice skeleton for a good introduction was
given by #cite(<claerbout1991scrutiny>, form: "prose");:
#emph[review–claim–agenda];. In the review part, the background of the
project is covered. This leads up to your claim, which is typically that
some entity (software, device) or knowledge (research questions) is
missing and sorely needed. The agenda part briefly summarises how your
thesis contributes.
]
/ Requirements\:: #block[
The requirements chapter should lead up to a concrete description of
both the functional and non-functional requirements for whatever is to
be developed at both a high level (use cases) and lower levels (low
level use cases, requirements). If a classical waterfall development
process is followed, this chapter is the product of the requirement
phase. If a more agile model like, e.g., SCRUM is followed, the
requirements will appear through the project as, e.g., the user stories
developed in the sprint planning meetings.
]
/ Technical design\:: #block[
The technical design chapter describes the big picture of the chosen
solution. For a software development project, this would typically
contain the system arcitechture (client-server, cloud, databases,
networking, services etc.); both how it was solved, and, more
importantly, why this architecture was chosen.
]
/ Development Process\:: #block[
In this chapter, you should describe the process that was followed. It
should cover the process model, why it was chosen, and how it was
implemented, including tools for project management, documentation etc.
Depending on how you write the other chapters, there may be good reasons
to place this chapters somewhere else in the thesis.
]
/ Implementation\:: #block[
Here you should describe the more technical details of the solution.
Which tools were used (programming languages, libraries, IDEs, APIs,
frameworks, etc.). It is a good idea to give some code examples. If
class diagrams, database models etc. were not presented in the technical
design chapter, they can be included here.
]
/ Deployment\:: #block[
This chapter should describe how your solution can be deployed on the
employer’s system. It should include technical details on how to set it
up, as well as discussions on choices made concerning scalability,
maintenance, etc.
]
/ Testing and user feedback\:: #block[
This chapter should describe how the system was tested during and after
development. This would cover everything from unit testing to user
testing; black-box vs. white-box; how it was done, what was learned from
the testing, and what impact it had on the product and process.
]
/ Discussion\:: #block[
Here you should discuss all aspect of your thesis and project. How did
the process work? Which choices did you make, and what did you learn
from it? What were the pros and cons? What would you have done
differently if you were to undertake the same project over again, both
in terms of process and product? What are the societal consequences of
your work?
]
/ Conclusion\:: #block[
The conclusion chapter is usually quite short – a paragraph or two –
mainly summarising what was achieved in the project. It should answer
the #emph[claim] part of the introduction. It should also say something
about what comes next ('future work').
]
/ Bibliography\:: #block[
The bibliography should be a list of quality-assured peer-reviewed
published material that you have used throughout the work with your
thesis. All items in the bibliography should be referenced in the text.
The references should be correctly formatted depending on their type
(book, journal article, conference publication, thesis etc.). The bibliography should
not contain links to arbitrary dynamic web pages where the content is
subject to change at any point of time. Such links, if necessary, should
rather be included as footnotes throughout the document. The main point
of the bibliography is to back up your claims with quality-assured
material that future readers will actually be able to retrieve years
ahead.
]
=== Research Project
<sec:resesarch>
For many master and some bachelor projects in computer science, the main
task is to gain knew knowledge about something. A thesis describing such
a project is typically structed as an extended form of a scientific
paper, following the so-called IMRaD (Introduction, Method, Results, and
Discussion) model:
/ Introduction\:: #block[
See #link(<sec:development>)[3.2.1];.
]
/ Background\:: #block[
Research projects should always be based on previous research on the
same and/or related topics. This should be described as a background to
the thesis with adequate bibliographical references. If the material
needed is too voluminous to fit nicely in the review part of the
introduction, it can be presented in a separate background chapter.
]
/ Method\:: #block[
The method chapter should describe in detail which activities you
undertake to answer the research questions presented in the
introduction, and why they were chosen. This includes detailed
descriptions of experiments, surveys, computations, data analysis,
statistical tests etc.
]
/ Results\:: #block[
The results chapter should simply present the results of applying the
methods presented in the method chapter without further ado. This
chapter will typically contain many graphs, tables, etc. Sometimes it is
natural to discuss the results as they are presented, combining them
into a 'Results and Discussion' chapter, but more often they are kept
separate.
]
/ Discussion\:: #block[
See #link(<sec:development>)[3.2.1];.
]
/ Conclusion\:: #block[
See #link(<sec:development>)[3.2.1];.
]
/ Bibliography\:: #block[
See #link(<sec:development>)[3.2.1];.
]
=== Monograph PhD Thesis
<sec:monograph>
Traditionally, it has been common to structure a PhD thesis as a single
book – a #emph[monograph];. If the thesis is in the form of one single
coherent research project, it can be structured along the lines of
#link(<sec:resesarch>)[3.2.2];. However, for such a big work that a PhD
thesis constitutes, the tasks undertaken are often more diverse, and
thus more naturally split into several smaller research projects as
follows:
/ Introduction\:: #block[
The introduction would serve the same purpose as for a smaller research
project described in #link(<sec:development>)[3.2.1];, but would
normally be somewhat more extensive. The #emph[agenda] part should
inform the reader about the structure of the rest of the document, since
this may vary significantly between theses.
]
/ Background\:: #block[
Where as background chapters are not necessarily needed in smaller
works, they are almost always need in PhD thesis. They may even be split
into several chapters if there are significantly different topics to
cover. See #link(<sec:resesarch>)[3.2.2];.
]
/ Main chapters\:: #block[
Each main chapter can be structured more or less like a scientific
paper. Depending on how much is contained in the introduction and
background sections, the individual introduction and background sections
can be significantly reduced or even omitted completely.
- (Introduction)
- (Background)
- Method
- Results
- Discussion
- Conclusion
]
/ Discussion\:: #block[
In addition to the discussions within each of the individual chapters,
the contribution of the thesis #emph[as a whole] should be thoroughly
discussed here.
]
/ Conclusion\:: #block[
In addition to the conclusions of each of the individual chapters, the
overall conclusion of the thesis, and how the different parts contribute
to it, should be presented here. The conclusion should answer to the
research questions set out in the main introduction. See also
#link(<sec:development>)[3.2.1];.
]
/ Bibliography\:: #block[
See #link(<sec:development>)[3.2.1];.
]
=== Compiled PhD Thesis
<sec:compiledphd>
Instead of writing up the PhD thesis as a monograph, compiled PhD theses
(also known as stapler theses, sandwich theses, integrated theses, PhD
by published work) consisting of reproductions of already published
research papers are becoming increasingly common. At least some of the
papers should already have been accepted for publication at the time of
submission of the thesis, and thus have been through a real quality
control by peer review.
/ Introduction\:: #block[
See #link(<sec:monograph>)[3.2.3];.
]
/ Background\:: #block[
See #link(<sec:monograph>)[3.2.3];.
]
/ Main contributions\:: #block[
This chapter should sum up #emph[and integrate] the contribution of the
thesis as a whole. It should not merely be a listing of the abstracts of
the individual papers – they are already available in the attached
papers, and, as such, not needed here.
]
/ Discussion\:: #block[
See #link(<sec:monograph>)[3.2.3];.
]
/ Conclusion\:: #block[
See #link(<sec:monograph>)[3.2.3];.
]
/ Bibliography\:: #block[
See #link(<sec:development>)[3.2.1];.
]
/ Paper I\:: #block[
First included paper with main contributions. It can be included
verbatim as a PDF. The publishers PDF should be used if the copyright
permits it. This should be checked with the SHERPA/RoMEO
database#footnote[#link("http://sherpa.ac.uk/romeo/index.php");] or with
the publisher. Even when it is no general permission by the publisher,
you may write and ask for one.
]
/ Paper II\:: #block[
etc.
]
== Back Matter
<back-matter>
Material that does not fit elsewhere, but that you would still like to
share with the readers, can be put in appendices. See
#link(<app:additional>)[5];.
= Conclusion
<conclusion>
You definitely should use the `ntnu-thesis` typst template for your
thesis.
#show: appendix.with(chapters-on-odd: chapters-on-odd)
= Additional Material
<app:additional>
Additional material that does not fit in the main thesis but may still
be relevant to share, e.g., raw data from experiments and surveys, code
listings, additional plots, pre-project reports, project agreements,
contracts, logs etc., can be put in appendices. Simply issue the command
```#show: appendix``` in the main `.typ` file, and make one chapter per appendix.
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/214.%20read.html.typ | typst | read.html
The Need to Read
November 2022In the science fiction books I read as a kid, reading had often
been replaced by some more efficient way of acquiring knowledge.
Mysterious "tapes" would load it into one's brain like a program
being loaded into a computer.That sort of thing is unlikely to happen anytime soon. Not just
because it would be hard to build a replacement for reading, but
because even if one existed, it would be insufficient. Reading about
x doesn't just teach you about x; it also teaches you how to write.
[1]Would that matter? If we replaced reading, would anyone need to be
good at writing?The reason it would matter is that writing is not just a way to
convey ideas, but also a way to have them.A good writer doesn't just think, and then write down what he
thought, as a sort of transcript. A good writer will almost always
discover new things in the process of writing. And there is, as far
as I know, no substitute for this kind of discovery. Talking about
your ideas with other people is a good way to develop them. But
even after doing this, you'll find you still discover new things
when you sit down to write. There is a kind of thinking that can
only be done by writing.There are of course kinds of thinking that can be done without
writing. If you don't need to go too deeply into a problem, you can
solve it without writing. If you're thinking about how two pieces
of machinery should fit together, writing about it probably won't
help much. And when a problem can be described formally, you can
sometimes solve it in your head. But if you need to solve a
complicated, ill-defined problem, it will almost always help to
write about it. Which in turn means that someone who's not good at
writing will almost always be at a disadvantage in solving such
problems.You can't think well without writing well, and you can't write well
without reading well. And I mean that last "well" in both senses.
You have to be good at reading, and read good things.
[2]People who just want information may find other ways to get it.
But people who want to have ideas can't afford to.Notes[1]
Audiobooks can give you examples of good writing, but having
them read to you doesn't teach you as much about writing as reading
them yourself.[2]
By "good at reading" I don't mean good at the mechanics of
reading. You don't have to be good at extracting words from the
page so much as extracting meaning from the words.Japanese TranslationChinese TranslationItalian TranslationFrench Translation
|
|
https://github.com/Pablo-Gonzalez-Calderon/showybox-package | https://raw.githubusercontent.com/Pablo-Gonzalez-Calderon/showybox-package/main/manual/manual.typ | typst | MIT License | #import "../showy.typ": *
#import "template.typ": *
#import "@preview/codelst:2.0.1": sourcecode
#show: front-page
= Introduction
Showybox is a Typst package for creating colorful and customizable boxes, similar as `tcolorbox` for LaTeX users.
Currently, Showybox is still on developement, and all the code can be found at its GitHub repository #link("https://github.com/Pablo-Gonzalez-Calderon/showybox-package", "here"). New features are welcome. So, if you have an idea that would improve this package, go on and send us the code as a Pull Request.
= Usage
To use this library through the Typst package manager (for Typst 0.6.0 or greater), write #raw(lang: "typ", block: false, "#import \"@preview/showybox:" + version +"\": showybox") at the beginning of your Typst file.
Once imported, you can create an empty showybox by using the function #line-raw("showybox()") and giving a default body content inside the parenthesis or outside them using the squared brackets `[]`.
By default a showybox with these properties will be created:
#grid(
columns: (1fr, 2fr),
gutter: 20pt,
[
- No title
- No shadow
- Not breakable
- Black borders
- White background
- #raw(lang: "typc", "5pt") of border radius
- #raw(lang: "typc", "1pt") of border thickness
],[
#sourcecode(raw(
block: true,
lang: "typ",
"#import \"@preview/showybox:" + version +"\": showybox \n\n#showybox()[This is a simple showybox with the properties said before :)]"
))
#showybox()[This is a simple showybox with the properties said before :)]
])
= Parameters
In version #version all the parameters that the #raw(lang: "typc", "showybox()") function can receive are shown below:
#sbox-parameters()
The usage and posible values of all the parameters are listed below.
== Title #type-block("string") #type-block("content")
When it's not empty, correponds to a #type-block("string") or a #type-block("content") used as the title of the showybox.
Default value is #line-raw("\"\"") (empty string)
#grid(
columns: (1fr, 1.5fr),
column-gutter: 11pt,
)[
#showybox(
title: "Hi there! I'm Mr. Title"
)[And I'm Mrs. Body]
#showybox()[And I'm Mrs. Body]
][
#sourcecode(```typ
#showybox(
title: "Hi there! I'm Mr. Title"
)[And I'm Mrs. Body]
#showybox(/*Untitled*/)[And I'm Mrs. Body]
```)
]
== Footer #type-block("string") #type-block("content")
When it's not empy, corresponds to a #type-block("string") or a #type-block("content") used as the footer of the showybox.
Default is #raw(lang: "typc", "\"\"") (empty `string`).
#sourcecode(```typ
#showybox(
title: "Hi there! I'm Mr. Title",
footer: "And finally I'm Mr. Footer"
)[And I'm Mrs. Body]
```)
#showybox(
title: "Hi there! I'm Mr. Title",
footer: "And finally I'm Mr. Footer"
)[And I'm Mrs. Body]
== Frame #type-block("dictionary")
This parameter contains all options that are useful for setting a showybox's frame properties. The frame contains the title,the body and the footer of the showybox. It even includes the showybox borders! Frame's dictionary options are listed below:
#frame-parameters()
=== title-color
#type-block("color")
The color used as background where the title goes.
Default is #line-raw("black").
=== body-color
#type-block("color")
The color that is used as background where the showybox's body goes.
Default is #line-raw("white").
=== footer-color
#type-block("color")
The color that is used as background where the footer goes.
Default is #line-raw("luma(220)")
=== border-color
#type-block("color")
It's the color used for the frame's borders and the boxed-title borders. It's independent of `title-color`, `body-color` and `footer-color`, so maybe you would want to use similar colors with them.
Default is #line-raw("black").
#sourcecode(```typ
#showybox(
title: "Stokes' theorem",
frame: (
border-color: blue,
title-color: blue.lighten(30%),
body-color: blue.lighten(95%),
footer-color: blue.lighten(80%)
),
footer: "Information extracted from a well-known public encyclopedia"
)[
Let $Sigma$ be a smooth oriented surface in $RR^3$ with boundary $diff Sigma equiv Gamma$. If a vector field $bold(F)(x,y,z)=(F_x (x,y,z), F_y (x,y,z), F_z (x,y,z))$ is defined and has continuous first order partial derivatives in a region containing $Sigma$, then
$ integral.double_Sigma (bold(nabla) times bold(F)) dot bold(Sigma) = integral.cont_(diff Sigma) bold(F) dot dif bold(Gamma) $
]
```)
#showybox(
title: "Stokes' theorem",
frame: (
border-color: blue,
title-color: blue.lighten(30%),
body-color: blue.lighten(95%),
footer-color: blue.lighten(80%)
),
footer: "Information extracted from a well-known public encyclopedia"
)[
Let $Sigma$ be a smooth oriented surface in $RR^3$ with boundary $diff Sigma equiv Gamma$. If a vector field $bold(F)(x,y,z)=(F_x (x,y,z), F_y (x,y,z), F_z (x,y,z))$ is defined and has continuous first order partial derivatives in a region containing $Sigma$, then
$ integral.double_Sigma (bold(nabla) times bold(F)) dot bold(Sigma) = integral.cont_(diff Sigma) bold(F) dot dif bold(Gamma) $
]
=== radius
#type-block("relative-length") #type-block("dictionary")
Indicates how much round are the borders of the frame. It sets _all_ the border radii together if a #type-block("relative-length") passed, or individually if a #type-block("dictionary") is given.
It excludes the boxed-title border radii (if present). Their radius is set in `boxed-style` dictionary inside `title-style`.
Default is #line-raw("5pt").
=== thickness
#type-block("length") #type-block("dictionary")
Indicates the thickness of the frame borders as a #type-block("length") or a #type-block("dictionary"). If it's a dictionary, it can specify `top`, `bottom`, `left`, `right`, `x`, `y` or `rest` thickness.
It excludes the thickness of any separator located inside the box (their thickness is set in `sep` property).
Default is #line-raw("1pt").
=== dash
#type-block("string")
Corresponds to the frame border's style. It can be any kind of style used for #line-raw("line()"). For instance, it can be #line-raw("\"solid\""), #line-raw("\"dotted\""), #line-raw("\"densely-dotted\""), #line-raw("\"loosely-dotted\""), #line-raw("\"dashed\""), #line-raw("\"densely-dashed\""), #line-raw("\"loosely-dashed\""), #line-raw("\"dash-dotted\""), #line-raw("\"densely-dash-dotted\"") or #line-raw("\"loosely-dash-dotted\"")
Default is #line-raw("\"solid\"").
=== inset, title-inset, body-inset, and footer-inset
#type-block("relative-length") #type-block("dictionary")
How much to pad the showybox's content. It can be a #type-block("relative-length") or a #type-block("dictionary"). If it's a dictionary, it can specify `top`, `bottom`, `left`, `right`, `x`, `y` or `rest` insets.
If `title-inset`, `body-inset` or `footer-inset` is given, this property is ignored while setting the inset of the title, the body or the footer, respectively.
Default is #line-raw("(x: 1em, y: 0.65em)").
#sourcecode(
```typ
#showybox(
frame: (
border-color: red.darken(30%),
title-color: red.darken(30%),
radius: 0pt,
thickness: 2pt,
body-inset: 2em,
dash: "densely-dash-dotted"
),
title: "Gauss's Law"
)[
The net electric flux through any hypothetical closed surface is equal to $1/epsilon_0$ times the net electric charge enclosed within that closed surface. The closed surface is also referred to as Gaussian surface. In its integral form:
$ Phi_E = integral.surf_S bold(E) dot dif bold(A) = Q/epsilon_0 $
]
```
)
#showybox(
frame: (
border-color: red.darken(30%),
title-color: red.darken(30%),
radius: 0pt,
thickness: 2pt,
body-inset: 2em,
dash: "densely-dash-dotted"
),
title: "Gauss's Law"
)[
The net electric flux through any hypothetical closed surface is equal to $1/epsilon_0$ times the net electric charge enclosed within that closed surface. The closed surface is also referred to as Gaussian surface. In its integral form:
$ Phi_E = integral.surf_S bold(E) dot dif bold(A) = Q/epsilon_0 $
]
== Title style #type-block("dictionary")
This parameter contains all options that are useful for setting showybox's title properties. Despite you can set some of this properties while setting `title` parameter, it becomes a useful option while making several showyboxes with similar styles.
#title-style-parameters()
=== color
#type-block("color")
Title's text color.
Default is `white`.
=== weight
#type-block("integer") #type-block("string")
Title's font weight. It can be an integer between #line-raw("100") and #line-raw("900"), or a predefined weight name (#line-raw("\"thin\""), #line-raw("\"extralight\""), #line-raw("\"light\""), #line-raw("\"regular\""), #line-raw("\"medium\""), #line-raw("\"semibold\""), #line-raw("\"bold\""), #line-raw("\"extrabold\"") and #line-raw("\"black\"")).
Default is #line-raw("\"regular\"").
=== align
#type-block("alignment") #type-block("2d-alignment")
How to align title's content. It can be an unidimensional alignment or a bidimensional alignment.
Default is `left`.
=== sep-thickness
#type-block("length")
How much is the thickness of the separator line that is between the title and the body.
Default is #line-raw("1pt").
#sourcecode(
```typ
#showybox(
title-style: (
weight: 900,
color: red.darken(40%),
sep-thickness: 0pt,
align: center
),
frame: (
title-color: red.lighten(80%),
border-color: red.darken(40%),
thickness: (left: 1pt),
radius: 0pt
),
title: "Carnot cycle's efficency"
)[
Inside a Carnot cycle, the efficiency $eta$ is defined to be:
$ eta = W/Q_H = frac(Q_H + Q_C, Q_H) = 1 - T_C/T_H $
]
```
)
#showybox(
title-style: (
weight: 900,
color: red.darken(40%),
sep-thickness: 0pt,
align: center
),
frame: (
title-color: red.lighten(80%),
border-color: red.darken(40%),
thickness: (left: 1pt),
radius: 0pt
),
title: "Carnot cycle's efficency"
)[
Inside a Carnot cycle, the efficiency $eta$ is defined to be:
$ eta = W/Q_H = frac(Q_H + Q_C, Q_H) = 1 - T_C/T_H $
]
=== boxed-style
#type-block("dictionary") #type-block("none")
If it's not #line-raw("none") (i.e. it's a #type-block("dictionary")), indicates that the title must be placed as a "floating box" around the
top side of the showybox's body.
Further details are present in @boxed-style
Default is #line-raw("none").
== Boxed style #type-block("dictionary") <boxed-style>
#boxed-style-parameters()
=== anchor
#type-block("dictionary")
A #type-block("dictionary") with keys `x` and `y` indicating where to place the anchor of the boxed-title. The possible values for each direction are listed below:
For `x` anchor:
- #line-raw("left"): Set the anchor to the left side of the boxed-title.
- #line-raw("center"): Set the anchor to the center of the horizontal center of the boxed-title.
- #line-raw("right"): Set the anchor to the right side of the boxed-title.
For `y` anchor:
- #line-raw("top"): Set the anchor to the top of the boxed-title.
- #line-raw("horizon"): Set the anchor to the vertical center of the boxed-title.
- #line-raw("bottom"): Set the anchor to the bottom of the boxed-title.
Default is #line-raw("(x: left, y: horizon)").
=== offset
#type-block("dictionary")
A #type-block("dictionary") with keys `x` and `y` indicating how much to offset the boxed-title in x and y directions.
Default is #line-raw("(x: 0pt, y: 0pt)").
#observation()[
By default, the boxed-title has a #line-raw("1em") "invisible-offset" (it's not set via `offset` property) at both left and right sides. This is made for aesthetic purposes, so the boxed-title will look nicer by default.
Additionally, the boxed-title *never* will have the full width of the showybox's main container, because otherwise it'll look like a "strange" version of default titles, loosing the "floating" illusion.
]
=== radius
#type-block("relative-length") #type-block("dictionary")
Radius of the boxed-title. It is applied to all corners simultaneously if a #type-block("relative-length") is given, or it's applied individually to each of them according to a #type-block("dictionary") keys.
Default is #line-raw("5pt").
#sourcecode(
```typ
#showybox(
title-style: (
boxed-style: (
anchor: (
x: center,
y: horizon
),
radius: (top-left: 10pt, bottom-right: 10pt, rest: 0pt),
)
),
frame: (
title-color: green.darken(40%),
body-color: green.lighten(80%),
footer-color: green.lighten(60%),
border-color: green.darken(60%),
radius: (top-left: 10pt, bottom-right: 10pt, rest: 0pt)
),
title: "Clairaut's theorem",
footer: text(size: 10pt, weight: 600, emph("This will be useful every time you want to interchange partial derivatives in the future."))
)[
Let $f: A arrow RR$ with $A subset RR^n$ an open set such that its cross derivatives of any order exist and are continuous in $A$. Then for any point $(a_1, a_2, ..., a_n) in A$ it is true that
$ frac(diff^n f, diff x_i ... diff x_j)(a_1, a_2, ..., a_n) = frac(diff^n f, diff x_j ... diff x_i)(a_1, a_2, ..., a_n) $
]
```
)
#showybox(
title-style: (
boxed-style: (
anchor: (
x: center,
y: horizon
),
radius: (top-left: 10pt, bottom-right: 10pt, rest: 0pt),
)
),
frame: (
title-color: green.darken(40%),
body-color: green.lighten(80%),
footer-color: green.lighten(60%),
border-color: green.darken(60%),
radius: (top-left: 10pt, bottom-right: 10pt, rest: 0pt)
),
title: "Clairaut's theorem",
footer: text(size: 10pt, weight: 600, emph("This will be useful every time you want to interchange partial derivatives in the future."))
)[
Let $f: A arrow RR$ with $A subset RR^n$ an open set such that its cross derivatives of any order exist and are continuous in $A$. Then for any point $(a_1, a_2, ..., a_n) in A$ it is true that
$ frac(diff^n f, diff x_i ... diff x_j)(a_1, a_2, ..., a_n) = frac(diff^n f, diff x_j ... diff x_i)(a_1, a_2, ..., a_n) $
]
== Body style #type-block("dictionary")
This parameter contains all options that are useful for setting general-style properties for the showybox's body.
#body-style-parameters()
=== color
#type-block("color")
Body's text color.
Default is `black`.
=== align
#type-block("alignment") #type-block("2d-alignment")
How to align body's content. It can be an unidimensional alignement or a bidimensional alignement.
Default is `left`.
#sourcecode(
```typ
#showybox(
body-style: (
align: center,
color: red.darken(20%)
),
frame: (
body-color: yellow.lighten(60%),
title-color: red.darken(20%),
thickness: 0pt,
body-inset: (y: 1em)
),
title-style: (
sep-thickness: 0pt,
color: yellow.lighten(80%),
align: center
),
width: 70%,
align: center,
title: "That is the question"
)[
To be, or not to be, that is the question: \
Whether 'tis nobler in the mind to suffer \
The slings and arrows of outrageous fortune, \
Or to take Arms against a Sea of troubles, \
And by opposing end them: to die, to sleep \
No more; and by a sleep, to say we end \
The heart-ache, and the thousand natural shocks \
That Flesh is heir to? 'Tis a consummation \
Devoutly to be wished. To die, to sleep, \
To sleep, perchance to Dream...
]```
)
#showybox(
body-style: (
align: center,
color: red.darken(20%)
),
frame: (
body-color: yellow.lighten(60%),
title-color: red.darken(20%),
thickness: 0pt,
body-inset: (y: 1em)
),
title-style: (
sep-thickness: 0pt,
color: yellow.lighten(80%),
align: center
),
width: 70%,
align: center,
title: "That is the question"
)[
To be, or not to be, that is the question: \
Whether 'tis nobler in the mind to suffer \
The slings and arrows of outrageous fortune, \
Or to take Arms against a Sea of troubles, \
And by opposing end them: to die, to sleep \
No more; and by a sleep, to say we end \
The heart-ache, and the thousand natural shocks \
That Flesh is heir to? 'Tis a consummation \
Devoutly to be wished. To die, to sleep, \
To sleep, perchance to Dream...
]
== Footer style #type-block("dictionary")
This parameter contains all options that are useful for setting showybox's footer properties. Despite you can set some of this properties while setting `footer` parameter, it becomes a useful option while making several showyboxes with similar styles.
#footer-style-parameters()
=== color
#type-block("color")
Footer's text color.
Default is #line-raw("luma(85)").
=== weight
#type-block("integer") #type-block("string")
Footer's font weight. It can be an integer between #line-raw("100") and #line-raw("900"), or a predefined weight name (#line-raw("\"thin\""), #line-raw("\"extralight\""), #line-raw("\"light\""), #line-raw("\"regular\""), #line-raw("\"medium\""), #line-raw("\"semibold\""), #line-raw("\"bold\""), #line-raw("\"extrabold\"") and #line-raw("\"black\"")).
Default is #line-raw("\"regular\"").
=== align
#type-block("alignment") #type-block("2d-alignment")
How to align footer's content. It can be an unidimensional alignment or a bidimensional alignment.
Default is `left`.
=== sep-thickness
#type-block("length")
How much is the thickness of the separator line that is between the footer and the body.
Default is #line-raw("1pt").
#sourcecode(
```typ
#showybox(
footer-style: (
sep-thickness: 0pt,
align: right,
color: black
),
title: "Divergence theorem",
footer: [
In the case of $n=3$, $V$ represents a volumne in three-dimensional space, and $diff V = S$ its surface
]
)[
Suppose $V$ is a subset of $RR^n$ which is compact and has a piecewise smooth boundary $S$ (also indicated with $diff V = S$). If $bold(F)$ is a continuously differentiable vector field defined on a neighborhood of $V$, then:
$ integral.triple_V (bold(nabla) dot bold(F)) dif V = integral.surf_S (bold(F) dot bold(hat(n))) dif S $
]```
)
#showybox(
footer-style: (
sep-thickness: 0pt,
align: right,
color: black
),
title: "Divergence theorem",
footer: [
In the case of $n=3$, $V$ represents a volumne in three-dimensional space, and $diff V = S$ its surface
]
)[
Suppose $V$ is a subset of $RR^n$ which is compact and has a piecewise smooth boundary $S$ (also indicated with $diff V = S$). If $bold(F)$ is a continuously differentiable vector field defined on a neighborhood of $V$, then:
$ integral.triple_V (bold(nabla) dot bold(F)) dif V = integral.surf_S (bold(F) dot bold(hat(n))) dif S $
]
== Separator properties (`sep`) #type-block("dictionary")
This parameter contains all options that are used for setting all the separator's styles of your showybox. To learn more about how to use separators, see @separators.
#sep-parameters()
=== thickness
#type-block("length")
Corresponds to the separator thickness.
Default is #line-raw("1pt").
=== gutter
#type-block("relative-length")
The size of the gutter space above and below the separator.
Default is #line-raw("0.65em").
=== dash
#type-block("string")
It's the separator's dash pattern. It can be any kind of style used for #line-raw("line()"). For instance, it can be #line-raw("\"solid\""), #line-raw("\"dotted\""), #line-raw("\"densely-dotted\""), #line-raw("\"loosely-dotted\""), #line-raw("\"dashed\""), #line-raw("\"densely-dashed\""), #line-raw("\"loosely-dashed\""), #line-raw("\"dash-dotted\""), #line-raw("\"densely-dash-dotted\"") or #line-raw("\"loosely-dash-dotted\"")
Default is #line-raw("\"solid\"").
#sourcecode(
```typ
#showybox(
sep: (
thickness: 0.5pt,
dash: "loosely-dashed"
),
title: "Coordinate systems"
)[
*Cartesian coordinate system*
A Cartesian coordinate system for a three-dimensional space consists of an ordered triplet of lines (the axes) that go through a common point (the origin), and are pair-wise perpendicular.
A way to represent a point $r$ is using the unit vectors ($bold(i)$, $bold(j)$, and $bold(k)$) is:
$ bold(r) = x bold(i) + y bold(j) + z bold(k) $
][
*Spherical coordinate system*
A spherical coordinate system is a coordinate system for three-dimensional space where the position of a point is specified by three numbers: the radial distance of that point from a fixed origin ($r$); its polar angle measured from a fixed polar axis or zenith direction ($theta$); and the azimuthal angle of its orthogonal projection on a reference plane that passes through the origin and is orthogonal to the fixed axis, measured from another fixed reference direction on that plane ($phi$).
The position of a point or particle (although better written as a triple $(r, theta, phi)$ can be written as:
$ bold(r) = r bold(hat(r)) $
]```
)
#showybox(
sep: (
thickness: 0.5pt,
dash: "loosely-dashed"
),
title: "Coordinate systems"
)[
*Cartesian coordinate system*
A Cartesian coordinate system for a three-dimensional space consists of an ordered triplet of lines (the axes) that go through a common point (the origin), and are pair-wise perpendicular.
A way to represent a point $r$ is using the unit vectors ($bold(i)$, $bold(j)$, and $bold(k)$) is:
$ bold(r) = x bold(i) + y bold(j) + z bold(k) $
][
*Spherical coordinate system*
A spherical coordinate system is a coordinate system for three-dimensional space where the position of a point is specified by three numbers: the radial distance of that point from a fixed origin ($r$); its polar angle measured from a fixed polar axis or zenith direction ($theta$); and the azimuthal angle of its orthogonal projection on a reference plane that passes through the origin and is orthogonal to the fixed axis, measured from another fixed reference direction on that plane ($phi$).
The position of a point or particle (although better written as a triple $(r, theta, phi)$ can be written as:
$ bold(r) = r bold(hat(r)) $
]
== Shadow properties #type-block("dictionary")
The given #type-block("dictionary") contains all properties that are used for showing a showybox with a shadow. When this property is absent (i.e. it's not set or set as #line-raw("none")), the showybox has no shadow.
#shadow-parameters()
=== color
#type-block("color")
Shadow's color.
Default is #line-raw("luma(128)").
=== offset
#type-block("relative-length") #type-block("dictionary")
How much to offset the shadow in x and y direction either as a #type-block("relative-length") or a #type-block("dictionary") with keys `x` and `y`.
Default is #line-raw("4pt").
#sourcecode(
```typ
#showybox(
shadow: (
color: yellow.lighten(55%),
offset: 3pt
),
frame: (
title-color: red.darken(30%),
border-color: red.darken(30%),
body-color: red.lighten(80%)
),
title: "Coulomb's law"
)[
Coulomb's law in vector form states that the electrostatic force $bold(F)$ experienced by a charge $q_1$ at position $bold(r)$ in the vecinity of another charge $q_2$ at position $bold(r')$, in a vacuum is equal to
$ bold(F) = frac(q_1 q_2, 4 pi epsilon_0) frac(bold(r) - bold(r'), bar.v bold(r) - bold(r') bar.v^3) $
]```
)
#showybox(
shadow: (
color: yellow.lighten(55%),
offset: 3pt
),
frame: (
title-color: red.darken(30%),
border-color: red.darken(30%),
body-color: red.lighten(80%)
),
title: "Coulomb's law"
)[
Coulomb's law in vector form states that the electrostatic force $bold(F)$ experienced by a charge $q_1$ at position $bold(r)$ in the vecinity of another charge $q_2$ at position $bold(r')$, in a vacuum is equal to
$ bold(F) = frac(q_1 q_2, 4 pi epsilon_0) frac(bold(r) - bold(r'), bar.v bold(r) - bold(r') bar.v^3) $
]
== Width #type-block("relative-length")
This parameter sets the showybox's width.
Default is #line-raw("100%").
== Align #type-block("alignment")
How to align showybox inside it's container (useful for showyboxes with #line-raw("width < 100%")).
Default is `left`.
== Breakable #type-block("boolean")
This parameter indicates whether a showybox can or cannot break if it reaches an end of page or the end of its container.
Default is #line-raw("false")
== Spacing, above, and below #type-block("relative-length")
`spacing` sets how much space to insert above and below the showybox, unless `above` or `below` are given.
By default it's the `block`'s default spacing in your document.
#sourcecode(
```typ
#block(
height: 4.5cm,
inset: 1em,
fill: luma(250),
stroke: luma(200),
columns(2)[
#showybox(
title-style: (
boxed-style: (
anchor: (x: center, y: horizon)
)
),
breakable: true,
width: 90%,
align: center,
title: "Newton's second law"
)[
If a body of mass $m$ experiments an acceleration $bold(a)$ due to a net force $sum bold(F)$, this acceleration is related to the mass and force by the following equation:
$ bold(a) = frac(sum bold(F), m) $
]
]
)```
)
#block(
height: 4.5cm,
inset: 1em,
fill: luma(250),
stroke: luma(200),
columns(2)[
#showybox(
title-style: (
boxed-style: (
anchor: (x: center, y: horizon)
)
),
breakable: true,
width: 90%,
align: center,
title: "Newton's second law"
)[
If a body of mass $m$ experiments an acceleration $bold(a)$ due to a net force $sum bold(F)$, this acceleration is related to the mass and force by the following equation:
$ bold(a) = frac(sum bold(F), m) $
]
]
)
= Separators <separators>
Sometimes you would wish to split a content into two or more sections inside the same showybox. The #line-raw("showybox()") function allows you to do that by putting several #type-block("content") elements separated by commas inside the parenthesis `()` of the function. Each individual #type-block("content") element will be a separated section inside the showybox.
Alternatively, you can put adjacent #type-block("content")elements one after another next to the closing parenthesis of the function. Both cases generates the same outcome.
= Encapsulation
Showyboxes can be put inside another showyboxes! As you may think, it's easy to do it: just put a showybox inside the body of another, and ta-da!
#sourcecode(
```typ
#showybox(
title: "Parent container",
lorem(10),
columns(2)[
#showybox(
title-style: (boxed-style: (:)),
title: "Child 1",
lorem(10)
)
#colbreak()
#showybox(
title-style: (boxed-style: (:)),
title: "Child 2",
lorem(10)
)
]
)```
)
#showybox(
title: "Parent container",
lorem(10),
columns(2)[
#showybox(
title-style: (boxed-style: (:)),
title: "Child 1",
lorem(10)
)
#colbreak()
#showybox(
title-style: (boxed-style: (:)),
title: "Child 2",
lorem(10)
)
]
) |
https://github.com/MoserGitHub/qmd_ctutypst | https://raw.githubusercontent.com/MoserGitHub/qmd_ctutypst/main/_extensions/CTU-Bern/qmd_ctutypst/typst-template.typ | typst | // CTU Bern, typst template
// <NAME>, <NAME>
// CTU Bern, Department of Clinical Research, University of Bern
// Some source https://github.com/LaPreprint/typst/blob/main/lapreprint.typ
// Last changes:
// - Added project number
// - Multiple authors
// - TOC
#let ctu_typst_template(
title: none,
subtitle: none,
projectno: none,
toc: false,
author: (),
affiliations: (),
path_logo: "/_extensions/CTU-Bern/qmd_ctutypst/",
// logo_size: filename (fore example, "dcrlogo.jpg")
logo: "DCRlogo.svg",
// logo_size: percentage (for example, 80%) or auto
logo_size: 100%,
logo2: "unibelogo.svg",
// logo_size2: percentage (for example, 80%) or auto
logo_size2: 40%,
date: datetime.today(),
paper-size: "a4",
font-face: "Arial",
heading-numbering: "1.1.1",
project_type: "Project",
body,
) = {
// Spacer for footer
let spacer = text(fill: gray)[#h(8pt) | #h(8pt)]
// Set document metadata
set document(title: title)
// Set the body font
set text(font: font-face)
// Configure title page
set page(
paper-size,
margin: (left: 3cm, right: 2cm, top: 5cm, bottom: 4cm),
header: block(
width: 100%,
inset: (top: 1pt, right: 2pt),
if (logo != none) {
place(
top+right,
dy: -2cm,
float: false,
box(
width: 27%,
if (paper-size == "a4") { image(path_logo+logo, width: 100%) } else if (paper-size == "a3") { image(path_logo+logo, width: 90%) } else if (paper-size == "a2") { image(path_logo+logo, width: 70%) } else if (paper-size == "a1") { image(path_logo+logo, width: 60%) } else if (paper-size == "a0") { image(path_logo+logo, width: 50%) }
)
)
}
),
footer: block(
width: 100%,
inset: (top: 1pt, right: 2pt),
if (logo2 != none) {
place(
top+left,
dx: 0cm,
dy: -0.6cm,
float: false,
box(
width: 40%,
height: 100%,
if (paper-size == "a4") { image(path_logo+logo2, width: 40%) } else if (paper-size == "a3") { image(path_logo+logo2, width: 30%) } else if (paper-size == "a2") { image(path_logo+logo2, width: 20%) } else if (paper-size == "a1") { image(path_logo+logo2, width: 15%) } else if (paper-size == "a0") { image(path_logo+logo2, width: 10%) }
)
)
}
),
)
v(0.1fr)
// Set title
set align(left)
text(size: 17pt, title, weight: "bold")
v(0.01fr)
// Set subtitle
if subtitle != none {
text(size: 14pt, subtitle, weight: "semibold")
}
v(0.01fr)
// Set project number
if projectno != none {
text(size: 14pt, project_type + " number: " + projectno)
}
v(0.01fr)
// set text(size: 10pt)
text("Date: ")
date.display("[month repr:long] [day], [year]")
v(0.05fr)
// First horizontal line
line(length: 100%)
if author.len()>1 {
text(size: 14pt, "Authors: ")
v(0.01fr)
}
if author.len()==1 {
text(size: 14pt, "Author: ")
v(0.01fr)
}
if author != none and author != [] {
let count = author.len()
let ncols = calc.min(count, 3)
grid(
columns: (1fr,) * ncols,
row-gutter: 1.5em,
..author.map(author =>
align(left)[
#author.name \
#author.affiliation \
#author.email
]
)
)
}
// Second horizontal line
line(length: 100%)
v(0.2fr)
// Set counter for pages
counter(page).update(0)
// Table of content
if toc != false {
// Space between section heading
show heading: it => {
it.body
v(0.7em)
}
pagebreak()
counter(page).update(0)
outline()
}
// Configure main document pages
set page(
paper-size,
margin: (left: 3cm, right: 2cm, top: 5cm, bottom: 4cm),
numbering: "1",
number-align: right,
header: block(
width: 100%,
inset: (top: 1pt, right: 2pt),
if (logo != none) {
place(
top+right,
dy: -2cm,
float: false,
box(
width: 27%,
if (paper-size == "a4") { image(path_logo+logo, width: 100%) } else if (paper-size == "a3") { image(path_logo+logo, width: 90%) } else if (paper-size == "a2") { image(path_logo+logo, width: 70%) } else if (paper-size == "a1") { image(path_logo+logo, width: 60%) } else if (paper-size == "a0") { image(path_logo+logo, width: 50%) }
),
)
}
),
footer: block(
width: 100%,
inset: (top: 1pt, right: 2pt),
[
#place(
top+left,
dx: 0cm,
dy: -0.6cm,
float: false,
box(
width: 40%,
height: 100%,
if (paper-size == "a4") { image(path_logo+logo2, width: 40%) } else if (paper-size == "a3") { image(path_logo+logo2, width: 30%) } else if (paper-size == "a2") { image(path_logo+logo2, width: 20%) } else if (paper-size == "a1") { image(path_logo+logo2, width: 15%) } else if (paper-size == "a0") { image(path_logo+logo2, width: 10%) }
)
),
#grid(columns: (100%, 20%),
align(right)[
#text(
size: 9pt, fill: gray.darken(50%)
)[
#counter(page).display() of #locate((loc) => {counter(page).final(loc).first()})
]
],
)
]
)
)
pagebreak()
// Configure headings.
set heading(numbering: heading-numbering)
// Space between section headings
show heading: set block(above: 1cm, below: 0.5cm)
set align(left)
text(size: 9pt, body)
set par(justify: true, leading: 2em)
}
|
|
https://github.com/khicken/CSDS310 | https://raw.githubusercontent.com/khicken/CSDS310/main/Assignment%202/Assignment%202.typ | typst | #import "@preview/lovelace:0.3.0": pseudocode-list
#set enum(numbering: "ai)")
#set align(right)
<NAME> \
9/21/24
#set align(center)
= CSDS 310 Assignment 2
#set align(left)
_Note: Arrays are zero-indexed._
== Problem 1
+ $log^k n = o(n^epsilon)$, proven by the Limit Asymptotic Theorem:
$
lim_(n->oo) f(n)/g(n) &= lim_(n->oo) (log^k n)/(n^epsilon)
= lim_(n->oo) ((log n)/(n^(epsilon slash k)))^k #text()[, applying L'Hopital's:] \
&eq.star lim_(n->oo) ((1 slash n)/(epsilon n^(epsilon slash k - 1)))^k \
&= ((0)/(epsilon (oo)^(epsilon slash k - 1)))^k \
&= 0
$
This means that $g(n)$ is the asymptotic upper bound of $f(n)$. As this result does not depend on constants $k, epsilon$, this is a strict bound$-$which is also part of the Limit Asymptotic Theorem. \ \
+ $n^k = o(c^n)$, proven by the Limit Asymptotic Theorem again:
$
lim_(n->oo) f(n)/g(n) &= lim_(n->oo) (n^k)/(c^n) \
&eq.star lim_(n->oo) (k n^(k-1))/(c^n) \
&eq.star lim_(n->oo) (k(k-1) n^(k-2))/(c^n)
$
As the denominator remains fixed, this pattern will continue until:
$
lim_(n->oo) (k(k-1)(...)(2)(1) n^(1))/(c^n) &eq.star lim_(n->oo) (k(k-1)(...)(2))/(c^n) \
&= 0
$
By the same reason as part a), this result proves that $g(n)$ is the asymptotic strict upper bound of $f(n)$. \ \
+ There is no asymptotic relation between the two. If we were to prove this through the closest definition of Big-O notation, stating there exists some constant $a > 0$ that satisfies the following:
$
0 <= f(n) <= a g(n) \ 0 <= (sqrt(n)) <= a (n^sin(n)) \ 0 <= n^(1/2) <= a n^sin(n) \ 0 <= ln(n^(1/2)) <= ln(a n^sin(n)) \
0 <= 1/2 <= a sin(n)
$
Regardless of what we choose for $a$, $sin(n)$ can be $0$ for sufficiently large inputs for $n$, making the inequality false. If we were to try other notation definitions, there will still be no bound. \ \
== Problem 2
+ True. By the definition of Big O, with $a in bb(R)$ such that $a > 0$:
$
0 <= f(n) <= a g(n) \
0 <= f(n) + c <= a f(n) \
0 <= 1 <= (a f(n))/(f(n) + c)
$
Using a limit to evaluate a sufficiently large $n$:
$
lim_(n->oo) (a f(n))/(f(n)+c)
&eq.star lim_(n->oo) (a f'(n))/(f'(n)) \
&= lim_(n->oo) a \ &= a
$
Since there exists $a$ such that $a >= 1$ to make the inequality will hold true, this proves the original statement.
+ False. For $f(n) = 2^n$, by the definition of Theta Notation
$0 <= c_1 g(n) <= f(n) <= c_2 g(n)$, with $c_1, c_2$ are positive and $n$ is sufficiently large. We have $g(n) = f(2n) = 2^((2n)) = (2^n)^2$. Substituting:
$
0 <= c_1 (2^n)^2 &<= 2^n <= c_2 (2^n)^2 \
0 <= c_1 2^n &<= 1 <= c_2 2^n
$
No value of $c_1, c_2$ can fix this inequality the way I can fix her for any sufficiently large $n$. Thus, the statement is false.
+ True. Let $g(n)=f(2n)=(2n)^c=2^c n^c$. By the definition of Big O, with $a in bb(R)$ such that $a > 0$:
$
0 <= f(n) <= a g(n) \
0 <= n^c <= a (2^c n^c) \
0 <= 1 <= a dot 2^c
$
Suppose $a=1$ and given that $c>0$, for any sufficiently large value of $n$ the inequality holds true. Thus, there exists a constant which holds the statement true.
== Problem 3
+ Converting $T(n)$ to Master Theorem form, $T(n) = a T(n/b) + Theta(n^d)$. This falls under Case 2, thus $T(n)=Theta(n log n)$
+ yeah
== Problem 4
Pseudocode:
#pseudocode-list[
+ *procedure* MERGE(A, n):
+ *if* $n_A$ == 1:
+ *return* A
+ A' ← Array of $ceil(n/2)$ elements
+ *for* $0 <= i < floor(n slash 2)$:
+ A'[i] ← SUBMERGE(A[2i], A[2i+1])
+ *if* $n$ is odd:
+ A'[$n slash 2$] ← A[$n-1$] \/\/ Put last element in A'
+ *return* MERGE(A')
]
The merging of two subarrays, cleverly named:
#pseudocode-list[
+ *procedure* SUBMERGE(A, B):
+ i ← 0
+ j ← 0
+ C ← Array of $n_A + n_B$ elements
+ *while* i + j < len(A) + len(B):
+ *if* i == len(A):
+ C[i+j] ← B[j]
+ j ← j + 1
+ *else if* j == len(B) or A[i] < B[j]:
+ C[i+j] ← A[i]
+ i ← i + 1
+ *else*:
+ C[i+j] ← B[j]
+ j ← j + 1
+ *endwhile*
+ *return* C
]
Proof:
We'll break up this proof in two: One for `SUBMERGE` and one for `MEGE`
Runtime analysis:
We can apply the Master Theorem since we have a recursive case in which the merging is linear, |
|
https://github.com/katamyra/Notes | https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS3001/Modules/SocialContract.typ | typst | #import "../../../template.typ": *
= Social Contract
== Hobbes' Beliefs
Man is inherently _evil_. In order to avoid man's evil state of nature, rational people understand that some sort of social cooperation is only possible when people mutually agree to follow certain guidelines.
He basically said without rules and reinforcement, people would not create anything of value and instead attack and defend from others until they die.
#theorem[
This leads to a *social contract* - the view that persons' moral and/or political obligations are dependent upon a contract or agreement among them to form the society in which they live.
]
== Social Contract Theory
#theorem[
Hobbes argues that everyone in society has implicitly agreed to two things:
+ The establishment of a set of moral rules to govern relations among citizens
+ A government capable of enforcing these rules
]
Hobbes believes that the morals derived from natural law do not permit individuals to challenge the laws of the sovereign, meaning that you cannot disobey the laws of the government.
All morally significant beings have certain rights such as the right to life, liberty, and property.
Living in a civil society gives a person moral quality they would not have otherwise
== Rights
_Rights_ can be classified according to the duties they put on others
#definition[
*Negative Rights* are rights that another can guarantee by leaving you alone to exercise your right.
- Right of free speech
- Right to be safe
- Right to move around
*Positive Right* - a right that obligates others to do something on your behalf (guarantee of an action)
- Right to free education
- Community and national security
*Absolute Right* - guaranteed without exception
*Limited Right* - may/can be restricted
]
== Rawls's Theory of Justice
Rawl notes that both cooperative and competitive behavior can be found in every society. The former because social cooperation produces more benefits than a situation in which individuals are completely on their own. The former because it is important how the benefits are divided among society.
To be well ordered, a society must establish the rights of its members and also determine a just way of distributing both the benefits and burdens of social cooperation
#theorem[
*Rawl's Principles of Justice*
+ Each person may claim a "fully adequate" number of basic rights and liberties, such as freedom of thought and speech, the right to be safe from harm, etc so long as these claims are consistent with everyone else having a claim to the same right and liberties
+ Any social and economic inequalities must satisfy two conditions: first, they are associated with positions in society that everyone has a fair and equal opportunity to assume, and second they are "to be to the greatest benefit of the least-advantaged members of society"
]
#definition[
*Difference principle*: societal and economic inequalities must be justified, which can only be done by showing that its overall effect is to benefit least advantaged members of society
]
*The Case For*:
- It is framed in the language of rights
- The cultures of many modern countries *FINISH REST OF SOCIAL CONTRACT*
- It is based on a solid understanding of human nature, recognizing that rational people act ouf of self-interest in the absence of a common agreement
- It explains why under certain circumstances civil disobedience can be the morally right decision
*The Case Against*:
- None of us signed the social contract
- Some actions can be characterized in multiple ways
*How do the philosophies compare?*
_Reason for making a rule_:
- *Utilitarianism*: it causes the greatest happiness for the most people
- *Kantianism*: it could be universalized for all people
- *Social contract theory*: rational people would collectively accept it as binding because of its benefits to the community
|
|
https://github.com/BeiyanYunyi/Architectural-Technology-and-Art-Paper | https://raw.githubusercontent.com/BeiyanYunyi/Architectural-Technology-and-Art-Paper/main/thesis.typ | typst | MIT License | #import "nju-thesis/template.typ": documentclass, tablex, fig, tlt, indent
#import "nju-thesis/utils/style.typ": 字号, 字体
#import "nju-thesis/utils/indent.typ": fake-par
#import "nju-thesis/utils/invisible-heading.typ": invisible-heading
// 双面模式,会加入空白页,便于打印
#let twoside = true
// #let twoside = true
#let (
doc,
preface,
mainmatter,
mainmatter-end,
appendix,
fonts-display-page,
cover,
decl-page,
abstract,
abstract-en,
outline-page,
list-of-figures,
list-of-tables,
notation,
acknowledgement,
) = documentclass(
// type: "bachelor", // "bachelor" | "master" | "doctor" | "postdoc", 文档类型,默认为本科生 bachelor
// degree: "academic", // "academic" | "professional", 学位类型,默认为学术型 academic
// anonymous: true, // 盲审模式
twoside: twoside, // 双面模式,会加入空白页,便于打印
// 可自定义字体,先英文字体后中文字体,应传入「宋体」、「黑体」、「楷体」、「仿宋」、「等宽」
// fonts: (楷体: ("Times New Roman", "FZKai-Z03S")),
info: (
title: "从乌托邦到现实:苏联构成主义建筑设计哲学",
title-en: "From Utopia to Reality: the Design Philosophy of Soviet Constructivist Architecture",
grade: "2021",
student-id: "11451400",
author: "田所浩二",
author-en: "<NAME>",
department: "淫梦药学院",
department-en: "School of Inmu",
major: "红茶研究",
major-en: "Black Tea Science",
supervisor: ("多田野数人", ""),
supervisor-en: "TDN",
// supervisor-ii: ("", ""),
// supervisor-ii-en: "",
submit-date: "一九一九 年 八 月 十 日",
super-title: "本科生课程论文",
),
)
// 文稿设置
#show: doc
// 字体展示测试页
// #fonts-display-page()
// 封面页
#cover()
// 前言
#show: preface
// 目录
#outline-page()
// 中文摘要
#abstract(
keywords: ("苏联", "构成主义", "现代建筑", "建筑艺术"),
)[ 构成主义,是1917年俄国革命后在苏联逐渐兴起的一系列建筑与艺术运动。它以功能性、简洁性、工业材料的使用为基本理念,并深刻影响了后来的现代主义建筑运动,如包豪斯学派等。 ]
// 英文摘要
#abstract-en(keywords: (
"USSR",
"Constructivist Architecture",
"Modern Architecture",
"Architecture Art",
))[
Constructivism, a series of architectural and artistic movements that gradually emerged in the Soviet Union after the Russian Revolution of 1917. It took functionality, simplicity, and the use of industrial materials as its basic philosophy, and profoundly influenced later modernist architectural movements such as the Bauhaus School.
]
#pagebreak()
#show: mainmatter
#pagebreak()
// 正文
= 构成主义的兴起
== 历史背景
1917年俄国革命推翻了沙皇统治,建立了苏维埃政权。革命后的苏联社会急需新的文化和艺术形式,以反映新政权的意识形态和社会理想。在这种背景下,构成主义作为一种新兴的艺术运动,迅速崛起,并得到了苏维埃政府的支持。
== 构成主义的起源
构成主义的起源可以追溯到俄国的前卫艺术运动,特别是立体主义和未来主义的影响。1913年,弗拉基米尔·塔特林(<NAME>)在莫斯科创作了他的“反浮雕”(Counter-Reliefs),标志着构成主义的萌芽。@MUSE202206022
塔特林的作品强调材料的本质和三维空间的探索,这些理念成为构成主义的核心原则。
= 构成主义成为主要艺术和建筑运动
== 理念与目标
构成主义倡导艺术与生活的融合,强调功能性和实用性,反对装饰主义和形式主义。构成主义者相信艺术应该为社会服务,推动社会进步。它们的作品常常强调几何形状、工业材料和简洁的设计。
=== 功能性
构成主义强调建筑和设计的功能性,认为形式应该服从功能。构成主义者主张每个设计元素都应有明确的用途,避免无用的装饰和繁琐的细节。他们相信,建筑和设计应该直接服务于社会和人的实际需求,提升生活质量。
=== 简洁性
简洁性是构成主义设计的另一个重要原则。构成主义者力求通过简洁的几何形状和线条来表达艺术和建筑的美感,摒弃复杂的装饰。简洁的设计不仅可以减少材料和劳动力的浪费,还可以增强作品的视觉冲击力和可读性。
=== 工业材料的使用
构成主义者热衷于使用现代工业材料,如钢铁、玻璃和混凝土等。他们认为,这些材料不仅可以实现更大的结构自由度和创新设计,还能够反映现代工业社会的精神。工业材料的使用使得建筑具有现代感和工业美学,同时也突出了材料的本质和质感。
=== 标准化与模块化设计
构成主义提倡建筑和设计的标准化和模块化,以提高生产效率和节约资源。他们相信,通过标准化的构件和模块化的设计,可以实现大规模生产和快速建造,适应现代社会的需求。这种方法不仅能够降低成本,还能够保证质量的一致性。
=== 社会功能与集体主义
构成主义强调建筑和设计的社会功能,主张集体主义精神,认为艺术和建筑应该为大众服务,而不是为少数特权阶层服务。他们的设计常常关注公共空间的利用和集体生活的需求,力图通过建筑和设计来促进社会的公平和进步。
=== 动态与运动
构成主义在艺术和设计中常常表现出对动态和运动的关注,强调形式的变化和空间的流动性。他们尝试通过几何形状的组合和分割来表现动感和节奏,使作品具有活力和动感。这种对动态的追求也反映在他们的建筑设计中,如塔特林的“第三国际纪念塔”,该塔的设计强调旋转和上升的运动感。
=== 多学科融合
构成主义者通常跨越多个学科,如建筑、绘画、雕塑和工业设计等,主张艺术和技术的结合,形成统一的设计语言。他们的作品不仅仅是建筑或艺术品,而是综合了多种元素的整体设计,体现了艺术与科学的融合。
== 主要人物和组织
构成主义的主要人物包括弗拉基米尔·塔特林、埃尔·利西茨基(El Lissitzky)、亚历山大·罗钦科(Alexander
Rodchenko)和娜塔利娅·冈察洛娃(Natalia
Goncharova)等。1919年,塔特林在莫斯科创立了“塔特林工作坊”,成为构成主义艺术家的重要聚集地。
=== 弗拉基米尔·塔特林
弗拉基米尔·塔特林(<NAME>,1885年12月28日-1953年5月31日)是苏联著名的艺术家、建筑师和设计师,是俄罗斯先锋艺术运动的重要人物之一,尤其以他的构成主义(Constructivism)作品闻名于世。塔特林出生于莫斯科,早年在莫斯科绘画、雕塑和建筑学院学习。他的艺术风格受到了俄罗斯传统艺术和现代欧洲艺术的双重影响。塔特林在年轻时曾是一名水手,这段经历丰富了他的世界观,并在他后来对机械和工业材料的兴趣中有所体现。塔特林是构成主义的创始人之一。构成主义是一种强调艺术应服务于社会和实用功能的艺术运动。塔特林的作品常常使用工业材料,如金属、玻璃和木材,试图将艺术与日常生活和工业生产结合起来。
塔特林最著名的作品是他为第三国际设计的纪念塔,即“塔特林塔”(Tatlin's
Tower)。这个项目于1919年至1920年设计,虽然从未建成,但其大胆的螺旋结构和革命性的设计理念对现代建筑产生了深远影响。塔特林塔原计划作为第三国际的总部,其设计象征着革命和社会进步。
== 重要作品与项目
构成主义建筑的代表作包括塔特林的“第三国际纪念塔”(Tatlin's Tower)、莫斯科的“雷宁研究所”(Narkomfin
Building)和舒霍夫塔(Shukhov Tower)。这些建筑作品体现了构成主义的核心理念,如功能性、工业材料的使用和对空间的创新探索。
=== 第三国际纪念塔
#fig(image("images/1.png", width: 70%), caption: [设计图])
弗拉基米尔·塔特林(Vladimir Tatlin)的“塔特林塔”,正式名称为“第三国际纪念塔”(Monument to the Third
International),是他最著名的未建成作品之一。这座塔被视为构成主义建筑的典范,也是20世纪早期革命性建筑设计的象征。
塔特林塔于1919年至1920年设计,正值俄罗斯十月革命后不久。这座纪念塔是为纪念第三国际(共产国际)而设计的,旨在象征新生的社会主义国家和革命精神。塔特林塔以其大胆的双螺旋结构著称。两条螺旋钢架从基座盘旋而上,形成一个动感十足的外观。这种设计不仅在视觉上给人以强烈的动感,还象征着革命的动力和进步。
塔的内部由三个旋转的几何形体构成:一个立方体、一个锥体和一个圆柱体。每个几何形体都以不同的速度旋转,并分别用于不同的功能空间。立方体每年旋转一周,作为立法机构的会议厅。锥体每月旋转一周,作为行政机构的办公空间。圆柱体每天旋转一周,作为新闻传播中心。
塔特林塔主要使用钢和玻璃等工业材料,反映了构成主义对工业和技术的崇拜。塔的设计结合了当时最先进的工程技术和建造理念,试图打破传统建筑形式。
=== 雷宁研究所
#fig(image("images/2.jpg", width: 70%), caption: [建筑外观])
由莫伊谢·金兹堡(Mo<NAME>burg)设计的雷宁研究所是一座标志性的构成主义住宅建筑。它通过模块化设计和标准化构件,实现了高效的空间利用和现代化的生活设施,体现了构成主义的社会功能和集体主义精神。
= 构成主义的影响与遗产
== 对现代建筑的影响
构成主义对现代建筑运动产生了深远影响,特别是在包豪斯学派和国际风格的形成中起到了重要作用。构成主义的理念和实践为现代建筑提供了新的视角和方法。
== 全球影响
构成主义不仅在苏联国内产生了重大影响,还通过国际展览和出版物传播到西方国家,对欧洲和美国的建筑师和设计师产生了启发。
= 结语
构成主义作为一种重要的艺术和建筑运动,深刻影响了20世纪的现代主义发展。它通过强调功能性、工业材料和简洁设计,推动了建筑和艺术的革新。尽管苏联的政治环境对构成主义的发展产生了影响,但其核心理念和实践仍然在全球范围内留下了持久的遗产。
// 手动分页
#if (twoside) {
pagebreak() + " "
}
#v(字号.五号)
// 参考文献
#[
#set text(font: 字体.黑体, size: 字号.四号)
#set par(first-line-indent: 0em)
#heading(numbering: none, level: 1)[参考文献]
#fake-par
#set text(font: 字体.宋体, size: 字号.小五)
#bibliography(
("bibs/ex01.bib"),
style: "gb-7714-2005-numeric",
title: none,
)
]
// 致谢
#acknowledgement[
感谢 NJU-LUG,感谢 NJUThesis LaTeX 模板。感谢 Dustella 对南京信息工程大学 Typst 模板的贡献。
感谢广州市第一人民医院徐利敏医生、南京鼓楼医院曹秋云医生、苏州市立医院周建英医生、上海四一一医院赵烨德医生。
]
// 手动分页
#if (twoside) {
pagebreak() + " "
}
// 正文结束标志,不可缺少
#mainmatter-end()
// 附录
#show: appendix
|
https://github.com/MrToWy/Bachelorarbeit | https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/main.typ | typst | #import "Template/template.typ": *
#show: project.with(
title: "Konzeption und Entwicklung eines Systems zur Verwaltung und Erstellung von Modulhandbüchern",
subtitle: "Bachelorarbeit im Studiengang Mediendesigninformatik",
author: "<NAME>",
author_email: "<EMAIL>",
matrikelnummer: 1629483,
prof: [
Prof. Dr. <NAME>\
Abteilung Informatik, Fakultät IV\
Hochschule Hannover\
#link("mailto:<EMAIL>")
],
second_prof: [
Prof. Dr. <NAME>\
Abteilung Informatik, Fakultät IV\
Hochschule Hannover\
#link("mailto:<EMAIL>")
],
date: "13. August 2024",
glossaryColumns: 1
)
#include "Chapters/1-Einleitung.typ"
#include "Chapters/2-Planung.typ"
#include "Chapters/3-Entwurf.typ"
#include "Chapters/4-Implementierung.typ"
#include "Chapters/5-Review.typ"
#include "Chapters/6-Fazit.typ"
#include "Chapters/Anhang.typ"
|
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CU/minea/1_generated/00_all/04_december.typ | typst | #import "../../../all.typ": *
#show: book
= #translation.at("M_04_december")
#include "../04_december/05.typ"
#pagebreak()
#include "../04_december/06.typ"
#pagebreak()
#include "../04_december/08.typ"
#pagebreak()
#include "../04_december/25.typ"
#pagebreak()
|
|
https://github.com/haxibami/haxipst | https://raw.githubusercontent.com/haxibami/haxipst/main/src/lib/set-metadata.typ | typst | #let set-metadata(
pdf-title: none,
pdf-author: (),
pdf-keywords: (),
pdf-date: auto,
body,
) = {
set document(
title: pdf-title,
author: pdf-author,
keywords: pdf-keywords,
date: pdf-date,
)
body
}
|
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history_CN/2015/MS-11.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (1 - 32)",
table(
columns: 4,
[排名], [运动员], [国家/地区], [积分],
[1], [马龙], [CHN], [3625],
[2], [樊振东], [CHN], [3404],
[3], [许昕], [CHN], [3345],
[4], [迪米特里 奥恰洛夫], [GER], [3233],
[5], [张继科], [CHN], [3197],
[6], [方博], [CHN], [3154],
[7], [#text(gray, "王皓")], [CHN], [3147],
[8], [闫安], [CHN], [3096],
[9], [水谷隼], [JPN], [3094],
[10], [庄智渊], [TPE], [3051],
[11], [斯特凡 菲格尔], [AUT], [3045],
[12], [黄镇廷], [HKG], [3003],
[13], [朱世赫], [KOR], [2996],
[14], [蒂姆 波尔], [GER], [2975],
[15], [吉村真晴], [JPN], [2973],
[16], [张禹珍], [KOR], [2970],
[17], [马克斯 弗雷塔斯], [POR], [2961],
[18], [安德烈 加奇尼], [CRO], [2957],
[19], [郑荣植], [KOR], [2949],
[20], [弗拉基米尔 萨姆索诺夫], [BLR], [2945],
[21], [于子洋], [CHN], [2932],
[22], [周雨], [CHN], [2922],
[23], [汪洋], [SVK], [2914],
[24], [马蒂亚斯 法尔克], [SWE], [2907],
[25], [SHIBAEV Alexander], [RUS], [2898],
[26], [丹羽孝希], [JPN], [2890],
[27], [唐鹏], [HKG], [2888],
[28], [梁靖崑], [CHN], [2888],
[29], [大岛祐哉], [JPN], [2877],
[30], [李尚洙], [KOR], [2865],
[31], [GERELL Par], [SWE], [2863],
[32], [罗伯特 加尔多斯], [AUT], [2854],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (33 - 64)",
table(
columns: 4,
[排名], [运动员], [国家/地区], [积分],
[33], [帕纳吉奥迪斯 吉奥尼斯], [GRE], [2852],
[34], [高宁], [SGP], [2849],
[35], [徐晨皓], [CHN], [2844],
[36], [西蒙 高兹], [FRA], [2834],
[37], [塩野真人], [JPN], [2832],
[38], [陈卫星], [AUT], [2832],
[39], [吉田海伟], [JPN], [2829],
[40], [MONTEIRO Joao], [POR], [2826],
[41], [卢文 菲鲁斯], [GER], [2824],
[42], [帕特里克 弗朗西斯卡], [GER], [2822],
[43], [CHIANG Hung-Chieh], [TPE], [2820],
[44], [乔纳森 格罗斯], [DEN], [2808],
[45], [李廷佑], [KOR], [2800],
[46], [WANG Zengyi], [POL], [2798],
[47], [艾曼纽 莱贝松], [FRA], [2792],
[48], [MATTENET Adrien], [FRA], [2791],
[49], [森园政崇], [JPN], [2789],
[50], [松平健太], [JPN], [2789],
[51], [TSUBOI Gustavo], [BRA], [2788],
[52], [利亚姆 皮切福德], [ENG], [2788],
[53], [KIM Donghyun], [KOR], [2787],
[54], [LI Hu], [SGP], [2781],
[55], [尚坤], [CHN], [2774],
[56], [#text(gray, "LIU Yi")], [CHN], [2763],
[57], [HE Zhiwen], [ESP], [2758],
[58], [奥马尔 阿萨尔], [EGY], [2755],
[59], [帕特里克 鲍姆], [GER], [2751],
[60], [CHEN Feng], [SGP], [2750],
[61], [夸德里 阿鲁纳], [NGR], [2745],
[62], [村松雄斗], [JPN], [2744],
[63], [雨果 卡尔德拉诺], [BRA], [2743],
[64], [DRINKHALL Paul], [ENG], [2742],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (65 - 96)",
table(
columns: 4,
[排名], [运动员], [国家/地区], [积分],
[65], [LI Ping], [QAT], [2741],
[66], [蒂亚戈 阿波罗尼亚], [POR], [2738],
[67], [HO Kwan Kit], [HKG], [2736],
[68], [KOU Lei], [UKR], [2735],
[69], [周恺], [CHN], [2733],
[70], [朴申赫], [PRK], [2724],
[71], [林高远], [CHN], [2722],
[72], [周启豪], [CHN], [2722],
[73], [丁祥恩], [KOR], [2722],
[74], [江天一], [HKG], [2722],
[75], [KONECNY Tomas], [CZE], [2718],
[76], [MACHI Asuka], [JPN], [2717],
[77], [KARAKASEVIC Aleksandar], [SRB], [2712],
[78], [LI Ahmet], [TUR], [2709],
[79], [HABESOHN Daniel], [AUT], [2705],
[80], [克里斯坦 卡尔松], [SWE], [2704],
[81], [博扬 托基奇], [SLO], [2698],
[82], [金珉锡], [KOR], [2697],
[83], [王臻], [CAN], [2694],
[84], [陈建安], [TPE], [2689],
[85], [<NAME>], [SVK], [2684],
[86], [<NAME>], [CZE], [2684],
[87], [吉田雅己], [JPN], [2683],
[88], [巴斯蒂安 斯蒂格], [GER], [2682],
[89], [安东 卡尔伯格], [SWE], [2682],
[90], [上田仁], [JPN], [2682],
[91], [PROKOPCOV Dmitrij], [CZE], [2681],
[92], [吴尚垠], [KOR], [2679],
[93], [GERALDO Joao], [POR], [2677],
[94], [PERSSON Jon], [SWE], [2676],
[95], [<NAME>], [GER], [2673],
[96], [<NAME>], [POL], [2667],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (97 - 128)",
table(
columns: 4,
[排名], [运动员], [国家/地区], [积分],
[97], [#text(gray, "KIM Hyok Bong")], [PRK], [2664],
[98], [<NAME>], [FRA], [2663],
[99], [KOSIBA Daniel], [HUN], [2658],
[100], [KANG Dongsoo], [KOR], [2657],
[101], [廖振珽], [TPE], [2656],
[102], [PAIKOV Mikhail], [RUS], [2656],
[103], [<NAME>], [GER], [2655],
[104], [MATSUDAIRA Kenji], [JPN], [2654],
[105], [#text(gray, "约尔根 佩尔森")], [SWE], [2652],
[106], [HACHARD Antoine], [FRA], [2652],
[107], [KIM Minhyeok], [KOR], [2646],
[108], [#text(gray, "张一博")], [JPN], [2645],
[109], [沙拉特 卡马尔 阿昌塔], [IND], [2644],
[110], [塞德里克 纽廷克], [BEL], [2643],
[111], [尼马 阿拉米安], [IRI], [2641],
[112], [OUAICHE Stephane], [ALG], [2640],
[113], [CIOTI Constantin], [ROU], [2639],
[114], [ZHAI Yujia], [DEN], [2638],
[115], [维尔纳 施拉格], [AUT], [2637],
[116], [斯蒂芬 门格尔], [GER], [2637],
[117], [MONTEIRO Thiago], [BRA], [2634],
[118], [VLASOV Grigory], [RUS], [2634],
[119], [薛飞], [CHN], [2631],
[120], [SEO Hyundeok], [KOR], [2630],
[121], [SAKAI Asuka], [JPN], [2629],
[122], [雅克布 迪亚斯], [POL], [2625],
[123], [米凯尔 梅兹], [DEN], [2622],
[124], [及川瑞基], [JPN], [2618],
[125], [#text(gray, "OYA Hidetoshi")], [JPN], [2616],
[126], [TAN Ruiwu], [CRO], [2616],
[127], [CHO Eonrae], [KOR], [2613],
[128], [#text(gray, "WU Zhikang")], [SGP], [2611],
)
) |
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/math/symbols.md | markdown | MIT License | # Symbols
Multiletter words in math refer either to local variables, functions, text operators, spacing or _special symbols_.
The latter are very important for advanced math.
```typ
$
forall v, w in V, alpha in KK: alpha dot (v + w) = alpha v + alpha w
$
```
You can write the same with unicode:
```typ
$
∀ v, w ∈ V, α ∈ 𝕂: α ⋅ (v + w) = α v + α w
$
```
## Symbols naming
> See all available symbols list [there](https://typst.app/docs/reference/symbols/sym/).
### General idea
Typst wants to define some "basic" symbols with small easy-to-remember words, and build complex ones using
combinations. For example,
```typ
$
// cont — contour
integral, integral.cont, integral.double, integral.square, sum.integral\
// lt — less than, gt — greater than
lt, lt.circle, lt.eq, lt.not, lt.eq.not, lt.tri, lt.tri.eq, lt.tri.eq.not, gt, lt.gt.eq, lt.gt.not
$
```
I highly recommend using WebApp/Typst LSP when writing math with lots of complex symbols.
That helps you to quickly choose the right symbol within all combinations.
Sometimes the names are not obvious, for example, sometimes it is used prefix `n-` instead of `not`:
```typ
$
gt.nequiv, gt.napprox, gt.ntilde, gt.tilde.not
$
```
### Common modifiers
- `.b, .t, .l, .r`: bottom, top, left, right. Change direction of symbol.
```typ
$arrow.b, triangle.r, angle.l$
```
- `.bl, tr`: bottom-left, top-right and so on. Where diagonal directions are possible.
- `.bar, .circle, .times, ...`: adds corresponding element to symbol
- `.double, .triple, .quad`: combine symbol 2, 3 or 4 times
- `.not` crosses the symbol
- `.cw, .ccw`: clock-wise and counter-clock-wise. For arrows and other things.
- `.big, .small`:
```typ
$plus.circle.big plus.circle, times.circle.big plus.circle$
```
- `.filled`: fills the symbol
```typ
$square, square.filled, diamond.filled, arrow.filled$
```
### Greek letters
Lower case letters start with lower case letter, upper case start with upper case.
For different versions of letters, use `.alt`
```typ
$
alpha, Alpha, beta, Beta, beta.alt, gamma, pi, Pi,\
pi.alt, phi, phi.alt, Phi, omicron, kappa, kappa.alt, Psi,\
theta, theta.alt, xi, zeta, rho, rho.alt, kai, Kai,
$
```
### Blackboard letters
Just use double of them. If you want to make some other symbol blackboard, use `bb`:
```typ
$bb(A), AA, bb(1)$
```
## Fonts issues
Default font is **New Computer Modern Math**. It is a good font, but there are some inconsistencies.
Typst maps symbol names to unicode, so if the font has wrong symbols, Typst will display wrong ones.
### Empty set
See example:
```typ
// nothing in default math font is something bad
$nothing, nothing.rev, diameter$
#show math.equation: set text(font: "Fira Math")
// Fira math is more consistent
$nothing, nothing.rev, diameter$
```
However, you can fix this with font feature:
```typ
#show math.equation: set text(features: ("cv01",))
$nothing, nothing.rev, diameter$
```
Or simply using "show" rule:
```typ
#show math.nothing: math.diameter
$nothing, nothing.rev, diameter$
``` |
https://github.com/grnin/Zusammenfassungen | https://raw.githubusercontent.com/grnin/Zusammenfassungen/main/helpers.typ | typst | // Helper functions
// (C) 2024, <NAME>, <NAME>
#let number-format(n, chunks, num-suffix) = {
box(
str(n)
.replace(regex("\s"), "") // remove whitespace from string
.codepoints() // get the individual digits
.rev() // reverse digits so that the MSB gets put in the last chunk
.chunks(chunks) // create groups of digits
.map(it => $mono(#it.join().rev())$) // join & format digits in chunk & reverse so the MSB within a chunk is in front
.rev() // un-reverse so the MSB is in front again
.join($thin$) + sub[#num-suffix] // join the groups together with a small space & add suffix
)
}
#let bits(n, suffix: true) = {
number-format(n, 4, if(suffix) { "b" } else { "" })
}
#let hex(n, suffix: true) = {
number-format(n, 2, if(suffix) { "h" } else { "" })
}
|
|
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/VerbaliInterni/VerbaleInterno_231121/meta.typ | typst | MIT License | #let data_incontro = "21-11-2023"
#let inizio_incontro = "16:00"
#let fine_incontro = "17:30"
#let luogo_incontro = "Chiamata Discord" |
https://github.com/0xPARC/0xparc-intro-book | https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/src/oram.typ | typst | #import "preamble.typ":*
// #import algorithmic: algorithm
To motivate Oblivious RAM, let us think of Signal’s usage scenario.
Signal is an encrypted messenger app with billions of users. They want
to support a private contact discovery application. In contact
discovery, a user Alice sends her address book to Signal, and Signal
will look up its user database and return Alice the information about
her friends. The problem is that many users want to keep their address
book private, and Signal wants to provide contact discovery without
learning the users’ contacts.
A naive solution is to rely on trusted hardware. Suppose Signal has a
secure processor (like Intel SGX) on its server. One can think of the
secure processor as providing a hardware sandbox (often referred to as
an #emph[enclave];). Now, Alice sends her address book in encrypted
format to the server’s enclave; further, the server’s database is also
encrypted as it is stored in memory and on disk. Now, the enclave has a
secret key that can decrypt the data and perform computation inside. At
first sight, this seems to solve the privacy problem, since data is
always encrypted in transit and at rest, and the server cannot see the
contents.
Unfortunately, encryption alone provides
little privacy in such scenarios. The enclave will need
to access encrypted entries stored on disk, and the server’s operating
system can easily observe the #emph[access patterns];, i.e., which
memory pages are being fetched by the enclave. The access patterns leak
exactly who Alice’s friends are even if the data is encrypted!
In general, access patterns of a program leak sensitive information
about your private data. As a simpler example, if you are performing binary
search over a sorted array, the entries accessed during the search would
leak your private query.
We can also think of
access pattern leakage through a programming language perspective: for
example, the following program has an `if`-branch dependent on secret
inputs.
(Maybe the secret input is the last bit of a secret key).
By observing whether memory location `x` or `y` is accessed, one
can infer which branch is taken.
#align(center)[
#block[
```
if (s) {
mem[x]
} else {
mem[y]
}
```
]
]
Therefore, we want to solve the following challenge:
#quote[How can we provably hide access patterns while preserving
efficiency?]
The solution Signal eventually deployed is an algorithmic technique
called Oblivious RAM (ORAM).
= Oblivious RAM: Problem Definitions
<oblivious-ram-problem-definitions>
Oblivious RAM (ORAM) is a powerful cryptographic protocol that
#emph[provably] hides access patterns to sensitive data.
We would like to ensure a very strong notion of security. In particular,
no information should be leaked about: 1) which data block is being
accessed; 2) the age of the data block (when it was last
accessed); 3) whether a single block is being requested repeatedly
(frequency); 4) whether data blocks are often being accessed
together (co-occurrence); or 5) whether each access is a read or a
write.
Let us explain the parts of an ORAM system.
An ORAM algorithm (the #emph[client];)
sits between a #emph[user]; who wants to access memory
and a #emph[server]; that has memory capabilities.
At the server-ORAM interface, the server simply acts as a memory:
the ORAM client sends read and write requests to the server,
and the server responds.
Between the ORAM and the user,
the user submits #emph[logical] read and write requests
to the ORAM client,
and the client will reply to each (after interaction with the server).
We will call #emph[physical] memory the memory that the server manages,
and #emph[logical] memory the memory the user wants to access.
Memory, both physical and logical, will be made up of "blocks";
our ORAM algorithm will support $N$ blocks of logical memory.
Formally, the user sends to the algorithm
a sequence of #emph[logical] requests, where each logical request
is of the form
$(mono("read"), mono("addr"))$ or $(mono("write"), mono("addr"),
mono("data"))$.
After each user request, the ORAM algorithm interacts with
the server to make a sequence of
#emph[physical] memory accesses, where each physical access either reads or
writes a block to a physical location.
And finally, the ORAM algorithm
turns back to the user and
returns an answer to the logical request.
For example, in Signal’s scenario,
the "user" and the "ORAM client"
are both in the hardware enclave,
and the "ORAM server" is the untrusted memory and disk on
Signal’s server.
The security requirement for ORAM is that the server should learn nothing
about the user's logical memory requests
from observing the sequence of physical memory requests.
For any two #emph[logical] request sequences, the ORAM’s
resulting #emph[physical] access sequences will be indistinguishable.
#remark[
In this security requirement,
we require that the server learn nothing from observing only the list of
physical addresses, and whether each physical
access is a read or write.
We don't say anything about the data that is written to physical memory.
In practice, we need to use encryption to hide
the contents of the blocks.
If we read a block and then write it back,
we should re-encrypt it with a different ciphertext,
or else the server would recognize it as the same block.
From now on we will simply assume secure encryption as
given, and focus on hiding the access patterns.
]
= Naive Solutions
<naive-solutions>
== Naive solution 1
<naive-solution-1.>
One trivial solution is for the client to read all blocks from the
server upon every logical request. Obviously this scheme leaks nothing
but would be prohibitively expensive.
== Naive solution 2
<naive-solution-2.>
Another trivial solution is for the client to store all blocks, and thus
the client need not access the server to answer any memory request. But
this defeats the numerous advantages of cloud outsourcing in the first
place. #emph[Henceforth, we require that client store only a small
amount of blocks] (maybe constant or polylogarithmic in $N$).
== Naive solution 3
<naive-solution-3.>
Another naive idea is to randomly permute all memory blocks through a
secret permutation known only to the client. Whenever the client wishes
to access a block, it will appear to the server to reside at a random
location.
Indeed, this scheme gives a secure #emph[one-time] ORAM scheme: it
provides security if every block is accessed only once. However, if the
client needs to access each block multiple times, then the access
patterns will leak statistical information such as frequency (how
often the same block is accessed) and co-occurrence (how likely
two blocks are accessed together). As mentioned earlier, one can
#cite("https://www.ndss-symposium.org/wp-content/uploads/2017/09/06_1.pdf", "leverage")
such statistical information to infer sensitive
secrets.
== Important observation
<important-observation.>
The above naive solution 3 gives us the following useful insight:
informally, if we want a "non-trivial" ORAM scheme, it appears that we
may have to relocate a block after it is accessed — otherwise, if the
next access to the same block goes back to the same location, we can
thus leak statistical information. It helps to keep this observation in
mind when we describe our ORAM scheme later.
= Binary-Tree ORAM: Data Structure
<data-structure>
We will learn about tree-based ORAMs.
Then, we will mention an
improvement called #cite("https://eprint.iacr.org/2013/280.pdf", "Path ORAM"),
which is the scheme
that Signal has deployed.
== Server data structure
<server-data-structure.>
The server stores a binary tree with $N$ leaves.
(If necessary, replace $N$ with the next larger power of $2$.)
Each node is called a
#emph[bucket];, and each bucket is a finite array that can hold up to
$Z$ number of blocks — for now, think of $Z$ as being relatively small
(maybe polylogarithmic in $N$); we will describe how to parametrize $Z$
later. Some of the blocks stored by the server are #emph[real];, other
blocks are #emph[dummy];. As will be clear later, these dummy blocks are
introduced for security:
we do not want the server to learn which buckets hold real blocks.
== Main path invariant
<main-path-invariant.>
The most important invariant is that at any point of time, each block is
mapped to a random path in the tree (also referred to as the block’s
designated path), where a path begins from the root and ends at some
leaf node — and thus a path can be specified by the corresponding leaf
node’s identifier. When a block is mapped to a path, it means that the
block can legitimately reside anywhere along the path.
== Imaginary position map
<imaginary-position-map.>
For the time being, we will rely on the following cheat (an assumption
that we can get rid of later). We assume that the client can store a
somewhat large position map that records the designated path of every
block. In general, such a position map would require roughly
$Theta (N log N)$ bits to store — but later we can recursively outsource
the storage of the position map to the server by placing position maps in
progressively smaller ORAMs.
= Binary Tree ORAM: Operations
<operations>
We now describe how to access blocks in our ORAM scheme.
== Fetching a block
<fetching-a-block.>
Given how our data structures are set up, accessing a block is very
easy: the client simply looks up its local position map, finds out on
which path the block is residing, and then reads each and every block on
the path. As long as the main invariant is respected, the client is
guaranteed to find the desired block.
== Remapping a block
<remapping-a-block.>
Recall that earlier, we have gained the informal insight that whenever a
block is accessed, it should relocate. Here, whenever we access a block,
we must remap it to a randomly chosen new path — otherwise, we would end
up going back to the same path if the block is requested again, thus
leaking statistical information.
To remap the block, we choose a fresh new path,
and we update the client’s
position map to associate the new path with the block. We now would like
to write this block back to the tree, to somewhere on the new path (and
if the request is a `write` request, the block’s contents are updated
before being written back to the server). But doing this is tricky! It
turns out that we cannot write the block back directly to the leaf
bucket of the new path — since doing so would reveal which new path the
block got assigned, this leaks information since if the next request
asks for the same block, it would then go to this new path; otherwise
most likely the next request will go to a different path.
For the same reason,
we cannot write this block back to any internal nodes of the
new path either, since writing to any internal node on the new path also
leaks partial information about the new path.
It turns out that the only safe location to write the block back is to
the root bucket! The root bucket resides on every path, and thus writing
the block back to the root does not violate the main path invariant; and
further, it does not leak any information about the new path.
Now this is great. Our idea thus is to write this block back to the root
bucket. However, there is also an obvious problem! The root bucket has a
capacity of $Z$, and if we keep writing blocks back to the root, soon
enough the root bucket will overflow! Therefore, we now introduce a new
procedure called #emph[eviction] to cope with this problem.
== Eviction
<eviction.>
Eviction is a maintenance operation performed upon every data access to
ensure that none of the buckets in the ORAM tree will ever overflow
except with negligible in $N$ failure probability. Note that if an
overflow does happen, the block that leads to the overflow can get lost
since there is no space to hold it on the server, and this can affect
the correctness of our ORAM scheme. However, we will guarantee that such
correctness failure happens only with negligible probability.
The high-level idea is very simple: whenever we can, we will try to move
blocks in the tree closer to the leaves, to allow space to free up in
smaller levels of the tree (levels closer to the root). There are
a few important considerations when performing such eviction:
- Data movement during eviction must respect the main path invariant:
each block can only be moved into buckets in which it can
legitimately reside.
- Data movement during eviction must retain #emph[obliviousness]:
the physical locations accessed during eviction should be independent
of the input requests to the ORAM.
- As we perform eviction, we pay a cost for this maintenance operation
and the cost is charged to each data access. Obviously, if we are
willing to pay more such cost, we can pack blocks closer to the
leaves, thus leaving more room in smaller levels. In this way,
overflows are less likely to happen. On the other hand, we also do not
want the eviction cost to be too expensive. Therefore, another tricky
issue is how we can design an eviction algorithm that achieves the
best of both worlds: with a small number of eviction operations, we
want to keep the probability of overflow very small
(technically: negligible in $N$).
#figure(image("binaryoram16-evict.png"),
caption: [
The `Evict` algorithm. Upon every data access operation, 2 buckets
are chosen at every level of the tree for eviction during which one
data block will be evicted to one of its children. To ensure
security, a dummy eviction is performed for the child that does not
receive a block; further, if the bucket chosen for eviction is
empty, dummy evictions are performed on both child buckets. In
this figure, $R$ denotes a real eviction and $D$ denotes a dummy
eviction.
]
)
We describe a simple candidate eviction scheme, and we will give an
informal analysis of the scheme later:
- #emph[\[An eviction algorithm\]] Upon every data access, we choose
at random $2$ buckets in every level of the tree for eviction (for the
root level, pick one bucket). If a bucket is chosen for eviction, we
will pop an arbitrary block (if one exists) from the bucket, and write
the block to one of its children.
Note that depending on the chosen block’s designated path, there is only
one child where the block can legitimately go. We must take precautions
to hide where this block is going: thus for the remaining child that
does not receive a block, we can perform a "dummy" eviction.
Additionally, if the bucket chosen for eviction is empty (does not
contain any real blocks), then we make a dummy eviction for both
children — this way we avoid leaking the information that the chosen
bucket is empty.
More specifically, to write an intended block to a child bucket, we
sequentially scan through the child bucket. If the slot is occupied with
a real block, we simply write the block back. If the slot is empty, we
write the intended block into that slot. A dummy eviction therefore is
basically reading every block sequentially and writing the original
contents back.
So far, we have not argued why any bucket that receives a block always
has space for this block — we will give an informal analysis later to show
that this is indeed the case.
== Algorithm pseudo-code
<algorithm-pseudo-code.>
We present the algorithm’s pseudo-code in Algorithms~@alg:access and
@alg:evict.
#algorithm[
The procedure $mono("Access")(mono("op"), mono("addr") , mono("data")^(\*))$
where $mono("op") = mono("read")$ or $mono("op") = mono("write")$
#strong[Assume:] each block is of the form
$(mono("addr") , mono("data") , l)$ where $l$ denotes the block’s
current designated path.
1.
Let $l^(\*)$ be a random value from $1$ to $N$.
Assign
$l arrow.l mono("position")[mono("addr")]$,
$mono("position")[mono("addr")] arrow.l l^(\*)$.
2. For each bucket from leaf $l$ to root do:
3. Scan $mono("bucket")$, and if
$(mono("addr") , mono("data")_0 , \_) in mono("bucket")$ then let
$mono("data")^(\*) arrow.l mono("data")_0$ and remove this block from
$mono("bucket")$.
4. End for
5. If $mono("op") = mono("read")$ then add
$(mono("addr") , mono("data")^(\*) , l^(\*))$ to the root bucket; else
add $(mono("addr") , mono("data") , l^(\*))$ to the root bucket.
6. Call the $mono("Evict")$ subroutine.
7. Return $mono("data")^(\*)$.
]<alg:access>
#algorithm[
The procedure $mono("evict")$
1. For each level $d$ from the root to the level of leaves $-1$, do:
2. $mono("bucket")_0$, $mono("bucket")_1 arrow.l$
randomly choose $2$
distinct buckets in the level $d$ (for the root level, pick one bucket).
3. For $mono("bucket") in \{ mono("bucket")_0, mono("bucket")_1 \}$ do:
4. $sans("block") :=$ pop a real block from $sans("bucket")$ if one exists;
else $sans("block") := (tack.t , tack.t , tack.t)$.
5. For each of the two children of $mono("bucket")$ in a fixed order:
scan the child
bucket reading and writing every block.
If $sans("block")$ is real and
wants to go to the child, write $sans("block")$ to an empty slot in the
child bucket.
6. End for
7. End for
]<alg:evict>
#remark[
Note that in a full-fledged implementation, all
blocks are typically encrypted to hide the contents of the block.
Whenever reading and writing back a block, the block must be
re-encrypted prior to being written back. If the encryption scheme is
secure, the server should not be able to tell whether the block’s
content has changed upon seeing the new ciphertext.
]
= Analysis
<analysis>
We will now discuss why the aforementioned binary-tree ORAM construction
1) preserves obliviousness; and
2) is correct (except with negligible probability).
== Obliviousness
<obliviousness.>
Obliviousness is easy to see.
First, whenever a block is
accessed, it is assigned to a new path and the choice of the new path is
kept secret from the server. So whenever the block is accessed again,
the server simply sees a random path being accessed.
Second,
the entire eviction process does not depend on the input requests
at all.
== Correctness
<correctness.>
Correctness is somewhat trickier to argue. As mentioned earlier, to
argue correctness, we must argue why no overflow will ever occur except
with negligible probability — as long as the bucket size $Z$ is set
appropriately.
#claim[
(Bucket size and overflow probability). #emph[If the
bucket size $Z$ is super-logarithmic in $N$, then over any polynomially
many accesses, no bucket overflows except with negligible in $N$
probability. ]
] <clm:bucketsize>
#proof[
The full proof uses results from
#cite("https://en.wikipedia.org/wiki/Queueing_theory", "queueing theory"),
in particular
#cite("https://en.wikipedia.org/wiki/Burke%27s_theorem", "Burke's theorem").
We will give a heuristic argument that doesn't require
any specialized knowledge.
- The root bucket (level $0$ of the ORAM tree)
receives exactly $1$ incoming block with every access,
and it is evicted on every access,
so the root bucket always ends up empty.
- There are $N$ leaf buckets, and $N$ blocks are assigned to them at random.
We leave it as an exercise to check that
the probability that more than $(log N)^2$ blocks are assigned to any one leaf
is negligible than $N$
(in other words: decays faster than $N^k$, for every $k$).
- Now consider a bucket, neither root nor leaf,
at level $i gt.eq 1$ of the ORAM tree.
A block will enqueue on one out of every $2^i$ accesses,
and with probability $1 / 2^(i - 1)$, the bucket is
chosen for eviction.
So for every non-leaf and non-root level of
the tree, with every ORAM access, the dequeue probability is twice as
large as the enqueue probability.
This situation is well-known in queueing theory as the
"M/M/1 queue":
- Every time step, with probability $p$, an item enqueues;
- Every time step, with probability $2 p$, an item dequeues if the queue
is non-empty.
Since the bucket is drained (on average) twice as fast as it is filled,
we expect that it's very unlikely for a lot of blocks to accumulate
in any one bucket.
Indeed, one can prove an exponential bound on the probability
that any one bucket gets too full:
$ Pr [upright("number of items in queue") > R] lt.eq exp (Omega (- R)). $
Unfortunately, this doesn't quite finish our analysis of the ORAM tree.
The reason is that the buckets in the ORAM tree are not independent, and
our informal argument above ignored possible dependence between buckets.
It turns out that this gap can be filled using Burke's theorem.
But at this point the reader should already be convinced that
the result is at least quite plausible.
]
= Binary-Tree ORAM: Recursion
<binary-tree-oram-recursion>
So far, we have cheated and pretended that the client can store a large
position map. We now describe how to get rid of this position map. The
idea is simple: instead of storing the position map on the client side,
we simply store it in a smaller ORAM denoted $sans("posORAM")_1$ on the
server. The position map of $sans("posORAM")_1$ will then be stored in
an even smaller ORAM denoted $sans("posORAM")_2$ on the server, and so
on. As long as the block size is at least $Omega (log N)$ bits, every
time we recurse, the ORAM’s size reduces by a constant factor; and thus
$O (log N)$ levels of recursion would suffice.
We can thus conclude with the following theorem.
#theorem[
#cite("https://eprint.iacr.org/2011/407.pdf", "Binary-tree ORAM")
#emph[For any
super-constant function $alpha (dot.op)$, there is an ORAM scheme that
achieves $O (alpha log^3 N)$ cost for each access: each logical
request will translate to $O (alpha log^3 N)$ physical accesses; and
moreover, the client is required to store only $O (1)$ number of
blocks.]
]
Note that in the total cost $O (alpha log^3 N)$, an $alpha log N$ factor
comes from the bucket size; another $log N$ factor comes from the total
height of the tree; and the remaining $log N$ factors comes from the
recursion.
= Path ORAM
<path-oram>
The design of the above binary-tree ORAM is a little silly: whenever we
visit a triplet of buckets for eviction, we only evict one block. For
this reason, the bucket size needs to be super-logarithmic to get
negligible failure probability.
It turns out that if we instead use a more aggressive eviction
algorithm, and with a more sophisticated proof, the bucket size can be
made constant. At this point, we are ready to introduce an improved
version called Path ORAM.
Unlike the above binary-tree ORAM, in Path ORAM, every bucket has
constant size (maybe 4 or 5), except the root bucket which is
super-logarithmic in size. Every time we access some path to fetch a
block, we also perform eviction on the same path. In particular, we will
rearrange the blocks on the path in the most aggressive manner possible:
we want to move the blocks as close to the leaf level as possible, but
#emph[without violating the path invariant];. With Path ORAM, every
access operation touches a single path, hence the name Path ORAM.
The cost of each access is $O (alpha log^2 N)$ for an
arbitarily small superconstant function $alpha$.
== Other Applications of ORAM
<other-applications-of-oram>
ORAM promises many potential applications. For instance, in Large
Language Models (LLMs), a commonly used technique is called Retrieval
Augmented Generation (RAG). RAG parses the user’s query and looks up the
relevant locations in a large knowledge base to fetch the relevant
entries. If we want to protect the privacy of users’ queries in LLMs, it
is also crucial to hide the access patterns, and this would be a great
application of ORAM.
Besides its usage in secure processors, ORAM is critical for scaling
cryptographic multi-party computation (MPC) to big data. Traditional MPC
techniques require us to express the desired computation as a circuit.
However, in the real-world, we program assuming the Random Access
Machine (RAM) model where a CPU can dynamically read and write a memory
array. Translating a RAM program to a circuit brute-force would incur a
linear (in the memory size) cost for each memory access! For example, a
binary search in a sorted database requires only logarithmic time on a
RAM, but it requires linear cost when expressed as a circuit.
Fortunately, ORAM again comes to our rescue. There is a line of work on
RAM-model MPC, and the idea is that we first translate the RAM to an
oblivious RAM, and at this point all the memory accesses are safe to
reveal. At this moment, we can use MPC to securely emulate a "secure
processor" that performs computation while accessing memory obliviously.
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/call_info/user_named_with.typ | typst | Apache License 2.0 | #let f(x, y: none) = x + y
#let g = f.with(y: 1)
#(/* position after */ g(1)) |
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/compiler/weeks/week4.typ | typst | #import "../../utils.typ": *
#section("Syntax based translation")
- Annotations for syntax rules
- attributes for symbols
- semantic rules per syntax rule
- semantic actions inside of syntax rules
- usage: additional actions during parsing
- type checks
- generate syntax tree
- code-generation
- direct evaluation
- limitations
- only really used for parsing of syntax-tree
- very complex and convoluted
#subsection("Example")
You can define rules with this, which have to adhere to a certain rule, here the
numbers always have to match according to mathematical rules.
#columns(2, [
#align(
center,
[#image("../../Screenshots/2023_10_09_08_30_31.png", width: 100%)],
)
#colbreak()
#align(
center,
[#image("../../Screenshots/2023_10_09_08_27_51.png", width: 100%)],
)
])
#section("Parser Categories")
#align(
center,
[#image("../../Screenshots/2023_10_09_08_41_34.png", width: 30%)],
)
- First Letter: L -> left to right
- Second Letter: L -> Top-Down Parser, R -> Bottom-Up Parser
- Third Letter: k -> how many symbols are looked ahead -> LL(1) would be the
parser for the module
#section("Bottom-Up Parser")
- read token without fixed goal
- check with each step if read tokens can be reduced into an EBNF-rule
- reduce if possible or continue reading if not
- at the end 1 last symbol remains, the starting symbol, otherwise syntax error
#columns(2, [
#text(green)[Benefits]
- more powerful than LL(k) parser -> left-recursion easy
#align(
center,
[#image("../../Screenshots/2023_10_09_08_57_41.png", width: 100%)],
)
#colbreak()
#text(red)[Benefits]
- less performant
])
#subsection("Token actions")
Per token, you can have 4 different actions that you can take:
- SHIFT
- REDUCE
- ACCEPT
- ERROR
#subsection("Example")
Rules for the example:
#align(
center,
[#image("../../Screenshots/2023_10_09_08_55_27.png", width: 60%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_09_08_55_54.png", width: 100%)],
)
#subsection("Bottom-Up categories")
- LR(0)
- parse table without lookahead
- state must be enough to parse
- SLR(k) (Simple LR)
- lookahead on reduce to solve conflicts
- no new states
- LALR(k) (Look-Ahead LR)
- analyzes language based on LR(0) conflicts
- uses lookahead to solve conflicts with new states
- LR(k)
- per grammarstep + lookahead a new state
- not usable in production -> too many states
#subsection("LR Parser implementation")
1. change grammar
- into BNF
2. calculate state machine
- item, handle, closure, goto
3. build parse table
- FOLLOWS-Set
#subsubsection("Change Grammar")
#align(
center,
[#image("../../Screenshots/2023_10_09_09_03_31.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_09_09_03_57.png", width: 80%)],
)
#subsubsection("Calculate State Machine")
#subsubsubsection("Item")
#text(teal)[On which item are we currently?]
#align(
center,
[#image("../../Screenshots/2023_10_09_09_05_12.png", width: 80%)],
)
#subsubsubsection("Closure")
#text(teal)[What can possibly follow after the item?]
#align(
center,
[#image("../../Screenshots/2023_10_09_09_05_33.png", width: 80%)],
)
#subsubsubsection("Goto")
#text(teal)[How much do we move forward?]
#align(
center,
[#image("../../Screenshots/2023_10_09_09_06_18.png", width: 80%)],
)
#subsubsubsection("State Machine for example")
#align(
center,
[#image("../../Screenshots/2023_10_09_09_11_16.png", width: 100%)],
)
#subsubsubsection("Follows Set")
#text(
teal,
)[All possible terminal symbols that can follow after a non-terminal symbol.]
#align(
center,
[#image("../../Screenshots/2023_10_09_09_12_06.png", width: 80%)],
)
#subsubsubsection("Parse Table")
#align(
center,
[#image("../../Screenshots/2023_10_09_09_13_09.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_09_09_15_33.png", width: 100%)],
)
- very complicated
- conflicts possible
- shift-reduce conflicts
- reduce-reduce conflicts
- possibly change grammar to solve conflicts
- use bigger lookaheads
#subsubsubsection("AntLR4 for smallj")
#align(
center,
[#image("../../Screenshots/2023_10_09_09_18_55.png", width: 60%)],
)
#subsection("LR vs LL in usage")
#align(
center,
[#image("../../Screenshots/2023_10_09_09_17_13.png", width: 60%)],
)
Powerfulness:
#align(
center,
[#image("../../Screenshots/2023_10_09_09_18_00.png", width: 60%)],
)
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/document_highlight/base.typ | typst | Apache License 2.0 | #for i in range(0) {
(/* position after */break)
} |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-circle_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test auto sizing.
#set circle(inset: 0pt)
Auto-sized circle.
#circle(fill: rgb("eb5278"), stroke: 2pt + black,
align(center + horizon)[But, soft!]
)
Center-aligned rect in auto-sized circle.
#circle(fill: forest, stroke: conifer,
align(center + horizon,
rect(fill: conifer, inset: 5pt)[But, soft!]
)
)
Rect in auto-sized circle.
#circle(fill: forest,
rect(fill: conifer, stroke: white, inset: 4pt)[
#set text(8pt)
But, soft! what light through yonder window breaks?
]
)
Expanded by height.
#circle(stroke: black, align(center)[A \ B \ C])
|
https://github.com/Midoria7/ComputerNetworkLab2 | https://raw.githubusercontent.com/Midoria7/ComputerNetworkLab2/main/template.typ | typst | // The project function defines how your document looks.
// It takes your content and some metadata and formats it.
// Go ahead and customize it to your liking!
#let chineseNumMap(num) = {
let chineseNum = (
"一", "二", "三", "四", "五", "六", "七", "八", "九", "十",
"十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
"二十一", "二十二", "二十三", "二十四", "二十五", "二十六", "二十七", "二十八", "二十九", "三十",
"三十一", "三十二", "三十三", "三十四", "三十五", "三十六", "三十七", "三十八", "三十九", "四十",
)
chineseNum.at(num - 1)
}
#let project(title: "", authors: (), body) = {
// Set the document's basic properties.
// set page(margin: 1.75in)
set par(leading: 1.2em, first-line-indent: 2em, justify: true)
// set text(font: "New Computer Modern")
show raw: set text(font: ("Fira Code Retina", "Source Han Serif"), lang: "zh")
show par: set block(spacing: 1.2em)
show heading: set block(above: 1.4em, below: 1em)
set document(author: authors, title: title)
set page(numbering: "1", number-align: center)
set text(font: ("Source Han Serif"), lang: "zh")
show math.equation: set text(weight: 400)
set heading(numbering: "1.1")
show heading: it=>{
if it.level == 1 {
pagebreak(weak: true)
set align(center)
if it.body != [参考文献] {
counter(heading).display("第一章 ")
}
it.body
} else if it.level == 2 {
it
} else {
counter(heading).display()
it.body
parbreak()
}
// if it.level == 2 {
// text()[#v(0.3em, weak: true)]
// text()[#h(0em)]
// }
}
show outline: it => locate(loc => {
set par(first-line-indent: 0em)
let chapterCounter = 1
let sectionCounter = 1
let subsectionCounter = 1
let headingList = query(selector(heading).after(loc), loc)
for i in headingList {
if i.outlined == false {
break
}
if i.level == 1 {
if i.body != [参考文献]{
strong([第#chineseNumMap(chapterCounter)章#h(1em)])
}
strong([#i.body #box(width: 1fr, repeat[.]) #counter(page).at(i.location()).at(0)\ ])
chapterCounter = chapterCounter + 1
sectionCounter = 1
} else if i.level == 2 {
strong([#h(1em)#calc.abs(chapterCounter - 1)\.#sectionCounter#h(1em)#i.body #box(width: 1fr, repeat[.]) #counter(page).at(i.location()).at(0)\ ])
sectionCounter += 1
subsectionCounter = 1
} else if i.level == 3 {
[#h(2em)#calc.abs(chapterCounter - 1)\.#calc.abs(sectionCounter - 1)\.#subsectionCounter#h(1em)#i.body #box(width: 1fr, repeat[.]) #counter(page).at(i.location()).at(0)\ ]
subsectionCounter += 1
}
}
})
// Title row.
align(center)[
#block(text(weight: 700, 1.75em, title))
]
// Author information.
pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center, strong(author))),
),
)
// Main body.
// set par(justify: true)
body
} |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/gviz/0.1.0/README.md | markdown | Apache License 2.0 | # GViz
GViz is a typst plugin that can render graphviz graphs.
It uses https://codeberg.org/Sekoia/layout as a backend, which means it can currently only render to SVG, and mostly supports basic features.
Import it like any other plugin: `#import "@preview/gviz:0.1.0": *`.
## Usage
```typst
#import "@preview/gviz:0.1.0": *
#show raw.where(lang: "dot-render"): it => render-image(it.text)
```dot-render
digraph mygraph {
node [shape=box];
A -> B;
B -> C;
B -> D;
C -> E;
D -> E;
E -> F;
A -> F [label="one"];
A -> F [label="two"];
A -> F [label="three"];
A -> F [label="four"];
A -> F [label="five"];
}```
#let my-graph = "digraph {A -> B}"
#render-image(my-graph)
SVG:
#raw(render(my-graph), block: true, lang: "svg")
```
## API
### render
Renders a graph in dot language and returns SVG code for it.
Parameters:
- code (string, bytes): Dot language code to be rendered.
Returns: string
### render-image
Renders a graph in dot language and returns an SVG image of it. Uses the same parameters as image.decode.
Parameters:
- code (string, bytes): Dot language code to be rendered.
- width (auto, relative): The width of the image.
- height (auto, relative): The height of the image.
- alt (none, string): A text describing the image.
- fit (string): How the image should adjust itself to a given area. See image.decode.
Returns: content |
https://github.com/maxgraw/bachelor | https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/1-introduction/0-index.typ | typst | Diese Arbeit befasst sich mit der Konzeption und Entwicklung einer Augmented Reality Konstruktionsumgebung für Möbelsysteme basierend auf WebXR. Im folgenden Kapitel werden die Motivation und das Ziel der Arbeit erläutert. Anschließend wird die Vorgehensweise beschrieben.
== Motivation
#include "motivation.typ"
== Ziel
#include "goal.typ"
== Vorgehensweise
#include "method.typ" |
|
https://github.com/adeshkadambi/ut-thesis-typst | https://raw.githubusercontent.com/adeshkadambi/ut-thesis-typst/main/1-introduction.typ | typst | MIT License | = Introduction
#lorem(25)
== Sub-heading
#lorem(20)
We derived a cool thing in @app1.
#v(0.5em)
#figure(
table(columns: 2)[A][B][C][D],
caption: [This is a simple table.],
)
#v(-0.5em)
=== Sub-sub-heading
#lorem(10) @Kadambi2023-iv
#lorem(20) (@circle).
#figure(
circle(),
caption: [This is a circle],
) <circle> |
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/AnalisiDeiRequisiti/meta.typ | typst | MIT License | #let title = "Analisi dei requisiti" |
https://github.com/tiankaima/typst-notes | https://raw.githubusercontent.com/tiankaima/typst-notes/master/feebf7-2023_fall_TA/lectures/lecture_1.typ | typst | #import "../utils.typ": *
= Lecture 1
```plain
Time: Week 2, 9.11 Mon
```
== 数域扩张
$
NN =>^("减法") ZZ =>^("除法") QQ =>^("极限") RR =>^("二次方程") CC
$
#definintion(name: $ZZ$)[
$
ZZ := {0} union NN^+ union (NN^-) \
NN^- := {-n | n in NN^+}
$
]
#definintion(name: $QQ$)[
$
QQ := {a / b | a,b in ZZ, b !=0}
$
]
#caption[
- $NN$的严格定义依赖Peano公理, 移步 $=>$ @peano, 这门课不做要求.
- $QQ$是可数集, 移步 $=>$ @QQ.countable, 这门课不做要求.
]
== $RR$
#homework[
$sqrt(2)$是无理数
]
常用的构造$RR$的方法有, 后两者均不要求掌握:
- 十进制小数
- Dedekind 分割
- Cauchy 列
=== 十进制小数
$
a_0.a_1a_2...=sum_(k=0)^infinity a_k / 10^k
$
=== Dedekind分割
这样构造核心是「分割」$QQ$, 将其分割为$A, B$, 满足:
- $Q = A union B$
- $A sect B = emptyset$ (_这点可忽略,直接要求第三条_, Why?)
- $forall a in A, forall b in B => a < b$
#caption[
请注意, Dedekind分割并不需要在无理数($RR without QQ$) 处分割, 分割出的也并不必然是无理数, 课堂上似乎传递了这样的误解, 例如:
$
A := {x in QQ | x < 0}, quad B := {x in QQ | x >= 0}
$
这样的分割并不是不能表示一个无理数.
]
这样分割的结果会有如下三种可能:
- 在$QQ$中$A$有最大数, $B$无最小数
- 在$QQ$中$A$无最大数, $B$有最小数
- *在$QQ$中$A$无最大数, $B$无最小数*
- #strike[在$QQ$中$A$有最大数, $B$有最小数], 不存在, Why?
我们说:
- 在前面这两种情况下, 我们说这个分割定义了一个有理数.
- 第三种情况下, 我们说这个分割定义了一个无理数$alpha$.
此时, 向$A$或者$B$中任一添加这个$alpha$, 都会让$QQ$更加「完备」.
- 我们把所有有理数的分割的的集合称为实数集, 记作$RR$. 每个分割都对应一个实数.
#caption[
我们在这里展开讨论 Dedekind 分割的一个经典例子, 这一点似乎让很多同学有困惑:
$
A&:={x in QQ | x>0 and x^2 < 2} union {x<0}\
B&:={x in QQ | x>0 and x^2 >2}
$
我们说明:$A$中不存在最大数:
#proof[
若存在最大数 $p^2<2 (p>0)$, 构造
$
q:= p + (2-p^2) / (p+2) = (2+2p) / (p+2)
$
容易说明: $q>p$, 同时 $q^2<2$ ,因此$A$中不存在最大数.
]
上文中提到, $sqrt(2)$不属于有理数, 因此这个 Dedekind 分割成功构造出了$sqrt(2)$这个无理数.
]
=== Cauchy列
用收敛数列的极限来定义实数, 例如
$
a_1 in QQ, quad a_1>sqrt(2), quad a_(n+1) = 1 / 2 (a_n + 2 / a_n) \
=> forall n, quad a_n in QQ, quad lim_(n->infinity) a_n = sqrt(2)
$
#caption[
这个例子说明:有理数的极限未必是有理数, 上面Dedekind的例子中也说明了这一点, 可以通过构造
$
cases(
a_(n+1) = (2 + 2a_n)/(a_n + 2),
a_0 = 1
)
$来得到一个单调递增, 收敛到$sqrt(2)$的数列.
从这个意义上说,$RR$是在$QQ$上引入极限运算的结果,实数可以定义为有序完备域.
]
#pagebreak()
== 一些问题
=== 补充知识
补充一些这门课可能用的记号和它们的`LaTeX`代码作为参考.
#grid(
columns: (1fr, 1fr),
table(
columns: (auto, auto, auto),
stroke: none,
[符号],
[说明],
[`LaTeX`],
$NN$,
[自然数],
`\mathbb{N}`,
$ZZ$,
[整数],
`\mathbb{Z}`,
$QQ$,
[有理数],
`\mathbb{Q}`,
$RR$,
[实数],
`\mathbb{R}`,
$CC$,
[复数],
`\mathbb{C}`,
$forall$,
[任意],
`\forall`,
$exists$,
[存在],
`\exists`,
$exists!$,
[唯一存在],
`\exists!`,
$subset$,
[子集],
`\subset`,
$subset.neq$,
[真子集],
`\subsetneq`,
$union$,
[并集],
`\cup`,
$sect$,
[交集],
`\cap`,
$without$,
[差集],
`\setminus`,
$union.plus$,
[并集(不相交)],
`\dot{\cup}`,
$in$,
[属于],
`\in`,
$in.not$,
[不属于],
`\notin`,
),
table(
columns: (auto, auto, auto),
stroke: none,
[符号],
[说明],
[`LaTeX`],
$arrow.r.double$,
[蕴含],
`\implies`,
$arrow.l.r.double$,
[等价],
`\iff`,
$arrow.tr$,
[单调递增],
`\nearrow`,
$arrow.br$,
[单调递减],
`\searrow`,
$arrow.r.long.bar$,
[映到],
`\mapsto`,
$eq.def$,
[定义为],
`\triangleq`,
$colon.eq$,
[定义为],
`:=`,
$tilde$,
[等价],
`\sim`,
$and$,
[与],
`\wedge`,
$or$,
[或],
`\vee`,
$prop$,
[成正比],
`\propto`,
$Sigma$,
[求和],
`\sum`,
$Pi$,
[求积],
`\prod`,
$qed$,
[证毕],
`\qed`,
$infinity$,
[无穷],
`\infty`,
),
)
#caption[
掌握这些符号后,请在证明中减少不必要的语言描述,直接使用符号表达即可.
在高中时可能更习惯使用这样的写法:
$
because "statement A" \
therefore "statement B"
$
但在今后的课程作业/考试中,请使用这样的写法:
$
"statement A" => "statement B"
$
更多内容会在习题课上进行说明.
]
=== 归纳法
#statement[
对于一个列命题 ${S_n}$ (其中每个元素$S_i$都是一个命题), 如果能说明:
- $S_1$成立
- $S_n => S_(n+1)$
则可以说明$forall n$, 命题$S_n$都成立.
]
有时这样的「命题列」的编号, 会跟题目中数列的编号出现混淆, 我们使用群里提出的一道题目来说明这个问题:
#homework[
$a_1, a_2, ..., a_n (n>=2)$都是正数且$a_1 + a_2 + ... + a_n < 1$,求证:
$
product_(k=1)^n (1+a_k) > 1 + sum_(k=1)^n a_k
$
]
一个很有价值的问题是, 如果在这里使用归纳法, 从$n$推向$n+1$时, 是否还能说明$a_1 + ... a_(n+1)<1$?因为我们只知道前$n$项和小于$1$, 但是不知道第$n+1$项的大小.
这里的问题就在于混淆了命题跟数列编号的问题, 按照「命题列」的思路, 我们来给出第$S_n$个命题的准确定义:
$
forall {a_k}_(k=1)^n quad sum_(k=1)^n a_k < 1 => product_(k=1)^n (1+a_k) > 1 + sum_(k=1)^n a_k
$
混用符号会导致混乱, 我们把$S_(n+1)$的定义用${b_n}$写出来:
$
forall {b_k}_(k=1)^(n+1) quad sum_(k=1)^(n+1) b_k < 1 => product_(k=1)^(n+1) (1+b_k) > 1 + sum_(k=1)^(n+1) b_k
$
在$S_(n+1)$的命题中, 一般情况下并不能自然的得到前$n$项直接套用$S_n$中的结论, 只不过这里:
$
b_1 +... + b_n < (b_1 + ... +b_n) + b_(n+1) < 1
$
进而这里的${b_k}_(k=1)^n$(前$n$项)自然符合$S_n$中的${a_n}$的要求, 进而可以使用$S_n$的结论.事实上甚至可以对${b_k}_(k=2)^(n+1)$(后$n$项)使用$S_n$的结论.
=== 邻域
#caption[
后续课程中会经常遇到以一点为中心的开区间, 或去掉这点本身的开区间, 分别称为这点的邻域和去心邻域.
$
U(a, delta) &:= (a-delta, a+delta) \
U^compose (a,delta) &:= (a-delta, a) union (a, a+delta)
$
]
#pagebreak() |
|
https://github.com/typst-jp/typst-jp.github.io | https://raw.githubusercontent.com/typst-jp/typst-jp.github.io/main/docs/changelog/0.6.0.md | markdown | Apache License 2.0 | ---
title: 0.6.0
description: Changes in Typst 0.6.0
---
# Version 0.6.0 (June 30, 2023)
## Package Management
- Typst now has built-in [package management]($scripting/#packages)
- You can import [published]($universe) community packages or create and use
[system-local](https://github.com/typst/packages#local-packages) ones
- Published packages are also supported in the web app
## Math
- Added support for optical size variants of glyphs in math mode
- Added argument to enable [`limits`]($math.limits) conditionally depending on
whether the equation is set in [`display`]($math.display) or
[`inline`]($math.inline) style
- Added `gt.eq.slant` and `lt.eq.slant` symbols
- Increased precedence of factorials in math mode (`[$1/n!$]` works correctly
now)
- Improved [underlines]($math.underline) and [overlines]($math.overline) in math
mode
- Fixed usage of [`limits`]($math.limits) function in show rules
- Fixed bugs with line breaks in equations
## Text and Layout
- Added support for alternating page [margins]($page.margin) with the `inside`
and `outside` keys
- Added support for specifying the page [`binding`]($page.binding)
- Added [`to`]($pagebreak.to) argument to pagebreak function to skip to the next
even or odd page
- Added basic i18n for a few more languages (TR, SQ, TL)
- Fixed bug with missing table row at page break
- Fixed bug with [underlines]($underline)
- Fixed bug superfluous table lines
- Fixed smart quotes after line breaks
- Fixed a crash related to text layout
## Command line interface
- **Breaking change:** Added requirement for `--root`/`TYPST_ROOT` directory to
contain the input file because it designates the _project_ root. Existing
setups that use `TYPST_ROOT` to emulate package management should switch to
[local packages](https://github.com/typst/packages#local-packages)
- **Breaking change:** Now denies file access outside of the project root
- Added support for local packages and on-demand package download
- Now watches all relevant files, within the root and all packages
- Now displays compilation time
## Miscellaneous Improvements
- Added [`outline.entry`]($outline.entry) to customize outline entries with show
rules
- Added some hints for error messages
- Added some missing syntaxes for [`raw`] highlighting
- Improved rendering of rotated images in PNG export and web app
- Made [footnotes]($footnote) reusable and referenceable
- Fixed bug with citations and bibliographies in [`locate`]
- Fixed inconsistent tense in documentation
## Development
- Added [contribution guide](https://github.com/typst/typst/blob/main/CONTRIBUTING.md)
- Reworked `World` interface to accommodate for package management and make it a
bit simpler to implement _(Breaking change for implementors)_
## Contributors
<contributors from="v0.5.0" to="v0.6.0" />
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/text/emoji.typ | typst | Apache License 2.0 | // Test emoji shaping.
---
// This should form a three-member family.
👩👩👦
// This should form a pride flag.
🏳️🌈
// Skin tone modifier should be applied.
👍🏿
// This should be a 1 in a box.
1️⃣
---
// These two shouldn't be affected by a zero-width joiner.
🏞🌋
|
https://github.com/eneoli/kit-thesis-template | https://raw.githubusercontent.com/eneoli/kit-thesis-template/main/common/cover.typ | typst | #import "../meta.typ": *
#set page(
margin: 30pt,
)
#rect(
width: 100%,
height: 95%,
radius: (
top-right: 15pt,
bottom-left: 15pt,
),
stroke: rgb("#8a8a8a") + 1pt,
inset: 20pt, [
#grid(
columns: (auto),
rows: (auto),
[#image("../assets/Logo_KIT.png", width: 115pt)],
)
#pad(top: 75pt)[
#align(center)[
#block(width: 75%)[
#text(font: "Liberation Sans", weight: "bold", size: 24pt)[#title]
]
]
]
#pad(top: 45pt)[
#align(center)[
#block(width: 50%)[
#text(size: 12pt)[#thesisType #linebreak() of]
]
]
]
#pad(top: 30pt)[
#align(center)[
#text(font: "Liberation Sans", weight: "bold", size: 18pt)[#author]
]
]
#pad(top: 30pt)[
#align(center)[
#text(size: 12pt)[
at the Department of #department#linebreak()#institute
]
]
]
#pad(top: 120pt)[
#align(center,
[#grid(
columns: (auto, auto),
rows: (auto),
align: (left, left),
gutter: (10pt, 15pt, 10pt, 15pt, 10pt, 15pt),
[#text(size: 12pt)[First examiner:]],
[#text(size: 12pt)[#reviewerOne]],
{ if reviewerTwo != none [#text(size: 12pt)[Second examiner:]] },
{ if reviewerTwo != none [#text(size: 12pt)[#reviewerTwo]] },
[#text(size: 12pt)[First advisor:]],
[#text(size: 12pt)[#advisorOne]],
{ if advisorTwo != none [#text(size: 12pt)[Second advisor:]] },
{ if advisorTwo != none [#text(size: 12pt)[#advisorTwo]] },
)]
)
]
]
)
#block(inset: 5pt)[
#text(
font: "Liberation Sans",
size: 8pt
)[KIT – The Research University in the Helmholtz Association #h(1fr)] #text(font: "Liberation Sans", weight: "bold", size: 22pt)[www.kit.edu]
] |
|
https://github.com/Ngan-Ngoc-Dang-Nguyen/thesis | https://raw.githubusercontent.com/Ngan-Ngoc-Dang-Nguyen/thesis/main/docs/upgrading.typ | typst | // trích bài báo Up- down grading the 1-median in a network Gassner
// #text(orange)[*Bài toán nâng cấp 1-median*]
#include "../tools/multi-section-ref.typ"
#import "../tools/macros.typ": eqref
#import "../typst-orange.typ": theorem, proof, lemma, proposition, corollary, example
#import "@preview/cetz:0.1.2": canvas, plot
#import "@preview/cetz:0.1.2"
Mục tiếp theo, ta sẽ xem xét một lớp bài toán khác được gọi là bài toán nâng cấp.
== BÀI TOÁN NÂNG CẤP 1-MEDIAN TRÊN CÂY
Giả sử một thành phố có mạng lưới các con đường nối liền các quận với nhau, với một bến xe buýt trung tâm đặt tại quận A - vị trí được chọn làm điểm trung chuyển tối ưu để người dân dễ dàng di chuyển tới các khu vực khác. Tuy nhiên, theo thời gian, khi dân số tăng lên và lưu lượng giao thông trở nên quá tải, việc di chuyển từ các quận tới quận A ngày càng mất nhiều thời gian, gây ra tình trạng tắc nghẽn và phiền toái.
Trong bối cảnh đó, thành phố đối mặt với thách thức lớn: ngân sách hạn chế không cho phép xây dựng lại hoàn toàn mạng lưới đường sá hay thay đổi vị trí của bến xe buýt trung tâm. Do vậy, giải pháp khả thi nhất là nâng cấp một số tuyến đường hiện có - có thể là mở rộng đường, nâng cao chất lượng cơ sở hạ tầng hoặc giảm tải giao thông ở những tuyến trọng điểm - nhưng vẫn phải đảm bảo không vượt quá giới hạn ngân sách.
Mục tiêu của việc nâng cấp này là làm sao giảm thiểu thời gian di chuyển trung bình của người dân từ các quận khác đến bến xe buýt tại quận A, giúp giao thông trở nên thuận tiện và hiệu quả hơn. Đây chính là một ví dụ cơ bản của bài toán nâng cấp, trong đó thành phố cố gắng tối ưu hóa hệ thống giao thông hiện tại thay vì xây dựng lại từ đầu, nhằm đạt được hiệu quả cao nhất trong giới hạn chi phí có sẵn.
Nói tóm lại, bài toán nâng cấp khác với các bài toán vị trí cổ điển. Các bài toán vị trí cổ điển vốn tập trung vào việc xác định vị trí tối ưu cho các cơ sở hạ tầng. Trong khi đó, bài toán nâng cấp tập trung vào việc điều chỉnh và nâng cấp mạng lưới cơ sở hạ tầng trong các giới hạn cho phép, nhằm tối ưu hóa kết quả trên mạng lưới đã thay đổi.
Luận văn này sẽ tập trung vào bài toán nâng cấp 1-median, trong đó mục tiêu là tối ưu hóa mạng lưới hiện có bằng cách điều chỉnh trọng số của các đỉnh trong một giới hạn cho phép. Quá trình nâng cấp phải đảm bảo tuân thủ các ràng buộc ngân sách tuyến tính, tức là việc phân bổ chi phí phải nằm trong mức ngân sách đã định. Bên cạnh việc phân tích chi tiết bài toán, luận văn cũng sẽ trình bày lại giới một thuật toán có độ phức tạp thời gian $O(n^2)$ đã được *Gassner* tìm ra, giúp giải quyết hiệu quả bài toán này trong thực tế.
// Giả sử một công ty có kế hoạch mở một nhà máy mới với sức chứa $B$. Hiện tại, công ty có $n$ kho hàng, mỗi kho có sức chứa $w_i$ với $i=1,...,n$, (và tổng lượng nguyên liệu thô tại nhà máy là $sum_(i=1)^n w_i$). Công ty muốn xác định số lượng nguyên liệu lưu trữ tại mỗi kho cũng như vị trí tối ưu để đặt nhà máy nhằm giảm thiểu tổng chi phí vận chuyển từ các kho đến nhà máy.
// Ứng dụng này có thể được mô hình hóa bằng bài toán nâng cấp 1-median, trong đó nhiệm vụ là thay đổi trọng số của các đỉnh (ở đây là sức chứa của mỗi kho) trong các giới hạn nhất định (nhà máy có thể nhận tối đa _B_ đơn vị) sao cho tổng chi phí vận chuyển đến vị trí của nhà máy được giảm thiểu. Do đó, bài toán này không cố định một vị trí và cải thiện tối đa chất lượng của nó bằng cách thay đổi trọng số đỉnh, mà thay vào đó, nó thực hiện hai bước: đầu tiên là thay đổi trọng số đỉnh và sau đó xác định vị trí tối ưu dựa trên các trọng số mới. Hay nói một cách cụ thể hơn, trong bài toán nâng cấp 1-median, ta phải thay đổi các tham số của mạng trong những giới hạn nhất định sao cho giá trị hàm mục tiêu 1-median tối ưu được giảm thiểu.
// Các bài toán nâng cấp có mối liên hệ chặt chẽ với các bài toán ngược (reverse), trong đó một nghiệm khả thi được cho trước và nhiệm vụ là thay đổi các tham số trong một số giới hạn nhất định để tối đa hóa giá trị mục tiêu của nghiệm khả thi đó. Ngoài ra, các bài toán ngược (inverse) cũng thuộc loại bài toán sửa đổi mạng, trong đó một nghiệm khả thi đã được cho trước. Tuy nhiên, ở đây nhiệm vụ là thay đổi các tham số trong một số giới hạn nhất định với chi phí tối thiểu để nghiệm khả thi đã cho trở thành nghiệm tối ưu đối với các tham số đã được sửa đổi. Các bài toán xác định vị trí ngược đã được nghiên cứu trong [6, 7, 12]. (xem bài của Gassner)
//Trong bài báo này, chúng tôi xem xét một biến thể của bài toán 1-median, trong đó mạng được sửa đổi trước khi cơ sở được đặt trên mạng. Các bài toán nâng cấp và hạ cấp có thể được xem như các bài toán hai cấp độ, trong đó một người ra quyết định (người hành động) thay đổi trọng số đỉnh trong một số giới hạn nhất định và một người ra quyết định khác (nhà lập kế hoạch vị trí hoặc người phản ứng) định vị cơ sở một cách tối ưu dựa trên các trọng số đỉnh mới. Mục tiêu của nhà lập kế hoạch vị trí là tối thiểu hóa giá trị mục tiêu 1-median. Tùy thuộc vào việc mục tiêu của người hành động và người phản ứng có giống nhau hay mâu thuẫn với nhau, chúng ta sẽ nói về các bài toán nâng cấp hoặc hạ cấp. Trong phiên bản nâng cấp, người hành động muốn tối thiểu hóa giá trị mục tiêu 1-median (tức là, người hành động và người phản ứng có cùng mục tiêu), trong khi trong phiên bản hạ cấp, người hành động tìm cách tối đa hóa giá trị mục tiêu 1-median trong khi nhà lập kế hoạch vị trí muốn tối thiểu hóa giá trị này. Do đó, phiên bản hạ cấp là một bài toán max-min.
// == #text(orange)[CHƯƠNG 2: KIẾN THỨC CHUẨN BỊ]
=== Định nghĩa và giải thuật
// Để tiếp cận bài toán một cách hiệu quả, trước tiên chúng ta sẽ tóm tắt ngắn gọn vấn đề và sau đó xây dựng mô hình toán học của nó.
// Mô tả bài toán: Cho đồ thị $G$, mỗi đỉnh trên đồ thị được gán một trọng số không âm. Từ trọng số trên, ta có thể tìm được điểm 1-median và giá trị hàm mục tiêu đạt được tại điểm đó. Nhiệm vụ của bài toán nâng cấp là điều chỉnh trọng số đỉnh thỏa mãn các ràng buộc nhất định, sao cho giá trị hàm mục tiêu median được tối thiểu. Sau đây, ta sẽ tiến hành mô hình hóa bài toán.
Cho đồ thị $G=(V,E)$, có $n$ đỉnh, mỗi đỉnh được gán một trọng số không âm, gọi là $w_v$.
Gọi $f(w)$ là giá trị mục tiêu 1-median với vecto trọng số $w$. Mục tiêu của bài toán nâng cấp 1-median là điều chỉnh trọng số đỉnh bằng $delta= (delta_v)_(v in V)$ sao cho $delta$ thỏa mãn điều kiện ràng buộc về ngân sách $B$, giới hạn điều chỉnh $u$ và đồng thời $f(w- delta)$ nhỏ nhất.
Khi đó, bài toán nâng cấp 1-median được biểu diễn như sau:
$
min_(delta in Delta) f(w- delta) = min_(delta in Delta) min_(x in V) sum_(v in V) (w_v - delta_v) d(v,x) \
"s.t." sum_(v in V) c_v delta_v <= B \
0 <= delta_v <= u_v \
$
Hoán đổi hai phép lấy giá trị nhỏ nhất, ta được:
$
min_(x in V) min_(delta in Delta) sum_(v in V) (w_v - delta_v) d(v,x) \
"s.t." sum_(v in V) c_v delta_v <= B \
0 <= delta_v <= u_v \
$ <eq:42>
Khi cố định một $x in V$ bất kỳ, ta được một bài toán reverse 1-median. Mỗi bài toán reverse 1-median là một bài toán xếp ba lô liên tục được giải trong thời gian $O(n)$ (đã được trình bày ở mục trước). Do đó bài toán #eqref(<eq:42>) có thể được giải bằng cách giải $n$ bài toán xếp ba lô liên tục và sau đó so sánh các giá trị mục tiêu cải thiện.
#theorem[ Bài toán nâng cấp 1-median bằng cách thay đổi trọng số đỉnh có thể được giải trong thời gian $O(n^2)$.]
Ta kết thúc mục này bằng một ví dụ minh họa sau:
Cho đồ thị $G=(V,E)$ có trọng số đỉnh và cạnh như hình bên dưới. Trong đó:
#align(center)[#table(
columns: 4,
[$v$], [1], [2], [3],
[$c_v$], [1], [1], [1],
[$u_v$], [2], [2], [2]
)]
với ngân sách $B=2.$
#align(center)[#canvas(length: 7%, {
import cetz.draw: *
let y = 2
let x = 4
let y-space = 1
let h=1.4
circle((0*h,3), radius: 0.05,fill:black, name: "v2")
content("v2.top", $v_2 (1)$, anchor: "top", padding: 0.2)
circle((-4,3), radius: 0.05,fill:black, name: "v1")
content("v1.top", $v_1 (4)$, anchor: "top", padding: 0.2)
circle((4,3), radius: 0.05,fill:black, name: "v3")
content("v3.top", $v_3 (4)$, anchor: "top", padding: 0.2)
line("v1","v2")
line("v2","v3")
}
)]
Các giá trị hàm mục tiêu với trọng số ban đầu là $f(v_1)=f(v_3)=9$ và $f(v_2)=8$. Do đó, đỉnh $v_2$ là điểm 1-median.
Bây giờ, ta sẽ giải bài toán xếp ba lô liên tục khi cố định $v_1$. Ta thu được $ delta_1 = delta_2 = 0 $ và $ delta_3 = 2. $
Vì vậy, giá trị mục tiêu ứng với trọng số mới của đỉnh $v_1$ là $tilde(f)(v_1) = 5.$
Do tính đối xứng, ta cũng thu được $ delta_1 = 2 $ và $delta_2 = delta_3 = 0. $
Giá trị mục tiêu ứng với trọng số mới của đỉnh $v_3$ là $tilde(f)(v_3) = 5.$
Cuối cùng, cố định đỉnh $v_2$, giải bài toán xếp ba lô liên tục ta được $ delta_1 = delta_3 = 1 $ và $ delta_2 = 0. $
Do đó, giá trị mục tiêu sau khi cải thiện là $tilde(f)(v_2) = 6.$
vậy sau khi nâng cấp, đỉnh $v_1$ và $v_3$ có thể trở thành 1-median và giá trị mục tiêu đạt được là 5. Đồng thời, dẫn đến việc đỉnh $v_2$ không còn giữ được tính tối ưu của nó.
// Ký hiệu giá trị mục tiêu 1-median tối ưu với trọng số đỉnh $w$ là $f(w)$. Sau đó, nhiệm vụ của bài toán nâng cấp 1-median là tăng các trọng số bằng \( \delta = (\delta_v){v \in V} \) sao cho \( \delta \) là một sự thay đổi trọng số đỉnh khả thi và \( z(w - \delta) \) được tối thiểu hóa. Tương tự, bài toán hạ cấp 1-median là tìm một sự thay đổi trọng số khả thi \( \delta \) sao cho \( z(w + \delta) \) được tối đa hóa.
// Một sự thay đổi trọng số đỉnh \( \delta = (\delta_v){v \in V} \) được gọi là khả thi nếu một ràng buộc ngân sách được đáp ứng và các thay đổi nằm trong các giới hạn nhất định:
// - Gọi \( c_v \in \mathbb{R}^+ \) cho \( v \in V \) là chi phí thay đổi trọng số của đỉnh \( v \) một đơn vị.
// - Gọi \( u_v \in \mathbb{R}^+ \) cho \( v \in V \) là giới hạn trên cho việc thay đổi trọng số của đỉnh \( v \).
// - Hơn nữa, chúng ta được cung cấp tổng ngân sách \( B \).
// Sau đó, \( \delta \) là khả thi nếu \( \delta \in \Delta \) với ∆ = (δ vX∈V cvδv ≤ B and 0 ≤ δv ≤ uv for all v ∈ V )
// Do đó, chúng ta có thể định nghĩa các bài toán nâng cấp và hạ cấp như sau:
// Gọi \( G = (V, E) \) là một đồ thị với các trọng số đỉnh \( w_v \in \mathbb{R}^+ \), các hệ số chi phí \( c_v \in \mathbb{R}^+ \) và các giới hạn \( u_v \in \mathbb{R}^+ \) cho tất cả \( v \in V \), các độ dài cạnh \( \ell_e \in \mathbb{R}^+ \) cho tất cả \( e \in E \), và tổng ngân sách \( B \).
// Sau đó, bài toán nâng cấp 1-median, viết tắt là Up1Median, là để giải quyết:
// \[
// \min_{\delta \in \Delta} z(w - \delta) = \min_{\delta \in \Delta} \min_{x \in V} \sum_{v \in V} (w_v - \delta_v) d(v, x).
// \]
// Và bài toán hạ cấp 1-median, viết tắt là Down1Median, là để giải quyết:
// \[
// \max_{\delta \in \Delta} z(w + \delta) = \max_{\delta \in \Delta} \min_{x \in V} \sum_{v \in V} (w_v + \delta_v) d(v, x).
// \]
// Trong bài báo này, chúng tôi sẽ trình bày một thuật toán thời gian \( O(n^2) \) cho Up1Median với điều kiện ma trận khoảng cách được cho trước. Đối với Down1Median, một công thức lập trình tuyến tính được đưa ra. Do đó, Down1Median có thể được giải quyết trong thời gian đa thức. Nếu đồ thị cơ bản là một cây, một loại tính chất lõm có thể được chứng minh cho Down1Median, điều này dẫn đến một thuật toán thời gian \( O(n \log n) \).
// // == #text(orange)[Giải bài toán]
// == Giải bài toán
// Phần này dành riêng cho việc nâng cấp 1-median trong một đồ thị. Cho một đồ thị \( G = (V, E) \), trọng số đỉnh \( w_v \in \mathbb{R}^+ \), hệ số chi phí \( c_v \in \mathbb{R}^+ \) và các giới hạn \( u_v \leq w_v \in \mathbb{R}^+ \) cho tất cả \( v \in V \), độ dài cạnh \( \ell_e \in \mathbb{R}^+ \) cho tất cả các cạnh \( e \in E \) và một ngân sách \( B \), nhiệm vụ là giải quyết:
// \[
// \min_{\delta \in \Delta} \min_{x \in V} \sum{v \in V} (w_v - \delta_v)d(v, x)
// \]
// Vì chúng ta có thể hoán đổi hai phép toán tối thiểu đầu tiên, Down1Median tương đương với:
// \[
// \min_{x \in V} \min_{\delta \in \Delta} \sum{v \in V} (w_v - \delta_v) d(v, x)
// \]
// Điều này dẫn đến \( n \) bài toán reverse 1-median. Đối với mỗi đỉnh \( x \in V \), giá trị mục tiêu tương ứng của 1-median phải được cải thiện tối đa bằng một thay đổi trọng số khả thi. Cuối cùng, giá trị mục tiêu tốt nhất sau khi nâng cấp bằng với giá trị mục tiêu tối ưu của Up1Median. Mỗi bài toán reverse 1-median là một bài toán knapsack liên tục có thể được giải quyết trong thời gian \( O(n) \) (Balas và Zemel [1]). Do đó, Up1Median có thể được giải quyết bằng cách giải quyết \( n \) bài toán knapsack liên tục và cuối cùng so sánh các giá trị mục tiêu đã được cải thiện tối đa.
// Định lý 1. Nâng cấp 1-median bằng cách thay đổi trọng số đỉnh có thể được giải quyết trong thời gian \( O(n^2) \) với điều kiện ma trận khoảng cách được cung cấp.
// Chúng tôi kết thúc phần này với một ví dụ minh họa một số tính chất của Up1Median. Nói chung, 1-median thay đổi sau khi thay đổi trọng số tối ưu. Xét ví dụ sau đây của Up1Median được cho trong Hình 1 với \( B = 2 \).
// (vẽ hình)
// Các giá trị mục tiêu đối với các trọng số ban đầu là \( f(1) = f(3) = 9 \) và \( f(2) = 8 \). Do đó, đỉnh 2 là 1-median duy nhất. Bây giờ, cố định đỉnh 1 và cải thiện tối đa giá trị mục tiêu của nó. Khi đó \( \delta_1 = \delta_2 = 0 \) và \( \delta_3 = 2 \) là một cải thiện tối ưu và do đó giá trị mục tiêu mới của đỉnh 1 bằng \( \tilde{f}(1) = 5 \). Do đối xứng, \( \delta_1 = 2 \) và \( \delta_2 = \delta_3 = 0 \) là sự cải thiện tối ưu của đỉnh 3 với giá trị mục tiêu cải thiện \( \tilde{f}(3) = 5 \). Nếu đỉnh 2 được cải thiện tối đa thì \( \delta_1 = \delta_3 = 1 \) và \( \delta_2 = 0 \), và do đó giá trị mục tiêu cải thiện của đỉnh 2 là \( \tilde{f}(2) = 6 \). Như vậy, hoặc đỉnh 1 hoặc đỉnh 3 là 1-median sau khi thay đổi trọng số tối ưu, và do đó đỉnh 2 mất tính tối ưu của nó. |
|
https://github.com/DrGo/typst-tips | https://raw.githubusercontent.com/DrGo/typst-tips/main/refs/page-setup.md | markdown | ---
description: |
An in-depth guide to setting page dimensions, margins, and page numbers in
Typst. Learn how to create appealing and clear layouts and get there quickly.
---
# Page setup guide
A good page setup is the basis for every legible document. This guide will help
you to set up pages, margins, headers, footers, and page numbers to your heart's
content so you can get started with writing.
In Typst, each page has a width and a height, and margins on all four sides. The
top and bottom margin may contain a header and footer. The set rule of the
`page` element is where you control all of the page setup. If you make changes
with this set rule, Typst will ensure that there is a new and conforming empty
page afterwards, so it may insert a page break. Therefore, it is best to specify
your page set rule at the start of your document or in your template.
```example
#set rect(width: 100%, height: 100%)
#set page(
"iso-b7",
header: rect(),
footer: rect(),
number-align: top + center,
)
#rect(fill: rgb("#565565"))
```
This example visualizes the dimensions for page content, headers, and footers.
The page content is the page size (ISO B7) minus each side's default margin. In
the top and the bottom margin, there are stroked rectangles visualizing header
and footer. They do not touch the main content, instead they are offset by 30%
of the respective margin. You can control this offset by specifying
`header-ascent` and `footer-descent`.
Below, the guide will go more into detail on how to accomplish common page setup
requirements with examples.
## Customize page size and margins
Typst's default page size is A4 paper. Depending on your region and your
use-case, you will want to change this. You can do this by using the `page` set
rule and passing it a string argument to use a common page size. Options include
the complete ISO 216 series (e.g. `"iso-a4"`, `"iso-c2"`), customary US formats
like `"us-legal"` or `"us-letter"`, and more. Check out the reference for the
page size argument to learn about all available options.
```example
#set page("us-letter")
This page likes freedom.
```
If you need to customize your page size to some dimensions, you can specify the
named arguments `width` and `height` instead.
```example
#set page(width: 12cm, height: 12cm)
This page is a square.
```
### Change the page's margins
Margins are a vital ingredient for good typography: Typographers consider lines
that fit between 45 and 75 characters best length for legibility and your
margins help define line widths. By default, Typst will create margins
proportional to the page size for your document. To set custom margins, you will
use the `margin` argument in the `page` set rule.
The `margin` argument will accept a length if you want to set all margins to the
same width. However, you often want to set different margins on each side. To do
this, you can pass a dictionary:
```example
#set page(margin: (top: 3cm, bottom: 2cm, x: 1.5cm))
#lorem(100)
```
The page margin dictionary can have keys for each side (`top`, `bottom`, `left`,
`right`), but you can also control left and right together by setting the `x`
key of the margin dictionary, like in the example. Likewise, the top and bottom
margins can be adjusted together by setting the `y` key.
If you do not specify margins for all sides in the margin dictionary, the old
margins will remain in effect for the unset sides. To prevent this and set all
remaining margins to a common size, you can use the `rest` argument. For
example, `#set page(margin: (left: 1.5in, rest: 1in))` will set the left margin
to 1.5 inch and the remaining margins to one inch.
### Different margins on alternating pages
Sometimes, you'll need to alternate horizontal margins for even and odd pages,
for example to have more room towards the spine of a book than on the outsides
of its pages. Typst keeps track of whether a page is to the left or right of the
binding. You can use this information and set the `inside` or `outside` keys of
the margin dictionary. The `inside` margin points towards the spine, the
`outside` margin points towards the edge of the bound book.
```example
#set page(margin: (
inside: 2.5cm,
outside: 2cm,
y: 1.75cm,
))
```
Typst will assume that documents written in Left-to-Right scripts are bound on
the left while books written in Right-to-Left scripts are bound on the right.
However, you will need to change this in some cases: If your first page is
output by a different app, the binding is reversed from Typst's perspective.
Also, some books, like English-language Mangas are customarily bound on the
right, despite English using Left-to-Right script. To change the binding side
and explicitly set where `inside` and `outside` are, set the `binding` argument
in the `page` set rule.
```example
#set text(lang: "es")
// Produce a book bound on the right,
// even though it is set in Spanish.
#set page(binding: right)
```
If `binding` is `left`, `inside` margins will be on the left on odd pages, and
vice versa.
## Add headers and footers
Headers and footers are inserted in the top and bottom margin of every page. You
can add custom headers and footers or just insert a page number.
In case you need more than just a page number, the best way to insert a header
and a footer are the `header` and `footer` arguments of the `page` set rule. You
can pass any content as their values:
```example
#set page(header: [
_<NAME> Thesis_
#h(1fr)
National Academy of Sciences
])
```
Headers are bottom-aligned by default, so that they do not collide with the top
edge of the page. You can change this by wrapping your header in the `align`
function.
### Different header and footer on specific pages
You'll need different headers and footers on some pages. For example, you may
not want a header and footer on the title page. The example below shows how to
conditionally remove the header on the first page:
```example
#set page(
header: locate(loc => {
if (counter(page).at(loc).first() > 1) [
_Lisa Strassner's Thesis_
#h(1fr)
National Academy of Sciences
]
}),
)
```
This example may look intimidating, but let's break it down: We are telling
Typst that the header depends on the current location. The `loc` value allows
other functions to find out where on the page we currently are. We then ask
Typst if the page counter is larger than one at our current position. The page
counter starts at one, so we are skipping the header on a single page. Counters
may have multiple levels. This feature is used for items like headings, but the
page counter will always have a single level, so we can just look at the first
one.
You can, of course, add an `else` to this example to add a different header to
the first page instead.
### Adapt headers and footers on pages with specific elements
The technique described in the previous section can be adapted to perform more
advanced tasks using Typst's labels. For example, pages with big tables could
omit their headers to help keep clutter down. We will mark our tables with a
`<big-table>` label and use the query system to find out if such a label exists
on the current page:
```example
#set page(
header: locate(loc => {
let page-counter = counter(page)
let matches = query(<big-table>, loc)
let has-no-table = matches.all(m =>
page-counter.at(m.location()) !=
page-counter.at(loc)
)
if (has-no-table) [
_Lisa Strassner's Thesis_
#h(1fr)
National Academy of Sciences
]
}),
)
#lorem(100)
#pagebreak()
#table() <big-table>
```
Here, we query for all instances of the `<big-table>` label. We then check that
none of the tables are on the page at our current position. If so, we print the
header. This example also uses variables to be more concise. Just as above, you
could add an `else` to add another header instead of deleting it.
## Add and customize page numbers
Page numbers help readers keep track and reference your document more easily.
The simplest way to insert footnotes is the `numbering` argument of the page set
rule. You can pass a _numbering pattern_ string that shows how you want your
pages to be numbered.
```example
#set page(numbering: "1")
```
Above, you can check out the simplest conceivable example. It adds a single
Arabic page number at the center of the footer. You can specify other characters
than `"1"` to get other numerals. For example, `"i"` will yield lowercase Roman
numerals. Any character that is not interpreted as a number will be output
as-is. For example, put dashes around your page number by typing this:
```example
#set page(numbering: "— 1 —")
```
You can add the total number of pages by entering a second number character in
the string.
```example
#set page(numbering: "1 of 1")
```
Go to the numbering function reference to learn more about the arguments you can
pass here.
In case you need to right- or left-align the page number, use the
`numbering-align` argument of the page set rule. Alternating alignment between
even and odd pages is not currently supported using this property. To do this,
you'll need to specify a custom footer with your footnote and query the page
counter as described in the section on conditionally omitting headers and
footers.
### Custom footer with page numbers
Sometimes, you need to add other content than a page number to your footer.
However, once a footer is specified, the `numbering` argument of the `page` set
rule is ignored. This section shows you how to add a custom footer with page
numbers and more.
```example
#set page(
footer: locate(loc => {
let page-num = counter(page).at(loc).first()
let page-total = counter(page).final(loc).first()
strong[American Society of Proceedings]
h(1fr)
[#page-num/#page-total]
})
)
```
The example above shows how to add a custom footer with page numbers. First of
all, we need to recover the page number using the page counter. For this, we are
using the `locate` function to check the page counter, just like in the
conditional header section. We then store the current and final page number in
variables.
Then, we can proceed to build our footer. We add a strong label on the left,
insert all the free space on the line, and finally display the current page
number and the page total. This would work just the same in the header and with
any content.
We can, of course, use the `numbering` function to use numbering pattern strings
like before:
```example
#set page(
footer: locate(loc => {
let page-num = counter(page).at(loc).first()
let page-total = counter(page).final(loc).first()
strong[American Society of Proceedings]
h(1fr)
numbering("i of I", page-num, page-total)
})
)
```
The numbering function accepts multiple arguments. It will use the arguments in
order for each number character. You could, for example, put the page total in
front of the page number by reversing the argument order.
We can even use these variables to get more creative with the page number. For
example, let's insert a circle for each page.
```example
#set page(
footer: locate(loc => {
let page-num = counter(page).at(loc).first()
let circles = (
box(circle(radius: 2pt, fill: navy)),
) * page-num
align(right, circles.join(h(1pt)))
})
)
```
In this example, we use the number of pages to create an array of circles. The
circles are wrapped in a box so they can all appear on the same line, because
they are blocks and would otherwise create paragraph breaks. The length of this
array depends on the current page number.
We then insert the circles at the right side of the footer, with 1pt of space
between them. The join method of an array will attempt to _join_ the different
values of an array into a single value, interspersed with its argument. In our
case, we get a single content value with circles and spaces between them that we
can use with the align function.
### Reset the page number and skip pages
Do you, at some point in your document, reset the page number? Maybe you want to
start with the first page only after the title page. Or maybe you need to skip a
few page numbers because you will insert pages into the final printed product.
The right way to modify the page number is to manipulate the page counter. The
simplest manipulation is to set the counter back to 1.
```example
#counter(page).update(1)
```
This line will reset the page counter back to one. It should be placed at the
start of a page because it will otherwise create a page break. You can also also
update the counter given its previous value by passing a function:
```example
#counter(page).update(i => i + 5)
```
In this example, we skip five pages. `i` is the current value of the page
counter and `i + 5` is the return value of our function.
<!-- ## Add columns
### Columns after start of doc
### Balanced columns
### Marginals -->
<!-- One-off modification -->
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/scripting/methods.typ | typst | // Test method calls.
--- method-whitespace ---
// Test whitespace around dot.
#test( "Hi there" . split() , ("Hi", "there"))
--- method-mutating ---
// Test mutating indexed value.
#{
let matrix = (((1,), (2,)), ((3,), (4,)))
matrix.at(1).at(0).push(5)
test(matrix, (((1,), (2,)), ((3, 5), (4,))))
}
--- method-multiline ---
// Test multiline chain in code block.
#{
let rewritten = "Hello. This is a sentence. And one more."
.split(".")
.map(s => s.trim())
.filter(s => s != "")
.map(s => s + "!")
.join("\n ")
test(rewritten, "Hello!\n This is a sentence!\n And one more!")
}
--- method-unknown ---
// Error: 2:10-2:13 type array has no method `fun`
#let numbers = ()
#numbers.fun()
--- method-unknown-but-field-exists ---
// Error: 2:4-2:10 type content has no method `stroke`
// Hint: 2:4-2:10 did you mean to access the field `stroke`?
#let l = line(stroke: red)
#l.stroke()
--- method-mutate-on-temporary ---
// Error: 2:2-2:43 cannot mutate a temporary value
#let numbers = (1, 2, 3)
#numbers.map(v => v / 2).sorted().map(str).remove(4)
--- assign-to-method-invalid ---
// Error: 2:3-2:19 cannot mutate a temporary value
#let numbers = (1, 2, 3)
#(numbers.sorted() = 1)
--- method-mutate-on-std-constant ---
// Error: 2-5 cannot mutate a constant: box
#box.push(1)
|
|
https://github.com/university-makino/Microcomputer-control-and-exercises | https://raw.githubusercontent.com/university-makino/Microcomputer-control-and-exercises/master/report/本レポート3/report.typ | typst | // ライブラリの実装 //
#import "@preview/codelst:2.0.1": sourcecode
//フォント設定//
#let gothic = "YuMincho"
//本文フォント//
#set text(11pt, font: gothic, lang: "ja")
//タイトル・見出しフォント//
#set heading(numbering: "1.1")
#let heading_font(body) = {
show regex("[\p{scx: Han}\p{scx: Hira}\p{scx: Kana}]"): set text(font: gothic)
body
}
#show heading: heading_font
// ページ設定 //
#set page(
paper: "a4",
margin: (x: 25mm, y: 25mm),
columns: 1,
//fill: 背景色,
numbering: "1",
number-align: center,
header: [
#set text(8pt)
]
)
// 数式の表示の仕方を表示 //
#set math.equation(numbering: "(1)")
//本文ここから//
= 演習の目的
実験を通して、加速度センサ KXM52-1050の使い方と仕組みの習得を目的とする。
= 演習の使用部品
== @加速度センサ の電子部品 ( 加速度センサ KXM52-1050) を次のような点から調べなさい。
#figure(
image("./img/加速度センサ.png",width: 50%),
caption: "加速度センサ"
)<加速度センサ>
=== どのような部品か
加速度の測定を目的とした慣性センサの1つで、3次元の慣性運動(直行3軸方向の並進運動)を検出する。
利用用途としては、ビルや橋梁などの建造物の傾斜や地震時の傾き計測にも利用される @acc_marubun 。
=== どのような仕組みか
KXM52-1050の加速度センサーはMEMS静電容量方式の加速度センサーであり、固定電極と可動電極、スプリングから構成されている。加速度が加わっていない状態では、固定電極と可動電極の間の距離は同じである。加速度がかかると可動電極が移動し、固定電極との位置関係に変化が生じ、電極間静電容量が変化する @acc_techweb 。
=== どのような入力を取り扱うのか
加速度センサは、加速度を検出するため、物体の3軸の加速度を感知し、物体の動きを検出ができる。
=== 入力に応じて出力がどう変化するのか (データシートや仕様書を参考に)
KXM52-1050のデータシートによると、以下のような特性がある@acc_datasheet 。
- 電源電圧(Vdd) 2.7V~5.5V(標準3.3V)
- 測定レンジ ±2g
- 感度 (Vdd/5) V/g
- 0G出力 (Vdd/2) V
出力電圧をv(V)、加速度をa(単位はg)とすると、出力電圧と加速度の関係は @出力の式 であらわされる。
$ v = a * v_d/5 * v_d/2 $<出力の式>
例えば、Vddが5V、加速度が1gのときは、aに1を代入して、3.5Vの電圧が出力される。
=== どのようなピンアサイン (各ピンの役割) か <H_加速度センサーピンアサイン>
KXR94-1050をそのままの使用は難しいため、基盤に半田付けし、使いやすくモジュール化したものを用いる。
しかし、KXR94-1050は廃盤となっており、代替品としてKXR94-2050がある @acc_akitsuki_datasheet 。
今回は、KXR94-2050とあまり違いがないと仮定をして、KXR94-2050のピンアサインを @H_加速度センサーピンアサイン @加速度センサーピンアサイン に示す。
- Vdd: 電源電圧
- Enable: センサの有効/無効を制御するピン
- GND: グラウンド (接地)
- Vmux: センサの出力レンジを制御するピン
- Out Z: Z軸方向の加速度を出力するピン
- Out Y: Y軸方向の加速度を出力するピン
- Out X: X軸方向の加速度を出力するピン
- Self Test: セルフテストを実行するピン
#figure(
grid(
columns: 1,
image("./img/加速度センサーピンアサイン1.png",width: 75%),
image("./img/加速度センサーピンアサイン2.png",width: 75%)
),
caption: "加速度センサーピンアサイン"
)<加速度センサーピンアサイン>
=== 正しい動作の条件,範囲は何か
秋月電子によると、以下のような仕様がある @acc_akitsuki 。
- 電源電圧min.:2.5V
- 電源電圧max.:5.25V
- 加速度チャンネル:3
- 測定加速度max.:±2g
- 測定項目:加速度
- インターフェイス:アナログ
- 実装タイプ:スルーホール
- パッケージ:DIP8
#pagebreak() // ページを分ける
= 課題内容
== 物体の傾きや動きを計測する
=== 実験その1 (動作確認)
ブレッドボードを以下のようにした場合,アナログ入力はどのような値をとるか調べ,グラフに表
しなさい.また,どの部分がどの場合か,グラフ上に示しなさい.
- ブレッドボードを卓上に置いたとき
- 左に傾けたとき
- 手前に傾けたとき
- ブレッドボードを裏返したとき
*回路図*
@実験1回路図 は、実験その1の回路図を示す。
加速度センサをアナログ入力に接続して、加速度センサの傾きや動きを測定する装置を作成する。
加速度センサに5Vの電源を供給し、出力電圧をアナログ入力に接続する。
A0,A1,A2 はそれぞれ X軸、Y軸、Z軸の加速度を出力するピンである。
センサの動きや傾きを検知し、センサ内部の抵抗値が変化し、アナログ入力の値が変化する。
#figure(
image("./img/実験1回路図.png",width: 70%),
caption: "実験1回路図 傾きや動きを測定する装置"
)<実験1回路図>
#pagebreak() // ページを分ける
*プログラム*
@値の取得をするソースコード1 , @値の取得をするソースコード2 , @値の取得をするソースコード3 は、実験その1で使用したアナログ入力値を取得するソースコードを示す。
#figure(
sourcecode[```c
// writeFile
import processing.serial.*;
import cc.arduino.*;
Arduino arduino;
PFont myFont;
int usePin0 = 0;
int usePin1 = 1;
int usePin2 = 2;
String Label0 = "array0";
String Label1 = "array1";
String Label2 = "array2";
int[] array0 = new int[0];
int[] array1 = new int[0];
int[] array2 = new int[0];
int input0, input1, input2;
boolean isRecording = false;
```],
caption: "値の取得をするソースコード (1-3)"
)<値の取得をするソースコード1>
#figure(
sourcecode[```c
// setup Method
void setup(){
size(600, 250);
arduino = new Arduino(this, "/dev/cu.usbserial-14P54810",57600);
myFont = loadFont("CourierNewPSMT-48.vlw");
textFont(myFont, 30);
frameRate(30);
}
void draw(){
background(120);
input0 = arduino.analogRead(usePin0);
input1 = arduino.analogRead(usePin1);
input2 = arduino.analogRead(usePin2);
// show analog input values
fill(255);
text( "A0 x = " + input0, 15, 30);
text( "A1 y = " + input1, 15, 60);
text( "A2 z = " + input2, 15, 90);
// visualise analog input values
noStroke();
rect( 235, 10, (input0)/4, 20);
rect(235,40,(input1)/4,20);
rect(235,70,(input2)/4,20);
stroke( 255, 0, 0);
line( 235, 5, 235, 125);
line( 490, 5, 490, 125);
if( isRecording ){
// If it’s Recording, use array to store data.
array0 = append( array0, input0);
array1 = append( array1, input1);
array2 = append( array2, input2);
// display it’s recording
text( "Recording...", 40, 180);
text( "Press any key to End Recording",40, 210);
if(second()%2 ==1 ){
fill(255,0,0);
ellipse( 25, 170, 9,9);
}
} else {
// If it’s not Recording, show how to use.
text( "Press Esc key to Exit", 40, 180);
text( "Press any key to Record", 40, 210);
}
}
```],
caption: "値の取得をするソースコード (2-3)"
)<値の取得をするソースコード2>
#figure(
sourcecode[```c
void keyPressed() {
if( isRecording ){
// making contents of csv file
String[] lines = new String[array0.length +1 ];
lines[0] = "Steps," + Label0 + ","+Label1+","+Label2;
for (int i = 0; i < array0.length; i++) {
lines[i+1] = (i+1) + "," + array0[i] +"," + array1[i] + "," + array2[i];
}
// making filename
String filename = "Rec" + year();
if( month() < 10 ){ filename += "0";}
filename += month();
if( day() < 10 ){ filename += "0";}
filename += day() + " ";
if( hour() < 10 ){ filename += "0";}
filename += hour();
if( minute() < 10 ){ filename += "0";}
filename += minute();
if( second() < 10 ){ filename += "0";}
filename += second() + ".csv";
saveStrings(filename, lines);
// Initializing
array0 = expand(array0, 0);
array1 = expand(array1, 0);
array2 = expand(array2, 0);
isRecording = false;
} else {
// Switch on
isRecording = true;
}
}
// write file
```],
caption: "値の取得をするソースコード (3-3)"
)<値の取得をするソースコード3>
- プログラムの概要
センサから ArduinoA0 A1 A2 ピンへの入力値をアナログ入力として読み込む。読み込んだ値を数値として表示し、CSVに書き込みを行う。
- プログラムの説明
- 1–17 行目: プログラムに必要な変数の宣言および定義またはライブラリのインポートを行う。
- 20–25 行目: Arduino およびプログラムの初期設定
- 21 行目で画面表示に用いるウィンドウサイズを横 600px,縦 250px と定義している。
- 22 行目で"/dev/cu.usbserial-14P54810"のポートと 57600 の速度で通信する arduino インスタンスを生成する.
- 24 行目でフォントを読み込む。
- 25 行目でフレームレートを 30 としている.
- 27–62 行目:プログラムの動作
- 29–31 行目でアナログ入力を読み込むための変数 input0, input1, input2 を宣言している。
- 34–44 行目で表示の設定を行う。
- 45–61 行目で レコーディングを行うための処理を行う。
- 64–94 行目で 入力されたkeyにおける処理を行う。
- 入力をされたら、CSVファイルに書き込む処理を行う。
*結果*
今回の実験の軸の定義としては @加速度センサの軸 のように定義する。
1番ピンを右下にして4番ピンを右上にして、X軸、Y軸を図のように定義する。
Z軸については、図に対して垂直な方向をZ軸とする。
軸の定義は、データシートをもとにしている。
左に傾けた時は、x軸方向に正の向きに傾けた時と定義をする。
手前に傾けた時は、y軸方向に正の向きに傾けた時と定義をする。
#figure(
image("./img/加速度センサの軸.png",width: 50%),
caption: "加速度センサの軸"
)<加速度センサの軸>
実験結果は、@加速度センサを傾けた時のグラフ に示す。
#figure(
image("./img/実験1のグラフ.png",width: 80%),
caption: "加速度センサを傾けた時のグラフ"
)<加速度センサを傾けた時のグラフ>
角度を変化させず、動作をさせず、水平に保った場合はx軸,y軸は500前後の値を示す。z軸は750前後の値を示す。
角度の瞬間的な変化を出力するのではなく、傾けた分だけ値が増減する。また、角度を水平にしない限り最初の値に戻らない。
同じ大きさの角度に傾けた場合ほぼ同じ大きさの値を示す。
*考察*
値はブレッドボードの角度の変化をした場合その角度の変化を検知して値が変化すると考えられる。
KXM52-1050の加速度センサーはMEMS静電容量方式の加速度センサーであり、固定電極と可動電極、スプリングから構成されている。加速度が加わっていない状態では、固定電極と可動電極の間の距離は同じである。加速度がかかると可動電極が移動し、固定電極との位置関係に変化が生じ、電極間静電容量が変化する。
そのため、角度を傾けた場合、重力加速度を受け可動電極が一定の方向に移動し静電容量が変化するため、角度の変化を検出しない時に0に戻らず、一定の大きさの静電容量を維持し続ける。
卓上に置いた時にz軸の値だけ大きくなっているのはセンサに掛かっている力が重力だけでz軸に対して掛かっているためであると考えられる。
=== 実験その2 (3軸方向の識別)
ブレッドボードを以下の方向に,急激に動かした場合,アナログ入力はどのような値をとるか調べ,
グラフに表しなさい.また,どの部分がどの方向か,グラフ上に示しなさい.
- 奥に動かしたとき(突き刺すような動き)
- 右に動かしたとき
- 上に動かしたとき
*回路図・プログラム*
回路図・プログラムは実験その1と同じである。
#pagebreak() // ページを分ける
*結果*
実験結果は、@加速度センサを動かした時のグラフ に示す。
#figure(
image("./img/実験2のグラフ.png",width: 80%),
caption: "加速度センサを動かした時のグラフ"
)<加速度センサを動かした時のグラフ>
値はブレッドボードが速度変化をした場合その動作の変化を検知して値が変化する。
角度を変化させず、動作をさせず、水平に保った場合はx軸,y軸は500前後の値を示す。z軸は750前後の値を示す。
動作の瞬間的な変化を出力する。
同じような速度で動かした場合ほぼ同じ大きさの値を示す。
動作を始めた時は値がその軸の方向に大きくなるが、動作を終了した時は一度、軸の逆の方向に大きくなり、最初の値に戻る。
*考察*
KXM52-1050の加速度センサーはMEMS静電容量方式の加速度センサーであり、固定電極と可動電極、スプリングから構成されている。加速度が加わっていない状態では、固定電極と可動電極の間の距離は同じである。加速度がかかると可動電極が移動し、固定電極との位置関係に変化が生じ、電極間静電容量が変化する。
そのため、各軸に対して加速度を与えられるため、可動電極が一定の方向に移動し静電容量が変化する。その後、加速度が与えられないと元の位置に可動電極が戻るため、値は元の値に戻る。
また、急激に物体に加速度を与えた後、動作を止めるため逆方向に力を加えるため、慣性の法則が働く。ゆえに、狙った力と逆の作用が見られる。
卓上に置いた時にz軸の値だけ大きくなっているのはセンサに掛かっている力が重力だけでz軸に対して掛かっているからである。
今回の実験において、 KXM52-1050の仕様書と比較をして、同じ動作を行なっていた。
#pagebreak() // ページを分ける
=== 発展その1 (傾きを用いたアニメーション制御)
@発展その1の加速度センサの動作イメージ @発展その1の記号の動作イメージ のように,加速度センサを用いて,傾けた向きに傾きの大きさだけ記号が動く(加速度センサの傾きをトレースする) ようにしなさい.また,平らな場所に置くと記号が中央に戻るようにしなさい.
#figure(
image("./img/発展その1の加速度センサの動作イメージ.png",width: 50%),
caption: "発展1の加速度センサの動作イメージ"
)<発展その1の加速度センサの動作イメージ>
#figure(
image("./img/発展その1の記号の動作イメージ.png",width: 50%),
caption: "発展1の記号の動作イメージ"
)<発展その1の記号の動作イメージ>
*回路図*
回路図は実験その1と同じである。
#pagebreak() // ページを分ける
*プログラム*
@加速度センサの傾きを用いたアニメーション制御のソースコード は、加速度センサの傾きをトレースするソースコードを示す。
#figure(
sourcecode[```java
import processing.serial.*;
import cc.arduino.*;
Arduino arduino;
PFont myFont;
// Arduinoのピン
int analogPin0 = 0;
int analogPin1 = 1;
int analogPin2 = 2;
void setup() {
size(600, 300);
// Arduinoの初期化
arduino = new Arduino(this, "/dev/cu.usbserial-14P54810");
// フォントの読み込みと設定
myFont = loadFont("CourierNewPSMT-48.vlw");
textFont(myFont, 30);
// フレームレートの設定
frameRate(30);
}
int prevX = 0;
int prevY = 0;
void draw() {
background(120);
// アナログピンからの入力を取得
int x = arduino.analogRead(analogPin0);
int y = arduino.analogRead(analogPin1);
int z = arduino.analogRead(analogPin2);
// 平滑化フィルターをかける
float smoothness = 0.2; // 平滑化の度合いを調整する値
x = (int)(x * smoothness + (1 - smoothness) * prevX);
y = (int)(y * smoothness + (1 - smoothness) * prevY);
fill(255);
text("o", 300+( -1 * (x-536)), 150+ (y-488));//横
// 前回の値を更新する
prevX = x;
prevY = y;
}
```],
caption: "加速度センサの傾きを用いたアニメーション制御のソースコード"
)<加速度センサの傾きを用いたアニメーション制御のソースコード>
- プログラムの概要
センサから ArduinoA0 A1 A2 ピンへの入力値をアナログ入力として読み込む。読み込んだ値をもとに、記号を動かすアニメーションを行う。
- プログラムの説明
- 1–10 行目: プログラムに必要な変数の宣言および定義またはライブラリのインポートを行う。
- 12–24 行目: Arduino およびプログラムの初期設定
- 13 行目で画面表示に用いるウィンドウサイズを横 600px,縦 300px と定義している。
- 16 行目で"/dev/cu.usbserial-14P54810"のポートと 57600 の速度で通信する arduino インスタンスを生成する.
- 19 行目でフォントを読み込む。
- 23 行目でフレームレートを 30 としている.
- 26–27 行目で以前の値を保持するための変数 prevX, prevY を宣言している。
- 29–48 行目:プログラムの動作
- 30 行目で背景色を設定する。
- 33–35 行目でアナログ入力を読み込むための変数 x, y, z を宣言している。
- 38–40 行目で平滑化フィルターをかける。
- 43 行目で記号を表示する。
- 46–47 行目で前回の値を更新する。
*結果*
記号を中央に寄せるために、ブレットボードを机に置いている時の値を引き、値の差分を出し、画面の中央座標を足し中心に持っていった。
X軸方向が逆に反応していたのを修正するために、x軸の値に-1かけるて動作を反転させた。
そのままの値をアニメーションにするとがたつきが起きたが、フィルターをかけると滑らかに動くようになった。
*考察*
センサーのデータは5Vのデータを0~1024までの値として受け取る。
負の値を取らないため、なにも傾けていない状態を中央値の500ぐらいを取り、そこからの変化をしている。
したがって、中央値の500を引くと、差分が出てくる。その差分を中央座標からの変化量と照らし合わせるとうまく動作する。
センサを右に傾けたとき記号は左動き、センサを左に傾けたとき記号は右に動いた。また、センサをY軸方向に傾けたとき、記号は傾けた向きと同様に動いた。この事象からX軸方向は逆向きに反応している。したがってX軸に-1をかけると傾けた向きと同じ動作をする。
実験1、2からもわかるようにセンサを動かしていない時でも測定値は多少変わってしまう。そのため、その値のまま記号を動かすようにアニメーションを作るとがたつきが起きてしまった。しかし、平滑化フィルタを使い値を平均化するとがたつきがなくなり滑らかに動くアニメーションを作れる。
一つ前の値に0.2を掛け、受け取った値に0.8をかけ、その二つの値を足し平均化するようにした。
=== 発展その2(移動速度を用いたアニメーション制御)
実験その2で作成したグラフを参考に,急激に動かした方向を検出した場合,画面上の記号が検出
した方向に動いた後,中央に戻るようにしなさい.
*回路図*
回路図は実験その1と同じである。
#pagebreak() // ページを分ける
*プログラム*
@移動速度を用いたアニメーション制御のソースコード1 , @移動速度を用いたアニメーション制御のソースコード2 は、移動速度を用いたアニメーション制御のソースコードを示す。
#figure(
sourcecode[```java
import processing.serial.*;
import cc.arduino.*;
Arduino arduino;
PFont myFont;
// Arduinoのピン
int analogPin0 = 0;
int analogPin1 = 1;
void setup() {
size(600, 300);
// Arduinoの初期化
arduino = new Arduino(this, "/dev/cu.usbserial-14P54810");
// フォントの読み込みと設定
myFont = loadFont("CourierNewPSMT-48.vlw");
textFont(myFont, 30);
// フレームレートの設定
frameRate(30);
}
// 前回の値を保持する変数
int prevX = 0;
int prevY = 0;
int count = 0;
String status = "None";
final float SMOOTHNESS = 0.2;
final int THRESHOLD = 70;
void draw() {
background(120);
// アナログピンからの入力を取得
int x = readAndSmooth(analogPin0, prevX);
int y = readAndSmooth(analogPin1, prevY);
// 状態を更新
if (status != "None" && count < 30) {
count++;
} else {
count = 0;
status = getStatus(x, y);
}
// 状態に応じて表示位置を変更
displayStatus(status);
// 前回の値を更新する
prevX = x;
prevY = y;
}
```],
caption: "移動速度を用いたアニメーション制御のソースコード (1-2)"
)<移動速度を用いたアニメーション制御のソースコード1>
#figure(
sourcecode[```java
// アナログピンからの入力を取得し、平滑化する
int readAndSmooth(int pin, int prevValue) {
int value = arduino.analogRead(pin);
return (int)(value * SMOOTHNESS + (1 - SMOOTHNESS) * prevValue);
}
// 状態を取得する
String getStatus(int x, int y) {
if (prevX - x > THRESHOLD) {
return "Left";
} else if (prevX - x < -THRESHOLD) {
return "Right";
} else if (prevY - y > THRESHOLD) {
return "Down";
} else if (prevY - y < -THRESHOLD) {
return "Up";
}
return "None";
}
// 状態に応じて表示位置を変更する
void displayStatus(String status) {
fill(255);
switch (status) {
case "Left":
text("o", 230, 150);
break;
case "Right":
text("o", 370, 150);
break;
case "Up":
text("o", 300, 70);
break;
case "Down":
text("o", 300, 220);
break;
default:
text("o", 300, 150);
break;
}
}
```],
caption: "移動速度を用いたアニメーション制御のソースコード (2-2)"
)<移動速度を用いたアニメーション制御のソースコード2>
- プログラムの概要
センサから ArduinoA0 A1 A2 ピンへの入力値をアナログ入力として読み込む。読み込んだ値をもとに、移動速度を検出し、記号を動かすアニメーションを行う。
- プログラムの説明
- 1–9 行目: プログラムに必要な変数の宣言および定義またはライブラリのインポートを行う。
- 11–23 行目: Arduino およびプログラムの初期設定
- 12 行目で画面表示に用いるウィンドウサイズを横 600px,縦 300px と定義している。
- 15 行目で"/dev/cu.usbserial-14P54810"のポートと 57600 の速度で通信する arduino インスタンスを生成する.
- 18 行目でフォントを読み込む。
- 22 行目でフレームレートを 30 としている.
- 26–27 行目で以前の値を保持するための変数 prevX, prevY を宣言している。
- 28–29 行目で状態を保持するための変数 count, status を宣言している。
- 30–31 行目で平滑化の度合いを調整する値 SMOOTHNESS, 閾値を設定する値 THRESHOLD を宣言している。
- 33–53 行目:プログラムの動作
- 30 行目で背景色を設定する。
- 37–38 行目でアナログ入力を読み込むための変数 x, y を宣言している。
- 41–45 行目で状態を更新する。1秒ほど状態を確認しその状態が続いた場合、状態を更新する。
- 49行目で状態に応じて表示位置を変更する。
- 52–53 行目で前回の値を更新する。
- 57–60 行目でアナログピンからの入力を取得し、平滑化する関数 readAndSmooth を定義している。
- 62–75 行目で状態を取得する関数 getStatus を定義している。
- 77–84 行目で状態に応じて表示位置を変更する関数 displayStatus を定義している。
*結果*
閾値を使い、どの方向に動かしたか判断する。
慣性による逆方向の入力を受け付けないために一度閾値を超えたら1秒間入力を無視する。
閾値を超えるのが、+70と-70の値を超えた場合、その方向に動いたと判断する。
*考察*
急激に動かすと慣性による逆方向への力がはたらいてしまい、急に動かした方向とは逆の方向にも検知してしまう。これを防ぐために一度閾値を超えたら一定時間記号を止めると、動かした方向のみをはっきり検知できる。
=== まとめ
今回の実験では、加速度センサを用いて、センサの動きや傾きを検知し、センサ内部の抵抗値が変化し、アナログ入力の値が変化を確認した。また、その値をもとにアニメーションを制御するプログラムを作成した。
アニメーションを制御するプログラムを作成し、センサの動きや傾きを視覚的に確認できた。また、センサの動きや傾きを検知し、センサの動作原理を理解できた。
#pagebreak() // ページを分ける
// bibファイルの指定 //
#bibliography("./bibliography.bib")
|
|
https://github.com/glocq/typst-forthright-cv | https://raw.githubusercontent.com/glocq/typst-forthright-cv/master/src/settings.typ | typst | MIT License | /**************************
* Spacing and image size *
**************************/
// Space around the whole CV
#let pageMargin = 1.2cm
// Space under name
#let nameSpace = 1.4em
// Space under description
#let descriptionSpace = 1.3em
// Space under personal details
#let detailSpace = 0em
// Minimum space between the photo and the rest of the header
#let photoSpace = 1em
// Height of the space between the header and the rest of the content
#let headerSpace = 20pt
// Width of the space between the main section and the sidebar
#let sidebarSpace = 20pt
// Size of the sidebar relative to the whole width
#let sidebarSize = 35%
// Space between consecutive entries, or between a section title
// and an entry, or between an entry and a section title
#let interEntry = 1.6em
// Space between consecutive items (entry title, organisation, etc.)
// inside one entry
#let interItem = 0.9em
// Space between lines of a same paragraph
#let interLine = 0.7em
// Image size
#let imageSize = 2.8cm
/**************
* Font style *
**************/
// Global values common to several styles
// The Nerd font is only needed for icons (phone, mail, etc.)
#let globalFont = ("Source Sans Pro", "Symbols Nerd Font")
#let globalFontSize = 12pt
#let accentColor = rgb("#800020")
#let lightGray = rgb("#ededef")
#let mediumGray = rgb("#78787e")
#let darkGray = rgb("#3c3c42")
// Styles of individual elements
#let firstNameStyle(content) = text(
font: globalFont,
fill: black,
weight: "light",
size: 25pt,
content
)
#let lastNameStyle(content) = text(
font: globalFont,
fill: black,
weight: "bold",
size: 25pt,
content
)
#let descriptionStyle(content) = text(
font: globalFont,
fill: accentColor,
weight: "medium",
size: 13pt,
style: "oblique",
content
)
#let detailsStyle(content) = text(
font: globalFont,
fill: black,
weight: "regular",
size: globalFontSize,
content
)
#let sectionStyle(content) = text(
font: globalFont,
fill: accentColor,
weight: "bold",
size: 16pt,
content
)
#let titleStyle(content) = text(
font: globalFont,
fill: black,
weight: "bold",
size: globalFontSize,
content
)
#let organisationStyle(content) = text(
font: globalFont,
fill: darkGray,
weight: "medium",
style: "oblique",
size: globalFontSize,
content
)
#let locationStyle(content) = text(
font: globalFont,
fill: mediumGray,
weight: "medium",
style: "oblique",
size: globalFontSize,
content
)
#let dateStyle(content) = text(
font: globalFont,
fill: accentColor,
weight: "medium",
size: globalFontSize,
content
)
#let bodyStyle(content) = text(
font: globalFont,
fill: darkGray,
weight: "regular",
size: globalFontSize,
content
)
// Color of hyperlinks
#let linkColor = accentColor
// How much bolder than regular text to make *strong* text
#let strongDelta = 150
|
https://github.com/jbirnick/typst-great-theorems | https://raw.githubusercontent.com/jbirnick/typst-great-theorems/master/README.md | markdown | MIT License | > [!NOTE]
> This is a [Typst](https://typst.app/) package. Click [here](https://typst.app/universe/package/great-theorems/) to find it in the Typst Universe.
# `great-theorems`
This package allows you to make **theorem/proof/remark/...** blocks.
Features:
- supports advanced counters through both [headcount](https://typst.app/universe/package/headcount/) and [rich-counters](https://typst.app/universe/package/rich-counters/)
- easy adjustment of style:
* change prefix
* change how title is displayed
* change formatting of body
* change suffix
* change numbering style
* configure _all_ parameters of the [`block`](https://typst.app/docs/reference/layout/block/), including background color, stroke color, rounded corners, inset, ...
- can adjust style also on individual basis (e.g. to highlight main theorem)
- works with labels/references
- sane and smart defaults
## Showcase
In the following example we use [rich-counters](https://typst.app/universe/package/rich-counters/) to configure section-based counters.
You can also use [headcount](https://typst.app/universe/package/headcount/).
```typ
#import "@preview/great-theorems:0.1.1": *
#import "@preview/rich-counters:0.2.1": *
#set heading(numbering: "1.1")
#show: great-theorems-init
#show link: text.with(fill: blue)
#let mathcounter = rich-counter(
identifier: "mathblocks",
inherited_levels: 1
)
#let theorem = mathblock(
blocktitle: "Theorem",
counter: mathcounter,
)
#let lemma = mathblock(
blocktitle: "Lemma",
counter: mathcounter,
)
#let remark = mathblock(
blocktitle: "Remark",
prefix: [_Remark._],
inset: 5pt,
fill: lime,
radius: 5pt,
)
#let proof = proofblock()
= Some Heading
#theorem[
This is some theorem.
] <mythm>
#lemma[
This is a lemma. Maybe it's used to prove @mythm.
]
#proof[
This is a proof.
]
= Another Heading
#theorem(title: "some title")[
This is a theorem with a title.
] <thm2>
#proof(of: <thm2>)[
This is a proof of the theorem which has a title.
]
#remark[
This is a remark.
The remark box has some custom styling applied.
]
```
![](example.png)
## Usage
### `great-theorems-init`
First, make sure to apply the following inital `show` rule to your document:
```typ
#show: great-theorems-init
```
This is important to make the blocks have the correct alignment and to display references correctly.
### `mathblock`
The main constructor you will use is `mathblock`, which allows you to construct a theorem/proof/remark/... environment in exactly the way you like it.
Please see the showcase above for on example on how to use it.
We now list and explain all possible arguments.
- `blocktitle` (required)
Usually something like `"Theorem"` or `"Lemma"`. Determines how references are displayed, and also determines the default `prefix`.
- `counter` (default: `none`)
If you want your `mathblock` to be counted, pass the counter here.
Accepts either a Typst-native [`counter`](https://typst.app/docs/reference/introspection/counter/) (which can be made to depend on the section with the [headcount](https://typst.app/universe/package/headcount/) package) or a `rich-counter` from the [rich-counters](https://typst.app/universe/package/rich-counters/) package.
If you want multiple `mathblock` environments to share the same counter, just pass the same counter to all of them.
- `numbering` (default: `"1.1"`)
The numbering style that should be used to display the counters.
**Note:** If you use the [headcount](https://typst.app/universe/package/headcount/) package for your counters, you have to pass the `dependent-numbering` here.
- `prefix` (default: contructed from `blocktitle`, bold style)
What should be displayed before the body.
If you didn't pass a counter, it should just be a piece of content like `[*Theorem.*]`.
_If you passed a counter_, it should a function/closure, which takes the current counter value as an argument and returns the corresponding prefix; for example `(count) => [*Theorem #count.*]`
- `titlix` (default: `title => [(#title)]`)
How a title should be displayed. Will be placed after the prefix if a title is present.
Must be function which takes the title and returns the corresponding content that should be displayed.
- `suffix` (default: `none`)
A suffix that will be displayed after the body.
- `bodyfmt` (default: `body => body` i.e. no special formatting)
A function that will style/transform the body.
For example, if you want your theorem contents to be displayed in oblique style, you could pass `text.with(style: "oblique")`.
- arguments for the surrounding [`block`](https://typst.app/docs/reference/layout/block/)
The `mathblock`, as the name suggests, is surrounded by a [`block`](https://typst.app/docs/reference/layout/block/), which can be styled to have a background color, stroke color, rounded corners, etc. .
You can just pass all arguments that you could pass to a `block` also to `mathblock`, and it will be "passed through" the surrounding `block`.
For example, you could write `#let theorem = mathblock(..., fill: yellow, inset: 5pt)`.
So far we have discussed how you _setup_ your environment with `#let theorem = mathblock(...)`.
Now let's discuss how to use the resulting `theorem` command.
Again, please see the showcase above for some examples on how to use it.
We now list and explain all possible arguments (apart from the body).
- `title` (default: `none`)
This allows you to set a title for your theorem/lemma/..., which will be displayed according to `titlix`.
- all the arguments from `mathblock`, except `blocktitle` and `counter`
You can change all the parameters of your `mathblock` also on an individual basis, i.e. for each occurrence separately, by just passing the respective arguments, including `numbering`, `prefix`, `titlix`, `suffix`, `bodyfmt`, and arguments for `block`.
These will take precedence over the global configuration.
### `proofblock`
Also a proof environment can be constructed with `mathblock`, for example:
```
#let proof = mathblock(
blocktitle: "Proof",
prefix: [_Proof._],
suffix: [#h(1fr) $square$],
)
```
However, for convenience, we have made another `proofblock` constructor.
It works exactly the same as `mathblock`, the only differences being:
- it has different default values for `blocktitle`, `prefix`, and `suffix`
- it has no `counter` and `numbering` argument
- the `titlix` argument is replaced with a `prefix_with_of` argument (also consisting of a function), which will be used as a prefix when the constructed environment is used with `of` parameter
The constructed environment will have the following changes compared to an environment constructed with `mathblock`
- the `title` argument is replaced with an `of` argument, which is used to denote to which theorem/lemma/... the proof belongs
This can be either just content, or a label, in which case a reference to the label is displayed.
## FAQ
- _What is the difference to the ctheorems package?_
You can achieve pretty much the same results with both packages.
One goal of `great-theorems` was to have a cleaner implementation, for example by separating the counter functionality from the theorem block functionality.
`ctheorems` also uses deprecated Typst functionality that will soon be removed.
In the end, however, in comes down to personal preference, and `ctheorems` was certainly a big inspiration for this package!
- _How to set up the counters the way I want?_
Please consult the documentation of [headcount](https://typst.app/universe/package/headcount/) and [rich-counters](https://typst.app/universe/package/rich-counters/) respectively, we support both packages as well as native [`counter`](https://typst.app/docs/reference/introspection/counter/)s.
- _My theorems are all center aligned?!_
You forgot to put the initial show rule at the start of your document:
```typ
#show: great-theorems-init
```
- _My theorems break across pages, how do I stop that behavior?_
You can pass `breakable: false` to `mathblock` to construct a non-breakable environment.
- _I have a default style for all my theorems/lemmas/remarks/..., and I'm writing boilerplate when I construct theorem/lemma/remark environments._
You can essentially define your own defaults like this:
```typ
#let my_mathblock = mathblock.with(fill: yellow, radius: 5pt, inset: 5pt)
#let theorem = my_mathblock(...)
#let lemma = my_mathblock(...)
#let remark = my_mathblock(...)
...
```
- _The documentation is too short or unclear... how do I do X?_
Please just open an [issue on GitHub](https://github.com/jbirnick/typst-great-theorems/issues), and I will happily answer your question and extend the documentation!
|
https://github.com/smorad/um_cisc_7026 | https://raw.githubusercontent.com/smorad/um_cisc_7026/main/lecture_6_techniques.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
// FUTURE TODO: Swap order, modern techniques -> classification
#set math.vec(delim: "[")
#set math.mat(delim: "[")
#let ag = (
[Review],
[Dirty Secret of Deep Learning],
[Optimization is Hard],
[Deeper Neural Networks],
[Activation Functions],
[Parameter Initialization],
[Stochastic Gradient Descent],
[Modern Optimization],
[Weight Decay],
[Coding]
)
// 3:00
#show: university-theme.with(
aspect-ratio: "16-9",
short-title: "CISC 7026: Introduction to Deep Learning",
short-author: "<NAME>",
short-date: "Lecture 6: Techniques"
)
#title-slide(
title: [Modern Techniques],
subtitle: "CISC 7026: Introduction to Deep Learning",
institution-name: "University of Macau",
)
#slide(title: [Admin])[
Quiz 2 grades online, mean 3.5/4 #pause
Assignment 2 grades online, mean 82/100 #pause
Assignment 3 due next week #pause
Syllabus has optional reading for most lectures #pause
d2l.ai Section 5.1-5.5, 6.1-6.3, 12.1-12.10
]
#aslide(ag, none)
#aslide(ag, 0)
// 4:30
#sslide[
Many problems in ML can be reduced to *regression* or *classification* #pause
*Regression* asks how many #pause
- How long will I live? #pause
- How much rain will there be tomorrow? #pause
- How far away is this object? #pause
*Classification* asks which one #pause
- Is this a dog or muffin? #pause
- Will it rain tomorrow? Yes or no? #pause
- What color is this object? #pause
So far, we only looked at regression. Now, let us look at classification
]
#sslide[
*Task:* Given a picture of clothes, predict the text description #pause
$X: bb(Z)_(0,255)^(32 times 32) #image("figures/lecture_5/classify_input.svg", width: 80%)$ #pause
$Y : & {"T-shirt, Trouser, Pullover, Dress, Coat,"\
& "Sandal, Shirt, Sneaker, Bag, Ankle boot"}$ #pause
*Approach:* Learn $bold(theta)$ that produce *conditional probabilities* #pause
$ f(bold(x), bold(theta)) = P(bold(y) | bold(x)) = P(vec("T-Shirt", "Trouser", dots.v) mid(|) #image("figures/lecture_5/shirt.png", height: 20%)) = vec(0.2, 0.01, dots.v) $
]
#sslide[
If events $A, B$ are not disjoint, they are *conditionally dependent* #pause
$ P("cloud") = 0.2, P("rain") = 0.1 $ #pause
$ P("rain" | "cloud") = 0.5 $ #pause
$ P(A | B) = P(A sect B) / P(B) $ #pause
#side-by-side[Walk outside][
$P("Rain" sect "Cloud") = 0.1 \
P("Cloud") = 0.2$
$P("Rain" | "Cloud") = 0.1 / 0.2 = 0.5$
]
]
#sslide[
How can we represent a probability distribution for a neural network? #pause
$ bold(v) = { vec(v_1, dots.v, v_(d_y)) mid(|) quad sum_(i=1)^(d_y) v_i = 1; quad v_i in (0, 1) } $ #pause
There is special notation for this vector, called the *simplex* #pause
$ Delta^(d_y - 1) $
]
#sslide[
The simplex $Delta^k$ is an $k - 1$-dimensional triangle in $k$-dimensional space #pause
#cimage("figures/lecture_5/simplex.svg", height: 70%)
It has only $k - 1$ free variables, because $x_(k) = 1 - sum_(i=1)^(k - 1) x_i$
]
#sslide[
The softmax function maps real numbers to the simplex (probabilities)
$ "softmax": bb(R)^k |-> Delta^(k - 1) $ #pause
$ "softmax"(vec(x_1, dots.v, x_k)) = (e^(bold(x))) / (sum_(i=1)^k e^(x_i)) = vec(
e^(x_1) / (e^(x_1) + e^(x_2) + dots e^(x_k)),
e^(x_2) / (e^(x_1) + e^(x_2) + dots e^(x_k)),
dots.v,
e^(x_k) / (e^(x_1) + e^(x_2) + dots e^(x_k)),
) $ #pause
If we attach it to our model, we can output probabilities!
$ f(bold(x), bold(theta)) = "softmax"(bold(theta)^top overline(bold(x))) $
]
#sslide[
*Question:* Why do we output probabilities instead of a binary values
$ f(bold(x), bold(theta)) = vec(
P("Shirt" | #image("figures/lecture_5/shirt.png", height: 10%)),
P("Bag" | #image("figures/lecture_5/shirt.png", height: 10%)),
dots.v
) = vec(0.25, 0.08, dots.v); quad f(bold(x), bold(theta)) = vec(
1,
0,
dots.v
)
$ #pause
*Answer 1:* Outputting probabilities results in differentiable functions #pause
*Answer 2:* We report uncertainty, which is useful in many applications
]
#sslide[
#cimage("figures/lecture_5/fashion_mnist_probs.png", height: 80%)
]
#sslide[
We consider the label $bold(y)_[i]$ as a conditional distribution
$ P(bold(y)_[i] | bold(x)_[i]) = vec(
P("Shirt" | #image("figures/lecture_5/shirt.png", height: 10%)),
P("Bag" | #image("figures/lecture_5/shirt.png", height: 10%))
) = vec(1, 0) $ #pause
We approximate this with our model $f(bold(x), bold(theta))$ #pause
Our loss function measures the difference between two distributions #pause
$ P(bold(y)_[i] | bold(x)_[i]), quad f(bold(x), bold(theta)) $
]
#sslide[
The *Kullback-Leibler Divergence (KL)* measures the difference between distributions #pause
#cimage("figures/lecture_5/forwardkl.png", height: 50%)
]
#sslide[
From the KL divergence, we derived the *cross-entropy loss* function, which we use for classification #pause
$ = - sum_(i=1)^(d_y) P(y_i | bold(x)) log f(bold(x), bold(theta))_i $ #pause
$ cal(L)(bold(x), bold(y), bold(theta)) = [- sum_(j=1)^n sum_(i=1)^(d_y) P(y_([j], i) | bold(x)_[j]) log f(bold(x)_[j], bold(theta))_i ] $
]
// 12:30
#sslide[
Finish coding exercise
https://colab.research.google.com/drive/1BGMIE2CjlLJOH-D2r9AariPDVgxjWlqG#scrollTo=AnHP-PHVhpW_
]
// 12:30 + 15:00?
#sslide[
#cimage("figures/lecture_6/poor_minima.png")
]
#aslide(ag, 0)
#aslide(ag, 1)
#sslide[
So far, I gave you the impression that deep learning is rigorous #pause
Biological inspiration, theoretical bounds and mathematical guarantees #pause
For complex neural networks, deep learning is a *science* not *math* #pause
There is no widely-accepted theory for why deep neural networks are so effective #pause
In modern deep learning, we progress using trial and error #pause
Today we experiment, and maybe tomorrow we discover the theory
]
#sslide[
Scientific method: #pause
+ Collect observations #pause
+ Form hypothesis #pause
+ Run experiment #pause
+ Publish theory #pause
However, there is a second part: #pause
+ Find existing theory #pause
+ Show counterexample through experiment #pause
+ Publish counterexample #pause
+ Update or falsify theory
Deep learning is new, so much of part 2 has not happened yet!
]
#sslide[
For many concepts, the *observations* are stronger than the *theory* #pause
Observe that a concept improves many types of neural networks #pause
Concepts we discuss today are known to improve neural networks #pause
We will discuss theories about why they improve neural networks #pause
If you do not believe the theory, prove it wrong and be famous! #pause
Even if we do not agree on *why* a concept works, if we *observe* that it helps, we can still use it #pause
This is how medicine works (e.g., Anesthetics)!
]
#sslide[
Theoretical advancements are still very important! #pause
Imagine the 40 years of neural network research before we understood how to train neural networks #pause
#cimage("figures/lecture_1/timeline.svg", width: 77%) #pause
Are modern networks too complex for humans to understand?
]
#aslide(ag, 1)
#aslide(ag, 2)
// 15:00 + 15:00
#sslide[
A 2-layer neural network can represent *any* continuous function to arbitrary precision #pause
$ | f(bold(x), bold(theta)) - g(bold(x)) | < epsilon $ #pause
$ lim_(d_h -> oo) epsilon = 0 $ #pause
However, finding such $bold(theta)$ is a much harder problem
]
#sslide[
Gradient descent only guarantees convergence to a *local* optima #pause
#cimage("figures/lecture_6/poor_minima.png", height: 80%)
]
#sslide[
#cimage("figures/lecture_6/poor_minima.png", height: 75%)
Harder tasks can have millions of local optima, and many of the local optima are not very good!
]
#sslide[
Many of the concepts today create a *flat* loss landscape #pause
#cimage("figures/lecture_6/skip_connection_img.png", height: 70%) #pause
Gradient descent reaches a better optimum more quickly in these cases
]
#aslide(ag, 2)
#aslide(ag, 3)
#sslide[
A two-layer neural network is sufficient to approximate any continuous function to arbitrary precision #pause
But only with infinite width $d_h -> oo$ #pause
For certain problems, adding one more layer is equivalent to *exponentially* increasing the width
#text(size: 18pt)[- <NAME>, and <NAME>. "The power of depth for feedforward neural networks." Conference on learning theory. PMLR, 2016.] #pause
$ 2 times 32 times 32 => 2^(2 times 32 times 32) approx 10^616; quad "universe has " 10^80 "atoms"$ #pause
One more layer can solve this problem $3 times 32 times 32$ #pause
We need more layers for harder problems
]
// 24:00 + 15:00
#sslide[
#cimage("figures/lecture_6/filters.png", width: 120%)
]
#sslide[
In fact, we do not just need *deeper* networks, but also *wider* networks #pause
The number of neurons in a deep neural network affects the quality of local optima #pause
From Choromanska, Anna, et al. _The loss surfaces of multilayer networks._ (2014): #pause
- "For large-size networks, most local minima are equivalent and yield similar performance on a test set." #pause
- "The probability of finding a “bad” (high value) local minimum is non-zero for small-size networks and decreases quickly with network size"
]
#sslide[
This is a difficult finding to conceptualize #pause
The plots I show you are always 3D (2 parameters) #pause
For neural networks with 1,000,000+ parameters, our geometric intuition begins to fail #pause
We understand bigger/deeper networks often perform better, but we are missing deeper theory #pause
We call such networks *overparameterized* neural networks
]
#sslide[
To summarize, deeper and wider neural networks tend to produce better results #pause
Add more layers to your network #pause
Increase the width of each layer
]
#sslide[
#side-by-side(align: top)[
```python
# Deep neural network
from torch import nn
d_x, d_y, d_h = 1, 1, 16
# Linear(input, output)
l1 = nn.Linear(d_x, d_h)
l2 = nn.Linear(d_h, d_y)
``` #pause
][
```python
# Deeper and wider neural network
from torch import nn
d_x, d_y, d_h = 1, 1, 256
# Linear(input, output)
l1 = nn.Linear(d_x, d_h)
l2 = nn.Linear(d_h, d_h)
l3 = nn.Linear(d_h, d_h)
...
l6 = nn.Linear(d_h, d_y)
```
]
]
#sslide[
```python
import torch
d_x, d_y, d_h = 1, 1, 256
net = torch.nn.Sequential(
torch.nn.Linear(d_x, d_h),
torch.nn.Sigmoid(),
torch.nn.Linear(d_h, d_h),
torch.nn.Sigmoid(),
...
torch.nn.Linear(d_h, d_y),
)
x = torch.ones((d_x,))
y = net(x)
```
]
// 32:00 + 15:00
#sslide[
```python
import jax, equinox
d_x, d_y, d_h = 1, 1, 256
net = equinox.nn.Sequential([
equinox.nn.Linear(d_x, d_h),
equinox.nn.Lambda(jax.nn.sigmoid),
equinox.nn.Linear(d_h, d_h),
equinox.nn.Lambda(jax.nn.sigmoid),
...
equinox.nn.Linear(d_h, d_y),
])
x = jax.numpy.ones((d_x,))
y = net(x)
```
]
#aslide(ag, 3)
#aslide(ag, 4)
#sslide[
The sigmoid function was the standard activation function until \~ 2012 #pause
#cimage("figures/lecture_1/timeline.svg", width: 90%) #pause
In 2012, people realized that ReLU activation performed much better
]
#sslide[
#side-by-side[#sigmoid #pause][
The sigmoid function can result in a *vanishing gradient* #pause
$ f(bold(x), bold(theta)) = sigma(bold(theta)_3^top sigma(bold(theta)_2^top sigma(bold(theta)_1^top overline(bold(x))))) $ #pause
]
#only(4)[
$ gradient_bold(theta_1) f(bold(x), bold(theta)) =
gradient [sigma](bold(theta)_3^top sigma(bold(theta)_2^top sigma(bold(theta)_1^top overline(bold(x)))))
dot gradient[sigma](bold(theta)_2^top sigma(bold(theta)_1^top overline(bold(x))))
dot gradient[sigma](bold(theta)_1^top overline(bold(x)))
$
]
#only((5,6))[
$ gradient_bold(theta_1) f(bold(x), bold(theta)) =
underbrace(gradient [sigma](bold(theta)_3^top sigma(bold(theta)_2^top sigma(bold(theta)_1^top overline(bold(x))))), < 0.5)
dot underbrace(gradient[sigma](bold(theta)_2^top sigma(bold(theta)_1^top overline(bold(x)))), < 0.5)
dot underbrace(gradient[sigma](bold(theta)_1^top overline(bold(x))), < 0.5)
$
]
#only(6)[
$ gradient_bold(theta_1) f(bold(x), bold(theta)) approx 0 $
]
]
// Stopped here
#sslide[
#only((1,2))[To fix the vanishing gradient, researchers use the *rectified linear unit (ReLU)*]
#side-by-side[$ sigma(x) = max(0, x) \ gradient sigma(x) = cases(0 "if" x < 0, 1 "if" x >= 0) $ #pause][#relu #pause]
#only((3,4,5))[Looks nothing like a biological neuron]
#only((4,5,6))[However, it works much better than sigmoid in practice]
#only((5,6,7))[Via chain rule, gradient is $1 dot 1 dot 1 dots$ which does not vanish]
#only((6,7,8))[If layers outputs one positive number, gradient will not vanish]
#only((7,8,9))[*Question:* Any problems?]
#only((8,9,10))[*Answer:* Zero gradient region!]
#only((9, 10))[Neurons can get "stuck", always output 0]
#only((10))[These neurons cannot recover, they are *dead neurons*]
]
#sslide[
#side-by-side[$ sigma(x) = max(0, x) \ gradient sigma(x) = cases(0 "if" x < 0, 1 "if" x >= 0) $ ][#relu]
These neurons cannot recover, they are *dead neurons* #pause
Training for longer results in more dead neurons #pause
Dead neurons hurt your network!
]
#sslide[
To fix dying neurons, use *leaky ReLU* #pause
#side-by-side[$ sigma(x) = max(0.1 x, x) \ gradient sigma(x) = cases(0.1 "if" x < 0, 1 "if" x >= 0) $ #pause][#lrelu #pause]
Small negative slope allows dead neurons to recover
]
#sslide[
#side-by-side[
There are other activation functions that are better than leaky ReLU #pause
- Mish #pause
- Swish #pause
- ELU #pause
- GeLU #pause
- SeLU #pause
][
#cimage("figures/lecture_6/activations.png")
] #pause
They are all very similar #pause
I usually use leaky ReLU because it works well enough
]
#sslide[
https://pytorch.org/docs/stable/nn.html#non-linear-activations-weighted-sum-nonlinearity
https://jax.readthedocs.io/en/latest/jax.nn.html#activation-functions
]
#aslide(ag, 4)
#aslide(ag, 5)
#sslide[
Recall 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)$]
})
})
]
#sslide[
Initial $bold(theta)$ is starting position for gradient descent #pause
#cimage("figures/lecture_6/poor_minima.png", height: 70%) #pause
Pick $bold(theta)$ that results in good local minima
]
#sslide[
Start simple, initialize all parameters to 0
$ bold(theta) = mat(
0, dots, 0;
dots.v, dots.down, dots.v;
0, dots, 0
), mat(
0, dots, 0;
dots.v, dots.down, dots.v;
0, dots, 0
), dots $ #pause
*Question:* Any issues? #pause
*Answer:* For ReLU activation, the gradient will always be zero
$ gradient_bold(theta)_1 f = gradient[sigma] (bold(theta)^top_2 sigma( bold(theta)_1^top overline(bold(x)))) space gradient[sigma]( bold(theta)_1^top overline(bold(x))) space overline(bold(x)) $ #pause
$ gradient_bold(theta)_1 f = gradient[sigma] (bold(0)^top sigma ( bold(0)^top overline(bold(x)))) space gradient[sigma] ( bold(0)_1^top overline(bold(x))) space overline(bold(x)) = 0 $
]
#sslide[
Ok, so initialize $bold(theta) = bold(1)$ #pause
$ bold(theta) = mat(
1, dots, 1;
dots.v, dots.down, dots.v;
1, dots, 1
), mat(
1, dots, 1;
dots.v, dots.down, dots.v;
1, dots, 1
), dots $ #pause
*Question:* Any issues? #pause
$ z_i = sigma(sum_(j=1)^d_x theta_j dot overline(x)_j) = sigma(sum_(j=1)^d_x overline(x)_j) $ #pause
All neurons in layer have the same gradient,and will receive the same update. Equivalent to a network of width 1, not good!
]
#sslide[
We randomly initialize $bold(theta)$ to break symmetry
$ bold(theta) = mat(
-0.5, dots, 2;
dots.v, dots.down, dots.v;
0.1, dots, 0.6
), mat(
1.3, dots, 1.2;
dots.v, dots.down, dots.v;
-0.8, dots, -1.1
), dots $ #pause
But what scale? If $bold(theta) << 0$ the gradient will vanish to zero, if $bold(theta) >> 0$ the gradient explode to infinity #pause
Almost everyone initializes following a single paper from 2010: #pause
- <NAME>, and <NAME>. "Understanding the difficulty of training deep feedforward neural networks." #pause
- Maybe there are better options?
]
#sslide[
Here is the magic equation, given the input and output size of the layer is $d_h$
$ bold(theta) tilde cal(U)[ - sqrt(6) / sqrt(2 d_h), sqrt(6) / sqrt(2 d_h)] $ #pause
If you have different input or output sizes, such as $d_x, d_y$, then the equation is
$ bold(theta) tilde cal(U)[ - sqrt(6) / sqrt(d_x + d_y), sqrt(6) / sqrt(d_x + d_y)] $
]
#sslide[
These equations are designed for ReLU and similar activation functions #pause
They prevent vanishing or exploding gradients
]
#sslide[
Usually `torch` and `jax/equinox` will automatically use this initialization when you create `nn.Linear`
```python
layer = nn.Linear(d_x, d_h) # Uses Glorot init
```
You can find many initialization functions at https://pytorch.org/docs/stable/nn.init.html
For JAX it is https://jax.readthedocs.io/en/latest/jax.nn.initializers.html
]
#sslide[
```python
import torch
d_h = 10
# Manually
theta = torch.zeros((d_h + 1, d_h))
torch.nn.init.xavier_uniform_(theta)
theta = torch.nn.Parameter(theta)
# Using nn.Linear
layer = torch.nn.Linear(d_h, d_h)
# Use .data, to bypass autograd security
torch.nn.init.xavier_uniform_(layer.weight.data)
torch.nn.init.xavier_uniform_(layer.bias.data) # Or zero
```
]
#sslide[
```python
import jax
d_h = 10
init = jax.nn.initializers.glorot_uniform()
theta = init(jax.random.key(0), (d_h + 1, d_h))
```
]
#sslide[
```python
import jax, equinox
d_h = 10
layer = equinox.nn.Linear(d_h, d_h, key=jax.random.key(0))
# Create new bias and weight
init = jax.nn.initializers.glorot_uniform()
new_weight = init(jax.random.key(1), (d_h, d_h))
new_bias = init(jax.random.key(2), (d_h,))
# Use a lambda function to save space
# tree_at creates a new layer with the new weight
layer = equinox.tree_at(lambda l: l.weight, layer, new_weight)
layer = equinox.tree_at(lambda l: l.bias, layer, new_weight)
```
]
#sslide[
Remember, in `equinox` and `torch`, `nn.Linear` is already initialized correctly! #pause
In some cases, you may want to use different initializations #pause
- Reinforcement learning #pause
- Recurrent neural networks
]
#aslide(ag, 5)
#aslide(ag, 6)
// Now, let us talk a little bit more about optimization
// We computed the gradient over the entire training dataset
// This works with the datasets we have examined so far
// However, some datasets are much larger
// >700 TB Datasets for Large Language Models: A Comprehensive Survey
// We cannot fit this dataset into the memory on colab, so what do we do?
// We introduce stochastic gradient Descent
// Rather than compute the gradient over the dataset
// We approximate the gradient in a stochastic manner
// algorithm
// Really hard problems can have many local optima
// They can also have very large datasets
// We do not like getting stuck in local minima
#sslide[
#algorithm({
import algorithmic: *
Function("Gradient Descent", args: ($bold(X)$, $bold(Y)$, $cal(L)$, $t$, $alpha$), {
Cmt[Randomly initialize parameters]
Assign[$bold(theta)$][$"Glorot"()$]
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 dot bold(J)$]
})
Return[$bold(theta)$]
})
}) #pause
Gradient descent computes $gradient cal(L)$ over all $bold(X)$
]
#sslide[
This works for our small datasets, where $n = 1000$ #pause
*Question:* How many GB are the LLM datasets? #pause
*Answer:* About 774,000 GB according to _Datasets for Large Language Models: A Comprehensive Survey_ #pause
This is just the dataset size, the gradient is orders of magnitude larger
$ gradient_bold(theta) cal(L)(bold(x)_[i], bold(y)_[i], bold(theta)) = mat(
(partial f_1) / (partial x_1), dots, (partial f_ell) / (partial x_1);
dots.v, dots.down, dots.v;
(partial f_n) / (partial x_1), dots, (partial f_ell) / (partial x_1);
)_[i]
$
]
#sslide[
*Question:* We do not have enough memory to compute the gradient. What can we do? #pause
*Answer:* We approximate the gradient using a subset of the data #pause
We call this *stochastic gradient descent* (SGD)
]
/*
#sslide[
First, we sample random datapoint indices
$ i, j, k, dots tilde cal(U)[1, n] $ #pause
Then construct a *batch* of training data
$ vec(bold(x)_[i], bold(x)_[j], bold(x)_[k], dots.v); quad vec(bold(y)_[i], bold(y)_[j], bold(y)_[k], dots.v) $ #pause
We call this *stochastic gradient descent*
]
*/
#sslide[
#algorithm({
import algorithmic: *
Function("Stochastic Gradient Descent", args: ($bold(X)$, $bold(Y)$, $cal(L)$, $t$, $alpha$), {
Assign[$bold(theta)$][$"Glorot"()$]
For(cond: $i in 1 dots t$, {
Assign[$bold(X), bold(Y)$][$"Shuffle"(bold(X)), "Shuffle"(bold(Y))$]
For(cond: $j in 0 dots n / B - 1$, {
Assign[$bold(X)_j$][$mat(bold(x)_[ j B], bold(x)_[ j B + 1], dots, bold(x)_[ (j + 1) B - 1])^top$]
Assign[$bold(Y)_j$][$mat(bold(y)_[ j B], bold(y)_[ j B + 1], dots, bold(y)_[ (j + 1) B - 1])^top$]
Assign[$bold(J)$][$gradient_bold(theta) cal(L)(bold(X)_j, bold(Y)_j, bold(theta))$]
Assign[$bold(theta)$][$bold(theta) - alpha bold(J)$]
})
})
Return[$bold(theta)$]
})
})
]
#sslide[
Stochastic gradient descent (SGD) is useful for saving memory #pause
But it can also improve performance #pause
Since the "dataset" changes every update, so does the loss manifold #pause
This makes it less likely we get stuck in bad optima
#cimage("figures/lecture_5/saddle.png")
]
#sslide[
`torch.utils.data.DataLoader` helps with SGD #pause
```python
import torch
dataloader = torch.utils.data.DataLoader(
training_data,
batch_size=32, # How many datapoints to sample
shuffle=True, # Randomly shuffle each epoch
)
for epoch in number_of_epochs:
for batch in dataloader:
X_j, Y_j = batch
loss = L(X_j, Y_j, theta)
...
```
]
#aslide(ag, 6)
#focus-slide[Relax]
#aslide(ag, 7)
#sslide[
Gradient descent is a powerful tool, but it has issues #pause
+ It can be slow to converge #pause
+ It can get stuck in poor local optima #pause
Improve gradient descent convergence rate, while also preventing premature convergence #pause
It is hard to teach adaptive optimization solely through equations #pause
I want to show you a video to prepare you
https://www.youtube.com/watch?v=MD2fYip6QsQ&t=77s
]
#sslide[
The video simulations provide an intuitive understanding of adaptive optimizers #pause
The key behind modern optimizers is two concepts:
- Momentum #pause
- Adaptive learning rate #pause
Let us discuss the algorithms more slowly
]
#sslide[
Review gradient descent again, because we will be making changes to it #pause
#algorithm({
import algorithmic: *
Function("Gradient Descent", args: ($bold(X)$, $bold(Y)$, $cal(L)$, $t$, $alpha$), {
Cmt[Randomly initialize parameters]
Assign[$bold(theta)$][$"Glorot"()$]
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 dot bold(J)$]
})
Return[$bold(theta)$]
})
})
]
#sslide[
Introduce *momentum* first #pause
#algorithm({
import algorithmic: *
Function(redm[$"Momentum"$] + " Gradient Descent", args: ($bold(X)$, $bold(Y)$, $cal(L)$, $t$, $alpha$, redm[$beta$]), {
Assign[$bold(theta)$][$"Glorot"()$]
Assign[#redm[$bold(M)$]][#redm[$bold(0)$] #text(fill:red)[\# Init momentum]]
For(cond: $i in 1 dots t$, {
Assign[$bold(J)$][$gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta))$ #text(fill: red)[\# Represents acceleration]]
Assign[#redm[$bold(M)$]][#redm[$beta dot bold(M) + (1 - beta) dot bold(J)$] #text(fill: red)[\# Momentum and acceleration]]
Assign[$bold(theta)$][$bold(theta) - alpha dot #redm[$bold(M)$]$]
})
Return[$bold(theta)$]
})
})
]
#sslide[
Now *adaptive learning rate* #pause
#algorithm({
import algorithmic: *
Function(redm[$"RMSProp"$], args: ($bold(X)$, $bold(Y)$, $cal(L)$, $t$, $alpha$, $beta$, redm[$epsilon$]), {
Assign[$bold(theta)$][$"Glorot"()$]
Assign[#redm[$bold(V)$]][#redm[$bold(0)$] #text(fill: red)[\# Init variance]]
For(cond: $i in 1 dots t$, {
Assign[$bold(J)$][$gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta))$ \# Represents acceleration]
Assign[#redm[$bold(V)$]][#redm[$beta dot bold(V) + (1 - beta) dot bold(J) dot.circle bold(J) $] #text(fill: red)[\# Magnitude]]
Assign[$bold(theta)$][$bold(theta) - alpha dot #redm[$bold(J) ⊘ root(dot.circle, bold(V) + epsilon)$]$ #text(fill: red)[\# Rescale grad by prev updates]]
})
Return[$bold(theta)$]
})
})
]
#sslide[
Combine *momentum* and *adaptive learning rate* to create *Adam* #pause
#algorithm({
import algorithmic: *
Function("Adaptive Moment Estimation", args: ($bold(X)$, $bold(Y)$, $cal(L)$, $t$, $alpha$, greenm[$beta_1$], bluem[$beta_2$], bluem[$epsilon$]), {
Assign[$bold(theta)$][$"Glorot"()$]
Assign[$#greenm[$bold(M)$], #bluem[$bold(V)$]$][$bold(0)$]
For(cond: $i in 1 dots t$, {
Assign[$bold(J)$][$gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta))$]
Assign[#greenm[$bold(M)$]][#greenm[$beta_1 dot bold(M) + (1 - beta_1) bold(J)$] \# Compute momentum]
Assign[#bluem[$bold(V)$]][#bluem[$beta_2 dot bold(V) + (1 - beta_2) dot bold(J) dot.circle bold(J)$] \# Magnitude]
//Assign[$hat(bold(M))$][$bold(M) "/" (1 - beta_1)$ \# Bias correction]
//Assign[$hat(bold(V))$][$bold(V) "/" (1 - beta_2)$ \# Bias correction]
Assign[$bold(theta)$][$bold(theta) - alpha dot #greenm[$bold(M)$] #bluem[$⊘ root(dot.circle, bold(V) + epsilon)$]$ \# Adaptive param update]
})
Return[$bold(theta)$ \# Note, we use biased $bold(M), bold(V)$ for clarity]
})
})
]
#sslide[
```python
import torch
betas = (0.9, 0.999)
net = ...
theta = net.parameters()
sgd = torch.optim.SGD(theta, lr=alpha)
momentum = torch.optim.SGD(
theta, lr=alpha, momentum=betas[0])
rmsprop = torch.optim.RMSprop(
theta, lr=alpha, momentum=betas[1])
adam = torch.optim.Adam(theta, lr=alpha, betas=betas)
...
sgd.step(), momentum.step(), rmsprop.step(), adam.step()
```
]
#sslide[
```python
import optax
betas = (0.9, 0.999)
theta = ...
sgd = optax.sgd(lr=alpha)
momentum = optax.sgd(lr=alpha, momentum=betas[0])
rmsprop = optax.rmsprop(lr=alpha, decay=betas[1])
adam = optax.adam(lr=alpha, b1=betas[0], b2=betas[1])
v = rmsprop.init(theta)
theta, v = rmsprop.update(J, v, theta)
mv = adam.init(theta) # contains M and V
theta, mv = mv.update(J, mv, theta)
```
]
#aslide(ag, 7)
#aslide(ag, 8)
#sslide[
Many modern optimizers also include *weight decay* #pause
Weight decay penalizes large parameters #pause
$ cal(L)_("decay")(bold(X), bold(Y), bold(theta)) = cal(L)_("decay")(bold(X), bold(Y), bold(theta)) + lambda sum_(i) theta_i^2 $ #pause
This results in a smoother, parabolic loss landscape that is easier to optimize #pause
(Unproven opinion) It reduces the number of saddle points and local minima
]
#sslide[
$ z = sin^2(x) + sin^2(y) $
#side-by-side[
#cimage("figures/lecture_6/wd0.png")
][
#cimage("figures/lecture_6/wd1.png")
]
]
#sslide[
Weight decay is built into the Adam optimizer #pause
But the implementation is wrong! #pause
Years later, someone noticed and published a new paper that fixes weight decay implementation #pause
```python
Lambda = 0.01
opt = torch.optim.adamw(..., weight_decay=Lambda)
opt = optax.adamw(..., weight_decay=Lambda)
```
]
#aslide(ag, 8)
#aslide(ag, 9)
#sslide[
https://colab.research.google.com/drive/1qTNSvB_JEMnMJfcAwsLJTuIlfxa_kyTD#scrollTo=YVkCyz78x4Rp
] |
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/098.%20artistsship.html.typ | typst | artistsship.html
The Other Half of "Artists Ship"
November 2008One of the differences between big companies and startups is that
big companies tend to have developed procedures to protect themselves
against mistakes. A startup walks like a toddler, bashing
into things and falling over all the time. A big company is more
deliberate.The gradual accumulation of checks in an organization is a kind of
learning, based on disasters that have happened to it or others
like it. After giving a contract to a supplier who goes bankrupt
and fails to deliver, for example, a company might require all
suppliers to prove they're solvent before submitting bids.As companies grow they invariably get more such checks, either in
response to disasters they've suffered, or (probably more often)
by hiring people from bigger companies who bring with them customs
for protecting against new types of disasters.It's natural for organizations to learn from mistakes. The problem
is, people who propose new checks almost never consider that the
check itself has a cost.Every check has a cost. For example, consider the case of making
suppliers verify their solvency. Surely that's mere prudence? But
in fact it could have substantial costs. There's obviously the
direct cost in time of the people on both sides who supply and check
proofs of the supplier's solvency. But the real costs are the ones
you never hear about: the company that would be the best supplier,
but doesn't bid because they can't spare the effort to get verified.
Or the company that would be the best supplier, but falls just short
of the threshold for solvency—which will of course have been set
on the high side, since there is no apparent cost of increasing it.Whenever someone in an organization proposes to add a new check,
they should have to explain not just the benefit but the cost. No
matter how bad a job they did of analyzing it, this meta-check would
at least remind everyone there had to be a cost, and send them
looking for it.If companies started doing that, they'd find some surprises. <NAME> recently spoke at Y Combinator about selling software to
corporate customers. He said that in most companies software costing
up to about $1000 could be bought by individual managers without
any additional approvals. Above that threshold, software purchases
generally had to be approved by a committee. But babysitting this
process was so expensive for software vendors that it didn't make
sense to charge less than $50,000. Which means if you're making
something you might otherwise have charged $5000 for, you have to
sell it for $50,000 instead.The purpose of the committee is presumably to ensure that the company
doesn't waste money. And yet the result is that the company pays
10 times as much.Checks on purchases will always be expensive, because the harder
it is to sell something to you, the more it has to cost. And not
merely linearly, either. If you're hard enough to sell to, the
people who are best at making things don't want to bother. The
only people who will sell to you are companies that specialize in
selling to you. Then you've sunk to a whole new level of inefficiency.
Market mechanisms no longer protect you, because the good suppliers
are no longer in the market.Such things happen constantly to the biggest organizations of all,
governments. But checks instituted by governments can cause much
worse problems than merely overpaying. Checks instituted by
governments can cripple a country's whole economy. Up till about
1400, China was richer and more technologically advanced than Europe.
One reason Europe pulled ahead was that the Chinese government
restricted long trading voyages. So it was left to the Europeans
to explore and eventually to dominate the rest of the world, including
China.In more recent times, Sarbanes-Oxley has practically destroyed the
US IPO market. That wasn't the intention of the legislators who
wrote it. They just wanted to add a few more checks on public
companies. But they forgot to consider the cost. They forgot that
companies about to go public are usually rather stretched, and that
the weight of a few extra checks that might be easy for General
Electric to bear are enough to prevent younger companies from being
public at all.Once you start to think about the cost of checks, you can start to
ask other interesting questions. Is the cost increasing or decreasing?
Is it higher in some areas than others? Where does it increase
discontinuously? If large organizations started to ask questions
like that, they'd learn some frightening things.I think the cost of checks may actually be increasing. The reason
is that software plays an increasingly important role in companies,
and the people who write software are particularly harmed by checks.Programmers are unlike many types of workers in that the best ones
actually prefer to work hard. This doesn't seem to be the case in
most types of work. When I worked in fast food, we didn't prefer
the busy times. And when I used to mow lawns, I definitely didn't
prefer it when the grass was long after a week of rain.Programmers, though, like it better when they write more code. Or
more precisely, when they release more code. Programmers like to
make a difference. Good ones, anyway.For good programmers, one of the best things about working for a
startup is that there are few checks on releases. In true startups,
there are no external checks at all. If you have an idea for a new
feature in the morning, you can write it and push it to the production
servers before lunch. And when you can do that, you have more
ideas.At big companies, software has to go through various approvals
before it can be launched. And the cost of doing this can be
enormous—in fact, discontinuous. I was talking recently to a
group of three programmers whose startup had been acquired a few
years before by a big company. When they'd been independent, they
could release changes instantly. Now, they said, the absolute
fastest they could get code released on the production servers was
two weeks.This didn't merely make them less productive. It made them hate
working for the acquirer.Here's a sign of how much programmers like to be able to work hard:
these guys would have paid to be able to release code immediately,
the way they used to. I asked them if they'd trade 10% of the
acquisition price for the ability to release code immediately, and
all three instantly said yes. Then I asked what was the maximum
percentage of the acquisition price they'd trade for it. They said
they didn't want to think about it, because they didn't want to
know how high they'd go, but I got the impression it might be as
much as half.They'd have sacrificed hundreds of thousands of dollars, perhaps
millions, just to be able to deliver more software to users. And
you know what? It would have been perfectly safe to let them. In
fact, the acquirer would have been better off; not only wouldn't
these guys have broken anything, they'd have gotten a lot more done.
So the acquirer is in fact getting worse performance at greater
cost. Just like the committee approving software purchases.And just as the greatest danger of being hard to sell to is not
that you overpay but that the best suppliers won't even sell to
you, the greatest danger of applying too many checks to your
programmers is not that you'll make them unproductive, but that
good programmers won't even want to work for you.<NAME>'s famous maxim "artists ship" works both ways. Artists
aren't merely capable of shipping. They insist on it. So if you
don't let people ship, you won't have any artists.
|
|
https://github.com/kdog3682/2024-typst | https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/ex-riemann-graph.typ | typst | // how do length and size work for these plots?
#set page(margin: 0.5pt)
#import "@preview/cetz:0.2.0"
#let exists(params) = {
return true
}
// utility helper
#let get-anchor(a, b, ..args) = {
let key = str(a) + "." + str(b)
let args.named().at("delimiter", default: "")
let positional = args.pos()
if positional.len() > 0 {
return positional.map((x) => key + delimiter + x)
}
return key
}
#let plotter(plot, body) = {
plot.plot(name: "plot", size: (6, 6),
// x-grid: true,
// y-grid: true,
// grid: true, // doesnt work
axis-style: "school-book",
x-tick-step: 2,
x-minor-tick-step: 1,
y-tick-step: auto, {
body
})
}
#let grapher(domain, fn, length: 0.5in, riemann: (beneath: true, rect-style: (fill: yellow.lighten(80%)))) = cetz.canvas(length: length, {
import cetz.plot
import cetz.draw: *
plotter(plot, {
plot.add(domain: domain, fn)
// these anchors normalize the rectangle to the graph
// this normaliztion is more effective
if exists(riemann) {
for i in range(..domain) {
let value = if i > 0 {
fn(i)
} else if i < 0 {
fn(i + 1)
} else {
0
}
plot.add-anchor(str(i) + "a", (i, value))
plot.add-anchor(str(i) + "b", (i + 1, 0))
}
}
})
if exists(riemann) {
for i in range(..domain) {
let (a, b) = get-anchor("plot", i, "a", "b")
rect(a, b, ..riemann.rect-style)
}
}
})
#grapher((-5, 5), x => -calc.pow(x, 3))
|
|
https://github.com/danbalarin/vse-typst-template | https://raw.githubusercontent.com/danbalarin/vse-typst-template/main/lib/macros.typ | typst | #import "headings.typ": heading-blocks
#let heading-like(body, level: 1) = {
heading-blocks.at(level)(body)
}
#let revisit(body) = {
box(
fill: luma(205),
outset: (y: 6pt, x: 6pt),
radius: 2pt
)[
#text(fill: color.hsl(0deg, 100%, 47%))[#body]
]
}
#let custom-lorem = (number) => {
revisit[#lorem(number)]
} |
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/数理逻辑/作业/ml-2_2-hw.typ | typst | #import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark
#import "../../template.typ": *
#import "../main.typ": not1, True, False, infer
#import "../main.typ": *
#show: note.with(
title: "作业2_1",
author: "YHTQ",
date: datetime.today().display(),
logo: none,
withOutlined : false,
withTitle : false,
withHeadingNumbering: false
)
#set heading(numbering:
(..nums) =>
{
let nums1 = nums.pos()
nums1.insert(0, 4)
numbering("1.1.(a)", ..nums1)
}
)
= #empty
(本题中 $=$ 均指真值相等)\
由于替换原理,只需证明公理模式中变量均为元变量时情景即可。
- $L1 : p_1 -> (p_2 -> p_1)$\
显然 $p_1 = True$ 时 $p_2 -> p_2 = True$,因此是重言式
- $L2 : (p_1 -> (p_2 -> p_3)) -> ((p_1 -> p_2) -> (p_1 -> p_3))$\
$p_1 = False$ 时公式化简为 $True -> (True -> True)$,$p_1 = True$ 时化简为 $(p_2 -> p_3) -> (p_2 -> p_3)$,都是重言式
- $L3 : (not1 p_1 -> not1 p_2) -> (p_2 -> p_1) $\
注意到:
$
(not1 p_1 -> not1 p_2) -> (p_2 -> p_1) &= (not1 not1 p_1 or not1 p_2) -> (not1 p_2 or p_1) \
&= (p_1 or not1 p_2) -> (not1 p_2 or p_1)
$
而熟知 $p_1 or not1 p_2 = not1 p_2 or p_1$,因此上式是重言式
= #empty
== #empty
#let tL = $tack_L$
#let tL1 = $tack_(L^+)$
- 一方面,若 $calA$ 是 $L$ 中定理,则 $tL calB <=> {A} tack_L calB <=> tL1 calB$
- 另一方面,假设 $calA$ 不是 $L$ 中定理,而它显然是 $L^+$ 中定理,因此定理集不同。
== #empty
由于 $L^+$ 只是比 $L$ 增加了公理,定理集扩大是显然的。\
在 $L$ 中有:
$
(not1 p_1 -> p_2) -> (p_1 -> not1 p_2) = (not1 not1 p_1 or p_2) -> (not1 p_1 or not1 p_2) = (p_1 or p_2) -> (not1 p_1 or not1 p_2)
$
容易验证它不是永假式,因此 $not1 calA$ 不是重言式,由完全性定理它不是 $L$ 中定理,因此 $L$ 中加入 $not1 not1 calA$ 是一致扩张。熟知 $calA tack not1 not1 calA, not1 not1 calA tack calA$,因此这个扩张等价于 $L^+$,自然 $L^+$ 是一致的。
= #empty
显然若 $calB$ 是矛盾,则 $calB models$ 任意公式,由完全性 $calB tL$ 所有公式,这将导致 $tL1$ 所有公式,意味着 $L^+$ 不是一致的。
= #empty
由于 $J$ 是一致完全扩充,因此 $calA, not1 calA$ 恰有一个是其中定理:
- 如果 $calA$ 是定理,则加上 $calA$ 的扩张还是本身,当然是一致的
- 如果 $calA$ 不是定理,则 $not1 calA$ 是定理,将导致扩充后 $calA, not1 calA$ 同时是定理,导致不一致性
= #empty
#let line = math.hyph.nobreak
#let lines(n) = $line$ * n
#let ax(x) = $#x line q #x p line$
#let implyPre(x, y, z) = $#x q #y p #z $
#let imply(x, y, z) = $#x line q #y p #z line$
取 $x = #lines(1)$,则 $ax(line)$ 是公理模式产生的公理\
取 $x = #lines(2), y = line, z = line$,则上面说明 $implyPre(#lines(2), line, line)$ 是定理,由推理规则 $imply(#lines(2), line, line)$ 是定理\
#lemma[][
系统中定理一定形如 $x q y p z$,其中 $x, y, z$ 都只由 $line$ 构成
]<f-lemma>
#proof[
- 由公理模式生成的定理显然符合该形式
- 由推理规则生成的定理显然也符合该形式
因此所有定理都符合该形式
]
公式是否具有上述形式是容易判定的,不符合该形式的公式一定不是定理,因此下面只讨论符合该形式的公式。\
#definition[][
- 定义所有符合 @f-lemma 的公式集为 $cal(F)$,定理集为 $cal(T)$
- 若 $x$ 是只由 #line 组成的公式,定义 $n(x)$ 为其中 #line 的数量,显然若 $x, y$ 都是这样的公式则 $x = y <=> n(x) = n(y)$
- 定义:
$
funcDef(v, cal(F), NN^3, x q y p z, (n(x), n(y), n(z)))
$
@f-lemma 保证了定义合理,同时显然有 $v(x) = v(y) <=> x = y$
]
#lemma()[][
设 $calA in cal(F)$,则 $calA in cal(T) <=> v(calA) in v(cal(T))$
]<completeness>
#proof[
前面已经说明 $v$ 是单射,做简单的集合逻辑运算即可。
]
#proposition[][
- $calA$ 是公理模式生成的公理当且仅当 $exists n, v(calA) = (n+1, n, 1)$
- 设 $calA$ 是定理且 $n(calA) = (r, s, t)$,则由推理规则生成的定理 $calB$ 满足 $(r+1, s, t+1)$
- $v(cal(T)) + (1, 0, 1) subset v(cal(T))$
]
#proof[
- 若 $calA$ 是公理模式生成的公理,则取 $n = n(x)$ 即可。反之,取 $x = n$ 个 #line 即可
- 显然
- 任取 $v(calA) in v(cal(T)) <=> calA in cal(T)$,则 $calA$ 利用推理规则生成的定理 $calB in cal(T)$ 恰好满足 $v(calB) = v(calA) + (1, 0, 1)$,因此 $v(calA) + (1, 0, 1) in v(cal(T))$,得证
]
#theorem[][
定义:
$
funcDef(p, NN^3, NN^3, (a\, b\, c), (a+1\, b\, c+1))\
funcDef(f, P(NN^3), P(NN^3), S, S union p(S))\
$
并设 $S_0 = {(n+1, n, 1) | n in NN}$,则有:
$
v(cal(T)) = union_(n in NN) f^n (S_0)
$
更进一步,它等于 $union_(n in NN) f^n ({(m + 1, m , 1) | m in NN}) = {(m + n + 1, m, n + 1) | m, n in NN}$
]<semantics>
#proof[
由形式系统的定义及上面的命题,$v(cal(T))$ 就是 $S_0$ 在 $f$ 作用下的闭包,当然具有上面的形式。之后的计算是容易的。
]
@semantics 结合 @completeness 即可得到定理的判定方法。在 @semantics 给出的语义下,它是完全的,但并不完全是加法,因为从 @semantics 可以看出 $0 + 0$ 并不能在此语言中被表达。换言之,若以自然数加法为语义则它具有 soundness ,但不具有 completeness 。 |
|
https://github.com/dadn-dream-home/documents | https://raw.githubusercontent.com/dadn-dream-home/documents/main/contents/07-thiet-ke-kien-truc/index.typ | typst | = Thiết kế kiến trúc
Nhóm đề xuất mẫu thiết kế ở backend và frontend như sau.
#include "1-backend/index.typ"
#include "2-frontend/index.typ" |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/game-theoryst/0.1.0/src/utils/programming_utils.typ | typst | Apache License 2.0 |
#let if-else(condition, tru-val, fal-val) = {
if condition { tru-val } else { fal-val }
}
#let if-none(obj, tru-val, fal-val) = {
if-else(obj == none, tru-val, fal-val)
}
// Utility: Require Key
#let req-key(dict, key, warn: none) = {
if key not in dict.keys() {
if (warn == none) {
dict.insert(key, none)
} else {
assert(false, message: warn)
}
}
return dict
}
// Require keys
#let req-keys(dict, keys, warn: none) = {
for key in keys { dict = req-key(dict, key) }
return dict
} |
https://github.com/ivaquero/book-control | https://raw.githubusercontent.com/ivaquero/book-control/main/control.typ | typst | #let chapter(filename) = {
include filename
context counter(heading).update(0)
}
#chapter("01-动态系统.typ")
#chapter("02-传递函数.typ")
#chapter("03-状态空间方程.typ")
#chapter("04-时域响应分析.typ")
#chapter("05-比例积分控制.typ")
#chapter("06-比例微分控制.typ")
#chapter("07-频域响应分析.typ")
#chapter("08-奈奎斯特稳定性.typ")
#chapter("09-控制器设计.typ")
#chapter("10-状态观测器.typ")
#chapter("11-反馈线性化控制.typ")
#chapter("12-非线性控制器.typ")
#chapter("13-动态规划.typ")
#chapter("14-线性二次型调节器.typ")
#chapter("15-轨迹追踪.typ")
#chapter("16-模型预测控制器.typ")
#chapter("A-傅立叶变换.typ")
#chapter("B-复矩阵.typ")
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/layout/grid/headers.typ | typst | --- grid-headers ---
#set page(width: auto, height: 12em)
#table(
columns: 5,
align: center + horizon,
table.header(
table.cell(colspan: 5)[*Cool Zone*],
table.cell(stroke: red)[*Name*], table.cell(stroke: aqua)[*Number*], [*Data 1*], [*Data 2*], [*Etc*],
table.hline(start: 2, end: 3, stroke: yellow)
),
..range(0, 6).map(i => ([John \##i], table.cell(stroke: green)[123], table.cell(stroke: blue)[456], [789], [?], table.hline(start: 4, end: 5, stroke: red))).flatten()
)
--- grid-headers-no-repeat ---
// Disable repetition
#set page(width: auto, height: 12em)
#table(
columns: 5,
align: center + horizon,
table.header(
table.cell(colspan: 5)[*Cool Zone*],
table.cell(stroke: red)[*Name*], table.cell(stroke: aqua)[*Number*], [*Data 1*], [*Data 2*], [*Etc*],
table.hline(start: 2, end: 3, stroke: yellow),
repeat: false
),
..range(0, 6).map(i => ([John \##i], table.cell(stroke: green)[123], table.cell(stroke: blue)[456], [789], [?], table.hline(start: 4, end: 5, stroke: red))).flatten()
)
--- grid-headers-gutter ---
#set page(width: auto, height: 12em)
#table(
columns: 5,
align: center + horizon,
gutter: 3pt,
table.header(
table.cell(colspan: 5)[*Cool Zone*],
table.cell(stroke: red)[*Name*], table.cell(stroke: aqua)[*Number*], [*Data 1*], [*Data 2*], [*Etc*],
table.hline(start: 2, end: 3, stroke: yellow),
),
..range(0, 6).map(i => ([John \##i], table.cell(stroke: green)[123], table.cell(stroke: blue)[456], [789], [?], table.hline(start: 4, end: 5, stroke: red))).flatten()
)
--- grid-header-relative-row-sizes ---
// Relative lengths
#set page(height: 10em)
#table(
rows: (30%, 30%, auto),
table.header(
[*A*],
[*B*]
),
[C],
[C]
)
--- grid-header-cell-with-y ---
#grid(
grid.cell(y: 1)[a],
grid.header(grid.cell(y: 0)[b]),
grid.cell(y: 2)[c]
)
--- grid-header-last-child ---
// When the header is the last grid child, it shouldn't include the gutter row
// after it, because there is none.
#grid(
columns: 2,
gutter: 3pt,
grid.header(
[a], [b],
[c], [d]
)
)
--- grid-header-nested ---
#set page(height: 14em)
#let t(n) = table(
columns: 3,
align: center + horizon,
gutter: 3pt,
table.header(
table.cell(colspan: 3)[*Cool Zone #n*],
[*Name*], [*Num*], [*Data*]
),
..range(0, 5).map(i => ([\##i], table.cell(stroke: green)[123], table.cell(stroke: blue)[456])).flatten()
)
#grid(
gutter: 3pt,
t(0),
t(1)
)
--- grid-header-hline-and-vline ---
// Test line positioning in header
#table(
columns: 3,
stroke: none,
table.hline(stroke: red, end: 2),
table.vline(stroke: red, end: 3),
table.header(
table.hline(stroke: aqua, start: 2),
table.vline(stroke: aqua, start: 3), [*A*], table.hline(stroke: orange), table.vline(stroke: orange), [*B*],
[*C*], [*D*]
),
[a], [b],
[c], [d],
[e], [f]
)
--- grid-header-not-at-first-row ---
// Error: 3:3-3:19 header must start at the first row
// Hint: 3:3-3:19 remove any rows before the header
#grid(
[a],
grid.header([b])
)
--- grid-header-not-at-first-row-two-columns ---
// Error: 4:3-4:19 header must start at the first row
// Hint: 4:3-4:19 remove any rows before the header
#grid(
columns: 2,
[a],
grid.header([b])
)
--- grow-header-multiple ---
// Error: 3:3-3:19 cannot have more than one header
#grid(
grid.header([a]),
grid.header([b]),
[a],
)
--- table-header-in-grid ---
// Error: 2:3-2:20 cannot use `table.header` as a grid header
// Hint: 2:3-2:20 use `grid.header` instead
#grid(
table.header([a]),
[a],
)
--- grid-header-in-table ---
// Error: 2:3-2:19 cannot use `grid.header` as a table header
// Hint: 2:3-2:19 use `table.header` instead
#table(
grid.header([a]),
[a],
)
--- grid-header-in-grid-header ---
// Error: 14-28 cannot place a grid header within another header or footer
#grid.header(grid.header[a])
--- table-header-in-grid-header ---
// Error: 14-29 cannot place a table header within another header or footer
#grid.header(table.header[a])
--- grid-header-in-table-header ---
// Error: 15-29 cannot place a grid header within another header or footer
#table.header(grid.header[a])
--- table-header-in-table-header ---
// Error: 15-30 cannot place a table header within another header or footer
#table.header(table.header[a])
--- grid-header-block-with-fixed-height ---
#set page(height: 15em)
#table(
rows: (auto, 2.5em, auto),
table.header(
[*Hello*],
[*World*]
),
block(width: 2em, height: 20em, fill: red)
)
--- grid-header-and-rowspan-non-contiguous-1 ---
// Rowspan sizing algorithm doesn't do the best job at non-contiguous content
// ATM.
#set page(height: 15em)
#table(
rows: (auto, 2.5em, 2em, auto, 5em),
table.header(
[*Hello*],
[*World*]
),
table.cell(rowspan: 3, lines(15))
)
--- grid-header-and-rowspan-non-contiguous-2 ---
// Rowspan sizing algorithm doesn't do the best job at non-contiguous content
// ATM.
#set page(height: 15em)
#table(
rows: (auto, 2.5em, 2em, auto, 5em),
gutter: 3pt,
table.header(
[*Hello*],
[*World*]
),
table.cell(rowspan: 3, lines(15))
)
--- grid-header-and-rowspan-non-contiguous-3 ---
// This should look right
#set page(height: 15em)
#table(
rows: (auto, 2.5em, 2em, auto),
gutter: 3pt,
table.header(
[*Hello*],
[*World*]
),
table.cell(rowspan: 3, lines(15))
)
--- grid-header-lack-of-space ---
// Test lack of space for header + text.
#set page(height: 8em)
#table(
rows: (auto, 2.5em, auto, auto, 10em),
gutter: 3pt,
table.header(
[*Hello*],
[*World*]
),
table.cell(rowspan: 3, lorem(80))
)
--- grid-header-orphan-prevention ---
// Orphan header prevention test
#set page(height: 12em)
#v(8em)
#grid(
columns: 3,
grid.header(
[*Mui*], [*A*], grid.cell(rowspan: 2, fill: orange)[*B*],
[*Header*], [*Header* #v(0.1em)]
),
..([Test], [Test], [Test]) * 20
)
--- grid-header-empty ---
// Empty header should just be a repeated blank row
#set page(height: 12em)
#table(
columns: 4,
align: center + horizon,
table.header(),
..range(0, 4).map(i => ([John \##i], table.cell(stroke: green)[123], table.cell(stroke: blue)[456], [789])).flatten()
)
--- grid-header-containing-rowspan ---
// When a header has a rowspan with an empty row, it should be displayed
// properly
#set page(height: 10em)
#let count = counter("g")
#table(
rows: (auto, 2em, auto, auto),
table.header(
[eeec],
table.cell(rowspan: 2, count.step() + context count.display()),
),
[d],
block(width: 5em, fill: yellow, lorem(15)),
[d]
)
#context count.display()
--- grid-header-expand ---
// Ensure header expands to fit cell placed in it after its declaration
#set page(height: 10em)
#table(
columns: 2,
table.header(
[a], [b],
[c],
),
table.cell(x: 1, y: 1, rowspan: 2, lorem(80))
)
--- grid-nested-with-headers ---
// Nested table with header should repeat both headers
#set page(height: 10em)
#table(
table.header(
[a]
),
table(
table.header(
[b]
),
[a\ b\ c\ d]
)
)
--- grid-nested-headers ---
#set page(height: 12em)
#table(
table.header(
table(
table.header(
[b]
),
[c],
[d]
)
),
[a\ b]
)
--- grid-header-stroke-edge-cases ---
// Test header stroke priority edge case (last header row removed)
#set page(height: 8em)
#table(
columns: 2,
stroke: black,
gutter: (auto, 3pt),
table.header(
[c], [d],
),
..(table.cell(stroke: aqua)[d],) * 8,
)
--- grid-header-hline-bottom ---
// Yellow line should be kept here
#set text(6pt)
#table(
column-gutter: 3pt,
inset: 1pt,
table.header(
[a],
table.hline(stroke: yellow),
),
table.cell(rowspan: 2)[b]
)
--- grid-header-hline-bottom-manually ---
// Red line should be kept here
#set page(height: 6em)
#set text(6pt)
#table(
column-gutter: 3pt,
inset: 1pt,
table.header(
table.hline(stroke: red, position: bottom),
[a],
),
[a],
table.cell(stroke: aqua)[b]
)
--- grid-header-rowspan-base ---
#set page(height: 7em)
#set text(6pt)
#let full-block = block(width: 2em, height: 100%, fill: red)
#table(
columns: 3,
inset: 1.5pt,
table.header(
[a], full-block, table.cell(rowspan: 2, full-block),
[b]
)
)
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/scripting/while.typ | typst | // Test while expressions.
--- while-loop-basic ---
// Should output `2 4 6 8 10`.
#let i = 0
#while i < 10 [
#(i += 2)
#i
]
// Should output `Hi`.
#let iter = true
#while iter {
iter = false
"Hi."
}
#while false {
dont-care
}
--- while-loop-expr ---
// Value of while loops.
#test(while false {}, none)
#let i = 0
#test(type(while i < 1 [#(i += 1)]), content)
--- while-loop-condition-content-invalid ---
// Condition must be boolean.
// Error: 8-14 expected boolean, found content
#while [nope] [nope]
--- while-loop-condition-always-true ---
// Error: 8-25 condition is always true
#while 2 < "hello".len() {}
--- while-loop-limit ---
// Error: 2:2-2:24 loop seems to be infinite
#let i = 1
#while i > 0 { i += 1 }
--- while-loop-incomplete ---
// Error: 7 expected expression
#while
// Error: 8 expected expression
#{while}
// Error: 9 expected block
#while x
// Error: 7 expected expression
#while
x {}
// Error: 9 expected block
#while x something
|
|
https://github.com/loqusion/typix | https://raw.githubusercontent.com/loqusion/typix/main/docs/api/derivations/mk-typst-derivation.md | markdown | MIT License | # mkTypstDerivation
A generic derivation constructor for running Typst commands.
## Parameters
**Note:** All parameters for `stdenv.mkDerivation`[^stdenv] are also available.
### `buildPhaseTypstCommand`
Command (or commands) to run during [`buildPhase`][nixpkgs-buildphase]. Any
output should typically be written to `$out`, e.g. `typst compile <source>
"$out"`.
See also: [Typst CLI Usage][typst-cli-usage]
### `src`
{{#include common/src.md}}
### `fontPaths` (optional) { #fontpaths }
{{#include common/font-paths.md}}
#### Example { #fontpaths-example }
{{#include common/font-paths-example.md:mktypstderivation_example}}
### `installPhaseCommand` (optional) { #installphasecommand }
{{#include common/install-phase-command.md}}
### `virtualPaths` (optional) { #virtualpaths }
{{#include common/virtual-paths.md}}
#### Example { #virtualpaths-example }
{{#include common/virtual-paths-example.md:head}}
{{#include common/virtual-paths-example.md:mktypstderivation_example}}
{{#include common/virtual-paths-example.md:tail}}
## Source
- [`mkTypstDerivation`](https://github.com/loqusion/typix/blob/main/lib/mkTypstDerivation.nix)
## Footnotes
[^stdenv]: [`stdenv`][nixpkgs-stdenv] (not for the faint of heart)
[nixpkgs-buildphase]: https://nixos.org/manual/nixpkgs/stable/#build-phase
[nixpkgs-stdenv]: https://nixos.org/manual/nixpkgs/stable/#chap-stdenv
[typst-cli-usage]: https://github.com/typst/typst#usage
|
https://github.com/HynDuf/typst-cv | https://raw.githubusercontent.com/HynDuf/typst-cv/master/README.md | markdown | Apache License 2.0 | # Typst CV
- This is a heavily-customized Typst CV template by [https://github.com/mintyfrankie/brilliant-CV](https://github.com/mintyfrankie/brilliant-CV) (so heavily that the usage is even different 😄). See the original template to see what it can do.
- I only customized it to be exactly like I wanted so it might not be as **customizable** as the original template.
## How to use
1. Change your personal data in `template/metadata.toml` and `template/module_*/`.
2. See `main.typ` for CV structure and `main_letter.typ` for cover letter. Change it to however you like.
3. Run commands to generate `main.pdf` and `main_letter.pdf` respectively.
```typst
typst compile main.typ
```
```typst
typst compile main_letter.typ
```
## Preview
### CV
<div>
<img src=".github/screenshots/CV.jpg" alt="CV" align="center">
</div>
### Cover Letter
<div>
<img src=".github/screenshots/cover_letter.jpg" alt="cover_letter" align="center">
</div>
|
https://github.com/Mondei1/dhge-typst-template | https://raw.githubusercontent.com/Mondei1/dhge-typst-template/master/README.md | markdown | # DHGE Typst Vorlage
Diese Vorlage dient dazu einen perfekten Einstieg in Typst und in das Schreiben einer **Projektarbeit** bereitzustellen.
>[!WARNING]
>Die Vorlage gilt nur für Projektarbeiten. Außerdem übernehme ich keine Haftung falls doch was falsch ist 😶🌫️
Wenn du einen Fehler gefunden hast oder eine Optimierung vorschlagen möchtest, dann öffne gerne eine Pull Request.
## Typst
- [Webseite](https://typst.app/)
- [Docs](https://typst.app/docs/)
- [Universe](https://typst.app/universe) - Neu mit Typst `0.11` (Übersicht vieler anderer Vorlagen und Addons)
## Quellenangaben
Die DHGE hat ihr eigenes Quellenformat und an diesem Repository hängt ein weiteres Repo von [DeEskalator](https://github.com/DeEskalator), der netterweise eine CSL zur Verfügung stellt, die versucht, den DHGE-Standard weitestgehend zu implementieren. Typst unterstützt dieses Format, allerdings kann das manchmal noch zu Problemen führen.
>[!IMPORTANT]
>Das `urldate`-Feld in der `.bib` (bzw. `Zuletzt geprüft am:` in Citavi) muss im **YYYY-MM-DD** Format angegeben sein. Sonst schlucken Typst und LaTeX dieses Feld einfach und zeigen es nicht an.
### Mit LaTeX
Eine weitere Möglichkeit wäre LaTeX. Damit könntet ihr euer Quellenverzeichnis mit LaTeX erstellen und dann an die Typst PDF anhängen.
Ein **Nachteil** ist, dass die von Typst generierten Verlinkungen innerhalb des Dokuments verloren gehen. Außerdem kann mit LaTeX kein CSL verwendet werden, zumindest nicht mit BibLaTeX.
<details>
<summary>LaTeX Dokument</summary>
Das LaTeX-Dokument *sollte* alle formalen Eigenschaften erfüllen.
```latex
% Quellen.tex
\documentclass[11pt]{article}
\usepackage[utf8]{inputenc}
% Times New Roman
\usepackage{mathptmx}
%% Page counter on bottom right
\makeatletter
\renewcommand*{\ps@plain}{%
\let\@mkboth\@gobbletwo
\let\@oddhead\@empty
\def\@oddfoot{%
\reset@font
\hfil
\thepage
}
\let\@evenhead\@empty
\let\@evenfoot\@oddfoot
}
\makeatother
\pagestyle{plain}
%%% Page Dimensions
\usepackage[
a4paper,
left=3cm,
right=2cm,
top=2.5cm,
bottom=2.5cm
]{geometry}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel,isodate}
% Incompatable with biblatex :(
%\usepackage{citation-style-language}
% Sources
\usepackage[
backend=bibtex
,style=alphabetic
,block=none
,indexing=false
,citereset=none
,isbn=true
,url=true
,doi=true
,firstinits=true
]{biblatex}
\addbibresource{sources.bib}
\begin{document}
\section{Quellen}
% Unteres Python-Skript ausführen um Quellen hier hinzuzufügen
% z. B. \cite{Cun92}
\pagebreak
\pagenumbering{Alph}
\printbibliography[title=Literaturverzeichnis]
\end{document}
```
</details>
<details>
<summary>Python Skript zur Generierung der Cite-Keys aus eurer .bib-Datei</summary>
Hier ein kleines *(von ChatGPT generiertes)* Python Skript welches die Keys aus eurer `.bib`-Datei extrahiert und passend für oberes Tex-Dokument extrahiert.
```python
import re
def extract_keys_from_bib(bib_file):
with open(bib_file, 'r') as file:
bib_data = file.read()
# Extracting keys using regular expression
keys = re.findall(r"@.*?\{(.*?),", bib_data)
return keys
def generate_cite_lines(keys):
cite_lines = []
for key in keys:
cite_lines.append("\\cite{" + key + "}")
return cite_lines
def main():
bib_file = input("Enter the path to the BibLaTeX (.bib) file: ")
keys = extract_keys_from_bib(bib_file)
cite_lines = generate_cite_lines(keys)
for line in cite_lines:
print(line)
if __name__ == "__main__":
main()
```
</details>
## To-Do
- [ ] bessere Verwendung der Vorlage durch weitere Auslagerungen
|
|
https://github.com/DaAlbrecht/lecture-notes | https://raw.githubusercontent.com/DaAlbrecht/lecture-notes/main/discrete_mathematics/graph_theory.typ | typst | MIT License | #import "@preview/diagraph:0.3.0": *
#import "../template.typ": *
#set table(
fill: (x, y) =>
if y == 0 {
gray.lighten(40%)
},
align: right,
)
= Graph Theory
== Basic Definitions
#definition[
A Graph $G$ is a pair $G = (V, E)$ where $V$ is a set of vertices and $E$ is a set of edges $brace.l a, b brace.r$ where $a, b in V, a eq.not b$.
]
An edge $e = brace.l a, b brace.r$ always connects two vertices $a$ and $b$. The vertices $a$ and $b$ are called the *endpoints* of the edge $e$.
#example[
A graph $G = (V, E)$ with $V = brace.l a, b, c, d brace.r$ and $E = brace.l brace.l a, b brace.r, brace.l b, c brace.r, brace.l a, d brace.r brace.r, brace.l d, b brace.r brace.r$.
#raw-render(
```
graph {
rankdir=LR
a -- b
b -- c
a -- d
d -- b
}
```)
]
#definition[
A graph $H = (V, E)$ is a *subgraph* of a graph $G = (V', E')$ if $V subset V'$ and $E subset E'$.
]
#example[
A graph $G = (V, E)$ with $V = brace.l a, b, c, d brace.r$ and $E = brace.l brace.l a, b brace.r, brace.l b, c brace.r, brace.l a, d brace.r brace.r,
brace.l d, b brace.r brace.r$
\
has a subgraph $H = (V', E')$ with $V' = brace.l a, b, c brace.r$ and $E' = brace.l brace.l a, b brace.r, brace.l b, c brace.r brace.r, brace.l a, c brace.r$.
#raw-render(
```
graph {
rankdir=LR
a -- b
b -- c
a -- c
}
```)
]
To reduce confusion, graphs are often drawn so that the edges do not cross each other. For all graphs that this is possible, the graph is called a *planar graph*.
#pagebreak()
According to our previous definition, a graph can not have an edge that connects a vertex to itself. However, in some cases, it is useful to allow such edges. A graph that allows edges to connect a vertex to itself or
multiple edges between the same vertices is called a *multigraph*.
#example[
A graph $G = (V, E)$ with $V = brace.l a, b, c brace.r$ and $E = brace.l brace.l a, c brace.r, brace.l a, b brace.r, brace.l c, c brace.r brace.r$.
#raw-render(
```
graph {
rankdir=LR
a -- c
a -- b
c -- c
}
```)
]
#pagebreak()
#table(
columns: (auto,2fr,1.5fr),
align: (center,left,left),
table.header(
[Term], [Definition], [Example]
),
[Vertex], [A point in a graph], $a$,
[Edge], [A connection between two vertices], $brace.l a, b brace.r$,
[Subgraph], [A graph that is a subset of another graph], $H = (V', E')$,
[Planar Graph], [A graph that can be drawn without edges crossing], render("graph { a -- b }"),
[Multigraph], [A graph that allows edges to connect a vertex to itself or multiple edges between the same vertices],[#render("graph { a--a a--b b--a }")
$E = brace.l brace.l a, a brace.r, brace.l a, b brace.r, brace.l b, a brace.r brace.r$],
[Loop], [An edge that connects a vertex to itself], render("graph { a -- a }"),
[Adjacent], [Two vertices are adjacent if they are connected by an edge], [#render("graph { a -- b }") $a$ and $b$ are adjacent],
[Incident (edges)], [Two edges are incident if they share a vertex], [#render("graph { a -- b a -- c }") $brace.l a, b brace.r$ and $brace.l a, c brace.r$ are incident],
[Incident (vertex)], [An edge is incident to a vertex if the vertex is an endpoint of the edge], [#render("graph { a -- b a -- c }") $a$ is incident to $brace.l a, b brace.r$],
[Degree], [The number of edges incident to a vertex], [#render("graph { a -- b a -- c }") The degree of $a$ is $2$],
[Isolated Vertex], [A vertex with degree $0$], [#render("graph { a }") $a$ is an isolated vertex],
)
#statement[
Given a graph $G = (V, E)$, the sum of the degrees of all vertices is equal to twice the number of edges.
$ sum_(v in V) deg(v) = 2 |E| $
]
It is important to note that in a multigraph with loops, each loop contributes $+2$ to the degree of the vertex it is incident to.
#pagebreak()
#statement[
In each graph, the number of vertices with odd degree is even.
]
This must be the case because the sum of the degrees of all vertices is equal to twice the number of edges. Since the sum of the degrees is even (due to the factor of $2$), the number of vertices with odd degree must be even (odd + odd = even).
#example[
In the graph $G = (V, E)$ with $V = brace.l a, b, c, d brace.r$ and $E = brace.l brace.l a, b brace.r, brace.l b, c brace.r, brace.l a, d brace.r brace.r, brace.l d, b brace.r brace.r$,
#raw-render(
```
graph {
rankdir=LR
a -- b
b -- c
a -- d
d -- b
}
```
)
the vertices $a$ and $d$ have an even degree, while $b$ and $c$ have an odd degree.
]
=== Equivalency of Graphs
Two graphs are considered equivalent if they have the same number of vertices and edges, and the edges are connected in the same way.
#definition[
Two graphs $G = (V, E)$ and $H = (V', E')$ are *isomorphic* if there is a bijection $f: V -> V'$ such that $brace.l a, b brace.r in E$ if and only if $brace.l f(a), f(b) brace.r in E'$.
]
#example[
The graphs $G = (V, E)$ and $H = (V', E')$ with $V = brace.l a, b, c brace.r$, $V' = brace.l x, y, z brace.r$, $E = brace.l brace.l a, b brace.r, brace.l b, c brace.r brace.r$, and $E' = brace.l brace.l x, y brace.r, brace.l y, z brace.r brace.r$ are isomorphic.
#raw-render(
```
graph {
rankdir=LR
a -- b
b -- c
}
```
)
#raw-render(
```
graph {
rankdir=LR
x -- y
y -- z
}
```
)
The bijection $f$ is defined as $f(a) = x$, $f(b) = y$, and $f(c) = z$.
]
#pagebreak()
=== Directed Graphs
In a directed graph, the edges have a direction. An edge $e = brace.l a, b brace.r$ is directed from $a$ to $b$. The vertex $a$ is called the *tail* of the edge, and the vertex $b$ is called the *head* of the edge.
#example[
A directed graph $G = (V, E)$ with $V = brace.l a, b, c brace.r$ and $E = brace.l brace.l a, b brace.r, brace.l b, c brace.r, brace.l c, a brace.r brace.r$.
#raw-render(
```
digraph {
rankdir=LR
a -> b
b -> c
c -> a
}
```
)
]
== Representation of Graphs in Computers
=== Matrix Representation
Graphs can be represented in computers in different ways. One common representation is the *adjacency matrix*.
#definition[
The *adjacency matrix* of a graph $G = (V, E)$ is a matrix $A$ of size $|V| times |V|$
where $ A_(i j) = 1$ if there is an edge between vertices $v_i$ and $v_j$, and $0$ otherwise.
]
#example[
The adjacency matrix of the graph $G = (V, E)$ with $V = brace.l a, b, c brace.r$ and $E = brace.l brace.l a, b brace.r, brace.l b, c brace.r, brace.l c, a brace.r brace.r$ is:
$
#raw-render(
```
graph {
rankdir=LR
a -- b
b -- c
c -- a
}
```
)
mat(
0 , 1 , 1;
1 , 0 , 1;
1 , 1 , 0;
)
$
]
#definition[
The *Incidence Matrix* of a graph $G = (V, E)$ is a matrix $A$ of size $|V| times |E|$
where $ A_(i j) = 1$ if vertex $v_i$ is incident to edge $e_j$, and $0$ otherwise.
]
#example[
The incidence matrix of the graph $G = (V, E)$ with $V = brace.l a, b, c brace.r$ and $E = brace.l brace.l a, b brace.r, brace.l b, c brace.r, brace.l c, a brace.r brace.r$ is:
$
#raw-render(
```
graph {
rankdir=LR
a -- b
b -- c
c -- a
}
```
)
mat(
1 , 0 , 1;
1 , 1 , 0;
0 , 1 , 1;
)
$
]
#pagebreak()
==== Multigraphs
In the adjacency matrix of a multigraph, the value of $A_(i j)$ is the number of edges between vertices $v_i$ and $v_j$.
#example[
The adjacency matrix of the multigraph $G = (V, E)$ with $V = brace.l a, b, c brace.r$ and $E = brace.l a a, a b, b a, b c, c a, a c brace.r$ is:
$
#raw-render(
```
graph {
rankdir=LR
a -- a
a -- b [label=" "]
b -- a [label=" "]
b -- c
c -- a
a -- c
}
```
)
mat(
2 , 2 , 2;
2 , 0 , 1;
2 , 1 , 0;
)
$
]
=== List Representation
Another common representation is the *adjacency list*.
#definition[
The *adjacency list* of a graph $G = (V, E)$ is a list of size $|V|$ where each element $A[i]$ is a list of vertices adjacent to vertex $v_i$.
]
#example[
The adjacency list of the graph $G = (V, E)$ with $V = brace.l a, b, c brace.r$ and $E = brace.l brace.l a, b brace.r, brace.l b, c brace.r, brace.l c, a brace.r brace.r$ is:
#raw-render(
```
graph {
rankdir=LR
a -- b
b -- c
c -- a
}
```
)
#table(
columns: 2,
align: (center,left),
stroke: none,
table.header(
[Vertex], [Adjacent Vertices]
),
table.hline(start: 0),
table.vline(x: 1),
[a], [b, c],
[b], [a, c],
[c], [a, b],
)
]
The adjacency list representation is more space-efficient than the adjacency matrix representation for sparse graphs,
because the number of elements in an adjacency list is twice the number of edges, while the number of elements in an adjacency matrix is $|V|^2$.
#pagebreak()
= Cycles and Paths
Given the following graph $G = (V, E)$
\
$V = brace.l a, b, c, d, e brace.r , E = brace.l a b, a d, a c, b d, b c, d c, d e, c e brace.r$:
#raw-render(
```
graph {
rankdir=LR
a -- b
a -- d
a -- c
b -- d
b -- c
d -- c
d -- e
c -- e
}
```
)
In this graph, there are multiple paths from the vertex $a$ to the vertex $e$. One such path could be $a d, d c, c b, b d, d e$.
This path is called a *walk*.
#definition[
a walk is a sequence of incident edges in a graph.
Properties of a walk:
- A walk is called *closed* if the start and end vertices are the same.
- The number of edges in a walk is called the *length* of the walk.
]
#example[
$a, d, c, b, d, e$ is a walk of length $5$ in the graph $G$.
]
#definition[
A *trail* is a walk where no edge is repeated.
]
#example[
$a, d, c, b, d, e$ is a trail in the graph $G$.
]
#definition[
A *path* is a trail where no vertex is repeated.
]
#example[
$a, d, c, e$ is a path in the graph $G$.
]
#definition[
A *cycle* is a non-empty trail where the start and end vertices are the same.
]
#example[
$a, d, c, b, a$ is a cycle in the graph $G$.
]
== Calculating the Number of Paths
The number of paths of length $k$ between two vertices $a$ and $b$ can be calculated using the adjacency matrix $A$ of the graph.
#statement[
The number of paths of length $k$ between vertices $a$ and $b$ is the value of $A^k_(a b)$.
]
#example[
Given is the following adjacency matrix $A$ that does not contain weights:
$
A = mat(
0 , 1 , 0 , 0;
1 , 0 , 1 , 0;
0 , 0 , 0 , 1;
0 , 0 , 1 , 0;
)
$
We are looking for the number of paths of length $3$ between vertices $2$ and $3$.
For this, we calculate $A^3$:
$
A^2 = mat(
1 , 0 , 1 , 0;
0 , 1 , 0 , 1;
0 , 0 , 1 , 0;
0 , 0 , 0 , 1;
)
$
$
A^3 = mat(
0 , 1 , 0 , 1;
1 , 0 , 2 , 0;
0 , 0 , 0 , 1;
0 , 0 , 1 , 0;
)
$
The value of $A^3_(2 3)$ is $2$, which means that there are $2$ paths of length $3$ between vertices $2$ and $3$.
]
#pagebreak()
#definition[
In an undirected graph $G = (V, E)$, two vertices $a$ and $b$ are called *connected* if $G$ contains a path from $a$ to $b$.
If a graph contains a path between every pair of vertices, it is called *connected*.
]
#example[
The graph $G = (V, E)$ with $V = brace.l a, b, c, d brace.r$ and $E = brace.l a b, a d, a c, b d, b c, d c brace.r$ is connected.
#raw-render(
```
graph {
rankdir=LR
a -- b
a -- d
a -- c
b -- d
b -- c
d -- c
}
```
)
]
#definition[
A maximal connected subgraph of a graph $G$ is called a *connected component*.
]
#example[
The graph $G = (V, E)$ with $V = brace.l a, b, c, d, e brace.r$ and $E = brace.l a b, a d brace.r$ has three connected components.
#raw-render(
```
graph {
rankdir=LR
a -- b
a -- d
c
e
}
```
)
The connected components are $brace.l a, b, d brace.r$, $brace.l c brace.r$, and $brace.l e brace.r$.
]
#definition[
A graph is called *disconnected* if it contains more than one connected component.
]
#pagebreak()
== Breadth-First Search (BFS)
Breadth-First Search (BFS) is an algorithm used to traverse graphs. It starts at a given vertex and explores all of its neighbors at the present depth before moving on to the vertices at the next depth level.
*Algorithm:*
1. Determine the starting vertex $s$, mark it as visited, and add it to the queue.
2. Take the first vertex $v$ from the queue:
- If $v$ is the target vertex, the search is complete.
- Otherwise, add all unvisited neighbors of $v$ to the queue and mark them as visited.
3. Repeat step 2 until the queue is empty.
4. If the queue is empty and the target vertex has not been found, the target vertex is not reachable from the starting vertex.
To check if a graph is connected, we can start a BFS from any vertex and check if all vertices are visited at the end.
#statement[
A connected graph with $n$ vertices has at least $n-1$ edges.
A graph with more than $((n-1)(n-2))/2$ edges is connected.
]
Another way to check if a graph is connected is by checking the adjacency matrix. If the matrix $A^k$ contains only non-zero values, the graph is connected.
#pagebreak()
=== Eulerian Paths and Cycle
#definition[
An *Eulerian path* is a path that visits every edge exactly once.
]
#example[
The graph $G = (V, E)$ with $V = brace.l a, b, c, d brace.r$ and $E = brace.l a b, a d, a c, b d, b c, d c brace.r$ has an Eulerian path $a, b, d, c, a, d, b, c$.
#raw-render(
```
graph {
rankdir=LR
a -- b
a -- d
a -- c
b -- d
b -- c
d -- c
}
```
)
]
#statement[
A connected (Multi)graph has an Eulerian cycle if and only if all vertices have an even degree.
]
=== Fleury’s Algorithm
Fleury's algorithm is an algorithm used to find an Eulerian cycle in a graph.
*Algorithm:*
1. Start at any vertex $v$.
2. While there are unvisited edges in the graph:
- If $v$ has no neighbors, add $v$ to the cycle and remove it from the graph.
- If $v$ has neighbors, choose the neighbor $u$ that is not a bridge (an edge whose removal would disconnect the graph) if possible.
- Add the edge $v-u$ to the cycle and remove it from the graph.
- Set $v = u$.
3. The cycle is complete when all edges have been visited.
=== Hamiltonian Cycle
#definition[
A *Hamiltonian cycle* is a cycle that visits every vertex exactly once.
]
#statement[
In a graph with $n$ vertices, a Hamiltonian cycle must exists if a minimum of $1/2(n-1)(n-2)+2$ edges are present.
]
#pagebreak()
= Trees
#definition[
A *tree* is a connected graph with no cycles.
]
#example[
The graph $G = (V, E)$ with $V = brace.l a, b, c, d brace.r$ and $E = brace.l a b, a d, a c brace.r$ is a tree.
#raw-render(
```
graph {
rankdir=LR
a -- b
a -- d
a -- c
}
```
)
The graph $H = (V, E)$ with $V = brace.l a, b, c, d brace.r$ and $E = brace.l a b, a d, a c, b d brace.r$ is not a tree because it contains a cycle.
#raw-render(
```
graph {
rankdir=LR
a -- b [color=red]
a -- d [color=red]
a -- c
b -- d [color=red]
}
```
)
]
#definition[
If all connected components of a graph are trees, the graph is called a *forest*.
]
#statement[
A connected graph $G$ with $n$ vertices is a tree if and only if:
- $G$ has $n-1$ edges.
- If one edge is removed from $G$, it becomes disconnected.
- Between any two vertices in $G$, there is exactly one path.
]
#pagebreak()
#definition[
A *spanning tree* of a graph $G$ is a subgraph that is a tree and contains all vertices of $G$.
]
#example[
The graph $G = (V, E)$ with $V = brace.l a, b, c, d, e, f brace.r$ and $E = brace.l a b, a d, a c, b d, f a, f b brace.r$
has a spanning tree $T = (V, E')$ with $V = brace.l a, b, c, d, e, f brace.r$ and $E' = brace.l a d, a c, f a, f b brace.r$.
$G$:
#raw-render(
```
graph {
rankdir=LR
a -- b
a -- d
a -- c
b -- d
f -- a
f -- b
}
```
)
$T$:
#raw-render(
```
graph {
rankdir=LR
a -- d
a -- c
f -- a
f -- b
}
```
)
]
== Naming
#table(
columns: (auto,1.5fr,1.5fr),
align: (center,left,left),
table.header(
[Term], [Definition], [Example]
),
[root], [A vertex with no incoming edges], [#render("graph { a -- b a -- c }") $a$ is the root],
[leaf], [A vertex with no outgoing edges], [#render("graph { a -- b b -- c }") $c$ is a leaf],
[level], [The distance from the root], [#render("graph { a -- b a -- c b -- d }") $a$ is level $0$, $b$ is level $1$, $c$ is level $1$, $d$ is level $2$],
[parent], [A vertex $v$ is the parent of vertex $u$ if there is an edge $v-u$], [#render("graph { a -- b a -- c b -- d }") $a$ is the parent of $b$],
[child], [A vertex $u$ is a child of vertex $v$ if there is an edge $v-u$], [#render("graph { a -- b a -- c b -- d }") $b$ is a child of $a$],
[sibling], [Two vertices that share the same parent], [#render("graph { a -- b a -- c b -- d c -- d }") $b$ and $c$ are siblings],
[ancestor], [A vertex $v$ is an ancestor of vertex $u$ if there is a path from $v$ to $u$], [#render("graph { a -- b a -- c b -- d }") $a$ is an ancestor of $d$],
[descendant], [A vertex $u$ is a descendant of vertex $v$ if there is a path from $v$ to $u$], [#render("graph { a -- b a -- c b -- d }") $d$ is a descendant of $a$],
[binary tree], [A tree where each vertex has at most two children], [#render("graph { a -- b a -- c b -- d }")],
)
#pagebreak()
== Binary Search Trees
#definition[
A *binary search tree* (BST) is a binary tree where each vertex has at most two children, and the left child of a vertex contains a value less than the vertex, while the right child contains a value greater than the vertex.
]
#example[
The following binary tree is a binary search tree:
#raw-render(
```
graph {
8 -- 3
8 -- 10
3 -- 1
3 -- 6
6 -- 4
6 -- 7
10 -- 14
14 -- 13
}
```
)
]
=== Operations
#definition[
*Search*: To find a value in a binary search tree, start at the root and compare the value with the current vertex. If the value is less than the current vertex, move to the left child. If it is greater, move to the right child. Repeat this process until the value is found or corresponding subtree is empty, then the value is not in the tree.
*Insert*: To insert a value into a binary search tree, search for the value. If the value is not found, insert it as a leaf at the position where the search ended.
*Delete*: To delete a value from a binary search tree, search for the value. If the value is found:
- If the vertex has no children, remove the vertex.
- If the vertex has one child, replace the vertex with its child.
- If the vertex has two children, replace the vertex with the smallest value in the right subtree.
]
#statement[
The maximum amount of comparisons needed to search for a value in a binary search tree with length $n$ is $n + 1$.
]
The time complexity of searching, inserting, and deleting in a binary search tree is $O(h)$, where $h$ is the height of the tree.
This makes it crucial to ensure the height is minimized. The height of a tree is highly dependent on the order of insertion and deletion operations.
#example[
A Binary Search Tree with the values $brace.l 4, 8, 9, 14, 16, 20, 25, 31 brace.r$:
worst case height: 7
#raw-render(
```
graph {
rankdir=LR
4 -- 8
8 -- 9
9 -- 14
14 -- 16
16 -- 20
20 -- 25
25 -- 31
}
```,
width: 100%
)
compact height: 3
#raw-render(
```
graph {
rankdir=TD
14 -- 8
8 -- 4
8 -- 9
14 -- 20
20 -- 16
20 -- 25
25 -- 31
}
```,
)
]
One method to try to minimize the height of a binary search tree is a *devided and conquer* approach. This approach involves inserting the median value of the list as the root, then recursively inserting the median value of the left and right sublists as the left and right children of the root.
#pagebreak()
#statement[
In a binary search tree with length $l$, is the maximum data that can be stored:
$
n = sum_(k=0)^(l) 2^k = 2^(l+1) - 1
$
Resulting in a search time of $O(log_2(n))$.
]
= Weighted Graphs
#definition[
A *weighted graph* is a graph $G = (V, E)$ where each edge $e = brace.l a, b brace.r$ has a weight $w(e) gt.eq 0$.
]
#example[
The graph $G = (V, E)$ with $V = brace.l a, b, c brace.r$ and $E = brace.l brace.l a, b brace.r, brace.l b, c brace.r brace.r$ has the weights $w(brace.l a, b brace.r) = 3$ and $w(brace.l b, c brace.r) = 2$.
#raw-render(
```
graph {
rankdir=LR
a -- b [label="3"]
b -- c [label="2"]
}
```
)
or as an adjacency matrix:
$
mat(
0 , 3 , 0;
3 , 0 , 2;
0 , 2 , 0;
)
$
]
#definition[
A *complete graph* is a graph where every pair of vertices is connected by a distinct edge.
A complete graph with $n$ vertices has $n(n-1)/2$ edges and is denoted as $K_n$.
]
== Traveling Salesman Problem
The Traveling Salesman Problem (TSP) is a problem where a salesman must visit all cities in a list exactly once and return to the starting city. The goal is to find the shortest path that visits all cities.
#example[
Given the following weighted graph $G = (V, E)$ with $V = brace.l a, b, c brace.r$ and $E = brace.l brace.l a, b brace.r, brace.l b, c brace.r, brace.l a, c brace.r brace.r$:
#raw-render(
```
graph {
rankdir=LR
a -- b [label="3"]
b -- c [label="2"]
a -- c [label="1"]
}
```
)
The shortest path that visits all cities is $a, c, b$ with a total weight of $3$.
]
#statement[
The Traveling Salesman Problem is NP-hard, meaning that there is no known polynomial-time algorithm to solve it.
]
= Minimum Spanning Trees
#definition[
A *minimum spanning tree* (MST) of a weighted graph $G = (V, E)$ is a spanning tree with the smallest possible sum of edge weights.
]
== Kruskal's Algorithm
Kruskal's algorithm is an algorithm used to find the minimum spanning tree of a graph.
*Algorithm:*
1. Sort all edges by weight.
2. Start with an empty graph $T$.
3. For each edge $e$ in the sorted list:
- If adding $e$ to $T$ does not create a cycle (i.e., the endpoints of $e$ are not already connected in $T$), add $e$ to $T$.
4. Repeat step 3 until $T$ has $|V| - 1$ edges.
#pagebreak()
#example[
Given the following weighted graph:
#raw-render(
```
graph {
rankdir=LR
a -- b [label="3"]
b -- c [label="2"]
a -- c [label="1"]
a -- d [label="4"]
c -- d [label="5"]
}
```
)
1. sorted edges: $brace.l brace.l a, c brace.r, brace.l b, c brace.r, brace.l a, b brace.r, brace.l a, d brace.r, brace.l c, d brace.r brace.r$
2. start with an empty graph $T$:
#raw-render(
```
graph {
rankdir=LR
}
```
)
3. add $brace.l a, c brace.r$ to $T$:
#raw-render(
```
graph {
rankdir=LR
a -- c [label="1"]
}
```
)
4. add $brace.l b, c brace.r$ to $T$:
#raw-render(
```
graph {
rankdir=LR
a -- c [label="1"]
b -- c [label="2"]
}
```
)
do *not* add $brace.l a, b brace.r$ to $T$ because it would create a cycle
5. add $brace.l a, d brace.r$ to $T$:
#raw-render(
```
graph {
rankdir=LR
a -- c [label="1"]
b -- c [label="2"]
a -- d [label="4"]
}
```
)
The minimum spanning tree is $brace.l brace.l a, c brace.r, brace.l b, c brace.r, brace.l a, d brace.r brace.r$. The total weight is $7$.
]
== Dijkstra's Algorithm
Dijkstra's algorithm is an algorithm used to find the shortest path in a weighted graph $G = (V, E)$ between a source vertex $s$ and any other destination vertex $v$.
*Algorithm:*
1. Start at the source vertex $s$.
2. Set the distance to $s$ as $0$ and all other distances as $infinity$.
3. While there are unvisited vertices:
- Take the unvisited vertex $u$ with the smallest distance.
- For each neighbor $v$ of $u$:
- If the distance to $u$ plus the weight of the edge $u-v$ is smaller than the current distance to $v$, update the distance to $v$.
4. Repeat step 3 until all vertices are visited.
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Allemand_Ex_10_10_2023.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: "Allemand Ex 10 10 2023",
authors: (
"<NAME>",
),
date: "30 Octobre, 2023",
)
#set heading(numbering: "1.1.")
== Exercice 4
<exercice-4>
- die Aufführung : eine Person, die ihre Vorstellung der Welt oder der
Gesellschaft durch ihr Werk vermittelt
- das Exil : wenn eine Person in einem anderen Land leben muss
- ein engagierter Künstler: die künstlerische Leitung einer Inszenierung
- die Ungerechtigkeit: ein Situation, in der Menschen nicht die gleichen
Rechte haben
- die Regiearbeit : die Inszenierung eines Theaterstücks auf der Bühne
|
|
https://github.com/Cldfire/site | https://raw.githubusercontent.com/Cldfire/site/main/resume/resume.typ | typst | #import "alta-typst.typ": alta, term, skill, styled-link
#alta(
name: "<NAME>",
links: (
(name: "email", link: "mailto:<EMAIL>"),
(name: "website", link: "https://cldfire.dev", display: "cldfire.dev"),
(
name: "github",
link: "https://github.com/Cldfire",
display: "@Cldfire",
),
(
name: "mastodon",
link: "https://hachyderm.io/@Cldfire",
display: <EMAIL>",
),
(
name: "location",
link: "https://maps.apple.com/?address=New%20York,%20NY,%20United%20States",
display: "NYC",
),
),
tagline: [Software Developer passionate about building impactful systems and
high-performing teams.],
[
== Experience
=== Senior Developer\
_1Password_\
#term[Sep 2020 --- Present][Remote]
- Key contributor towards passkey support across all major browsers in the
1Password browser extension.
- Overhauled a complex, years-old browser extension build system used weekly by
over sixty developers. Decreased warm build times by over 90% (1m 20s -> 5s).
#styled-link("https://blog.1password.com/new-extension-build-system",
)[blog.1password.com/new-extension-build-system]
- Worked on high-impact CI improvements with a cross-functional team, resulting in
a 50% and 60% reduction to p50 and p90 merge request pipeline times
(respectively).
- Led the build & release process for the 1Password browser extension. Overhauled
the existing system to ensure predictability and implement automated nightly
releases.
- Owned the implementation & launch of Unlock with SSO in the 1Password browser
extension, collaborating with multiple teams.
- Key contributor towards the 1Password browser extension for iOS. Rebuilt many
aspects of the desktop extension in less than 90 days in order to launch day-one
on the App Store.
- Accelerated developers & teams across the company by sharing knowledge and
providing guidance/mentoring on a day-to-day basis.
=== Intern\
_1Password_\
#term[Summer 2020][Remote]
- Worked with Rust and Typescript to improve autofilling data into websites across
our browser extension and desktop app products.
- Heavy focus on automated testing and graceful degredation of accuracy when faced
with poorly designed pages.
=== Student Developer\
_Google Summer of Code with FFmpeg_\
#term[Summer 2019][Remote]
Worked independently to research, design, and implement a hardware-accelerated,
single-pass video stabilization filter for the FFmpeg library. #styled-link(
"https://cldfire.dev/blog/gsoc-2019",
)[https://cldfire.dev/blog/gsoc-2019]
#colbreak()
== Projects
==== nvml-wrapper #styled-link("https://github.com/Cldfire/nvml-wrapper")[github]
A safe and ergonomic Rust wrapper for the NVIDIA Management Library (NVML). Used
in production by Twitter and other companies.
==== minecraft-status #styled-link("https://github.com/Cldfire/minecraft-status")[github]
An iOS app with widgets that display the results of pinging a Minecraft server,
supporting both Java and Bedrock editions. Rust business logic with SwiftUI
frontend.
==== mc-server-wrapper #styled-link("https://github.com/Cldfire/mc-server-wrapper")[github]
Lightweight Minecraft server wrapper binary that provides a Discord chat bridge
and other features for vanilla servers.
==== actualbudget/actual #styled-link("https://github.com/actualbudget/actual")[github]
Ported an old, complex React Native component to the web, unlocking mobile
transaction entry for the popular local-first personal finance app Actual. PR: #styled-link("https://github.com/actualbudget/actual/pull/1340")[\#1340]
==== rust-lang/rust #styled-link("https://github.com/rust-lang/rust")[github]
Implemented the Ayu theme for rustdoc: #styled-link("https://github.com/rust-lang/rust/pull/71237")[\#71237]
== Education
==== University of Akron\
#term[2016 --- 2020][Akron, OH]
- B.S. in Computer Science with a minor in Mathematics — *3.9 GPA*
- Dean's List, President's List
- Completed 4/5 of degree and then left to accept a job offer
== Other
==== Lightning Talk at Programming Conference\
_Rust Belt Rust_\
#term[2017][Columbus, OH]
Gave impromptu talk about my work theming various sites in the Rust community. #styled-link("https://youtu.be/7VulqInDO6Y")[https://youtu.be/7VulqInDO6Y]
== Skills
Rust, Typescript, Javascript, FFI, Swift, React, SwiftUI, C, C++, native
messaging, Git, CI, teamwork, debugging, problem-solving, and a love of asking _why_.
],
)
|
|
https://github.com/jamesrswift/typst-chem-par | https://raw.githubusercontent.com/jamesrswift/typst-chem-par/main/src/stateful.typ | typst | MIT License | #let Chemistry-Style-disable-state = state("Chemistry-Style-disable", true)
#let chem-toggle(bool) = {Chemistry-Style-disable-state.update(bool)}
#let if-state-enabled( it , fn ) = {
if ( Chemistry-Style-disable-state.get() == false ){ return it }
return fn
}
#let chem-disabled(content) = {
chem-toggle(false)
content
chem-toggle(true)
} |
https://github.com/Totti95U/ExerciseBattale2023 | https://raw.githubusercontent.com/Totti95U/ExerciseBattale2023/main/src/template.typ | typst | The Unlicense | // The project function defines how your document looks.
// It takes your content and some metadata and formats it.
// Go ahead and customize it to your liking!
#let project(title: "", abstract: [], authors: (), body) = {
// Set the document's basic properties.
set document(author: authors, title: title)
set page(numbering: "1", number-align: center)
set text(font: "Noto Serif CJK JP", lang: "ja")
show link: underline
show link: set text(rgb("#0000ee"))
// set heading(numbering: )
// Title row.
align(center)[
#block(text(weight: 700, 1.75em, title))
]
// Main body.
set par(justify: true)
body
}
#let c_exer = counter("exercise")
#let contblock(name, conts) = {
if conts.len() == 1 [
#block(width: 100%)[
#text(11.5pt)[*#name*]
#move(dy: -7pt)[
#block(width: 100%)[#conts.at(0)]
]
]
] else [
#block(width: 100%)[
#text(11.5pt)[*#name (#conts.at(0))*]
#move(dy: -7pt)[
#block(width: 100%)[#conts.at(1)]
]
]
]
}
#let definition(..conts) = contblock("定義", conts.pos())
#let exercise(dif, ..conts) = {
c_exer.step()
contblock("問題 " + c_exer.display() + " (難易度: " + str(dif) + ")", conts.pos())
}
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.0.1/vector.typ | typst | Apache License 2.0 | /// Return a new vector of dimension `dim` with all fields
/// set to `init` (defaults to 0).
#let new(dim, init: 0) = {
return range(0, dim).map(x => init)
}
/// Return dimension of vector v
#let dim(v) = { assert(type(v) == "array", message: "Expected vector to be of array type, got: " + repr(v)); return v.len() }
/// Convert vector `v` to row or column matrix
#let as-mat(v, mode: "row") = {
if mode == "column" {
return (v,)
} else if mode == "row" {
return (for c in v { (c,) }, )
} else {
panic("Invalid mode " + mode)
}
}
/// Convert vector to vector of different dimension
/// with missing fields of `v` set to fields of vector `init`
#let as-vec(v, init: (0, 0, 0)) = {
for i in range(0, calc.min(dim(v), dim(init))) {
init.at(i) = v.at(i)
}
return init
}
/// Return length of vector v
#let len(v) = {
return calc.sqrt(v.fold(0, (s, c) => s + c * c))
}
/// Add two vectors of the same dimension
#let add(v1, v2) = {
if dim(v1) != dim(v2) {
v1 = as-vec(v1)
v2 = as-vec(v2)
}
assert(dim(v1) == dim(v2), message: "Cannot add vectors, " + repr(v1) + " and " + repr(v2) + " are not of the same dimensions.")
return v1.zip(v2).map(((a, b)) => a + b)
}
/// Substract two vectors of the same dimension
#let sub(v1, v2) = {
if dim(v1) != dim(v2) {
v1 = as-vec(v1)
v2 = as-vec(v2)
}
assert(dim(v1) == dim(v2), message: "Cannot subtract vectors, " + repr(v1) + " and " + repr(v2) + " are not of the same dimensions.")
return v1.zip(v2).map(((a, b)) => a - b)
}
/// Return distance of vector a and b
/// - a (vector): Vector a
/// - b (vector): Vector b
#let dist(a, b) = len(sub(b, a))
/// Multiply each vector field with number `x`
#let scale(v, x) = v.map(s => s * x)
/// Divide each vector field by number `x`
#let div(v, x) = v.map(s => s / x)
/// Negate each vector field
#let neg(v) = scale(v, -1)
/// Normalize vector (divide by its length)
#let norm(v) = div(v, len(v))
/// Calculate dot product between two vectors `v1` and `v2`
#let dot(v1, v2) = {
assert(dim(v1) == dim(v2))
return v1.enumerate().fold(0, (s, t) => s + t.at(1) * v2.at(t.at(0)))
}
/// Calculate cross product of two vectors of dim 3
#let cross(v1, v2) = {
assert(dim(v1) == 3 and dim(v2) == 3)
let x = v1.at(1) * v2.at(2) - v1.at(2) * v1.at(1)
let y = v1.at(2) * v2.at(0) - v1.at(0) * v1.at(2)
let z = v1.at(0) * v2.at(1) - v1.at(1) * v1.at(0)
return (x, y, z)
}
/// Calculate angle between three points
#let angle(v1, c, v2) = {
assert(dim(v1) == dim(v2), message: "Vectors " + repr(v1) + " and " + repr(v2) + " do not have the same dimensions.")
if dim(v1) == 2 or dim(v1) == 3 {
v1 = sub(v1, c)
v2 = sub(v2, c)
return calc.acos(dot(norm(v1), norm(v2)))
} else {
panic("Invalid vector dimension")
}
}
/// Linear interpolation
#let lerp(v1, v2, t) = {
return add(
v1,
scale(
sub(
v2,
v1
),
t,
)
)
}
|
https://github.com/alberto-lazari/computer-science | https://raw.githubusercontent.com/alberto-lazari/computer-science/main/advanced-topics-pl/presentation/sections/compiler.typ | typst | #import "/common.typ": *
#new-section("Compiler")
#slide[
Steps to compile source files to PDF:
#uncover(1, mode: "transparent")[
+ Parsing
]
#uncover("1-2")[
2. Evaluation
]
#uncover(1, mode: "transparent")[
3. Lifting
+ Layout
+ Export
]
]
#slide(title: "Evaluation")[
No syntax errors #sym.arrow.double evaluation can happen:
#line-by-line(start: 2, mode: "transparent")[
1. Joined content value
2. Top level bindings
]
]
#slide(title: [Evaluation -- markup])[
#line-by-line(mode: "transparent")[
- Markup nodes #sym.arrow `content`
- Code blocks evaluated to final value (joined) #sym.arrow `content`
- Everything joined in the process
]
]
#slide(title: [Evaluation -- bindings])[
When evaluating a ```typst #let``` binding:
- Store `(name, value)` in the scope #uncover(2)[(closures are values)]
- Return `none`
]
#slide(title: [Evaluation -- bindings])[
Closures can't be statically checked (only syntax)
#only(1, example(error: "expected equals sign
┌─ /sections/compiler.typ:67:16
│
67 │ let g(x)(y) = { x + y }
│ ^ "
)[
```typst
#let f() = {
let g(x)(y) = { x + y }
}
```
])
#only(2, grid(columns: (auto, auto), gutter: 2em,
example[
```typst
#let x = 0
#let val() = {
x += 1
}
This compiles fine
```
],
example(error: "variables from outside the function are read-only and cannot be modified")[
```typst
#let x = 0
#let val() = {
x += 1
}
#val()
```
],
))
#only(3, grid(columns: (auto, auto), gutter: 2em,
example(error: "variables from outside the function are read-only and cannot be modified")[
```typst
#let x = 0
#let val() = {
x += 1
}
#val()
```
],
example[
```typst
#let x = 0
#let val = {
x += 1
}
#x
```
],
))
]
#slide(title: "Modules")[
- Evaluation of a single source file: `(content, bindings)`
- ```typst #include "module.typ"``` #sym.arrow content
- ```typst #import "module.typ"``` #sym.arrow bindings
#line-by-line(start: 2)[
- Immutability
- Caching
]
]
|
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/code/3.typ | typst | // #align(center,image("img/1.png",width:10em))
#set text(font: ("Times New Roman","STSong"))
#set heading(numbering: "1.")
#set par(justify: true,first-line-indent: 2em) // 两端对齐,段前缩进2字符
#set list(indent:4em)
#show heading: it => {
it
par()[#text()[#h(0.0em)]]
}
= 光纤光栅
我晚上晚上 |
|
https://github.com/loqusion/typix | https://raw.githubusercontent.com/loqusion/typix/main/docs/api/derivations/build-typst-project.md | markdown | MIT License | # buildTypstProject
Returns a derivation for compiling a Typst project.
If you want to build to the project directory, use
[`buildTypstProjectLocal`](build-typst-project-local.md) instead.
## Parameters
All parameters accepted by
[`mkTypstDerivation`](mk-typst-derivation.md#parameters) are also accepted by
`buildTypstProject`. They are repeated below for convenience.
### `src`
{{#include common/src.md}}
### `fontPaths` (optional) { #fontpaths }
{{#include common/font-paths.md}}
#### Example { #fontpaths-example }
{{#include common/font-paths-example.md:buildtypstproject_example}}
### `installPhaseCommand` (optional) { #installphasecommand }
{{#include common/install-phase-command.md}}
### `typstCompileCommand` (optional) { #typstcompilecommand }
{{#include common/typst-compile-command.md}}
Default is `typst compile`.
### `typstOpts` (optional) { #typstopts }
{{#include common/typst-opts.md:head}}
<!-- markdownlint-disable link-fragments -->
These are in addition to any options you manually pass in
[`typstCompileCommand`](#typstcompilecommand).
<!-- markdownlint-restore -->
{{#include common/typst-opts.md:tail}}
#### Example { #typstopts-example }
{{#include common/typst-opts-example.md:head}}
{{#include common/typst-opts-example.md:typstcompile}}
### `typstSource` (optional) { #typstsource }
{{#include common/typst-project-source.md}}
Default is `main.typ`.
### `virtualPaths` (optional) { #virtualpaths }
{{#include common/virtual-paths.md}}
#### Example { #virtualpaths-example }
{{#include common/virtual-paths-example.md:head}}
{{#include common/virtual-paths-example.md:buildtypstproject_example}}
{{#include common/virtual-paths-example.md:tail}}
## Source
- [`buildTypstProject`](https://github.com/loqusion/typix/blob/main/lib/buildTypstProject.nix)
|
https://github.com/onecalfman/TypstGenerator.jl | https://raw.githubusercontent.com/onecalfman/TypstGenerator.jl/main/example/test.typ | typst | MIT License | #let project(title, doc) = {
set document(author: ("Author"), title: title)
doc
}
#show: project.with("Report")
#set page(margin: (left: 20.0mm, right: 20.0mm, top: 30.0mm, bottom: 30.0mm), footer: grid(columns: (1fr, 1fr),
align(left, image(height: 12.0mm, "typst_banner.png") ),
align(right, image(height: 12.0mm, "julia.svg") )) )
#set heading(numbering: "I.I")
#page()[
#outline()
#heading(level: 1, "Report")
#v(12.0mm)
#set align(center)
#grid(
rect(height: 10.0mm, width: 3.0mm, align(horizon, text("1") )) ,
rect(height: 10.0mm, width: 6.0mm, align(horizon, text("2") )) ,
rect(height: 10.0mm, width: 9.0mm, align(horizon, text("3") )) )
#set align(left)
#lorem(200)
#heading(level: 2, "Important Topic")
#lorem(200)
#set align(center)]
#page(background: place(center + horizon, rotate(45.0deg, text(font: "Source Sans Pro", fill: luma(204), size: 60.0mm, "WATERMARK") )))[
#grid(columns: (1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr),
rotate(1.0deg, square(fill: rgb(33, 3, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(6.0deg, square(fill: rgb(33, 18, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(11.0deg, square(fill: rgb(33, 33, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(16.0deg, square(fill: rgb(33, 48, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(21.0deg, square(fill: rgb(33, 63, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(26.0deg, square(fill: rgb(33, 78, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(31.0deg, square(fill: rgb(33, 93, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(36.0deg, square(fill: rgb(33, 108, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(41.0deg, square(fill: rgb(33, 123, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(46.0deg, square(fill: rgb(33, 138, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(51.0deg, square(fill: rgb(33, 153, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(56.0deg, square(fill: rgb(33, 168, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(61.0deg, square(fill: rgb(33, 183, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(66.0deg, square(fill: rgb(33, 198, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(71.0deg, square(fill: rgb(33, 213, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(76.0deg, square(fill: rgb(33, 228, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(81.0deg, square(fill: rgb(33, 243, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ),
rotate(86.0deg, square(fill: rgb(33, 255, 100), size: 20.0mm, align(bottom, $ A = pi r^2 $)) ))
#v(10.0mm)
#figure(caption: text("The Julia language logo") , image(height: 50.0mm, "julia.svg") ) <test_fig>
#align(center, block(radius: 2.0mm, fill: cmyk(10%, 20%, 30%, 10%), inset: 4.2333333333333325mm)[
#numbering("i.i)", 531441, 2349)
#lorem(20)
#ref(<test_fig>)
#lorem(20)
$ A = pi ^2 $
#lorem(20)
#footnote()[ #lorem(10)]
$A = pi ^2$
#lorem(20)])
#v(20.0mm)
#grid(columns: (1fr, 1fr, 1fr, 1fr),
list(
text("Lorem") ,
text("ipsum") ,
text("dolor") ,
text("sit") ,
text("amet") ) ,
enum(
grid(columns: (10.583333333333332mm, 3.5277777777777777mm),
text("x^1") ) ,
grid(columns: (10.583333333333332mm, 3.5277777777777777mm),
text("x^2") ) ,
grid(columns: (10.583333333333332mm, 3.5277777777777777mm),
text("x^3") ) ,
grid(columns: (10.583333333333332mm, 3.5277777777777777mm),
text("x^4") ) ,
grid(columns: (10.583333333333332mm, 3.5277777777777777mm),
text("x^5") ) ) ,
enum(
text("Lorem") ,
text("ipsum") ,
text("dolor") ,
text("sit") ,
text("amet") ) ,
enum(
text("Lorem") ,
text("ipsum") ,
text("dolor") ,
text("sit") ,
text("amet") ,
enum(full: true, start: 4,
text("Lorem") ,
text("ipsum") ,
text("dolor") ,
text("sit") ,
text("amet") ) ) ) ]
#page(margin: (left: 20.0mm, right: 20.0mm))[
#figure(caption: "The industrial revolution was a distaster for mankind", grid(columns: (1fr, 2fr, 3fr, 4fr, 5fr),
square(size: 2.0mm, ) ,
square(size: 12.0mm, ) ,
square(size: 22.0mm, ) ,
square(size: 32.0mm, ) ,
square(size: 42.0mm, ) ) ) <uncle_ted>
#set par(justify: true)
#lorem(100)
#cite("netwok2020")
#lorem(50)
#ref(<uncle_ted>)
#lorem(50)
#columns(3)[
#lorem(100)
#heading(level: 4, outlined: false, "Par")
#lorem(100)
#bibliography("bibliography.bib") ]] |
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/sections/Introduzione.typ | typst | MIT License | #import "../functions.typ": glossary, team
#show link: underline
= Introduzione
== Scopo del documento
Questo documento ha lo scopo di stabilire con chiarezza le modalità con la quale verranno eseguite le attività dai membri del gruppo _SWAT Engineering_. In particolare verranno trattati i seguenti temi:
- Analisi dei rischi;
- Organizzazione temporale delle attività;
- Ripartizione dei compiti tra i componenti del gruppo;
- Stima dei costi e delle risorse delle varie iterazioni.
== Scopo del prodotto
Lo scopo è realizzare una #glossary("data pipeline") che, partendo dalla generazione di dati proveniente da alcuni sensori simulati, sia in grado di gestire, immagazzinare, analizzare e mostrare il flusso dati in tempo reale.
I sensori andranno a simulare il campionamento di alcune caratteristiche della città in osservazione, come temperatura, vento, traffico, e simili.
== Glossario
Al fine di evitare possibili ambiguità relative al linguaggio utilizzato nei documenti, viene fornito il _Glossario v1.0_, nel quale sono presenti tutte le definizioni di termini aventi uno specifico significato che vuole essere disambiguato. Tali termini, sono scritti in _corsivo_ e marcati con una #sub("G") a pedice.
== Riferimenti
=== Normativi
- _Norme di progetto v1.0_;
- Documento e presentazione di capitolato d'appalto C6 - InnovaCity:
- _ https://www.math.unipd.it/~tullio/IS-1/2023/Progetto/C6.pdf _
- _ https://www.math.unipd.it/~tullio/IS-1/2023/Progetto/C6p.pdf _
- Regolamento di progetto:
- _ https://www.math.unipd.it/~tullio/IS-1/2023/Dispense/PD2.pdf _
=== Informativi
- Slide dell'insegnamento di Ingegneria del Software:
- Modelli di sviluppo del software:
- _ https://www.math.unipd.it/~tullio/IS-1/2023/Dispense/T3.pdf _
- Gestione di progetto:
- _ https://www.math.unipd.it/~tullio/IS-1/2023/Dispense/T4.pdf _
- Analisi dei requisiti:
- _ https://www.math.unipd.it/~tullio/IS-1/2023/Dispense/T5.pdf _
== Scadenze
Di seguito sono riportate le date di scadenza che il gruppo _SWAT Engineering_ si impegna a rispettare per lo sviluppo del progetto "InnovaCity":
- *Prima revisione (#glossary[RTB] - Requirements and Technology Baseline):* 19 Gennaio 2024;
- *Seconda revisione (#glossary[PB] - Product Baseline):* 22 Marzo 2024;
- *Terza revisione (#glossary[CA] - Customer Acceptance):* 8 Aprile 2024. |
https://github.com/Menahra/CVTemplate | https://raw.githubusercontent.com/Menahra/CVTemplate/main/CVTemplate.typ | typst | #import "content/utils.typ": accentColor, spacing;
#import "content/LeftPane.typ": LeftPane;
#import "content/RightPane.typ": RightPane;
#let CVTemplate(
jsonFilePath,
configJsonFilePath,
photoPath,
locale,
) = {
let applicantData = json(jsonFilePath);
let config;
if (configJsonFilePath != none) {
config = json(configJsonFilePath);
}
let translations = json("./translations/" + locale + ".json");
// remove margins of page
set page(
margin: (x: 0pt, y: 0pt)
)
let rightContent;
if (config == none) {
rightContent = box(
width: 100%,
height: 100%,
inset: (x: spacing(amount: 3), y: spacing(amount: 4)),
RightPane(
applicantData,
translations
)
);
} else {
rightContent = box(
width: 100%,
height: 100%,
inset: (x: spacing(amount: 3), top: spacing(amount: 4), bottom: spacing(amount: 1)),
[
#box(
width: 100%,
height: 95%,
inset: (bottom: spacing(amount: 1.5)),
RightPane(
applicantData,
translations
)
)
#align(
center + bottom,
text(7pt, translations.attribution)
)
]
)
}
grid(
columns: (30%, 70%),
rows: 100%,
gutter: 0pt,
box(
width: 100%,
height: 100%,
fill: accentColor,
inset: spacing(amount: 3),
LeftPane(
applicantData,
photoPath,
translations
)
),
rightContent
)
};
|
|
https://github.com/grodino/uni-rennes-typst | https://raw.githubusercontent.com/grodino/uni-rennes-typst/main/src/slides.typ | typst | MIT License | #import "@local/polylux:0.3.1": polylux-slide, logic, utils
#import "colors.typ": *
////////////////////////////////////////////////////////////////////////////////
// GLOBAL THEME INFO //
////////////////////////////////////////////////////////////////////////////////
#let file-meta = state("file-meta")
#let is-appendix = state("is-appendix", false)
#let PRESENTATION-16-9 = (width: 841.89pt, height: 473.56pt)
////////////////////////////////////////////////////////////////////////////////
// TITLE SLIDE //
////////////////////////////////////////////////////////////////////////////////
#let title-slide(body) = polylux-slide(
locate(
loc => {
// Displays the title slide. Takes information passed to the theme when it
// was initialized
// Get the slides metadata
if file-meta == none {
return "State was not initialized"
}
let meta = file-meta.at(loc)
set text(font: "UniRennes")
hide(body)
// Main title + logos
block(
width: PRESENTATION-16-9.width,
height: 60%,
outset: 0em,
inset: 0em,
breakable: false,
stroke: none,
spacing: 0em,
stack(dir: ltr, if meta.logos != none {
block(width: 37%, inset: 1em, columns(2, for logo in meta.logos {
logo
}))
}, align(center + horizon, text(size: 1.7em, fill: primary.dark)[
#text(
font: "UniRennes Inline",
fill: accent-blue.light.darken(50%),
meta.title,
)
#text(size: .5em, style: "oblique", font: "Newsreader", meta.subtitle)
#text(size: .4em, weight: "regular")[
#meta.info
]
])),
)
// People
if meta.people != none {
set image(width: 2 * 2.4cm)
block(
width: PRESENTATION-16-9.width,
height: 40%,
outset: 0em,
inset: (x: .5em),
breakable: false,
stroke: none,
spacing: 0em,
fill: accent-blue.light.darken(50%),
align(
center + horizon,
for person in meta.people {
box(width: 100% / meta.people.len())[
#person.last()
#place(
top + center,
circle(radius: 2.4cm, stroke: 6pt + accent-blue.light.darken(50%)),
)
#v(-15pt)
#text(size: 20pt, fill: primary.light, person.first())
]
},
),
)
// The little seeparator between people and the title
place(
left + horizon,
dx: PRESENTATION-16-9.width / 2 - 6em / 2,
dy: 10%,
rect(width: 6em, height: .5em, radius: .25em, fill: accent-pink.light),
)
}
},
),
)
////////////////////////////////////////////////////////////////////////////////
// UTILS //
////////////////////////////////////////////////////////////////////////////////
// Displays the title and relevant information in the left banner
#let displayed-title(title, subtitle: none, vignette: none, appendix: false) = locate(
loc => {
let meta = file-meta.at(loc)
set align(bottom)
block(
width: 100%,
height: 100% - 3cm,
inset: 1em,
clip: true,
)[
//////////////////////////////////////////////////////////////////////////
// Slide title
#set align(top)
#text(font: "UniRennes", fill: primary.light, heading(level: 2, title))
//////////////////////////////////////////////////////////////////////////
// Slide subtitle
#if subtitle != none {
v(1em)
text(
fill: primary.light,
weight: "light",
style: "italic",
size: 24pt,
font: "Newsreader",
subtitle,
)
}
//////////////////////////////////////////////////////////////////////////
// Slide vignette
#if vignette != none {
set text(fill: primary.light, font: "Newsreader")
vignette
}
//////////////////////////////////////////////////////////////////////////
// Slide TOC
#set align(bottom)
// Get the current section name
#let sections = utils.sections-state.at(loc)
#let current-section = none
// Display the toc only when the first chapter has begun
#if sections.len() > 0 {
current-section = sections.last().body
for item in query(heading.where(level: 1, outlined: true), loc) {
if item.body == [Appendix] {
continue
}
if item.body != current-section {
text(fill: primary.light, font: "UniRennes", size: 16pt, item.body)
} else {
text(
fill: primary.light,
size: 16pt,
font: "UniRennes",
weight: "bold",
item.body,
)
}
linebreak()
}
}
]
if meta.logo != none {
block(width: 100%, inset: 10pt)[
#set align(left + bottom)
#set text(size: 12pt, fill: primary.light)
#let size = 2em
#stack(dir: ltr, {
set image(width: size, height: size)
meta.logo
}, box(height: size, width: 100% - size)[
#set align(right + horizon)
#if appendix == false {
logic.logical-slide.display() + "/"
numbering("1", logic.logical-slide.final(loc).first())
} else {
"Appx. " + logic.logical-appendix.display("1") + "/"
numbering("1", logic.logical-appendix.final(loc).first())
} \
//
#meta.short-authors
])
]
}
},
)
////////////////////////////////////////////////////////////////////////////////
// SLIDES DECLARATIONS //
////////////////////////////////////////////////////////////////////////////////
#let slide(title: none, subtitle: none, vignette: none, appendix: false, body) = locate(
loc => {
let meta = file-meta.at(loc)
polylux-slide(
appendix: appendix,
{
box(
width: meta.split-size * PRESENTATION-16-9.width,
height: 100%,
outset: 0em,
baseline: 0em,
stroke: none,
fill: accent-blue.light.darken(50%),
displayed-title(title, subtitle: subtitle, vignette: vignette, appendix: appendix),
)
box(
width: (100% - meta.split-size) * PRESENTATION-16-9.width,
height: 100%,
outset: 0em,
inset: 1em,
baseline: 0em,
stroke: none,
fill: primary.light,
)[
#set align(left + horizon)
#set text(fill: primary.dark)
#body
]
},
)
},
)
#let slide-full(body, appendix: false, fill: white) = polylux-slide(
appendix: appendix,
box(inset: 1em, width: PRESENTATION-16-9.width, height: 100%, fill: fill)[
#set align(center + horizon)
#set text(fill: primary.dark)
#body
],
)
////////////////////////////////////////////////////////////////////////////////
// NOTES //
////////////////////////////////////////////////////////////////////////////////
#let note(body) = locate(
loc => {
// Ignore notes that come from duplicated slides
if logic.subslide.at(loc).first() <= 1 [
#metadata((page: logic.logical-slide.at(loc).first(), body: body)) <note>
]
},
)
#let notes-page() = locate(loc => page(paper: "a4", margin: 1em)[
#let notes = query(<note>, loc)
#set text(size: 12pt)
#for note in notes {
text(size: 16pt, weight: "bold", [Slide #note.value.page])
linebreak()
note.value.body
parbreak()
}
])
////////////////////////////////////////////////////////////////////////////////
// THEME DECLARATION //
////////////////////////////////////////////////////////////////////////////////
#let unirennes-slides(
short-authors: [],
title: [],
subtitle: [],
info: [],
logo: none,
logos: none,
people: none,
split-size: 25%,
notes: "hide",
body,
) = {
// Set the page dimensions (depends on whether the notes are displayed)
let page-width = PRESENTATION-16-9.width
if "side" in notes {
page-width = 2 * PRESENTATION-16-9.width
}
set page(paper: "presentation-16-9", width: page-width, margin: 0pt)
// Set the outline entry properties when displayed as main content
show outline.entry: it => {
it.body
}
// emph with a different color
show emph: set text(fill: accent-orange.light)
// Headings :
// - level 1 is never displayed (only in TOC). Used from structure
// - level 2 is used for slides titles
// - level 3- is used inside the slides
// Hide level 1 headings but keep them in the TOC
show heading.where(level: 1): it => utils.register-section(it.body)
// Heading font properties
show heading.where(level: 2): set text(font: "UniRennes", size: 28pt)
// Regular text properties
set text(font: "Newsreader", weight: "light", size: 22pt)
// Change the marker for lists
set list(marker: (sym.triangle.filled.r, $=>$))
// Change the font of the labeled lists
show terms.item: it => [
#set par(hanging-indent: terms.hanging-indent)
#text(font: "UniRennes", weight: "bold", it.term)
#terms.separator
#it.description\
]
// Save all the theme information in a state container
file-meta.update((
short-authors: short-authors,
title: title,
subtitle: subtitle,
info: info,
logo: logo,
logos: logos,
people: people,
split-size: split-size,
notes: notes,
))
body
// Display all the notes in a4 pages
if "page" in notes { notes-page() }
} |
https://github.com/typst-jp/typst-jp.github.io | https://raw.githubusercontent.com/typst-jp/typst-jp.github.io/main/docs/changelog/0.2.0.md | markdown | Apache License 2.0 | ---
title: 0.2.0
description: Changes in Typst 0.2.0
---
# Version 0.2.0 (April 11, 2023)
## Breaking changes
- Removed support for iterating over index and value in
[for loops]($scripting/#loops). This is now handled via unpacking and
enumerating. Same goes for the [`map`]($array.map) method.
- [Dictionaries]($dictionary) now iterate in insertion order instead of
alphabetical order.
## New features
- Added [unpacking syntax]($scripting/#bindings) for let bindings, which allows
things like `{let (1, 2) = array}`
- Added [`enumerate`]($array.enumerate) method
- Added [`path`] function for drawing Bézier paths
- Added [`layout`] function to access the size of the surrounding page or
container
- Added `key` parameter to [`sorted`]($array.sorted) method
## Command line interface
- Fixed `--open` flag blocking the program
- New Computer Modern font is now embedded into the binary
- Shell completions and man pages can now be generated by setting the
`GEN_ARTIFACTS` environment variable to a target directory and then building
Typst
## Miscellaneous improvements
- Fixed page numbering in outline
- Added basic i18n for a few more languages (AR, NB, CS, NN, PL, SL, ES, UA, VI)
- Added a few numbering patterns (Ihora, Chinese)
- Added `sinc` [operator]($math.op)
- Fixed bug where math could not be hidden with [`hide`]
- Fixed sizing issues with box, block, and shapes
- Fixed some translations
- Fixed inversion of "R" in [`cal`]($math.cal) and [`frak`]($math.frak) styles
- Fixed some styling issues in math
- Fixed supplements of references to headings
- Fixed syntax highlighting of identifiers in certain scenarios
- [Ratios]($ratio) can now be multiplied with more types and be converted to
[floats]($float) with the [`float`] function
## Contributors
<contributors from="v0.1.0" to="v0.2.0" />
|
https://github.com/levinion/typst-dlut-templates | https://raw.githubusercontent.com/levinion/typst-dlut-templates/main/README.md | markdown | MIT License | # 大连理工大学-Typst-本科生论文模板
## Intro
![](images/cover.jpg)
![](images/code.jpg)
Typst 是一个全新的排版语言,它拥有相对较低的上手难度以及较为完备的排版功能,是 Latex 的一个非常有力的竞争对手。
该仓库包含了文献翻译和本科生论文等两个模板。如果你看过源码,可以知道其中包含了部分“魔法数字”,从而产生与 Word 导出的 PDF 相似的效果。与之相对,并没有完全采用学校官方模板中给出的参数。
如果在使用中遇到什么问题,欢迎提 ISSUE,如果本人有空会积极回复。
## 使用方式
请克隆仓库源码,然后使用以下方式进行编辑:
- 官方网页编辑器:[typst.app](https://typst.app/)
- VSCode:安装 typst 插件
- neovim:安装 typst-lsp 以及 typst.vim
- ...
## 注意事项
- 如果需要加粗,请使用`#bold`函数代替
- 如果需要引入公式,请使用`#equa`函数
- 如果需要引入图片,请使用`#pic`函数
- 如果需要使用三线表,请使用`#three_line_table`函数
- 不建议使用内置的`+`以及`-`添加列表,因为所有行都会缩进两个字符。如果这不构成影响,则可以使用。
如果有其他不明白的情况,请先查看`examples`文件夹下的实例或者`templates`文件夹下的模板文件。
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-11.typ | typst | Other | // Special messages for +, -, * and /.
// Error: 3-10 cannot add integer and string
#(1 + "2", 40% - 1)
|
https://github.com/EliasRothfuss/vorlage_typst_doku-master | https://raw.githubusercontent.com/EliasRothfuss/vorlage_typst_doku-master/main/chapter/vorgehen.typ | typst | = Vorgehen
<cha:vorgehen>
Je nach Art der Arbeit kann diese Kapitelüberschrift auch
Konzeptentwurf~lauten.
Beschreibung der Ausgangssituation und des Themenumfelds. Ggf. wird
darauf eingegangen, welche Randbedingungen und Einflüsse zu beachten
sind.
Anforderungsanalyse und Anforderungsdefinition, nach Möglichkeit
strukturiert, um zu einem späteren Zeitpunkt die Anforderungen
nachvollziehbar verifizieren zu können.
Herleitung einer Lösung (einer Methodik, eines experimentellen Aufbaus
oder von unterschiedlichen Konzepten), Lösungsbewertung und bewusste
Wahl des gewählten Vorgehens. An dieser Stelle ist auch auf die
Zuverlässigkeit einer Methodik oder auf die Genauigkeit von
Untersuchungen einzugehen. Die Überlegungen sollen dazu helfen, mit der
angestrebten Lösung die gestellten Anforderungen zu erfüllen, um
schließlich die Ziele der Arbeit erreichen zu können.
Bei einer Gegenüberstellung von verschiedenen Lösungsansätzen kann z.~B.
eine Nutzwertanalyse helfen. Dabei sind nicht nur z.~B. die Funktion,
Leistungsfähigkeit, Umsetzbarkeit und Nutzbarkeit, sondern auch z.~B.
wirtschaftliche Aspekte, wie Stück-, Entwicklungskosten oder
Ressourcenverbrauch zu berücksichtigen. Sehr bedeutend sind auch Aspekte
der Nachhaltigkeit unter Betrachtung des gesamten Lebenszyklus einer
erarbeiteten Lösung.
Sowohl bei der Anforderungsdefinition, als auch bei der Lösungsfindung
gibt es eine große Anzahl an verschiedenen Methoden. Eine kleine Auswahl
ist in der folgenden Aufzählung zu finden.
- Anforderungsdefinition mithilfe des Requirements Engineering
@Pohl.2021
- Systems Engineering Ansatz @Schluter.2023
- Agile Entwicklungsmethodiken @[email protected]@Wirdemann.2022
- Klassische Bewertungsverfahren @[email protected]
Ziel dieses Kapitels ist, dass auf Basis von umfassend und genau
formulierten Anforderungen (ggf. auch Nicht-Zielen) eine Lösungsvielfalt
erarbeitet wird, welche anschließend strukturiert bewertet wird, um eine
fundierte Begründung für die angestrebte Art der Umsetzung herzuleiten. |
|
https://github.com/cocodery/cocodery | https://raw.githubusercontent.com/cocodery/cocodery/main/resume/Resume.typ | typst | #show heading: set text(font: "Linux Biolinum")
#show link: underline
#set page(
margin: (x: 0.9cm, y: 1.3cm),
)
#set par(justify: true)
#let separate() = {v(-3pt); line(length: 100%); v(-5pt)}
= <NAME>
<EMAIL> |
<EMAIL> |
#link("https://github.com/cocodery")[github.com/cocodery]
== Education
#separate()
#link("http://www.cse.neu.edu.cn/")[Northeasten University] #h(1fr) 2019/09 -- 2023/07 \
Bachelor of Engineering in Computer Science and Technology #h(1fr) <NAME>, China \
- GPA 3.78 / 5.00, Outstanding Graduation Project(Thesis) for Undergraduate Students of Class2023 (#link("http://www.cse.neu.edu.cn/2023/0614/c6274a231929/page.htm")[1st place])
- A+ Courses(greater or equal to 90): Data Structures, Computer Organization, Computer Architecture, and 28 others
== Undergraduate graduation Project
#separate()
*Compiler Design and Implementation, from subset of C programming language to RISC-V assembly language*
Northeastern University, Advised by Professor <NAME> #h(1fr) Shenyang, China \
- Use parser tool #link("https://www.antlr.org/")[ANTLR] help with parsing SysY source code file and transfer it into ANTLR AST data structure
- Lowering AST into self-defined #link("https://llvm.org/docs/Reference.html#llvm-ir")[LLVM-IR] like intermediate representation for further processing
- Reproduce and design optimization algorithm, include mem2reg, DCE, DVNT, SCCP, recursive optimization, etc
- Generate LLVM IR file and verify them through #link("https://llvm.org/docs/CommandGuide/lli.html")[LLVM-Interpreter] for coverage of compiler functionality
- Calling LLVM backend and generate assembly file and running on #link("https://www.qemu.org/docs/master/system/target-riscv.html")[QEMU-RISCV]
- Result: fully support SysY and have similar performance with gcc -O2 and clang -O2
== Projects
#separate()
#link("https://github.com/cocodery/c2rvcompiler")[*C2RVCompiler*] #h(1fr) 2023/02 -- 2023/08 \
A compiler to translate SysY, a subset of C language, to RISC-V assembly language #h(1fr) Team Leader \
- Design front-end of compiler, type system, and intermediate representation
- Reproduce and design optimization algorithms, like mem2reg, DVNT, inline, SCCP, DCE, unrolling, etc
#link("https://github.com/cocodery/SysYCompiler")[*SysYCompiler*] #h(1fr) 2022/05 -- 2023/08 \
A compiler to translate SysY, a subset of C language, to ARM32 assembly language #h(1fr) Team Leader \
- Design front-end of compiler, type system, and intermediate representation
- Part of back-end of compiler, linear scan algorithm for register allocation
*NeuMIPS* #h(1fr) 2022/05 -- 2023/08 \
A 6-stage, dual-issue CPU for MIPS32 #h(1fr) Team Co-Leader \
- Framework construction of basic 5-stage pipeline CPU and enabling executing unprivileged instructions of MIPS32
- Booting a real operating system, successfully boot PMON, uCore, etc
== Open-Source Contribution
#separate()
#link("https://github.com/rust-lang/rust-clippy")[*rust-lang/rust-clippy*] \
Successfully merged: \
#link("https://github.com/rust-lang/rust-clippy/pull/11907")[PR\#11907] (fixes #link("https://github.com/rust-lang/rust-clippy/issues/11885")[Issue\#11885]) (merged on 08 Dec 2023) \
#link("https://github.com/rust-lang/rust-clippy/pull/11998")[PR\#11998] (fixes #link("https://github.com/rust-lang/rust-clippy/issues/11762")[Issue\#11762]) (merged on 23 Dec 2023) \
#link("https://github.com/rust-lang/rust-clippy/pull/12049")[PR\#12049] (fixes #link("https://github.com/rust-lang/rust-clippy/issues/11243")[Issue\#11243]) (merged on 09 Jan 2024) \
#link("https://github.com/rust-lang/rust-clippy/pull/12125")[PR\#12125] (fixes #link("https://github.com/rust-lang/rust-clippy/issues/12045")[Issue\#12045]) (merged on 19 Jan 2024) \
#link("https://github.com/rust-lang/rust-clippy/pull/12083")[PR\#12083] (fixes #link("https://github.com/rust-lang/rust-clippy/issues/11932")[Issue\#11932]) (merged on 28 Jan 2024) \
#link("https://github.com/rust-lang/rust-clippy/pull/12650")[PR\#12650] (fixes #link("https://github.com/rust-lang/rust-clippy/issues/12098")[Issue\#12098]) (merged on 09 May 2024)
#link("https://github.com/rust-lang/rust")[*rust-lang/rust*] \
#link("https://github.com/ferrocene/ferrocene")[*ferrocene/ferrocene*] \
6 contributions from #link("https://github.com/rust-lang/rust-clippy")[rust-lang/rust-clippy] mentioned above have synchronised. \
#link("https://github.com/rust-lang/rust/commits?author=cocodery")[Rust Commit Statistics] \
#link("https://github.com/rust-lang/rust/commits?author=cocodery")[Ferrocene Commit Statistics]
\
== Awards
#separate()
*Honor* \
- Outstanding Graduation Project(Thesis) for Undergraduate Students of Class2023(1st place) #h(1fr) 2023/07
- 3rd Class Scholarship of Northeastern University #h(1fr) 2021/09-2022/07
- 3rd Class Scholarship of Northeastern University #h(1fr) 2020/09-2021/07
- 2nd Class Scholarship of Northeastern University #h(1fr) 2019/09-2020/07
*Competition*
- 3rd prize of National College Student Compiler System Design Challenge\' 2023 #h(1fr) 2023/05 - 2023/08
- 3rd prize of National College Student Compiler System Design Challenge\' 2022 #h(1fr) 2022/05 - 2022/08
- 3rd prize of National College Student LoongSon Cup (CPU Design Challenge)\' 2022 #h(1fr) 2022/05 - 2022/08
- winner award of National College Student OS kernel challenge\' 2022 #h(1fr) 2022/05 - 2022/08
- 2nd prize of National College Student Mathematics Competition\' 2020 #h(1fr) 2020/05
== Skills
#separate()
*Programming languauges : * Rust, C++, C, Python \
*System and Tool : * Linux, Git, Cargo, CMake, make, Antlr \
*Technical Skills : * Compiler, Operating System(especially unikernel), Computer Architecture \
*Language : * Chinese(native), English(IELTS 6.5(B2))
#h(1fr) latest update on: 2024/Jun/02
|
|
https://github.com/8LWXpg/jupyter2typst | https://raw.githubusercontent.com/8LWXpg/jupyter2typst/master/README.md | markdown | MIT License | # Jupyter to Typst converter
Feel free to open a issue or PR!
## Features
- automatic image download/extract
- nice template
- support for KaTeX in markdown math (mostly complete)
Look for demos in [test](test) folder.
## Install
Download binary from [release](https://github.com/8LWXpg/jupyter2typst/releases/latest) page
Or
Install with cargo:
```bash
cargo install --git 'https://github.com/8LWXpg/jupyter2typst.git'
```
After that, you can use `jupyter2typst` in your terminal.
## Template
The output `.typ` file imports a template file. It is required to have a `template.typ` file in the same directory as the output `.typ` file.
Check the [template list](./template/template.md) for templates others have made.
Download the [template](./template/template.typ) file:
```bash
curl 'https://raw.githubusercontent.com/8LWXpg/jupyter2typst/master/template/template.typ' > template.typ
```
modify the `template.typ` to fit your needs.
## Usage
```bash
jupyter2typst <input> [-o <output>] [-i <img-path>]
```
- `input`: the path of the input `.ipynb` file
- `output`: the path of the output `.typ` file
- `img-path`: the path of the image folder, default is `./img`
## Contributing
### Adding a template
1. Create a new template file `<template-name>.typ` in the `template` folder
2. Add simple description in `template/template.md`
3. submit a PR with a preview image of `template/base.typ` compiled with the new template
## KaTeX support list
read [convert_list.md](convert_list.md)
|
https://github.com/yamoling/ulb-template-typst | https://raw.githubusercontent.com/yamoling/ulb-template-typst/main/main.typ | typst | #import "template/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: "Un super titre",
subtitle: [Et un super sous-titre],
date: "2025-2026",
authors: (
[Auteur #smallcaps("Un")],
[Autrice #smallcaps("Deux")],
),
faculty: "FACULTÉ DES SCIENCES",
department: "DÉPARTEMENT D'INFORMATIQUE"
)
#let note(it, header: none) = {
if header == none {
header = "Note"
}
rect(
radius: 10%,
width: 100%,
stroke: none,
inset: 0.6em,
fill: ULB_LIGHT,
[ #text(ULB_BLUE, [*#header:*]) #h(0.25em) #it ]
)
}
= Titre
#lorem(20)
= Code
```sh
# uv is a wonderful Python tool !
curl -LsSf https://astral.sh/uv/install.sh | sh
uv sync
```
Le code `inline` est aussi coloré.
= Notes
#note(header: "Un titre", lorem(50))
= Math
Les équations ont des numéros et sont référençables. L'@eq:syracuse définit la suite de Syracuse.
$
u_(n+1) = cases(u_n / 2 "si u_n est pair", 3u_n + 1 "si " u_n " est impair")
$ <eq:syracuse>
|
|
https://github.com/julyfun/speit-arch-lab01 | https://raw.githubusercontent.com/julyfun/speit-arch-lab01/main/main.typ | typst | #set page(paper: "us-letter")
#set heading(numbering: "1.1.")
#set figure(numbering: "1")
#import "@preview/codelst:2.0.0": sourcecode
#show raw.where(block: true): it => {
set text(size: 10pt)
sourcecode(it)
}
// 这是注释
#figure(image("sjtu.png", width: 50%), numbering: none) \ \ \
#align(center, text(17pt)[
Computer Architecture Lab01 \ \
#table(
columns: 2,
stroke: none,
rows: (2.5em),
// align: (x, y) =>
// if x == 0 { right } else { left },
align: (right, left),
[Name:], [<NAME> (Florian)],
[Student ID:], [521260910018],
[Date:], [#datetime.today().display()],
)
])
#pagebreak()
#set page(header: align(right)[
DB Lab1 Report - <NAME>
], numbering: "1")
#show outline.entry.where(
level: 1
): it => {
v(12pt, weak: true)
strong(it)
}
// [lib]
#import "@preview/tablem:0.1.0": tablem
#let three-line-table = tablem.with(
render: (columns: auto, ..args) => {
table(
columns: columns,
stroke: none,
align: center + horizon,
table.hline(y: 0),
table.hline(y: 1, stroke: .5pt),
table.hline(y: 4, stroke: .5pt),
table.hline(y: 7, stroke: .5pt),
..args,
table.hline(),
)
}
)
#outline(indent: 1.5em)
#set text(12pt)
#show heading.where(level: 1): it => {
it.body
}
#set list(indent: 0.8em)
= Purpose
Learn how to use C language macros and pointers, and become familiar with the memory error detection tool valgrind and the debugger gdb.
= Answers to Questions and Steps
== Exercise 1
See @c1, macros are modified to get the expected output.
== Exercise 2
- To set arguments in GDB, use `set args <arg1> <arg2> ...`. Then `start` or `run`.
- Create breakpoint: `b <line number>`.
- Use `i b` to list all breakpoints.
- Use `d <breakpoint number>` to delete a breakpoint.
- Execute the next line: `n`.
- Step into the function: `s`.
- Continue the program after breakpoint: `c`.
- Print expressions: `p <expression>`. Ex: `p a + 1`.
- Display after each step: `display <expression>`. Ex: `display count`.
- Use `undisplay <display number>` to delete a display.
- Display all variables: `i lo`.
- Quit GDB: `q`.
== Exercise 3
+ We can type and send text to stdin after GDB steps to the code `fgets(..., ..., stdin)`.
+ In GDB, type `set args < name.txt` before starting the program, this redirects stdin to the input file.
== Exercise 4
+ Why is Valgrind important and how is it useful?
- Valgrind is a powerful tool for debugging and profiling. It can detect memory leaks, memory errors, and provide detailed information about memory usage.
+ How do you run a program in Valgrind?
- Run `valgrind ./<program>` to check the program.
+ How do you interpret the error messages?
- `Conditional jump or move depends on uninitialised value(s)`
- This indicates usage of uninitialised value
- `Invalid write of size 4`
- This means the program trys to write to an invalid memory location, usually caused by array out of bounds, pointer errors and dynamic memory allocation errors.
- `by 0x48C379E: printf (printf.c:33)`
- This shows the function where the error occurs. (possibly because the compiler optimizes the code where the value is obtained)
+ Why might uninitialized variables result in "heisenbugs"?
- Because the value of uninitialized variables is unpredictable, the program may run correctly sometimes and fail at other times. This makes it difficult to reproduce the bug.
+ Why didn't the `no_segfault_ex` program segfault?
- That's because the program may allocate a bit more memory (padding memory) than needed, which can prevent immediate crashes from small out-of-bounds accesses.
+ Why does the `no_segfault_ex` produce inconsistent outputs?
- The boundary statement `j < sizeof(a)` actually leads to an out-of-bounds access, and out-of-bound value is just random.
+ Why is `sizeof` incorrect? How could you still use `sizeof` but make the code correct?
- The correct boundary should be `j < sizeof(a) / sizeof(a[0])`.
- The correct output is `sum of array is 15`.
== Exercise 5
I implemented the Floyd's tortoise and hare algorithm in @c5.
= Appendix
== Exercise 1 code <c1>
```cpp
#include <stdio.h>
/* Only change any of these 4 values */
#define V0 3
#define V1 3
#define V2 1
#define V3 3
int main(void) {
int a;
char* s;
/* This is a print statement. Notice the little 'f' at the end!
* It might be worthwhile to look up how printf works for your future
* debugging needs... */
printf("Computer Architecture:\n====================\n");
/* for loop */
for (a = 0; a < V0; a++) {
printf("Fighting ");
}
printf("\n");
/* switch statement */
switch (V1) {
case 0:
printf("Parallel\n");
case 1:
printf("SISD\n");
break;
case 2:
printf("SIMD\n");
case 3:
printf("Parallel\n");
break;
case 4:
printf("MISD\n");
break;
case 5:
printf("MIMD\n");
default:
printf("Cache\n");
}
/* ternary operator */
s = (V3 == 3) ? "Hi" : "Bye";
/* if statement */
if (V2) {
printf("%s POTATO\n", s);
} else {
printf("%s TOMATO\n", s);
}
return 0;
}
```
== Valgrind output in Ex4
Run on `segfault_ex.c`:
```
==259223== Memcheck, a memory error detector
==259223== Copyright (C) 2002-2017, and GNU GPL'd, by <NAME> et al.
==259223== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==259223== Command: ./1
==259223==
==259223== Invalid write of size 4
==259223== at 0x10914F: main (in /home/julyfun/Documents/GitHub/speit-arch-lab01
/1)
==259223== Address 0x1fff001000 is not stack'd, malloc'd or (recently) free'd
==259223==
==259223==
==259223== Process terminating with default action of signal 11 (SIGSEGV)
==259223== Access not within mapped region at address 0x1FFF001000
==259223== at 0x10914F: main (in /home/julyfun/Documents/GitHub/speit-arch-lab01
/1)
==259223== If you believe this happened as a result of a stack
==259223== overflow in your program's main thread (unlikely but
==259223== possible), you can try to increase the size of the
==259223== main thread stack using the --main-stacksize= flag.
==259223== The main thread stack size used in this run was 8388608.
==259223==
==259223== HEAP SUMMARY:
==259223== in use at exit: 0 bytes in 0 blocks
==259223== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==259223==
==259223== All heap blocks were freed -- no leaks are possible
==259223==
==259223== For lists of detected and suppressed errors, rerun with: -s
==259223== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
```
Run on `no_segfault_ex.c`:
```
==259392== Memcheck, a memory error detector
==259392== Copyright (C) 2002-2017, and GNU GPL'd, by <NAME> et al.
==259392== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==259392== Command: ./1
==259392==
==259392== Conditional jump or move depends on uninitialised value(s)
==259392== at 0x48D9AD6: __vfprintf_internal (vfprintf-internal.c:1516)
==259392== by 0x48C379E: printf (printf.c:33)
==259392== by 0x1091E7: main (in /home/julyfun/Documents/GitHub/speit-arch-lab01/1)
==259392==
==259392== Use of uninitialised value of size 8
==259392== at 0x48BD2EB: _itoa_word (_itoa.c:177)
==259392== by 0x48D8ABD: __vfprintf_internal (vfprintf-internal.c:1516)
==259392== by 0x48C379E: printf (printf.c:33)
==259392== by 0x1091E7: main (in /home/julyfun/Documents/GitHub/speit-arch-lab01/1)
==259392==
==259392== Conditional jump or move depends on uninitialised value(s)
==259392== at 0x48BD2FC: _itoa_word (_itoa.c:177)
==259392== by 0x48D8ABD: __vfprintf_internal (vfprintf-internal.c:1516)
==259392== by 0x48C379E: printf (printf.c:33)
==259392== by 0x1091E7: main (in /home/julyfun/Documents/GitHub/speit-arch-lab01/1)
==259392==
==259392== Conditional jump or move depends on uninitialised value(s)
==259392== at 0x48D95C3: __vfprintf_internal (vfprintf-internal.c:1516)
==259392== by 0x48C379E: printf (printf.c:33)
==259392== by 0x1091E7: main (in /home/julyfun/Documents/GitHub/speit-arch-lab01/1)
==259392==
==259392== Conditional jump or move depends on uninitialised value(s)
==259392== at 0x48D8C05: __vfprintf_internal (vfprintf-internal.c:1516)
==259392== by 0x48C379E: printf (printf.c:33)
==259392== by 0x1091E7: main (in /home/julyfun/Documents/GitHub/speit-arch-lab01/1)
==259392==
sum of array is 104252088
==259392==
==259392== HEAP SUMMARY:
==259392== in use at exit: 0 bytes in 0 blocks
==259392== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==259392==
==259392== All heap blocks were freed -- no leaks are possible
==259392==
==259392== Use --track-origins=yes to see where uninitialised values come from
==259392== For lists of detected and suppressed errors, rerun with: -s
==259392== ERROR SUMMARY: 21 errors from 5 contexts (suppressed: 0 from 0)
```
== Ex 5 code <c5>
```c
int ll_has_cycle(node *head) {
/* your code here */
node* u = head;
node* v = head;
while (v != NULL && v->next != NULL) {
v = v->next->next;
u = u->next;
if (u == v) {
return 1;
}
}
return 0;
}
```
|
|
https://github.com/Slyde-R/not-jku-thesis-template | https://raw.githubusercontent.com/Slyde-R/not-jku-thesis-template/main/template/content/Appendix.typ | typst | MIT No Attribution | #import "../utils.typ": todo, silentheading, flex-caption
#import "@preview/cheq:0.1.0": checklist
#show: checklist
#heading(numbering: none)[Appendix A: Supplementary Material]
#todo[Replace this with your appendix (not the organ)!]
#silentheading(2)[Introduction]
Thank you for participating in this survey. Your responses will help us understand how feline manipulation tactics affect human behavior. Please answer the following questions based on your experiences with your cat(s).
+ Frequency of Observed Behaviors
- How often does your cat meow to get your attention?
- [ ] Rarely
- [ ] Occasionally
- [ ] Frequently
- [ ] Very frequently
- How often does your cat purr to get your attention?
- [ ] Rarely
- [ ] Occasionally
- [ ] Frequently
- [ ] Very frequently
- How often does your cat bring objects (e.g., toys) to you?
- [ ] Rarely
- [ ] Occasionally
- [ ] Frequently
- [ ] Very frequently
+ Effectiveness of Behaviors
- How effective do you find meowing in getting your cat's needs met?
- [ ] Not effective
- [ ] Slightly effective
- [ ] Moderately effective
- [ ] Very effective
- How effective do you find purring in calming or eliciting a positive response from you?
- [ ] Not effective
- [ ] Slightly effective
- [ ] Moderately effective
- [ ] Very effective
- How effective is bringing objects (e.g., toys) in initiating play sessions or interaction?
- [ ] Not effective
- [ ] Slightly effective
- [ ] Moderately effective
- [ ] Very effective
+ Impact on Routines and Emotions
- How has your cat's behavior affected your daily routine?
- [ ] No impact
- [ ] Minor impact
- [ ] Moderate impact
- [ ] Significant impact
- How do you generally feel when your cat uses manipulation tactics?
- [ ] Frustrated
- [ ] Amused
- [ ] Indifferent
- [ ] Affectionate
+ Additional Comments
- Please provide any additional comments or experiences related to your cat's manipulation tactics.
#heading(numbering: none)[Appendix B: Interview Guide]
#silentheading(2)[Introduction]
Thank you for agreeing to participate in this interview. The following questions are designed to gather detailed insights into your experiences with your cat's behavior. Feel free to elaborate on your answers as much as you like.
+ Instances of Manipulation
- Can you describe a specific instance where your cat used manipulation tactics to achieve something?
- How did you respond to this behavior?
+ Emotional Responses
- How did you feel during and after the manipulation?
- Did the behavior change your emotional state or relationship with your cat?
+ Behavioral Changes
- Have you made any changes to your routine or behavior in response to your cat's manipulation?
- How have these changes affected your interactions with your cat?
+ General Impressions
- What do you think about the manipulation tactics used by your cat?
- Are there any particular behaviors you find especially effective or challenging? |
https://github.com/yyhhenry/typst-docx | https://raw.githubusercontent.com/yyhhenry/typst-docx/master/README.md | markdown | # Paste Typst docx
这是一个用于在WPS/Word中直接粘贴Typst内容的宏。
This is a macro for pasting Typst content directly into WPS/Word.
## 使用方法 Usage
保证电脑中已经安装了pandoc(添加到PATH),Rust环境,以及WPS/Word。
Make sure you have pandoc (added to PATH), Rust environment, and WPS/Word installed on your computer.
```bash
# install pandoc and rust
scoop install pandoc rustup
# install typst-docx
cargo install --git https://github.com/yyhhenry/typst-docx
```
在Normal.dotm中添加[Word VBA宏](scripts/macro.vba)或,然后根据需求添加到快捷访问工具栏。
Add [Word VBA macro](scripts/macro.vba) or [WPS JS macro](scripts/macro.js) to Normal.dotm, then add it to the Quick Access Toolbar as needed.
如果调用宏时选中了一些内容,会将选中的内容剪切。
If some content is selected when the macro is called, the selected content will be cut.
后端会编译剪切板中的Typst源码到Word内容,并由宏插入到当前光标处。样式会来自插入前光标处的样式,如果获取的样式不在样式库中,则会使用默认样式。
The backend will compile the Typst source code in the clipboard into Word content, and the macro will insert it at the current cursor position. The style will come from the style at the cursor before insertion. If the obtained style is not in the style library, the default style will be used.
运行宏时,如果后台未启动,会自动启动后台。
When running the macro, if the backend is not started, the backend will be started automatically.
## WPS兼容模式 WPS Compatibility Mode
使用[WPS JS宏](scripts/macro.js),其他设置方法与上述相同。
Use [WPS JS macro](scripts/macro.js), other settings are the same as above.
只能使用剪切板,不会自动剪切选中内容。
Only the clipboard can be used, and the selected content will not be cut automatically.
默认情况下会生成额外的末尾换行,当你在段落的中间插入Typst内容时,会断开段落。
By default, extra line breaks will be generated at the end, which will break the paragraph when you insert Typst content in the middle of a paragraph.
默认情况下会插入默认正文样式,请手动调整。
By default, the default body style will be inserted, please adjust manually.
WPS无法自动启动后台,需要手动启动后台。
WPS cannot start the backend automatically, you need to start the backend manually.
```bash
# start the backend manually
typst-docx
```
|
|
https://github.com/ohmycloud/computer-science-notes | https://raw.githubusercontent.com/ohmycloud/computer-science-notes/main/Misc/fastapi_with_docker.typ | typst | #import("circuedoc_template.typ"): conf
#show: doc => conf(
title: "使用 Docker 部署 FastAPI 程序",
author: "ohmycloud",
date: datetime.today().display(),
description: "Web 版",
doc,
)
= docker 安装
```bash
# 下载 docker-compose 到 /usr/local/bin/
ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
sudo -su iot_api
sudo docker network create docker_default
sudo docker-compose --compatibility up -d
```
= 编写 Dockerfile
```yaml
FROM python:3.11
MAINTAINER circue
ENV TZ=Asia/Shanghai \
DEBIAN_FRONTEND=noninteractive
WORKDIR /app
COPY requirements.txt /app
RUN mkdir -p /etc/apt
RUN touch /etc/apt/sources.list
RUN echo > /etc/apt/sources.list
# 更新apt-get源
RUN echo deb https://mirrors.aliyun.com/debian/ bullseye main contrib non-free >> /etc/apt/sources.list
RUN echo deb-src https://mirrors.aliyun.com/debian/ bullseye main contrib non-free >> /etc/apt/sources.list
RUN echo deb https://mirrors.aliyun.com/debian/ bullseye-updates main contrib non-free >> /etc/apt/sources.list
RUN echo deb-src https://mirrors.aliyun.com/debian/ bullseye-updates main contrib non-free >> /etc/apt/sources.list
RUN echo deb https://mirrors.aliyun.com/debian/ bullseye-backports main contrib non-free >> /etc/apt/sources.list
RUN echo deb-src https://mirrors.aliyun.com/debian/ bullseye-backports main contrib non-free >> /etc/apt/sources.list
RUN echo deb https://mirrors.aliyun.com/debian-security/ bullseye-security main contrib non-free >> /etc/apt/sources.list
RUN echo deb-src https://mirrors.aliyun.com/debian-security/ bullseye-security main contrib non-free >> /etc/apt/sources.list
RUN apt-get clean && apt-get update && apt-get -y install net-tools
RUN pip install --upgrade pip && pip install -i https://mirrors.aliyun.com/pypi/simple --no-cache-dir -r /app/requirements.txt
RUN pip install http://pypi.circue.tech/bigdata/datahouse/+f/463/f0bf0ec13d546/esc_app-0.3.42-py3-none-any.whl#sha256=463f0bf0ec13d54667b9d33643eef22334e31c67036e0f591ed65ab15db39f52
COPY ./ /app
WORKDIR /app/src/iot_api
CMD ["python", "main.py"]
```
更换 Debian 系统的源,更换 pip 的安装源。
= 编写 docker-compose.yml
```yaml
version: '3'
services:
iot-api:
build:
context: ./
dockerfile: ./Dockerfile
image: circue/iot-api
container_name: iot-api
networks:
docker_default:
aliases:
- iot-api
ports:
- "10217:10217"
volumes:
- /data/log:/log
deploy:
resources:
limits:
cpus: '1'
memory: 2G
networks:
default:
external:
name: docker_default
docker_default:
external: true
```
|
|
https://github.com/tiankaima/typst-notes | https://raw.githubusercontent.com/tiankaima/typst-notes/master/7e1810-algo_hw/utils.typ | typst | #let ans(it) = [
#pad(1em)[
#text(fill: blue)[
#it
]
]
]
#let rev1_note(it) = [
#box(inset: 1em)[
#text(fill: red)[
#it
]
]
]
#let notice(it) = [
#rect(inset: 1em, stroke: 0.02em + green, width: 100%)[
#set align(center)
#set text(fill: green)
*TODO:*
#it
]
] |
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/cjk-latin-spacing.typ | typst | Apache License 2.0 | // Test CJK-Latin spacing.
#set page(width: 50pt + 10pt, margin: (x: 5pt))
#set text(lang: "zh", font: "Noto Serif CJK SC", cjk-latin-spacing: auto)
#set par(justify: true)
中文,中12文1中,文12中文
中文,中ab文a中,文ab中文
#set text(cjk-latin-spacing: none)
中文,中12文1中,文12中文
中文,中ab文a中,文ab中文
---
// Issue #2538
#set text(cjk-latin-spacing: auto)
abc字
abc字#linebreak()
abc字#linebreak()
母
abc字\
母
|
https://github.com/maxdinech/typst-recipe | https://raw.githubusercontent.com/maxdinech/typst-recipe/main/example.typ | typst | #import "recipe.typ": recipe, note
#set text(lang: "fr")
#set text(10pt, font: "IBM")
#set page(
margin: (x: 54pt, y: 52pt),
numbering: "1",
number-align: right,
)
#let author = [<NAME>]
#let max-magrets-ananas = recipe(
title: [Magrets de canard à l'ananas],
author: author,
description: [
Sans doute mon plat préféré, cette recette du Sud-Ouest aux accords sucré-salé, sublimée par un vin proposant le juste équilibre de puissance et de fruits confits est une belle explosion de saveurs simples, les laissant toutes s'exprimer deux à deux en autant de mariages séduisants.
],
prep_time: "20 minutes",
bake_time: "15 minutes",
difficulty: "facile",
ingredients: [
- 3 magrets de canard
- 6 rondelles d'ananas
- 4 c.à.s. de miel
- 6 c.à.s de vinaigre
- sel, poivre
],
cookware: [],
steps: [
Sortir les magrets 20 minutes avant la cuisson. Découper l'excédent de gras sur les côtés des magrets. Inciser profondément en croisillons le gras du magret, sans couper la viande. Saler et poivrer les deux côtés.
Poser les magrets côté gras dans une poêle froide et chauffer à vif. Cuire 7 minutes#note("Cuire jusqu'a ce que le gras soit bien grillé. Quand il devient brun, on peut retourner.") en arrosant la chair et en retirant régulièrement l'excèdent de graisse fondue au fond de la poêle et en la réservant dans un bol#note("Cette graisse permettra de réaliser d'excellentes pommes de terres sautées qui accompagneront bien cette recette.").
Retourner les magrets et cuire 3 minutes côté chair puis les retirer de la sauteuse en les couvrant sous de l'aluminium.
Ajouter les tranches d'ananas et laisser caraméliser quelques minutes. Saler poivrer, réserver sur des assiettes chaudes.
Déglacer la poêle avec le vinaigre, puis ajouter le miel. Laisser frémir deux minutes puis baisser le feu au minimum.
Pour le service : découper le magret en tranches d'environ 1 cm. Les disposer en gardant la forme du magret sur un plat préalablement chauffé au four, ajouter l'ananas, et napper de la sauce au miel.
#colbreak()
#image("magrets-ananas.png", width: 100%)
],
remarks: [],
pairings: [
Le magret de canard est une viande assez puissante en goût, il faut donc l’accompagner avec un vin rouge relativement jeune (5-10 ans) qui pourra rivaliser avec cette puissance. On pourrait penser aux vins de Bordeaux, mais l'accord avec l'ananas de la recette ne me semble pas évident. On cherchera ainsi plutôt des vins de la vallée du Rhône méridionale, autour de Vacqueyras et Châteauneuf-du-Pape, à la recherche de notes d'orange, ou bien des vins du Languedoc pour leurs tanins puissants et les notes de prune. Ou encore, pour un accord plus régional, un malbec du Sud-Ouest. Par exemple :
- Cotes-du-Rhône, *Domaine des Tours* (#sym.euro)
- Minervois-la-Livinière, *Chateau Maris -- Les Planels* (#sym.euro#sym.euro)
- Terrasses du Larzac, *Domaine <NAME> 2018* (#sym.euro#sym.euro)
]
)
#let max-filet-pate = recipe(
title: [Filet mignon de porc en pâte],
author: author,
description: [Description ici],
prep_time: "20 minutes",
bake_time: "15 minutes",
difficulty: "facile",
ingredients: [
- 1 filet mignon de porc
- une pate feuilletée
- moutarde (4 c.s.)
- crème fraiche (4 c.s.)
- vin blanc (10 cl)
- sel (1 pincée)
- poivre
],
cookware: [
Un moule de 22cm
],
steps: [
+ Sortir les magrets 20 minutes avant la cuisson.
+ Retirer l'excedent de gras sur les cotes des magrets.
+ Avec un couteau, inciser profondément en croisillons le gras du magret, saler et poivrer les 2 cotés.
+ Poser les magrets cote gras dans une poele chauffee a vif
+ Cuire 5 minutes en arrosant le dessus des magrets avec le gras de cuisson
+ Retourner les magrets et cuire 3 minutes avant de les retirer de la sauteuse et les envelopper dans du papier aluminium.
#colbreak()
7. Reserver le gras de la sauteuse, ajouter les tranches d'ananas et laisser caraméliser quelques minutes. Saler poivrer, Réserver sur des assiettes chaudes.
+ Jetez la graisse contenue dans la poêle et remettez-la sur feu vif, avec les tranches d'ananas, leur jus et le reste de marinade des magrets. Faites-les caraméliser en les retournant souvent.
+ Dès que l'ananas est coloré, réglez le feu au minimum, posez les magrets dans la poêle, côté peau au-dessus, salez, poivrez, couvrez à demi et laissez sur feu doux encore 5 min.
+ aaa
],
remarks: [
- On peut utiliser l'excedent de graisse de canard (decoupe a la preparation et la graisse extraite pendant la cuisson) pour realiser des patates sautees.
]
)
#max-magrets-ananas
|
|
https://github.com/antonWetzel/Masterarbeit | https://raw.githubusercontent.com/antonWetzel/Masterarbeit/main/arbeit/visualisierung.typ | typst | #import "setup.typ": *
= Visualisierung
== Punkte
Grafikpipelines haben mehrere primitive Formen, welche gerendert werden können. Die verfügbaren primitiven Formen sind meistens Punkte, Linien und Dreiecke, wobei Dreiecke immer verfügbar sind. Für das Anzeigen von komplizierter Modellen werden mehrere primitiven Formen zusammengesetzt.
Der primitive Punkt hat dabei keine Größe, sondern wird mit genau einem Pixel dargestellt. Um einen Punkt mit einer Größe anzeigen, werden Dreiecke als primitive Form verwendet. Dabei hat ein Dreieck beliebige Eckpunkte und die Grafikpipeline färbt alle Pixel ein, welche zwischen den Eckpunkten liegen.
Um einen Kreis zu rendern, kann ein beliebiges Polygon gerendert werden, solange der gewünschte Kreis vollständig enthalten ist. Die Pixel, welche außerhalb vom Kreis liegen, werden beim Rendern verworfen, wodurch nur der Kreis übrig bleibt. Je mehr Ecken das Polygon hat, desto kleiner ist der Bereich vom Polygon, der nicht zum Kreis gehört. Jede Ecke und der benötigte Bereich erhöhen den benötigten Arbeitsaufwand.
=== Mögliche Polygone
Zuerst wird ein Kreis mit Position $(0, 0)$ und Radius $1$ benötigt. Mithilfe der Position vom Punkt und der Kamera wird der Kreis transformiert, dass die korrekten Pixel eingefärbt werden. In @visualisierung_polygon ist die Konstruktion für mögliche Polygone gegeben.
#figure(caption: [Seitenlänge für Polygone, welche den Einheitskreis enthalten.], grid(
columns: 2,
subfigure(
caption: [Dreieck],
cetz.canvas(length: 1.8cm, {
import cetz.draw: *
set-style(stroke: black)
circle((0, 0), radius: 1, fill: silver)
line((-1.73, -1), (-0.86, 0.5), (0, 0), close: true)
line((-1.73, -1), (0, -1), (0, 0), close: true)
line((0, -1), (1.73, -1), (0, 2), close: true)
arc((-1.73, -1), start: 0deg, stop: 30deg, anchor: "origin", radius: 0.65)
content((-1.45, -0.9), [$30°$], anchor: "west")
arc((0, -1), start: 90deg, stop: 180deg, anchor: "origin", radius: 0.35)
circle((-0.15, -0.85), radius: 0.01, fill: black)
arc((0, 0), start: 210deg, stop: 270deg, anchor: "origin", radius: 0.52)
content((-0.2, -0.2), [$60°$], anchor: "north")
content((0, -1), $w = 2 dot tan(60°) approx 3,46$, anchor: "north", padding: 0.1)
line((0, 0), (0, 2), (-0.86, 0.5))
content((0, 0), $h = 1 + 1 / cos(60°) = 3$, angle: 90deg, anchor: "north", padding: 0.1)
circle((0, 0), radius: 0.05, fill: black, stroke: none)
}),
), subfigure(
caption: [Quadrat],
cetz.canvas(length: 1.8cm, {
import cetz.draw: *
set-style(stroke: black)
line((-1, -1), (-1, 1), (1, 1), (1, -1), close: true)
circle((0, 0), radius: 1, fill: silver)
circle((0, 0), radius: 0.05, fill: black, stroke: none)
line((-1, -1), (1, 1))
line((-1, 0), (0, 0), (0, -1))
content((-0.5, 0.0), $1$, anchor: "south", padding: 0.1)
content((0.0, -0.5), $1$, anchor: "west", padding: 0.1)
content((0, -1), $a = 2$, anchor: "north", padding: 0.1)
}),
),
)) <visualisierung_polygon>
Das kleinste passende Dreieck ist ein gleichseitiges Dreieck. Ein mögliches Dreieck hat die Eckpunkte $(-tan(60°), -1)$, $(tan(60°), -1)$ und $(0, 2)$. Für das Dreieck werden drei Ecken und eine Fläche von $(w dot h) / 2 = (tan(60°) dot 2 dot 3) / 2 = tan(60°) dot 3 approx #number(5.2)$ benötigt.
Das kleinste mögliche Viereck ist das Quadrat mit Seitenlänge $2$. Um diesen anzuzeigen, wird das Quadrat entlang der Diagonalen in zwei Dreiecke unterteilt. Für die beiden Dreiecke werden sechs Ecken und eine Fläche von $a^2 =2^2 = 4$ benötigt.
In @visualiserung_vergleich_polygon ist ein Vergleich für eine Punktwolke gerendert mit unterschiedlichen Polygonen. Für Polygone mit mehr Ecken, wird der benötigte Bereich kleiner, es werden aber auch mehr Eckpunkte benötigt.
#let boxed(p, caption: []) = subfigure(box(image(p), stroke: 1pt, clip: true), caption: caption)
#figure(
caption: [Eine Punktwolke mit einem Polygonen oder Kreis für jeden Punkt.],
grid(
columns: 1 * 3,
gutter: 1em,
boxed("../images/crop/point_triangle.png", caption: [Dreiecke]),
boxed("../images/crop/point_quad.png", caption: [Quadrate]),
boxed("../images/crop/point_circle.png", caption: [Kreise]),
),
) <visualiserung_vergleich_polygon>
=== Anzeigen im dreidimensionalen Raum
Für jeden Punkt wird mit der Position $p$, Normalen $n$ und Größe $s$ und den Koordinaten $(x_i, y_i)$ vom Eckpunkt $i$ die zugehörige Position $p_i$ im dreidimensionalen Raum bestimmt. Wie in @dreieck_kreuzprodukt werden zuerst zwei Vektoren bestimmt, welche paarweise zueinander und zur Normalen orthogonal sind. Mit den Vektoren wird dann die dreidimensionale Position vom Eckpunkt berechnet.
#figure(caption: [Transformation der Eckpunkte mit der Normalen.], grid(
columns: 2,
subfigure(
caption: [$a$ und $b$ berechnen],
cetz.canvas(length: 1.6cm, {
import cetz.draw: *
set-style(stroke: black)
let test((x, y, z), name: "", paint: gray) = {
let l = x * x + y * y + z * z
let l = calc.sqrt(l) / 2
let x = x / l
let y = y / l
let z = z / l
line((x, 0, 0), (x, 0, z), (0, 0, z), stroke: (paint: paint, dash: "dashed"))
line((x, 0, z), (x, y, z), stroke: (paint: paint, dash: "dashed"))
line((0, 0, 0), (x + z / 2, y + z / 2), stroke: paint, mark: (end: ">", fill: paint), name: name)
}
test((-56, -182, 70), name: "b", paint: red)
content("b.end", [$b$], anchor: "east", padding: 0.1)
test((-28, 14, 14), name: "a", paint: green)
content("a.end", [$a$], anchor: "east", padding: 0.1)
test((3, 1, 5), name: "n", paint: black)
content("n.end", [$n$], anchor: "west", padding: 0.1)
line((-2, 0, 0), (2, 0, 0), stroke: gray + 2pt, mark: (end: ">", fill: gray), name: "x")
line((0, -2, 0), (0, 2, 0), stroke: gray + 2pt, mark: (end: ">", fill: gray), name: "y")
line((-1, -1), (1, 1, 0), stroke: gray + 2pt, mark: (end: ">", fill: gray), name: "z")
content("x.end", [$x$], anchor: "north", padding: 0.1)
content("y.end", [$y$], anchor: "west", padding: 0.1)
content("z.end", [$z$], anchor: "west", padding: 0.1)
test((1, 5, -3), name: "n_m", paint: blue)
content("n_m.end", [$(n_y, n_z, -n_x)$], anchor: "south", padding: 0.1)
}),
), subfigure(
caption: [Eckpunkt berechnen],
cetz.canvas(length: 2cm, {
import cetz.draw: *
set-style(stroke: black)
line((0, 0, 0), (0, 1, 0), mark: (end: ">", fill: black), name: "n")
line((0, 0, 0), (2, 0, 0), mark: (end: ">", fill: black), name: "a")
line((0, 0), (1, 1), mark: (end: ">", fill: black), name: "b")
content("n.end", [$n$], padding: 0.1, anchor: "east")
content("a.end", [$a$], padding: 0.1, anchor: "north")
content("b.end", [$b$], padding: 0.1, anchor: "west")
line((0, 0, 0), (0, 0, 1.5), stroke: green + 2pt)
line((0, 0, 0), (1.5, 0, 0), stroke: red + 2pt)
line((0, 0, 1.5), (1.5 + 1.5 / 2, 1.5 / 2), (1.5, 0, 0), stroke: (dash: "dashed"))
content((1.5 + 1.5 / 2, 1.5 / 2), [$p_i$], padding: 0.1, anchor: "west")
content((1.5 / 2, 0), [$x_i dot s$], anchor: "north", padding: 0.1)
content((0.4, 0.4), [$y_i dot s$], anchor: "west", padding: 0.1)
circle((0, 0), fill: black, radius: 0.0)
circle((1.5 + 1.5 / 2, 1.5 / 2), fill: black, radius: 0.02)
content((0, 0), [$p$], anchor: "east", padding: 0.1)
}),
)
)) <dreieck_kreuzprodukt>
Für den ersten Vektor $a$ wird mit der Normalen $n = (n_x, n_y, n_z)$ das Kreuzprodukt $a = (n_x, n_y, n_z) times (n_y, n_z, -n_x)$ bestimmt. Weil $norm(n) > 0$ ist, sind $n$ und $(n_y, n_z, -n_x)$ unterschiedlich. $a$ muss noch für die weiteren Berechnungen normalisiert werden. Für den zweiten Vektor $b$ wird das Kreuzprodukt $b = n times a$ bestimmt. Weil das Kreuzprodukt zweier Vektoren orthogonal zu beiden Vektoren ist, sind $n$, $a$ und $b$ paarweise orthogonal.
Die Vektoren $a$ und $b$ spannen dadurch eine Ebene auf, welche orthogonal zu $n$ ist. Für den Eckpunkt vom Dreieck wird die Position $p_i = p + a dot x_i dot s + b dot y_i dot s$ berechnet.
== Detailstufen
Je nach Scanner und Größe des abgetasteten Gebietes kann die Punktwolke unterschiedlich viele Punkte beinhalten. Durch Hardwarelimitierungen ist es nicht immer möglich, alle Punkte gleichzeitig anzuzeigen, während eine interaktive Wiedergabe gewährleistet ist.
Besonders für weit von der Kamera entfernte Punkte ist es nicht notwendig, alle Punkte genau anzuzeigen. Deshalb wird für weit entfernte Punkte eine vereinfachte Version berechnet und anstelle der originalen Punkte verwendet. Diese besteht aus weniger Punkten und benötigt dadurch weniger Ressourcen.
Für die gesamte Punktwolke wird ein Octree mit den Punkten erstellt. Am Anfang besteht der Octree aus einem Leaf-Knoten und die Punkte werden nacheinander zum Octree hinzugefügt. Dafür wird der Leaf-Knoten bestimmt, der zur Position vom Punkt gehört. Enthält der Leaf-Knoten weniger Punkte als die festgelegte Maximalanzahl, so wird der Punkt zum Knoten hinzugefügt. Wenn der Leaf-Knoten bereits voll ist, so wird dieser aufgeteilt. Der Leaf-Knoten wird mit einem Branch-Knoten mit acht Leaf-Knoten als Kinderknoten ersetzt und die Punkte vom Leaf-Knoten werden auf die Kinderknoten verteilt. Für die Unterteilung wird der Knoten entlang der x-, y- und z-Achse in der Mitte geteilt.
Alle Punkte gehören nach der Unterteilung zu einem Leaf-Knoten im Octree. Von den Leaf-Knoten aus bis zum Root-Knoten wird für jeden Branch-Knoten eine Punktwolke berechnet, welche als Vereinfachung der Punkte der zugehörigen Kinderknoten verwendet werden kann. In @visualiserung_lods sind die unterschiedlichen Stufen vom Octree mit zugehörigen Detailstufen visualisiert. Für jede höhere Stufe wird jeder Branch-Knoten durch seine Kinderknoten ersetzt, bis nur noch Leaf-Knoten angezeigt werden.
#figure(
caption: [Unterschiedliche Detailstufen. Jeder Würfel enthält bis zu $32768$ Punkte. In der höchsten Stufe werden alle Punkte im Datensatz angezeigt.],
box(width: 90%, grid(
columns: (3),
gutter: 1em,
subfigure(image("../images/crop/lod_0.png"), caption: [Stufe 0]),
subfigure(image("../images/crop/lod_1.png"), caption: [Stufe 1]),
subfigure(image("../images/crop/lod_2.png"), caption: [Stufe 2]),
subfigure(image("../images/crop/lod_3.png"), caption: [Stufe 3]),
subfigure(image("../images/crop/lod_4.png"), caption: [Stufe 4]),
subfigure(image("../images/crop/lod_5.png"), caption: [Stufe 5]),
subfigure(image("../images/crop/lod_6.png"), caption: [Stufe 6]),
subfigure(image("../images/crop/lod_7.png"), caption: [Stufe 7]),
subfigure(image("../images/crop/lod_8.png"), caption: [Stufe 8]),
)),
) <visualiserung_lods>
=== Berechnung der Detailstufen
Die Detailstufen werden wie bei "Fast Out-of-Core Octree Generation for Massive Point Clouds" @potree_lod von den untersten Branch-Knoten bis zum Root-Knoten berechnet. Dabei wird mit den Detailstufen der Kinderknoten die Detailstufe für den momentanen Knoten berechnet.
Dadurch haben zwar Berechnungen der gröberen Detailstufen für Knoten näher an der Wurzel nur Zugriff auf bereits vereinfachte Daten, aber die Anzahl der Punkte, mit denen die Detailstufe berechnet wird, ist viel kleiner. Solange die Detailstufen eine gute Vereinfachung der ursprünglichen Punkte sind, kann so der Berechnungsaufwand stark verringert werden.
Für die Berechnung einer Detailstufe wird der Voxel, welcher zu dem Knoten gehört, in eine feste Anzahl von gleich großen Teilvoxeln unterteilt. Für jeden Teilvoxel werden zuerst alle Punkt aus den Kinderknoten bestimmt, welche im Teilvoxel liegen. Liegt kein Punkt im Teilvoxel, so wird dieser übersprungen. Aus den Punkten im Teilvoxel wird ein repräsentativer Punkt bestimmt. Dafür werden die Positionen, Normalen und Größen der Punkte gemittelt und die Eigenschaften von einem der Punkte übernommen. Die Detailstufe besteht aus allen repräsentativen Punkten für die Teilvoxel, welche nicht leer waren.
Bei der nächst gröberen Detailstufe ist der Voxel vom Branch-Knoten doppelt so groß. Durch die feste Anzahl der Teilvoxel verdoppelt sich auch die Größe der Teilvoxel, wodurch die Punkte weiter vereinfacht werden.
== Eye-Dome-Lighting
Um die Punktwolke anzuzeigen, werden die Punkte aus dem dreidimensionalen Raum auf den zweidimensionalen Monitor projiziert. Dabei gehen die Tiefeninformationen verloren. Mit der Rendertechnik Eye-Dome-Lighting werden die Kanten von Punkten hervorgehoben, bei denen die Tiefe sich stark ändert.
Beim Rendern von 3D-Szenen wird für jedes Pixel die momentane Tiefe vom Polygon an dieser Stelle gespeichert. Das wird benötigt, dass bei überlappenden Polygonen das nähere Polygon an der Kamera angezeigt wird. Nachdem die Szene gerendert ist, wird mit den Tiefeninformationen für jedes Pixel der Unterschied zu den umliegenden Pixeln bestimmt. Ein Beispiel für die Tiefeninformationen ist in @eye_dome_depth gegeben. Je heller ein Pixel ist, desto weiter ist das zugehörige Polygon von der Kamera entfernt und Pixel ohne zugehöriges Polygon sind in Weiß.
#figure(
caption: [Tiefeninformationen nach dem Rendern der Szene. ],
box(image("../images/eye_dome_depth_edited.png"), stroke: 1pt),
) <eye_dome_depth>
Der Effekt entsteht dadurch, dass für jedes Pixel der maximale Unterschied in der Tiefe zu den umliegenden Pixeln bestimmt wird. Je größer der Unterschied, desto mehr wird das zugehörige Pixel verdunkelt. Eine Veranschaulichung ist in @eye_dome_example gegeben. Die Punktwolke ist zusätzlich ohne Farbe gerendert, um den Effekt hervorzuheben.
#let boxed(p, caption: []) = subfigure(box(image(p), fill: rgb(35%, 49%, 58%), stroke: 1pt), caption: caption)
#figure(
caption: [Waldgebiet mit und ohne Eye-Dome-Lighting. ],
grid(
columns: 2 * 1,
gutter: 1em,
boxed("../images/eye_dome_without.png", caption: [Ohne Eye-Dome-Lighting]),
boxed("../images/eye_dome_with.png", caption: [Mit Eye-Dome-Lighting]),
boxed("../images/eye_dome_white_without.png", caption: [Einfarbig ohne Eye-Dome-Lighting]),
boxed("../images/eye_dome_white_with.png", caption: [Einfarbig mit Eye-Dome-Lighting]),
),
) <eye_dome_example>
Die Kanten sind immer nur einem Pixel breit, wodurch der optische Effekt von der Auflösung beeinflusst wird. Wenn die Auflösung sehr niedrig ist, werden die Kanten breiter und für eine hohe Auflösung dünner.
Die Berechnung wird für jedes Pixel durchgeführt, wodurch der Aufwand nur Abhängig von der Anzahl der Pixel ist. Für eine Punktwolke mit sehr vielen Punkten bleibt dadurch der Aufwand für das Eye-Dome-Lighting gleich.
|
|
https://github.com/JonasSoerensen/CV | https://raw.githubusercontent.com/JonasSoerensen/CV/master/default/cv.typ | typst | #import "../cv.typ": *
#set page(paper: "a4", margin: 29pt)
#set text(font:"Avenir LT Pro")
#let title(..x) = {
text(weight: 500, fill:rgb("#000000"), ..x)
}
#cv(
[#text(weight:600, 25pt, tracking:10pt, grey([JONAS]))
\ #text(15pt, tracking:2pt, [INGERSLEV SØRENSEN])],
image(fit:"contain", "../formal.jpg"),
..section([CONTACT INFO])[
#table(
columns: (0.25fr, 1fr),
align: horizon,
stroke: none,
title[E-mail], link("mailto:<EMAIL>"),
title[Phone Nr], link("tel:+45 29923971"),
title[Address], link("https://goo.gl/maps/pTTcvM19ZNc2qP3w8")[Kollegiebakken 9, 802; Kongens Lyngby, 2800; Denmark],
title[LinkedIn], link("www.linkedin.com/in/jonas-ingerslev-soerensen/"),
title[Github], link("https://github.com/JonasSoerensen"),
)
],
..section[PROFESSIONAL\ SUMMARY][
With the acquisition of AxVac by Power Adhesives, I am now exploring new opportunities in compiler construction, low-level programming, and system optimization. My background in management and entrepreneurship has provided me with valuable experience in these areas.
On a personal note, I strive to be thoughtful and energetic, placing great importance on integrity and self-reflection. I am also enthusiastic about mentoring others to support their professional and personal development.
\
\
],
..section[EXPERIENCE][
#entry(title[Chief technical director] + [\ _*AxVac* | Copenhagen, Denmark_], [*2020-2024*])
AxVac, which was on the brink of bankruptcy, evolved into a pivotal supplier for leading fiberglass manufacturers such as Vestas and Siemens Gamesa, achieving €2.9 million in annual revenue prior to its acquisition. This turnaround was largely driven by an innovative image recognition system, which I designed and developed, leading to a reduction in production defects by up to 90%.
#entry(title[Software developer] + [\ _*Inniti* | Copenhagen, Denmark_], [*2021-2022*])
At Inniti, I addressed the challenge of optimizing IoT equipment for experiment automation to manage high traffic volumes. My responsibilities included minimizing inter-device communication, enhancing program performance, improving user experience, and broadening device compatibility.
#entry(title[Software developer] + [\ _*Aviation Cloud \\ Boeing* | Odense, Denmark_], [*2018-2020*])
Prior to its acquisition by Boeing, Aviation Cloud provided critical support for the ForeFlight app, delivering specialized information to private pilots that was typically unavailable for smaller aircraft. This encompassed local flight planning and tower-to-plane communication, areas for which I was directly responsible.
\
\
\
\
\
\
\
],
..section[EDUCATION][
#entry(title[Master of Computer Science & Engineering] + [\ _*Technical University of Denmark* | Kongens Lyngby, Denmark_], [*2020-2023*])
- Master thesis: _A programming language for computationel biochemistry_
- Mostly focused on programming languages, optimization\ and design of computationel machines.
- Winner of Lions den competition
#entry(title[Bachelor of Computer Science] + [\ _*University of Southern Denmark* | Odense, Denmark_], [*2016-2020*])
- Bachelor thesis: _A self programmable language_
- Graduated with Special Honours
- Honours proposition : Optimization & performance techniques for the Lotto Problem\ a derivative of the Set Cover problem
\
],
..section([REFERNCES],
table(
columns: (0.30fr, 1fr),
align: top,
stroke: none,
inset: (y: 10pt),
title[<NAME>], [
Chief Executive Director
\ AxVac
\ +4525717011
\ #link("mailto:<EMAIL>")]
,
title[<NAME>], [
Chief Technical Director
\ Inniti
\ +4525717011
\ #link("https://www.linkedin.com/in/anderslundrasmussen/")]
,
title[<NAME>], [
Vice President, Business & Military Aviation
\ Aviation Cloud
\ +4525717011
\ #link("https://www.linkedin.com/in/henrik-mhansen/")]
,
)
)
)
|
|
https://github.com/yonatanmgr/university-notes | https://raw.githubusercontent.com/yonatanmgr/university-notes/main/0366-%5BMath%5D/03661101-%5BCalculus%201A%5D/src/lectures/03661101_lecture_10.typ | typst | #import "/template.typ": *
#show: project.with(
title: "חדו״א 1א׳ - שיעור 10",
authors: ("<NAME>",),
date: "6 בפברואר, 2024",
)
#set enum(numbering: "(1.א)")
= טורים
== סדרת הסכומים החלקיים
תהי $(an)$ סדרה. נגדיר סדרה חדשה שנקראת *סדרת הסכומים החלקיים* של $(an)$ באופן הבא: $S_n = sum_(k=1)^n a_k$: $ S_1 = a_1, S_2 = a_1+a_2, dots, S_n = a_1 + a_2 + dots.h.c + a_n $
== הגדרת הטור
נאמר כי *הטור האינסופי* (או פשוט *הטור*) $sum_(k=1)^oo a_k = a_1 + a_2 + dots.h.c$ *מתכנס* אם הסדרה $(S_n)$ מתכנסת ואז נגדיר:
$ sum_(k=1)^oo a_k = liminff(S_n) $
אחרת, נאמר שהטור $sum_(k=1)^oo a_k$ *מתבדר*.
== דוגמאות
+ $sum_(k=1)^oo 1$ $arrl$ $forall k in NN, a_k = 1$ $arrl$ $S_n = 1+1+dots.h.c+1 =n$ $arrl$ $liminff(S_n)=oo$ כלומר הטור מתבדר.
+ $sum_(k=1)^oo (-1)^k$ $arrl$ $a_k = (-1)^k, forall k in NN$ $arrl$ $S_n = -1+1-1+1- dots.h.c = cases(-1 &"if" n "odd",0 &"else")$ $arrl$ $exists.not lim S_n$
והטור מתבדר.
+ $sum_(k=1)^oo 1/(2^k)$ $arrl$ $a_k = 1/(2^k), k in NN$ $arrl$ $S_n = 1/2 + 1/2^2+dots.h.c+1/2^n=frac(1/2 (1-(1/2)^n),1-1/2) = 1-1/2^n->1$ והטור מתכנס.
=== (טענה) הטור הגיאומטרי $sum_(k=1)^oo a_k$ (כלומר $a_k=a_1 q^(k-1)$) מתכנס אם״ם $abs(q)<1$ ובמקרה זה $sum_(k=1)^oo a_k = a_1/(1-q)$.
=== (טענה) הטור ההרמוני $sum_(k=1)^oo 1/k$ מתבדר.
==== הוכחה
בשיעור הקודם, הוכחנו שהסדרה $an = 1+1/2+dots.h.c + 1/n$ לא מתכנסת (בעזרת קריטריון קושי). אז, הטור $sum 1/k$ מתבדר.
== טענת כלליות על טורים
=== (טענה) אם הטור $sum an$ מתכנס אזי $an->0$. באופן שקול, אם $an cancel(->) 0$ אז $sum an$ מתבדר.
==== הוכחה
$sum an$ מתכנס $arrl$ $exists L in RR : S_n = sum_(k=1)^n a_k -->^(n->oo) L$ $arrl$ נגדיר $S_0 = 0$, ונקבל:
$ lim a_n = lim (S_n-S_(n-1)) = lim S_n - lim S_(n-1) = L-L=0 $ #QED
=== (משפט) קריטריון קושי להתכנסות טורים
הטור $sum an$ מתכנס $iff$ $forall epsilon>0 exists N(epsilon) in NN : abs(sum_(n=m+1)^(m+p) an) < epsilon, forall m >= N(epsilon) forall p in NN$ (1).
==== הוכחה
נסמן $S_n = sum_(k=1)^n a_k$ ואז $sum an$ מתכנס $iff$ קיים גבול ל-$(S_n)$ $iff$ הסדרה $(S_n)$ מקיימת את קריטריון קושי לסדרות, וזה בדיוק (1) כי:
$ abs(S_(m+p) - S_m) = abs(sum_(n=m+1)^(m+p) an) < epsilon, forall m >= N(epsilon) forall p in NN $ #QED
=== (טענה) חשבון טורים
+ אם $sum an$ ו-$sum b_n$ טורים מתכנסים, אזי הטור $sum an + b_n = sum an + sum b_n$ גם מתכנס.
+ אם $sum an$ מתכנס ו-$alpha in RR$ אזי הטור $sum (alpha an) = alpha sum an$ מתכנס.
== טור מתכנס בהחלט
נאמר כי $sum an$ *מתכנס בהחלט* אם הטור $sum abs(an)$ מתכנס.
=== (משפט) אם הטור $sum an$ מתכנס בהחלט אזי הוא מתכנס (גם לא בהחלט).
==== הוכחה
נתון $sum abs(an)$ מתכנס. לכן, לפי קריטיריון קושי עבור טורים:
$ forall epsilon>0 exists N(epsilon) in NN : abs(sum_(n=m+1)^(m+p) abs(an)) < epsilon, forall m >= N(epsilon) forall p in NN $
ואז, מאי-שוויון המשולש:
$ abs(sum_(n=m+1)^(m+p) an) <= sum_(n=m+1)^(m+p) abs(an) = abs(sum_(n=m+1)^(m+p) abs(an)) < epsilon, forall m >= N(epsilon) forall p in NN $
כלומר מתקיים קריטריון קושי לטור $sum an$ ואז הוא מתכנס.
#QED
== טורים חיוביים (אי-שליליים)
נסתכל בטורים $sum an$ כך ש-$forall n in NN, an >=0$. טורים כאלה נקראים *טורים חיוביים*.
=== (טענה) טור חיובי $sum an$ מתכנס $iff$ הסדרה $(S_n)$ חסומה מלמעלה.
=== (טענה) מבחן ההשוואה
יהיו $sum an$ ו-$sum b_n$ טורים חיוביים כך ש-$exists N_0 in NN: a_n >= b_n, forall n >=N_0$. אזי:
+ אם הטור $sum an$ מתכנס אז גם הטור $sum b_n$ מתכנס.
+ אם הטור $sum b_n$ מתבדר אז גם הטור $sum an$ מתבדר.
==== הוכחה
נסמן $S_n^a = sum a_k$ ו-$S_n^b = sum b_k$.
+ $sum an$ מתכנס $iff$ הסדרה $(S_n^a)$ מתכנסת $arrl$ הסדרה $(S_n^a)$ חסומה $arrl$ $(S_n^a)$ חסומה מלמעלה $arrl$ הסדרה $(S_n^b)$ חסומה מלמעלה $arrl$ $sum b_n$ מתכנס.
+ בשלילה. נניח $sum an$ מתכנס. אז, לפי (1), $sum b_n$ מתכנס. סתירה.
#QED
=== (טענה) מבחן השורש הכללי
יהי $sum an$ טור חיובי. אם קיימים $0<q<1$ ו-$N_0 in NN$ כך ש-$forall n >= N_0, root(n, an) <=q$, אזי הטור $sum an$ מתכנס.
==== הוכחה
$an <= q^n, forall n >= N_0$ ו-$sum q^n$ מתכנס כהנדסי עם $abs(q)<1$. אז, מקריטריון ההשוואה, $sum an$ מתכנס. $wide wide wide$ $QED$
=== (טענה) מבחן השורש הגבולי
יהי $sum an$ טור חיובי. נסמן $limsup root(n, an) = l$. אם $l<1$ אז הטור $sum an$ מתכנס; ואם $l>1$ אז הטור מתבדר.
==== הוכחה
+ נניח ראשית כי $l<1$. לכן $exists q, l tb(<q<,l+epsilon "," exists epsilon>0,"") 1$, כלומר $limsup root(n, an) < l+epsilon <1$ ואז לפי התכונות של $limsup$, $root(n, an) <= q = l+epsilon$ מתקיים כמעט תמיד. כלומר, $exists N_0 in NN : root(n, an) <= q forall n >= N_0$ ואז אנחנו עומדים בתנאי מבחן השורש הכללי.
+ נניח עתה כי $l>1$. אזי, $exists Q: 1 tb(<q<,l+epsilon "," exists epsilon>0,"") l = limsup root(n, an)$. ואז, לפי התכונות של $limsup$ העובדה $l-epsilon = Q <= root(n, an)$ הינה שכיחה. כלומר, יש אינסוף איברי הסדרה $Q <= root(n, an)$. כלומר, קיימת תת״ס עבורה מתקיים $1< Q<= root(n_k, ank)$ $arrl$ $1< Q^(n_k) <= ank$. אז $limits(lim)_(k->oo) ank = +oo$ $arrl$ $liminff(an) != 0$ $arrl$ $sum an$ מתבדר. #QED
|
|
https://github.com/mem-courses/calculus | https://raw.githubusercontent.com/mem-courses/calculus/main/note-2/2.空间解析几何.typ | typst | #import "../template.typ": *
#show: project.with(
course: "Calculus II",
course_fullname: "Calculus (A) II",
course_code: "821T0160",
semester: "Spring-Summer 2024",
title: "Note #2 空间解析几何",
authors: (
(
name: "<NAME>",
email: "<EMAIL>",
id: "3230104585",
),
),
date: "April 7, 2024",
)
#set math.mat(delim: "|")
#let aa = math.bold(math.italic("a"))
#let bb = math.bold(math.italic("b"))
#let cc = math.bold(math.italic("c"))
#let dd = math.bold(math.italic("d"))
#let ee = math.bold(math.italic("e"))
#let ii = math.bold(math.italic("i"))
#let jj = math.bold(math.italic("j"))
#let kk = math.bold(math.italic("k"))
#let rr = math.bold(math.italic("r"))
#let vv = math.bold(math.italic("v"))
#let nn = math.bold(math.italic("n"))
#let mm = math.bold(math.italic("m"))
= 行列式与矢量代数
== 行列式
=== 二阶行列式
$
mat(a_11,a_12;a_21,a_22) = a_11 a_22 - a_12 a_21
$
二阶矩阵的行列式为主对角线的积减去次对角线的积。
=== 三阶行列式
$
mat(a_11,a_12,a_13;a_21,a_22,a_23;a_31,a_32,a_33)
&= a_11 mat(a_22 a_23; a_32 a_33) - a_12 mat(a_21, a_23; a_31, a_33) + a_13 mat(a_21, a_22; a_31, a_32)\
&= a_11 a_22 a_33 + a_12 a_23 a_31 + a_13 a_21 a_32 - a_13 a_22 a_31 - a_12 a_21 a_33 - a_11 a_23 a_32\
$
== 矢量
=== 矢量的概念
#definition[
关于矢量的若干基本概念:
1. #def[数量]:只有大小,没有方向的量,记作 $a, b, c$ 等。
2. #def[矢量]:既有大小,又有方向的量,记作 $aa, bb, cc$(或 $arrow(a),arrow(b),arrow(c)$)等。
3. #def[自由矢量]:矢量不规定起点的位置。
4. #def[模]:矢量的大小,记为 $abs(arrow(A B))$ 或 $abs(aa)$。
5. #def[单位矢量]:模为 $1$ 的矢量。
6. #def[零矢量]:模为 $0$ 的矢量,记为 $arrow(0)$,方向任意。
]
#definition[
关于矢量的若干基本关系:
1. #def[相等]:矢量 $aa$ 与 $bb$ 大小相等且方向相同,即通过平移可以使他们重合,记为 $aa=bb$。
2. #def[平行(或共线)]:矢量 $aa$ 与 $bb$ 的方向相同或相反,记为 $a parallel b$。
3. #def[共面]:与同一个平面平行的矢量,称为#def[共面矢量]。
]
#definition[
设有非零向量 $aa,bb$。平移,使他们的起点重合,则此时的夹角 $theta sp (0<=theta<=pi)$ 称为矢量 $aa$ 与 $bb$ 的#def[夹角],记为 $(aa,bb)$。特别地,当 $theta = display(pi/2)$ 时,称 $aa$ 与 $bb$ #def[垂直],记作 $aa perp bb$。
特殊地,规定零矢量与任意矢量的夹角可以是任意值。
]
=== 矢量的线性运算
关于矢量的加法与减法略。
==== 矢量的数乘
#definition[
设 $lambda$ 为实数。数 $lambda$ 与矢量 $aa$ 的乘积是一个矢量,记作 $lambda aa$。
- 当 $lambda > 0$ 时,$lambda aa$ 与 $aa$ 同向;
- 当 $lambda < 0$ 时,$lambda aa$ 与 $aa$ 反向;
- 当 $lambda = 0$ 时,$lambda aa = bold(0)$,它的方向可以是任意的。
]
#theorem(name: "两个矢量共线的充要条件")[
设 $aa != bold(0)$,则 $bb parallel aa$ 的充要条件是存在唯一实数 $k$ 使得 $bb = k aa$。
]
#theorem(name: "三个矢量共面的充要条件之一")[
设 $aa,bb$ 不共线,则 $cc$ 与 $aa,bb$ 共面的充要条件是存在唯一实数 $lambda,mu$ 使得 $cc = lambda aa + mu bb$。
]
==== 矢量的单位化
#definition(name: "矢量的单位化")[
设 $aa != bold(0)$,则 $display(aa/abs(aa))$ 表示与 $aa$ 方向相同的单位矢量,记为 $ee_aa$。。
]
==== 矢量在三维空间中的分解
#theorem[
设 $aa,bb,cc$ 不共面,则对于空间中的任意一个向量 $dd$,存在唯一实数 $lambda,mu,upsilon$ 使得 $dd = lambda aa + mu bb + upsilon cc$。
]
= 空间解析几何
== 空间直角坐标系
空间直角坐标系要求是_右手系_。
#definition(name: "卦限")[
TBD:图。
]
#definition(name: "基本单位矢量")[
用 $ii, jj, kk$ 分别表示沿 $x,y,z$ 轴正方向的单位向量。
TBD:图。
]
== 空间中的矢量
=== 矢量的坐标表示
#definition[
起点在原点的矢量,设 $M(x, y, z)$,$rr = x ii + y jj + z kk= {x,y,z}$,称为#def[矢径] $rr=arrow(O M)$ 的坐标表达式。
]
#definition[
由勾股定理可知 $abs(rr) = abs(arrow(O M)) = sqrt(x^2+y^2+z^2)$,称为矢量#def[模的坐标表示]。
]
#definition[
非零矢量与三条坐标轴的正向的夹角 $alpha,beta,gamma$ 称为#def[方向角]。设 $rr=arrow(O M)={x,y,z}$,分析可知:
$ x = abs(rr) cos alpha quad quad y = abs(rr) cos beta quad quad z = abs(rr) cos gamma $
把 $cos alpha, cos beta, cos gamma$ 成为矢量 $rr$ 的#def[方向余弦]。当 $abs(rr) != 0$ 时,有:
$
cos alpha = x / sqrt(x^2+y^2+z^2) quad quad cos beta = y / sqrt(x^2+y^2+z^2) quad quad cos gamma = z / sqrt(x^2+y^2+z^2)
$
容易发现,$ee_rr = display(rr/abs(rr)) = {cos alpha, cos beta, cos gamma}$。故常用方向余弦来表示矢量的方向。
]
#theorem[
对于任意向量 $rr$,其方向余弦满足:
$ cos^2 alpha + cos^2 beta + cos^2 gamma = 1 $
]
=== 数量积
#definition[
矢量 $aa$ 与 $bb$ 的#def[数量积]记为 $aa dot bb$,
$ aa dot bb = abs(aa) abs(bb) cos theta $
其中 $theta$ 为 $aa$ 与 $bb$ 的夹角。数量积也称为#def[点积]。坐标表达式为
$ aa dot bb = a_x b_x + a_y b_y + a_z b_z $
]
#theorem(name: "数量积的几何意义")[
矢量 $aa$ 在矢量 $bb$ 上的投影长度记为 $(aa)_bb$,有 $(aa)_bb = aa dot ee_bb$。
]
#theorem(name: "两个矢量相互垂直的充要条件")[
$aa perp bb <=> aa dot bb = 0$。
]
=== 矢量积
#definition[
矢量 $aa$ 与 $bb$ 的#def[矢量积] $cc = aa times bb$ 规定为:
- 大小:$abs(cc) = abs(aa) abs(bb) sin theta$;
- 方向:$cc$ 的方向同时垂直于 $aa$ 和 $bb$,且 $aa, bb$ 与 $cc$ 成右手系。
TBD:配图
矢量积也称为#def[叉积]、#def[外积]。坐标表达式为:
$
aa times bb
= (a_y b_z - a_z b_y) ii - (a_x b_z - a_z b_x) jj + (a_x b_y - a_y b_x) kk
= mat(ii, jj, kk; a_x, a_y, a_z; b_x, b_y, b_z)
$
]
#theorem(name: "矢量积的几何意义")[
矢量 $aa,bb$ 的矢量积的模等于以这两个向量为邻边的平行四边形面积,即 $S = abs(aa times bb)$。
]
#theorem(name: "两个矢量平行的充要条件")[
$aa parallel bb <=> aa times bb = bold(0)$
]
#theorem(name: "矢量积的运算定律")[
1. 反交换律:$aa times bb = - bb times aa$。
2. 分配律:$(aa + bb) times cc = aa times cc + bb times cc$。
3. 若 $lambda$ 为数:$(lambda aa) times bb = aa times (lambda bb) = lambda (aa times bb)$。
]
#theorem(name: "基本单位矢量的矢量积")[
对于一组基本单位矢量 $ii,jj,kk$,有:
$
ii times ii = jj times jj = kk times kk = 0 quad quad ii times jj = kk, quad jj times kk = ii, quad kk times ii = jj
$
]
=== 混合积
#definition[
三个矢量 $aa,bb,cc$ 的#def[混合积]为 $(aa times bb) dot cc$。坐标表达式为:
$ (aa times bb) dot cc = mat(a_x, a_y, a_z; b_x, b_y, b_z; c_x, c_y, c_z) $
]
#theorem(name: "混合积的几何意义")[
矢量 $aa,bb,cc$ 的混合积的绝对值等于以这三个矢量为邻边的平行六面体的体积。即 $V = abs((aa times bb) dot cc)$。
]
#theorem(name: "三个矢量共面的充要条件之二")[
三矢量 $aa,bb,cc$ 共面 $<=>$ $(aa times bb) dot cc = 0$。
]
#theorem(name: "混合积的轮换对称性")[
$ (aa times bb) dot cc = (cc times aa) dot bb = (bb times cc) dot aa $
#note[
由行列式的性质,不难得到这一结论。
]
]
== 平面
=== 平面方程
#definition(name: "平面的点法式方程")[
过点 $M_0(x_0, y_0, z_0)$ 且与矢量 $nn=(A,B,C)$ 垂直的平面方程为
$ A(x-x_0) + B(y-y_0) + C(z-z_0) = 0 $
称为#def[平面的点法式方程]。将 $nn = {A,B,C}$ 称为平面的#def[法矢量]。
]
#note[
1. 这说明平面可用三元一次方程表示;反之,任一三元一次方程在 $A,B,C$ 不全为 $0$ 时表示一张平面。
2. 求两个不共线矢量 $aa,bb$ 张成的平面,就可以求出 $nn=aa times bb$ 为法向量,而得到平面的点法式方程。
]
#definition(name: "平面的一般式方程")[
对于平面的点法式方程,令 $D = -A x_0 - B y_0 - C z_0$,得
$ A x + B y + C z + D = 0 $
当 $A,B,C$ _不全为 $0$_ 时,称为#def[平面的一般式方程]。
]
#definition(name: "平面的截距式方程")[
设平面与 $x,y,z$ 三轴的交点为 $P(a,0,0)$、$Q(0,b,0)$、$R(0,0,c)$,则此平面方程为
$ x / a +y / b + z / c = 1 $
称为#def[平面的截距式方程]。
]
=== 两平面的夹角
#definition(name: "平面的夹角")[
两平面法矢量的夹角称为两平面的夹角。
]
=== 点到平面的距离
#theorem(name: "点到平面的距离公式")[
设 $P_0(x_0,y_0,z_0)$ 是平面 $A x+B y+C z+D=0$ 外一点,则 $P_0$ 到平面的距离为
$ d = abs(A x_0 + B y_0 + C z_0 + D) / sqrt(A^2 + B^2 + C^2) $
]
#note[
计算点到平面的距离时,直接套用公式是一种方法。还可以通过点坐标和平面的法向量得到点到平面的垂线的点向式方程,将这一垂线的参数式方程代入平面方程即可解出垂足坐标,从而用两点距离公式得到距离。
]
== 空间直线
=== 空间直线方程
#definition(name: "直线的一般式方程")[
空间直线可看成两个不平行平面的交线,即方程组
$ cases(A_1 x + B_1 y + C_1 z + D_1 = 0, A_2 x + B_2 y + C_2 z + D_2 = 0) $
其中,$A_1,B_1,C_1$ 与 $A_2,B_2,C_2$ 不对应成比例,则称为#def[直线的一般式方程]。
]
#definition(name: "直线的点向式方程")[
过点 $M_0 (x_0,y_0,z_0)$ 且与矢量 $vv = {l,m,n}, space (vv != bold(0))$ 平行的直线 $L$ 可被表示为
$ (x-x_0) / l = (y-y_0) / m = (z-z_0) / n $
当 $l,m,n$ _不全为 $0$_ 时,称为#def[直线的点向式方程]。
#warning[
1. 当 $l=0$ 时形式不变,但应理解为 $x=x_0$ 且 $display((y-y_0)/m = (z-z_0)/n)$;对于 $m,n$ 同理。
2. 方程不作化简,如 $display((x-6/5)/3=(y+2)/(-2)=(z-1)/3)$ _不能_化简为 $display((5x-6)/15=-(y+3)/2=(z-1)/3)$。
]
]
#definition(name: "直线的参数式方程")[
对于直线的点向式方程,取 $display((x-x_0)/l = (y-y_0)/m = (z-z_0)/n = t)$,可以得到
$
cases(
x = x_0 + l t,
y = y_0 + m t,
z = z_0 + n t
)
$
称为#def[直线的参数式方程],$l,m,n$ 称为直线的一组#def[方向数]。
]
#definition(name: "直线的两点式方程")[
过两点 $A(x_1,y_1,z_1)$ 和 $B(x_2,y_2,z_2)$ 的直线方程为
$ (x-x_1) / (x_2-x_1) = (y-y_1) / (y_2-y_1) = (z-z_1) / (z_2-z_1) $
称为#def[直线的两点式方程]。
]
=== 两条直线的位置关系
#definition(name: "空间直线的夹角")[
设直线 $L_1$ 的方向矢量为 $vv_1$,直线 $L_2$ 的方向矢量为 $vv_2$,称 $vv_1$ 和 $vv_2$ 之间的夹角 $theta$ 或 $pi - theta$ 为直线 $L_1$ 和 $L_2$ 的夹角。
]
=== 直线与平面的位置关系
#definition(name: "直线与平面的夹角")[
设直线 $L$ 的方向矢量为 $vv$,平面 $pi$ 的法矢量为 $nn$,若 $(nn,vv) = theta$,则称 $display(pi/2-theta)$ 或 $theta - display(pi/2)$ 为直线 $L$ 和平面 $pi$ 的夹角。
]
=== 点到直线的距离
#theorem(name: "点到直线的距离公式")[
直线 $L:space display((x-x_0)/l = (y-y_0)/m = (z-z_0)/n)$ 到点 $P(x_1,y_1,z_1)$ 的距离为
$ d = (arrow(M P) times vv) / vv $
其中 $M(x_0,y_0,z_0) in L$,$vv$ 是直线的方向矢量。
]
=== 直线在平面上的投影直线方程
TBD
=== 两条异面直线的距离
#theorem(name: "两条异面直线的距离公式")[
设直线 $L_1$ 和 $L_2$ 是两条异面直线,直线 $L_1$ 的方向矢量为 $vv_1$,直线 $L_2$ 的方向矢量为 $vv_2$,则两条直线的公垂线 $L$ 的方向矢量为 $vv = vv_1 times vv_2$。取 $M_1 in L_1,space M_2 in L_2$,则 $L_1,L_2$ 的距离为
$ d = (arrow(M_1 M_2) dot vv) / abs(vv) = (arrow(M_1 M_2) dot (vv_1 times vv_2)) / abs(vv_1 times vv_2) $
]
== 平面束
#definition[
称过直线 $L$ 的所有平面构成的集合为直线 $L$ 的#def[平面束]。设直线 $L$ 的方程为
$ cases(A_1 x + B_1 y + C_1 z + D_1 = 0, A_2 x + B_2 y + C_2z + D_2 = 0) $
其中,$A_1,B_1,C_1$ 和 $A_2,B_2,C_2$ 不对应成比例。则直线 $L$ 的#def[平面束方程]为:
$ lambda(A_1 x + B_1 y + C_1 z + D_1) + mu(A_2 x + B_2 y + C_2 z + D_2) = 0 $
]
== 曲面
=== 曲面
#definition(name: "曲面方程")[
若曲面 $S$ 与三元方程 $F(x,y,z)=0$ 有如下关系:
(1) $S$ 上任一点的坐标都满足方程 $F(x, y, z) = 0$;
(2) 坐标满足方程 $F(x, y, z) = 0$ 的点都在 $S$ 上。
那么,方程 $F(x, y, z)=0$ 叫做曲面 $S$ 的方程;曲面 $S$ 叫做 $F(x,y,z)=0$ 的图形。
]
#definition(name: "曲面的参数方程")[
曲面 $S$ 的参数方程为:
$ cases(x=x(u,v), y=y(u,v), z=z(u,v)) $
其中 $u,v$ 是参数。
]
=== 空间曲线
#definition(name: "空间曲线的一般式方程")[
空间曲线 $C$ 可看做空间两曲面的交线,即方程组
$ cases(F(x,y,z) = 0, G(x,y,z) = 0) $
]
#definition(name: "空间曲线的参数方程")[
空间曲线 $C$ 的参数方程为:
$ cases(x = x(t), y = y(t), z = z(t)) $
其中 $t$ 是参数。
]
#definition(name: "空间曲线在平面上的投影")[
设空间曲线 $Gamma$ 的方程为 $display(cases(F_1(x,y,z)=0,F_2(x,y,z)=0))$,消去变量 $z$ 得 $G(x,y)=0$。称 $G(x,y)=0$ 为曲线 $Gamma$ 在 $x O y$ 平面上的#def[投影柱面];称 $display(cases(G(x,y)=0,z=0))$ 为曲线 $Gamma$ 在 $x O y$ 平面上的#def[投影曲线]。类似的,可以得到在 $y O z$ 和 $x O z$ 平面上的投影曲线和投影柱面的定义。
#caution[当心隐含的定义域范围限制。]
]
=== 柱面
#definition[
由动直线 $L$ 沿着一定曲线 $Gamma$ 平行移动所形成的曲面称为#def[柱面]。称动直线 $L$ 为柱面的#def[母线],定曲线 $Gamma$ 为柱面的#def[准线]。
]
=== 锥面
#definition[
过空间一定点 $O$ 的一条动直线 $L$,沿空间_不过定点_的定曲线 $Gamma$ 移动所形成的曲面 $Sigma$ 称为#def[锥面]。称定点 $O$ 为锥面的#def[顶点],动直线 $L$ 为锥面的#def[母线],定曲线 $Gamma$ 为锥面的#def[准线]。
]
#example[
#problem[
设锥面 $Sigma$ 的准线 $Gamma$ 的方程为 $display(cases(F(x,y)=0,z=h))space (h!=0)$,且以原点为顶点,试求锥面 $Sigma$ 的方程。
]
#solution[
$forall M(x,y,z) in Sigma$,设过点 $M$ 的母线与准线 $Gamma$ 的交点为 $M_1(x_1,y_1,h)$,则 $arrow(O M_1) parallel arrow(O M)$,故
$ x_1 / x = y_1 / y=h / z $
解得 $display(x_1 = h/z x\,space y_1 = h/z y)$,故所求锥面方程为 $F(display(h/z x\,h/z y))=0$。
]
#note[
为什么有条件 $h!=0$?因为锥面的准线不能过其顶点。
]
特别地,将这里的准线方程换为 $display(cases(display(x^2/a^2 + y^2/b^2 =1), z=c)) space (c!=0)$,则锥面方程为 $display(x^2/a^2 + y^2/b^2 = z^2/c^2)$。称为#def[椭圆锥面]。将准线方程换为 $display(cases(x^2+y^2=a^2,z=c)) space (c!=0)$,则锥面方程为 $x^2+y^2=display(a^2/c^2 z^2)$,称为#def[圆锥面]。
]
=== 旋转曲面
#definition[
由一条曲线,绕一条定直线旋转,所生成的曲面称为#def[旋转曲面]。称这条定直线为旋转曲面的#def[旋转轴]。
]
#example[
#problem[
设曲线 $Gamma$ 的参数方程为 $display(cases(x=x(t),y=y(t),z=z(t)))$,假定 $Gamma$ 不是垂直于 $z$ 轴的平面上的曲线,求 $Gamma$ 绕 $z$ 轴旋转而成的旋转曲面 $Sigma$ 的方程。
]
#solution[
$forall M(x,y,z) in Sigma$,设点 $M$ 由点 $M_1(x_1,y_1,z) in Sigma$ 绕 $z$ 轴旋转而得,对应的参数是 $t_1$,则
$ x_1=x(t_1),quad y_1=y(t_1),quad z=z(t_1) $
解得 $x_1=x(z^(-1)(z)), space y_1 = y(z^(-1)(z))$。故所求曲面方程即
$ x^2+y^2 = [x(z^(-1)(z))]^2 + [y(z^(-1)(z))]^2 $
]
]
#conclusion[
对于部分特殊曲线和旋转轴对应的旋转曲面方程,有下表:
#table3(
width: 70%,
columns: (2fr, 0.7fr, 2.5fr),
[*曲线*],
[*旋转轴*],
[*旋转曲面方程*],
[#v(0.5em)$display(Gamma\:space cases(f(y,z)=0,x=0))$#v(0.5em)],
[$z$ 轴],
$f(pm sqrt(x^2+y^2),z)=0$,
[#v(0.5em)$display(Gamma\:space cases(f(y,z)=0,x=0))$#v(0.5em)],
[$y$ 轴],
$f(y,pm sqrt(x^2+z^2))=0$,
[#v(0.5em)$display(Gamma\:space cases(f(x,z)=0,y=0))$#v(0.5em)],
[$z$ 轴],
$f(pm sqrt(x^2+y^2),z)=0$,
[#v(0.5em)$display(Gamma\:space cases(f(x,z)=0,y=0))$#v(0.5em)],
[$x$ 轴],
$f(x,pm sqrt(y^2+z^2))=0$,
[#v(0.5em)$display(Gamma\:space cases(f(x,y)=0,z=0))$#v(0.5em)],
[$x$ 轴],
$f(x,pm sqrt(y^2+z^2))=0$,
[#v(0.5em)$display(Gamma\:space cases(f(x,y)=0,z=0))$#v(0.5em)],
[$y$ 轴],
$f(pm sqrt(x^2+z^2),y)=0$,
)
]
#example[
#problem[
$z=sqrt(x^2+y^2)$ 在空间解析几何中表示什么图形。
]
#solution[
可以发现,这是旋转轴为 $z$ 轴的旋转曲面。可看做曲线 $display(cases(z=sqrt(x^2+y^2),x=0))$ 绕 $z$ 轴旋转的结果。解得 $display(cases(z=|y|,x=0))$。画图可知,这是一个圆锥面。
]
]
== 二次曲面
#definition[
二次曲线$ a x^2 + b y^2 + c z^2 + d x y + e x z + f y z + g x + h y + i z + j = 0 $所表示的曲面称为#def[二次曲面]。一般用#def[截痕法]来了解二次曲面方程所表示曲面的总体特征。
]
=== 椭球面
#definition[
二次曲线 $display(x^2/a^2 + y^2/b^2 + z^2/c^2 = 1)$ 所表示的二次曲面称为#def[椭球面]。
用平行于坐标平面的平面对椭球面进行切割,得到是椭圆。
特别地,当 $a=b$ 时,这是一个以 $z$ 轴为旋转轴的椭球面,称为#def[旋转椭球面]。当 $a=b=c$ 时,称为#def[球面]。
]
=== 椭圆抛物面
#definition[
二次曲线 $z=display(x^2/a^2+y^2/b^2)$ 所表示的二次曲面称为#def[椭圆抛物面]。
用平面 $x=0$ 或 $y=0$ 切割椭圆抛物面,得到的是抛物线;用平面 $z=h$ 切割,得到的是椭圆。
特别地,当 $a=b$ 时,这是一个以 $z$ 轴为旋转轴的椭圆抛物面,称为#def[旋转抛物面]。
]
=== 单叶双曲面
#definition[
二次曲线 $display(x^2/a^2+y^2/b^2-z^2/c^2=1)$ 所表示的二次曲面称为#def[单叶双曲面]。
用平面 $x=0$ 或 $y=0$ 切割单叶双曲面,得到的是双曲线;用平面 $z=h$ 切割,得到是椭圆。
]
=== 双叶双曲面
#definition[
二次曲线 $display(x^2/a^2+y^2/b^2-z^2/c^2=-1)$ 所表示的二次曲面称为#def[双叶双曲面]。
切割双叶双曲面得到的图像与单叶双曲面类似。
]
=== 椭圆锥面
#definition[
二次曲线 $display(x^2/a^2+y^2/b^2-z^2/c^2=0)$ 所表示的二次曲面称为#def[椭圆锥面]。
]
=== 双曲抛物面
#definition[
二次曲线 $display(z=-x^2/a^2+y^2/b^2)$ 所表示的二次曲面称为#def[双曲抛物面]。
]
== 旋转变换\*
#definition[
#set math.mat(delim: "(")
在二维平面直角坐标系中,我们把平面围绕坐标原点按逆时针方向旋转 $phi$ 角的变换,称为旋转变换,记作 $bold(R)_phi$。$forall alpha = display(mat(x;y))$,设 $bold(R)_phi(alpha)$ 的坐标为 $display(mat(x';y'))$,则
$
mat(x';y') = mat(cos phi,-sin phi;sin phi,cos phi) mat(x;y)
quad => quad
cases(
x' = x cos phi - y sin phi,
y' = x sin phi + y cos phi,
)
$
#set math.mat(delim: "|")
]
|
|
https://github.com/mkpoli/ipsj-typst-template | https://raw.githubusercontent.com/mkpoli/ipsj-typst-template/master/compare/latex.typ | typst | #import "../template.typ": techrep, acknowledgement, numbering-affiliate, numbering-paffiliate, numbering-email, table, fake-bibliography
#import "@preview/tablex:0.0.8": hlinex
#set list(marker: "□")
#let affiliations = (
"IPSJ": [情報処理学会 \ IPSJ, Chiyoda, Tokyo 101–0062, Japan],
)
#let paffiliations = (
"JU": [現在,情報処理大学 \ Presently with Johoshori University]
)
#let authors = (
(
name: "<NAME>",
affiliations: ("IPSJ",),
email: "<EMAIL>"
),
(
name: "<NAME>",
affiliations: ("IPSJ",),
email: none
),
(
name: "<NAME>",
affiliations: ("IPSJ", "JU"),
email: "<EMAIL>"
)
)
#let emails = authors.map(author => author.email).filter(it => it != none)
// #show: doc => techrep(
#techrep(
title: [
情報処理学会研究報告の準備方法 \
(2018年10月29日版)
],
title_en: [
How to Prepare Your Paper for IPSJ SIG Technical Report \
(version 2018/10/29)
],
affiliations: (
"IPSJ": [情報処理学会 \ IPSJ, Chiyoda, Tokyo 101–0062, Japan],
),
paffiliations: (
"JU": [現在,情報処理大学 \ Presently with Johoshori University]
),
authors: (
(
name: "<NAME>",
affiliations: ("IPSJ",),
email: "<EMAIL>"
),
(
name: "<NAME>",
affiliations: ("IPSJ",),
email: none
),
(
name: "<NAME>",
affiliations: ("IPSJ", "JU"),
email: "<EMAIL>"
)
),
abstract: [
本稿は,情報処理学会研究報告に投稿する原稿を執筆する際の注意点等をまとめたものである.\
LaTeX と専用のスタイルファイルを用いた場合の論文フォーマットに関する指針,および論文の内容に関
してするべきこと,するべきでないことをまとめたべからずチェックリストからなる.本稿自体もLaTeX\
と専用のスタイルファイルを用いて執筆されているため,論文執筆の際に参考になれば幸いである.
],
copyright: "© 1959 Information Processing Society of Japan",
[
= はじめに
<はじめに>
情報処理学会では,研究報告の発行を行っている.
本稿では,まずそのスタイルファイルを用いた論文のフォーマットに関して述べる.
新たなスタイルファイルでは,
極力特別なコマンドは使わずに,標準的なLaTeXのスタイルを踏襲している.
論文フォーマットに関しては、@論文フォーマットの指針
で後述する指針に従って頂くが,
そこに規定されていること以外は標準的なLaTeXのコマンドをそのまま使うことができる.
本稿は,そのスタイルファイルを実際に使っているので,論文執筆の際に参考にされたい.
#place(bottom, float: true, {
set align(top + left)
set block(above: 0.5em, below: 0pt)
set text(size: 0.85em)
set par(leading: 0.5em)
line(length: 100%, stroke: 0.5pt)
grid(
columns: (auto, 1fr),
column-gutter: 1.5em,
row-gutter: 0.5em,
..for (i, content) in affiliations.values().enumerate() {
(
super(numbering(numbering-affiliate, i + 1)),
content
)
},
..for (i, content) in paffiliations.values().enumerate() {
(
super(numbering(numbering-paffiliate, i + 1)),
content
)
},
..for (i, content) in emails.enumerate() {
(
super(numbering(numbering-email, i + 1)),
content
)
}
)
})
= 投稿の流れ
<投稿の流れ>
== 準備
<準備>
情報処理学会論文誌ジャーナルのLaTeXスタイルファイルを含む論文執筆キットは
#quote(block: true)[
`http://www.ipsj.or.jp/jip/submit/style.html`
]
からダウンロードすることができる.論文執筆キットは以下のファイルを含んでいる.
+ `ipsj.cls `: 最終原稿用スタイルファイル
+ `ipsjdraft.sty `: 投稿用スタイル(査読用)
+ `ipsjpref.sty `: 序文用スタイル
+ `jsample.tex `: 本稿のソースファイル
+ `esample.tex `: 英文サンプルのソースファイル
+ `ipsjsort.bst `: jBibTEX スタイル(著者名順)
+ `ipsjunsrt.bst `: jBibTEX スタイル(出現順)
+ `bibsample.bib `: 文献リストのサンプル
+ `ebibsample.bib`: 英文文献リストのサンプル
+ `tech-jsample.tex:` 研究報告(和文)のサンプル
+ `tech-esample.tex:` 研究報告(英文)のサンプル
実行環境としてはLaTeX2eを前提としているので,準備されたい.
\
#v(0.5em)
== 原稿の作成と投稿
<原稿の作成と投稿>
本稿に従って用意した投稿用原稿のLaTeXソースからpdfファイルを作成し,
Adobeのpdf readerで読めることを確認した後,
#quote(block: true)[
`https://ipsj1.i-product.biz/ipsjsig/**`
]
\(\*\*部分は研究会の略称,DBS等)の研究会投稿システムにて,指示にし従い投稿する.
= 論文フォーマットの指針
<論文フォーマットの指針>
以下,情報処理学会論文誌ジャーナル用スタイルファイルを用いた論文フォーマットの指針について述べるので,
これに従って原稿を用意頂きたい.
LaTeXを用いた一般的な文章作成技術については,
#cite(<okumura>);#cite(<companion>) 等を参考にされたい.
#colbreak()
#v(1.5em)
= 論文の構成
<config>
ファイルは次のようになる.下線部は投稿時に省略可能なもの.
```
\documentclass[submit,techrep,noauthor]{ipsj}
```
必要ならばユーザーのマクロをここに記述
```
\begin{document}
\title{表題(和文)}
\etitle{表題(英文)}
\affiliate{所属ラベル}{<和文所属>\\<英文所属>}
```
必要ならば `\paffiliate` により現在の所属を宣言する
```
\paffiliate{現所属ラベル}{<和現所属>\\<英現所属>}
\author{情報 太郎}{T<NAME>}
{<所属ラベル>}[E-mail]
\author{処理 花子}{<NAME>}
{<所属ラベル2,現所属ラベル3>}
\begin{abstract}
<概要(和文)>
\end{abstract}
\begin{eabstract}
<概要(英文)>
\end{eabstract}
\maketitle
\section{`第1節の表題`}
……………
<本文>
……………
謝辞がある場合は
\begin{acknowledgment}
\end{acknowledgment}
\begin{thebibliography}{99}%9 or 99
\bibitem{1}
\bibitem{2}
\end{thebibliography}
付録がある場合は
\appendix
\section{`付録1節の表題`}
\end{document}
```
#v(2em)
== 表題・著者名等
<表題著者名等>
表題,著者名とその所属,および概要を前述のコマンドや環境により#strong[和文と
英文の双方について];定義した後,`\maketitle` によって出力する.
=== 表題
<表題>
表題は,`\title` および `\etitle` で定義した表題はセンタリングされる.
文字数の多いものについては,適宜 `\\` を挿入して改行する.
=== 著者名・所属
<著者名所属>
各著者の所属を第一著者から順に `\affiliate`
を用いてラベル(第1引数)を付けながら定義すると,
脚注に番号を付けて所属が出力される.
なお,複数の著者が同じ所属である場合には, 一度定義するだけで良い.
現在の所属は `\paffiliate` を用い,同様にラベル,所属先を記述する.
所属先には自動で「現在」, `\\`の改行で「Presently with」が挿入される.
著者名は `\author` で定義する.各著者名の直後に,英文著者名,
所属ラベルとメールアドレスを記入する. 著者が複数の場合は `\author`
を繰り返すことで, 2人,3人,…と増えていく.
現在の所属や,複数の所属先を追加する場合には,所属ラベルをカンマで区切り,追加すればよい.
また,メールアドレス部分は省略が可能である.
=== 概要
<概要>
和文の概要は `abstract` 環境の中に, 英文の概要は `eabstract`
環境の中に,それぞれ記述する.
== 本文
<本文>
=== 見出し
<見出し>
節や小節の見出しには `\section`, `\subsection`, `\subsubsection`,
`\paragraph` といったコマンドを使用する.
「定義」,「定理」などについては,`\newtheorem`で適宜環境を宣言し,そ
の環境を用いて記述する.
=== 行送り
<行送り>
2段組を採用しており,左右の段で行の基準線の位置が一致することを原則としている.
また,節見出しなど,
行の間隔を他よりたくさんとった方が読みやすい場所では,
この原則を守るようにスタイルファイルが自動的にスペースを挿入する.
したがって本文中では `\vspace` や `\vskip`
を用いたスペースの調整を行なわないようにすること.
=== フォントサイズ
<フォントサイズ>
フォントサイズは,スタイルファイルによって自動的に設定されるため,
基本的には著者が自分でフォントサイズを変更する必要はない.
=== 句読点
<句読点>
句点には全角の「.」, 読点には全角の「,」を用いる.
ただし英文中や数式中で「.」や「,」を使う場合には,
半角文字を使う.「。」や「、」は使わない.
=== 全角文字と半角文字
<全角文字と半角文字>
全角文字と半角文字の両方にある文字は次のように使い分ける.
+ 括弧は全角の「(」と「)」を用いる.但し,英文の概要,図表見出し,
書誌データでは半角の「\(」と「)」を用いる.
+ 英数字,空白,記号類は半角文字を用いる.ただし,句読点に関しては,
前項で述べたような例外がある.
+ カタカナは全角文字を用いる.
+ 引用符では開きと閉じを区別する. 開きには #raw("``")
を用い,閉じには`''` を用いる.
=== 箇条書
<箇条書>
箇条書に関する形式を特に定めていない.場合に応じて標準的な `enumerate`,
`itemize`, `description` の環境を用いてよい.
=== 脚注
<脚注>
脚注は `\footnote` コマンドを使って書くと,
ページ単位に#footnote[脚注の例.];や#footnote[二つめの脚注.];のような参照記号とともに脚注が生成される.
なお,ページ内に複数の脚注がある場合,参照記号はLaTeXを2回実行しないと正しくならないことに注意されたい.
また場合によっては,
脚注をつけた位置と脚注本体とを別の段に置く方がよいこともある.
この場合には,`\footnotemark` コマンドや `\footnotetext`
コマンドを使って対処していただきたい.
なお,脚注番号は論文内で通し番号で出力される.
=== OverfullとUnderfull
<overfullとunderfull>
組版時にはoverfullを起こさないことを原則としている.
従って,まず提出するソースが著者の環境でoverfullを起こさないように,
文章を工夫するなどの最善の努力を払っていただきたい. 但し,`flushleft`
環境,`\\`,`\linebreak`
などによる両端揃えをしない形でのoverfullの回避は,
できるだけ避けていただきたい.
また著者の執筆時点では発生しないoverfullが,
組版時の環境では発生することもある.
このような事態をできるだけ回避するために, 文中の長い数式や `\verb`
を避ける, パラグラフの先頭付近では長い英単語を使用しない,
などの注意を払うようにして頂きたい.
== 数式
<sec:Item>
=== 本文中の数式
<本文中の数式>
本文中の数式は `$` と `$`, `\(` と `\)`, あるいは `math` 環境のいず
れで囲んでもよい.
=== 別組の数式
<別組の数式>
別組数式\(displayed math)については `$$` と `$$` は使用せずに, `\[` と
`\]` で囲むか, `displaymath`, `equation`, `eqnarray`
のいずれかの環境を用いる. これらは
$ Delta_l = sum_(i = l \| 1)^L delta_(p i) $
のように,センタリングではなく固定字下げで数式を出力し,
かつ背が高い数式による行送りの乱れを吸収する機能がある.
#place(top + center, float: true, figure(
[
// #show raw: set block(stroke: 0.5pt + black, inset: 0.5em)
```
\begin{figure}[tb]
<図本体の指定>
\caption{<和文見出し>}
\ecaption{<英文見出し>}
\label{ . . . }
\end{figure}
```
],
caption: [
1段幅の図\
*Fig. 1* Single column figure with caption \
explicitly broken by \\\\.
],
supplement: "図"
))
=== eqnarray環境
<eqnarray環境>
互いに関連する別組の数式が2行以上連続して現れる場合には, 単に`\[` と
`\]`, あるいは `\begin{equation}` と`\end{equation}`
で囲った数式を書き並べるのではなく, `\begin``{eqnarray}` と
`\end{eqnarray}` を使って,
等号(あるいは不等号)の位置で縦揃えを行なった方が読みやすい.
=== 数式のフォント
<数式のフォント>
LaTeXが標準的にサポートしているもの以外の特殊な数式用フォントは,
できるだけ使わないようにされたい.
どうしても使用しなければならない場合には, その旨申し出て頂くとともに,
組版工程に深く関与して頂くこともあることに留意されたい.
== 図
<図>
1段の幅におさまる図は, の形式で指定する. 位置の指定に `h` は使わない.
また,図の下に和文と英文の双方の見出しを, `\caption` と `\ecaption`
で指定する.
文字数が多い見出しはは自動的に改行して最大幅の行を基準にセンタリングするが,
見出しが2行になる場合には適宜 `\\`
を挿入して改行したほうが良い結果となることがしばしばある (
の英文見出しを参照). 図の参照は `\figref{<`ラベル`>}` を用いて行なう.
また紙面スペースの節約のために, 1つの `figure`(または
`table`)環境の中に複数の図表を並べて表示したい場合には, と
のように個々の図表と各々の `\caption`/`\ecaption` を `minipage`
環境に入れることで実現できる. なお図と表が混在する場合, `minipage`
環境の中で`\CaptionType{figure}` あるいは `\CaptionType` `{table}`
を指定すれば, 外側の環境が `figure` であっても `table`
であっても指定された見出しが得られる.
2段の幅にまたがる図は, の形式で指定する. 位置の指定は `t`
しか使えない.
図の中身では本文と違い,
どのような大きさのフォントを使用しても構わない( 参照).
また図の中身として,encapsulate
されたPostScriptファイル(いわゆるEPSファイル)を読み込むこともできる.読み込みのため
], (
type: "figure",
value: [
#place(top + center, float: true)[
#set block(
width: 100%,
)
#show par: it => align(center, it)
// #show raw: it => align(center, it)
#figure(
```
\begin{figure*}[t]
<図本体の指定>
\caption{<和文見出し>}
\ecaption{<英文見出し>}
\label{~$dots.h$~}
\end{figure*}
```,
caption: [2 段幅の図\ *Fig. 3* Double column figure.]
)
<fig:double>
]
]
),
[
#place(left + top, float: true,
[
#grid(
columns: 2,
gutter: 1em,
[
#figure(
```
\begin{minipage}[t]%
{0.5\columnwidth}
\CaptionType{table}
\caption{…}
\ecaption{…}
\label{…}
\makebox[\textwidth][c]{%
\begin{tabular}[t]{lcr}
\hline\hline
left¢er&right\\\hline
L1&C1&R1\\
L2&C2&R2\\\hline
\end{tabular}}
\end{minipage}
```,
caption: [
表1の中身
],
supplement: [図]
)<fig:left>
],
figure(
[
#table(
columns: 3,
rows: (1.65em, auto, auto),
auto-vlines: false,
header-rows: 2,
align: center + horizon,
// align: center + horizon,
"left", "center", "right",
"L1", "C1", "R1",
"L2", "C2", "R2"
) <tab:right>
],
caption: [
@fig:left で作成した表
*Table 1* A table built by
Fig. 2
],
supplement: [表]
)
)
],
)
#figure(
[
#table(
columns: 4,
rows: (1.65em, auto, auto, auto),
header-rows: 1,
header-columns: 1,
inset: (left: 0.75em, right: 0.75em, top: 0.5em, bottom: 0.5em),
align: left + horizon,
// align: center + horizon,
[], [column1], [column2], [column3],
[row1], [item 1,1], [item 2,1], [---],
[row2], [---], [item 2,2], [item 3,2],
[row3], [item 1,3], [item 2,3], [item 3,3],
[row4], [item 1,4], [item 2,4], [item 3,4]
) <tab:right>
],
caption: [
表の例 \
*Table 2* An Example of Table.
],
supplement: [表]
)
には,プリアンブルで
#quote(block: true)[
`\usepackage{graphicx}`
]
を行った上で, `\includegraphics` コマンドを図を埋め込む箇所に置き,
その引数にファイル名(など)を指定する.
== 表
<表>
表の罫線はなるべく少なくするのが,仕上がりをすっきりさせるコツである.
罫線をつける場合には,
一番上の罫線には二重線を使い,左右の端には縦の罫線をつけない ().
表中のフォントサイズのデフォルトは`\footnotesize`である.
また,表の上に和文と英文の双方の見出しを, `\caption`と `\ecaption`
で指定する. 表の参照は `\tabref{<`ラベル`>}` を用いて行なう.
<tab:example> to
== 参考文献・謝辞
<参考文献謝辞>
=== 参考文献の参照
<参考文献の参照>
本文中で参考文献を参照する場合には`\cite`を使用する.
参照されたラベルは自動的にソートされ, `[]`でそれぞれ区切られる.
#quote(block: true)[
文献 `\cite{companion,okumura}` はLaTeXの総合的な解説書である.
]
と書くと;
#quote(block: true)[
文献#cite(<okumura>);#cite(<companion>);はLaTeXの総合的な解説書である.
]
が得られる.
=== 参考文献リスト
<参考文献リスト>
参考文献リストには, 原則として本文中で引用した文献のみを列挙する.
順序は参照順あるいは第一著者の苗字のアルファベット順とする.
文献リストはBiBTeXと`ipsjunsrt.bst`(参照順)
または`ipsjsort.bst`(アルファベット順)を用いて作り,
`\bibliograhpystyle`と`\bibliography`コマンドにより
利用することが出来る. これらを用いれば,
規定の体裁にあったものができるので, できるだけ利用していただきたい.
また製版用のファイル群には`.bib`ファイルではなく`.bbl`ファイルを
必ず含めることに注意されたい.
一方,何らかの理由でthebibliography環境で文献リストを
「手作り」しなければならない場合は,
このガイドの参考文献リストを注意深く見て,
そのスタイルにしたがっていただきたい.
=== 謝辞
<謝辞>
謝辞がある場合には, 参考文献リストの直前に置き,
`acknowledgment`環境の中に入れる.
= 論文内容に関する指針
<論文内容に関する指針>
論文の内容について,
論文誌ジャーナル編集委員会で作成した「べからず集」を以下に示す.
投稿前のチェックリストとして利用頂きたい. これ以外にも,査読者用,
メタ査読者用の「べからず集」#cite(<webpage2>);も公開しているので,
参照されたい. また,作文技術に関する@book1;@book2;@book3;@book4;のような書籍も参考になる.
== 書き方の基本
<書き方の基本>
- 研究の新規性,有用性,信頼性が読者に伝わるように記述する.
- 読み手に,読みやすい文章を心がける(内容が前後する,背景・
課題の設定が不明瞭などは読者にとって負担).
- 解決すべき問題が汎用化(一般的に記述)されていないのは再
考を要する(XX大学の問題という記述に終始).あるいは,
(単に「作りました」だけで)解決すべき問題そのものの記述
がないのは再考を要する.
- 結論が明確に記されていない,または,範囲,限界,問題点な
どの指摘が適切ではない,または,結論が内容にそったもので
はないものは再考を要する.
- 科学技術論文として不適当な表現や,分かりにくい表現がある
のは再考を要する.
- 極端な口語体や,長文の連続などは再考を要する.
- 章,節のたて方,全体の構成等が適切でない文章は再考を要す る.
- 文中の文脈から推測しないと内容の把握が困難な論文にしない.
- 説明に飛躍した点があり,仮説等の説明が十分ではないのは再 考を要する.
- 説明に冗長な点,逆に簡単すぎる点があるのは再考を要する.
- 未定義語を減らす.
== 新規性と有効性を明確に示す
<新規性と有効性を明確に示す>
- 在来研究との関連,研究の動機,ねらい等が明確に説明されて
いないのは再考を要する.
- 既知/公知の技術が何であって,何を新しいアイデアとして提
案しているのかが書かれていないのは再考を要する.
- 十分な参考文献は新規性の主張に欠かせない.
- 提案内容の説明が,概念的または抽象的な水準に終始していて,
読者が提案内容を理解できない(それだけで新規性が感じられ
ないもの)のは再考を要する.
- 論文で提案した方法の有効性の主張がない,またはきわめて貧
弱なのは再考を要する.
== 書き方に関する具体的な注意
<書き方に関する具体的な注意>
- 和文標題が内容を適切に表現していないのは再考を要する.
- 英文標題が内容を適切に表現していない,または英語として適
切でないのは再考を要する.
- アブストラクトが主旨を適切に表現していない,または英文が
適切ではないのは再考を要する.
- 記号・略号等が周知のものでなく,または,用語が適切でなく,
または,図・表の説明が適当ではないのは再考を要する.
- 個人的あるいは非常に小さなグループ/企業だけで通用するよ
うな用語が特別な説明もなしに多用されているのは再考を要す る.
- 図表自体は十分に明確ではない,または誤りがあるのは再考を 要する.
- 図表が鮮明ではないのは再考を要する.
- 図表が大きさ,縮尺の指定が適切でないのは再考を要する.
== 参考文献
<参考文献>
- 参考文献は10件以上必要(分野によっては20件以上,30件以上
という意見もある).
- 十分な参考文献は新規性の主張に欠かせない.
- 適切な文献が引用されておらず,その数も適切ではないのは再 考を要する.
- 日本人によるしかるべき論文を引用することで日本人研究コミュ
ニティの発展につながる.
- 参考文献は自分のものばかりではだめ.
== 二重投稿
<二重投稿>
- 二重投稿はしてはならない ─ ただし国際会議に採択された論
文を著作権が問題にならないように投稿することは構わない.
- 他の論文とまったく同じ図表を引用の明示なしに利用すること は禁止.
- 既発表の論文等との間に重複があるのは再考を要する.
== 他の人に読んでもらう
<他の人に読んでもらう>
- 投稿経験が少ない人は,採録された経験の豊富な人に校正して もらう.
- 読者の立場から見て論理的な飛躍がないかに注意して記述する.
== その他
<その他>
- 投稿前にチェックリストの各項目を満たしているか,必ず確認 する.
= おわりに
<おわりに>
本稿では,A4縦型2段組み用に変更したスタイルファイルを用いた論文のフォー
マット方法と,論文誌ジャーナル編集委員会がまとめた「べからず集」に基づく
論文の書き方を示した.内容的にまだ不十分の部分が多いため,意見,要望等を
#quote(block: true)[
`<EMAIL>`
]
までお寄せ頂きたい.
#acknowledgement[
A4横型に対するガイドを基に,本稿を作成した.
クラスファイルの作成においては,
京都大学の中島 浩氏にさまざまなご教示を頂き,
さらにBiBTeX関連ファイルの利用についても快諾頂いたことを深謝する.
また,A4横型に対するガイドを作成された当時の編集委員会の担当者に深謝する.
]
#bibliography("citation.yml", title: "参考文献", full: true, style: "./ipsj.csl")
#fake-bibliography(yaml("citation.yml"))
]
) |
|
https://github.com/chubetho/Bachelor_Thesis | https://raw.githubusercontent.com/chubetho/Bachelor_Thesis/main/templates/glossary.typ | typst | #import "../utils/glossarium.typ": print-glossary
// #import "@preview/glossarium:0.4.1": print-glossary
#heading("Glossary", numbering: none, outlined: true)
#print-glossary((
(
key: "html",
short: "HTML",
long: "HyperText Markup Language",
),
(
key: "spa",
short: "SPA",
long: "Single-Page Application",
),
(
key: "seo",
short: "SEO",
plural: "SEOs",
long: "Search Engine Optimization",
),
(
key: "dklb",
short: "DKLB",
long: "Deutsche Klassenlotterie Berlin",
),
(
key: "ddd",
short: "DDD",
long: "Domain-Driven Design",
),
(
key: "ui",
short: "UI",
long: "User Interface",
),
(
key: "ux",
short: "UX",
long: "User Experience",
),
(
key: "css",
short: "CSS",
long: "Cascading Style Sheets",
),
(
key: "cors",
short: "CORS",
long: "Cross-origin resource sharing",
),
(
key: "cdn",
short: "CDN",
long: "Content Delivery Network",
),
(
key: "ssi",
short: "SSI",
long: "Server-Side Includes",
),
(
key: "esi",
short: "ESI",
long: "Edge-Side Includes",
),
(
key: "dom",
short: "DOM",
long: "Document Object Model",
),
(
key: "ci",
short: "CI",
long: "Continous Integration",
),
(
key: "cd",
short: "CD",
long: "Continous Deployment",
),
))
#pagebreak(weak: true) |
|
https://github.com/Relacibo/typst-as-lib | https://raw.githubusercontent.com/Relacibo/typst-as-lib/main/examples/templates/template.typ | typst | MIT License | #import sys: inputs
#set page(paper: "a4")
#set text(font: "TeX Gyre Cursor", 11pt)
#let content = inputs.v
#let last_index = content.len() - 1
#for (i, elem) in content.enumerate() [
== #elem.heading
Text: #elem.text \
Num1: #elem.num1 \
Num2: #elem.num2 \
#if elem.image != none [#image.decode(elem.image, height: 40pt)]
#if i < last_index [
#pagebreak()
]
]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/fletcher/0.4.4/src/main.typ | typst | Apache License 2.0 | #import "utils.typ": *
#import "coords.typ": *
#import "layout.typ": *
#import "draw.typ": *
#import "edge.typ": *
/// Draw a labelled node in a diagram which can connect to edges.
///
/// - pos (coordinate): Dimensionless "elastic coordinates" `(x, y)` of the
/// node.
///
/// See the options of `diagram()` to control the physical scale of elastic
/// coordinates.
///
/// - name (label, none): An optional name to give the node.
///
/// Names can sometimes be used in place of coordinates. For example:
///
/// #example(```
/// fletcher.diagram(
/// node((0,0), $A$, name: <A>),
/// node((1,0.6), $B$, name: <B>),
/// edge(<A>, <B>, "->"),
/// )
/// ```)
///
/// Note that you can also just use variables to refer to coordinates:
///
/// #example(```
/// fletcher.diagram({
/// let A = (0,0)
/// let B = (1,0.6)
/// node(A, $A$)
/// node(B, $B$)
/// edge(A, B, "->")
/// })
/// ```)
///
/// - label (content): Content to display inside the node.
///
/// If a node is larger than its label, you can wrap the label in `align()` to
/// control the label alignment within the node.
///
/// #example(```typc
/// diagram(
/// node((0,0), align(bottom + left)[¡Hola!],
/// width: 3cm, height: 2cm, fill: yellow),
/// )
/// ```)
///
/// - inset (length, auto): Padding between the node's content and its outline.
///
/// In debug mode, the inset is visualised by a thin green outline.
///
/// #example(```
/// diagram(
/// debug: 3,
/// node-stroke: 1pt,
/// node((0,0), [Hello,]),
/// edge(),
/// node((1,0), [World!], inset: 10pt),
/// )
/// ```)
///
/// - outset (length, auto): Margin between the node's bounds to the anchor
/// points for connecting edges.
///
/// This does not affect node layout, only how closely edges connect to the
/// node.
///
/// In debug mode, the outset is visualised by a thin green outline.
///
/// #example(```
/// diagram(
/// debug: 3,
/// node-stroke: 1pt,
/// node((0,0), [Hello,]),
/// edge(),
/// node((1,0), [World!], outset: 10pt),
/// )
/// ```)
///
/// - width (length, auto): Width of the node. If `auto`, the node's width is
/// the width of the node #param[node][label], plus twice the
/// #param[node][inset].
///
/// If the width is not `auto`, you can use `align` to control the placement of the node's #param[node][label].
///
/// - height (length, auto): Height of the node. If `auto`, the node's height is the height of the node #param[node][label], plus twice the #param[node][inset].
///
/// If the height is not `auto`, you can use `align` to control the placement of the node's #param[node][label].
///
/// - enclose (array): Positions or names of other nodes to enclose by enlarging
/// this node.
///
/// If given, causes the node to resize so that its bounding rectangle
/// surrounds the given nodes. The center #param[node][pos] does not affect
/// the node's position if `enclose` is given, but still affects connecting
/// edges.
///
/// #box(example(```
/// diagram(
/// node-stroke: 1pt,
/// node((0,0), [ABC], name: <A>),
/// node((1,1), [XYZ], name: <Z>),
/// node(
/// text(teal)[Node group], stroke: teal,
/// enclose: (<A>, <Z>), name: <group>),
/// edge(<group>, (3,0.5), stroke: teal),
/// )
/// ```))
///
/// - shape (rect, circle, function, auto): Shape to draw for the node. If
/// `auto`, one of `rect` or `circle` is chosen depending on the aspect ratio
/// of the node's label.
///
/// Some other shape functions are provided in the `fletcher.shapes`
/// submodule, including
/// #{
/// dictionary(fletcher.shapes).keys()
/// .filter(i => i not in ("cetz", "draw", "vector"))
/// .map(i => [- #raw(i)]).join()
/// }
///
/// Custom shapes should be specified as a function `(node, extrude) => (..)`
/// returning `cetz` objects.
/// - The `node` argument is a dictionary containing the node's attributes,
/// including its dimensions (`node.size`), and other options (such as
/// `node.corner-radius`).
/// - The `extrude` argument is a length which the shape outline should be
/// extruded outwards by. This serves two functions: to support automatic
/// edge anchoring with a non-zero node `outset`, and to create multi-stroke
/// effects using the `extrude` node option.
/// See the ```plain src/shapes.typ``` source file for examples.
///
/// - stroke (stroke): Stroke style for the node outline.
///
/// Defaults to #the-param[diagram][node-stroke].
///
/// - fill (paint): Fill style of the node. The fill is drawn within the node
/// outline as defined by the first #param(full: false)[node][extrude] value.
///
/// Defaults to #the-param[diagram][node-fill].
///
/// - defocus (number): Strength of the "defocus" adjustment for connectors
/// incident with this node.
///
/// This affects how connectors attach to non-square nodes. If `0`, the
/// adjustment is disabled and connectors are always directed at the node's
/// exact center.
///
/// #stack(
/// dir: ltr,
/// spacing: 1fr,
/// ..(0.2, 0, -1).enumerate().map(((i, defocus)) => {
/// fletcher.diagram(spacing: 8mm, {
/// node((i, 0), raw("defocus: "+str(defocus)), stroke: black, defocus: defocus)
/// for y in (-1, +1) {
/// edge((i - 1, y), (i, 0))
/// edge((i, y), (i, 0))
/// edge((i + 1, y), (i, 0))
/// }
/// })
/// })
/// )
///
/// Defaults to #the-param[diagram][node-defocus].
///
/// - extrude (array): Draw strokes around the node at the given offsets to
/// obtain a multi-stroke effect. Offsets may be numbers (specifying multiples
/// of the stroke's thickness) or lengths.
///
/// The node's fill is drawn within the boundary defined by the first offset in
/// the array.
///
/// #diagram(
/// node-stroke: 1pt,
/// node-fill: red.lighten(70%),
/// node((0,0), `(0,)`),
/// node((1,0), `(0, 2)`, extrude: (0, 2)),
/// node((2,0), `(2, 0)`, extrude: (2, 0)),
/// node((3,0), `(0, -2.5, 2mm)`, extrude: (0, -2.5, 2mm)),
/// )
///
/// See also #the-param[edge][extrude].
///
/// - corner-radius (length): Radius of rounded corners, if supported by the
/// node #param[node][shape].
///
/// Defaults to #the-param[diagram][node-corner-radius].
///
/// - layer (number, auto): Layer on which to draw the node.
///
/// Objects on a higher `layer` are drawn on top of objects on a lower
/// `layer`. Objects on the same layer are drawn in the order they are passed
/// to `diagram()`.
///
/// By default, nodes are drawn on layer `0` unless they #param[node][enclose]
/// points, in which case `layer` defaults to `-1`.
///
/// - post (function): Callback function to intercept `cetz` objects before they
/// are drawn to the canvas.
///
/// This can be used to hide elements without affecting layout (for use with
/// #link("https://github.com/touying-typ/touying")[Touying], for example).
/// The `hide()` function also helps for this purpose.
///
#let node(
..args,
pos: auto,
name: none,
label: none,
inset: auto,
outset: auto,
fill: auto,
stroke: auto,
extrude: (0,),
width: auto,
height: auto,
radius: auto,
enclose: (),
corner-radius: auto,
shape: auto,
defocus: auto,
layer: auto,
post: x => x,
) = {
if args.named().len() > 0 { panic("Unexpected named argument(s):", args) }
if args.pos().len() > 2 { panic("Unexpected positional argument(s):", args.pos().slice(2)) }
// interpret first two positional arguments
if args.pos().len() == 2 {
(pos, label) = args.pos()
} else if args.pos().len() == 1 {
let arg = args.pos().at(0)
if type(arg) == array {
pos = arg
label = none
} else {
pos = auto
label = arg
}
}
let extrude = as-array(extrude).map(as-number-or-length.with(
message: "`extrude` must be a number, length, or an array of those"
))
metadata((
class: "node",
pos: pos,
name: pass-none(as-label)(name),
label: label,
inset: inset,
outset: outset,
enclose: as-array(enclose),
size: (width, height),
radius: radius,
shape: shape,
stroke: stroke,
fill: fill,
corner-radius: corner-radius,
defocus: defocus,
extrude: extrude,
layer: layer,
post: post,
))
}
#let resolve-node-options(node, options) = {
let to-pt(len) = to-abs-length(as-length(len), options.em-size)
node.stroke = map-auto(node.stroke, options.node-stroke)
if node.stroke != none {
let base-stroke = pass-none(stroke-to-dict)(options.node-stroke)
node.stroke = base-stroke + stroke-to-dict(node.stroke)
}
node.stroke = pass-none(stroke)(node.stroke) // guarantee stroke or none
node.fill = map-auto(node.fill, options.node-fill)
node.corner-radius = map-auto(node.corner-radius, options.node-corner-radius)
node.inset = to-pt(map-auto(node.inset, options.node-inset))
node.outset = to-pt(map-auto(node.outset, options.node-outset))
node.defocus = map-auto(node.defocus, options.node-defocus)
node.size = node.size.map(pass-auto(to-pt))
node.radius = pass-auto(to-pt)(node.radius)
if node.shape == auto {
if node.radius != auto { node.shape = "circle" }
if node.size != (auto, auto) { node.shape = "rect" }
}
let thickness = if node.stroke == none { 1pt } else {
map-auto(node.stroke.thickness, 1pt)
}
node.extrude = node.extrude.map(d => {
if type(d) == length { d }
else { d*thickness }
}).map(to-pt)
if type(node.outset) in (int, float) {
node.outset *= thickness
}
let default-layer = if node.enclose.len() > 0 { -1 } else { 0 }
node.layer = map-auto(node.layer, default-layer)
node
}
#let extract-nodes-and-edges-from-equation(eq) = {
assert(eq.func() == math.equation)
let terms = eq.body + []
let edges = ()
let nodes = ()
// convert math matrix into array-of-arrays matrix
let matrix = ((none,),)
let (x, y) = (0, 0)
for child in terms.children {
if child.func() == metadata {
if child.value.class == "edge" {
let edge = child.value
edge.vertices.at(0) = map-auto(edge.vertices.at(0), (x, y))
if edge.label != none { edge.label = $edge.label$ } // why is this needed?
edges.push(edge)
} else if child.value.class == "node" {
let node = child.value
node.pos = (x, y)
nodes.push(node)
}
} else if repr(child.func()) == "linebreak" {
y += 1
x = 0
matrix.push((none,))
} else if repr(child.func()) == "align-point" {
x += 1
matrix.at(-1).push(none)
} else {
matrix.at(-1).at(-1) += child
}
}
// turn matrix into an array of nodes
for (y, row) in matrix.enumerate() {
for (x, item) in row.enumerate() {
if not is-space(item) {
nodes.push(node((x, y), $item$).value)
}
}
}
(
nodes: nodes,
edges: edges,
)
}
#let interpret-diagram-args(args) = {
if args.named().len() > 0 {
let args = args.named().keys().join(", ")
panic("Unexpected named argument(s) to `diagram()`: " + args)
}
let positional-args = args.pos().flatten().join() + [] // join to ensure sequence
let objects = positional-args.children
let nodes = ()
let edges = ()
let prev-coord = (0,0)
let should-set-prev-edge-end-point = false
for obj in objects {
if obj.func() == metadata {
if obj.value.class == "node" {
let node = obj.value
nodes.push(node)
prev-coord = node.pos
if should-set-prev-edge-end-point {
// the `to` point of the previous edge is waiting to be set
edges.at(-1).vertices.at(-1) = node.pos
should-set-prev-edge-end-point = false
}
} else if obj.value.class == "edge" {
let edge = obj.value
if edge.vertices.at(0) == auto {
edge.vertices.at(0) = prev-coord
}
if edge.vertices.at(-1) == auto {
// if edge's end point isn't set, defer it until the next node is seen.
// currently, this is only allowed for one edge at a time.
if should-set-prev-edge-end-point { panic("Cannot infer edge end point. Please specify explicitly.") }
should-set-prev-edge-end-point = true
}
edges.push(edge)
}
} else if obj.func() == math.equation {
let result = extract-nodes-and-edges-from-equation(obj)
nodes += result.nodes
edges += result.edges
} else {
panic("Unrecognised value passed to diagram:", obj)
}
}
edges = edges.map(edge => {
if edge.vertices.at(-1) == auto {
edge.vertices.at(-1) = vector.add(edge.vertices.at(-2), (1,0))
}
edge
})
// allow nodes which enclose other nodes to have pos: auto
nodes = nodes.map(node => {
if node.enclose.len() > 0 and node.pos == auto {
let enclosed-centers = node.enclose
.map(resolve-label-coordinate.with(nodes))
node.pos = bounding-rect(enclosed-centers).center
}
node
})
for node in nodes {
assert(type(node.pos) == array, message: "Invalid position `pos` in node: " + repr(node))
}
(
nodes: nodes,
edges: edges,
)
}
/// Draw a diagram containing `node()`s and `edge()`s.
///
/// - ..args (array): Content to draw in the diagram, including nodes and edges.
///
/// The results of `node()` and `edge()` can be _joined_, meaning you can
/// specify them as separate arguments, or in a block:
///
/// ```typ
/// #diagram(
/// // one object per argument
/// node((0, 0), $A$),
/// node((1, 0), $B$),
/// {
/// // multiple objects in a block
/// // can use scripting, loops, etc
/// node((2, 0), $C$)
/// node((3, 0), $D$)
/// },
/// for x in range(4) { node((x, 1) [#x]) },
/// )
/// ```
///
/// Nodes and edges can also be specified in math-mode.
///
/// ```typ
/// #diagram($
/// A & B \ // two nodes at (0,0) and (1,0)
/// C edge(->) & D \ // an edge from (0,1) to (1,1)
/// node(sqrt(pi), stroke: #1pt) // a node with options
/// $)
/// ```
///
/// - debug (bool, 1, 2, 3): Level of detail for drawing debug information.
/// Level `1` or `true` shows a coordinate grid; higher levels show bounding boxes and
/// anchors, etc.
///
/// - spacing (length, pair of lengths): Gaps between rows and columns. Ensures
/// that nodes at adjacent grid points are at least this far apart (measured as
/// the space between their bounding boxes).
///
/// Separate horizontal/vertical gutters can be specified with `(x, y)`. A
/// single length `d` is short for `(d, d)`.
///
/// - cell-size (length, pair of lengths): Minimum size of all rows and columns.
/// A single length `d` is short for `(d, d)`.
///
/// - node-inset (length, pair of lengths): Default value of
/// #the-param[node][inset].
///
/// - node-outset (length, pair of lengths): Default value of
/// #the-param[node][outset].
///
/// - node-stroke (stroke, none): Default value of #the-param[node][stroke].
///
/// The default stroke is folded with the stroke specified for the node. For
/// example, if `node-stroke` is `1pt` and #the-param[node][stroke] is `red`,
/// then the resulting stroke is `1pt + red`.
///
/// - node-fill (paint): Default value of #the-param[node][fill].
///
/// - edge-stroke (stroke): Default value of #the-param[edge][stroke]. By
/// default, this is chosen to match the thickness of mathematical arrows such
/// as $A -> B$ in the current font size.
///
/// The default stroke is folded with the stroke specified for the edge. For
/// example, if `edge-stroke` is `1pt` and #the-param[edge][stroke] is `red`,
/// then the resulting stroke is `1pt + red`.
///
/// - node-corner-radius (length, none): Default value of
/// #the-param[node][corner-radius].
///
/// - edge-corner-radius (length, none): Default value of
/// #the-param[edge][corner-radius].
///
/// - node-defocus (number): Default value of #the-param[node][defocus].
///
/// - label-sep (length): Default value of #the-param[edge][label-sep].
/// - mark-scale (percent): Default value of #the-param[edge][mark-scale].
/// - crossing-fill (paint): Color to use behind connectors or labels to give
/// the illusion of crossing over other objects. See
/// #the-param[edge][crossing-fill].
///
/// - crossing-thickness (number): Default thickness of the occlusion made by
/// crossing connectors. See #param[edge][crossing-thickness].
///
/// - axes (pair of directions): The orientation of the diagram's axes.
///
/// This defines the elastic coordinate system used by nodes and edges. To make
/// the $y$ coordinate increase up the page, use `(ltr, btt)`. For the matrix
/// convention `(row, column)`, use `(ttb, ltr)`.
///
/// #stack(
/// dir: ltr,
/// spacing: 1fr,
/// fletcher.diagram(
/// axes: (ltr, ttb),
/// debug: 1,
/// node((0,0), $(0,0)$),
/// edge((0,0), (1,0), "->"),
/// node((1,0), $(1,0)$),
/// node((1,1), $(1,1)$),
/// node((0.5,0.5), `axes: (ltr, ttb)`),
/// ),
/// fletcher.diagram(
/// axes: (ltr, btt),
/// debug: 1,
/// node((0,0), $(0,0)$),
/// edge((0,0), (1,0), "->"),
/// node((1,0), $(1,0)$),
/// node((1,1), $(1,1)$),
/// node((0.5,0.5), `axes: (ltr, btt)`),
/// ),
/// fletcher.diagram(
/// axes: (ttb, ltr),
/// debug: 1,
/// node((0,0), $(0,0)$),
/// edge((0,0), (1,0), "->", bend: -20deg),
/// node((1,0), $(1,0)$),
/// node((1,1), $(1,1)$),
/// node((0.5,0.5), `axes: (ttb, ltr)`),
/// ),
/// )
///
/// - render (function): After the node sizes and grid layout have been
/// determined, the `render` function is called with the following arguments:
/// - `grid`: a dictionary of the row and column widths and positions;
/// - `nodes`: an array of nodes (dictionaries) with computed attributes
/// (including size and physical coordinates);
/// - `edges`: an array of connectors (dictionaries) in the diagram; and
/// - `options`: other diagram attributes.
///
/// This callback is exposed so you can access the above data and draw things
/// directly with CeTZ.
#let diagram(
..args,
debug: false,
axes: (ltr, ttb),
spacing: 3em,
cell-size: 0pt,
edge-stroke: 0.048em,
node-stroke: none,
edge-corner-radius: 2.5pt,
node-corner-radius: none,
node-inset: 6pt,
node-outset: 0pt,
node-fill: none,
node-defocus: 0.2,
label-sep: 0.2em,
mark-scale: 100%,
crossing-fill: white,
crossing-thickness: 5,
render: (grid, nodes, edges, options) => {
cetz.canvas(draw-diagram(grid, nodes, edges, debug: options.debug))
},
) = {
let spacing = as-pair(spacing)
let cell-size = as-pair(cell-size)
// if type(spacing) != array { spacing = (spacing, spacing) }
// if type(cell-size) != array { cell-size = (cell-size, cell-size) }
let options = (
debug: int(debug),
axes: axes,
spacing: spacing,
cell-size: cell-size,
node-inset: node-inset,
node-outset: node-outset,
node-stroke: node-stroke,
node-fill: node-fill,
node-corner-radius: node-corner-radius,
edge-corner-radius: edge-corner-radius,
node-defocus: node-defocus,
label-sep: label-sep,
edge-stroke: as-stroke(edge-stroke),
mark-scale: mark-scale,
crossing-fill: crossing-fill,
crossing-thickness: crossing-thickness,
)
let (nodes, edges) = interpret-diagram-args(args)
box(style(styles => {
let options = options
options.em-size = measure(h(1em)).width
let to-pt(len) = to-abs-length(len, options.em-size)
options.spacing = options.spacing.map(to-pt)
options.cell-size = options.cell-size.map(to-pt)
// resolve options and fancy coordinates in nodes and edges
let nodes = nodes.map(node => resolve-node-options(node, options))
let edges = edges.map(edge => resolve-edge-options(edge, options))
nodes = nodes.map(node => {
node.pos = resolve-label-coordinate(nodes, node.pos)
node
})
edges = edges.map(edge => {
let first-last-labels = (0, -1).map(i => {
if type(edge.vertices.at(i)) == label { edge.vertices.at(i) }
else { auto }
})
let verts = edge.vertices.map(resolve-label-coordinate.with(nodes))
edge.vertices = resolve-relative-coordinates(verts)
let first-last-verts = (0, -1).map(i => edge.vertices.at(i))
// the first/last snap-to value should be:
// - whatever the user sets, or if auto:
// - the first/last vertex name, or if it is not a name:
// - the first/last vertex coordinate
edge.snap-to = edge.snap-to
.zip(first-last-labels, first-last-verts)
.map(((option, label, vert)) => {
map-auto(map-auto(option, label), vert)
})
edge
})
// measure node sizes and determine diagram layout
for edge in edges {
if not edge.vertices.all(i => type(i) == array) {
panic("Could not determine edge vertices, found " + repr(edge.vertices) + ".")
}
}
let nodes = compute-node-sizes(nodes, styles)
let grid = compute-grid(nodes, edges, options)
// compute final/cetz coordinates for nodes and edges
nodes = nodes.map(node => {
node.final-pos = uv-to-xy(grid, node.pos)
node
})
nodes = compute-node-enclosures(nodes, grid)
edges = edges.map(edge => {
edge.final-vertices = edge.vertices.map(uv-to-xy.with(grid))
if edge.kind == "corner" {
edge = convert-edge-corner-to-poly(edge)
}
edge = apply-edge-shift(grid, edge)
edge
})
render(grid, nodes, edges, options)
}))
}
|
https://github.com/onomou/typst-examit | https://raw.githubusercontent.com/onomou/typst-examit/main/examit.typ | typst | MIT License | #import "@preview/cetz:0.2.2"
#import "utilities.typ": *
#import "questionit.typ": parsequestion, showquestion, pointscounter
#let totalpoints = context pointscounter.final()
#let examit(
body,
title: "Default Title",
subtitle: none,
date: none,
margin: (left: 18mm, right: 25mm, top: 16mm, bottom: 25mm),
cols: 1,
gutter: 1.3em,
questions: none,
instructions: none,
extrapicturebox: true,
dropallboxes: none,
namebox: "left",
pointsplacement: "right",
answerlinelength: 4cm,
defaultpoints: none,
lang: "en",
font: "Linux Libertine",
) = {
// Set the document's basic properties.
set document(title: title)
let gradetablewidth = 16em
let tableoffset = 5mm
set page(
paper: "us-letter",
margin: margin,
numbering: "1",
number-align: center,
footer: context [
#set text(8pt)
#grid(
// stroke: black+0.2mm,
columns: (1fr, 1fr, 1fr),
// rows: (2em),
align: (center, center+horizon, right+horizon),
[],
[
Page #counter(page).display(
"1 of 1",
both: true,
)
#label("page"+str(here().page()))
// Points so far: #pointscounter.at(<page1>)
],
move(
dx: 4em, [
Points on this page: #h(1em)
#box( baseline: 0pt, stroke: black+0.2mm, outset: 6pt, [
#let prev2 = counter("pre2")
#context (pointscounter.get().first() - prev2.get().first())#prev2.update(pointscounter.get().first())
])
#h(12pt)
#box( baseline: 0pt, stroke: black+0.2mm, outset: 6pt, [#hide("123")])
]
)
),
// #totalpages.step()
],
footer-descent: 40%,
background: {
context if here().page() == 1 [
#align(
// top,
top + right,
move(
dx: -tableoffset,
dy: tableoffset,
[
#let prev = counter("pre")
#block(
// stroke: black,
width: gradetablewidth, [
#table(
columns: (auto, auto, auto),
// inset: 1em,
align: center,
stroke: black+0.2mm,
[*Page*],[*Possible*],[*Score*],
..for x in range(1, counter(page).final().first()+1) {
(
[
#x
],
[
#context (pointscounter.at(label("page"+str(x))).first() - prev.get().first())
#prev.update(pointscounter.at(label("page"+str(x))).first())
],
[]
)
},
[_Total:_],[*#pointscounter.final().first()*]
)
]
)
]
)
)
]
context if calc.odd(here().page()) == true {
if namebox == "left" {
place(
left+top,
dx: -7cm+0.5cm,
dy: 0cm+0.5cm,
rotate(
-90deg,
origin: top+right,
box(
width: 7cm, height: 1cm, stroke: black + 0.2mm, [
#text(
size: 7pt, baseline: 1cm-1em, style: "italic", [#h(3pt)Full Name]
)
]
)
)
)
} else if namebox == "top" {
place(
left+top,
dx: 0cm+0.5cm,
dy: 0cm+0.5cm,
box(
width: 7cm, height: 1cm, stroke: black + 0.2mm, [
#text(
size: 7pt, baseline: 1cm-1em, style: "italic", [#h(3pt)Full Name]
)
]
)
)
}
}
}
)
// set text(font: "Linux Libertine", lang: "en")
// set text(font: "New Computer Modern")
set text(font: font, lang: lang)
// let pagewidth = layout(x => {length(x.width)})
// Title row.
align(center)[
#block(text(weight: 700, 1.75em, title))
// = #title
#if subtitle != none [
#v(-0.3em)
#block(text(weight: 700, 1.25em, subtitle))
// == #subtitle
]
#v(1em, weak: true)
#date
]
// Main body.
// set par(justify: true)
if instructions != none {
layout(x => [#block(stroke: none, width: x.width - gradetablewidth + tableoffset +3em, [#instructions])])
}
columns(cols, gutter: gutter, {
let questioncounter = counter("question")
let subquestioncounter = counter("subquestion")
set enum(full: false, numbering: (n) => {
counter("questioncounter").update(n)
numbering("1.a.", n)
})
let defaultspacing = none
show ref: it => {
if it.element.func() == figure and it.element.supplement == [examit] {
questioncounter.at(locate(it.target)).first()
} else {
it
}
}
if questions != none [
#for question in questions [
#if question.at("spacing", default: none) != none and question.at("question", default: none) == none {
defaultspacing = question.spacing
}
#if question.at("spacing", default: none) == "reset" {
let defaultspacing = none
}
#if defaultspacing != none and question.at("spacing", default: none) == none {
question.insert("spacing",defaultspacing)
}
#if question.at("colbreak", default: false) or question.at("pagebreak", default: false) or question.at("break", default: false) {
colbreak()
}
#if question.at("header", default: none) != none {
[
= #question.header
]
}
#if question.at("subheader", default: none) != none {
[
== #question.subheader
]
}
#if question.at("subsubheader", default: none) != none {
[
=== #question.subsubheader
]
}
#if question.at("question", default: none) != none [
#questioncounter.step()
#context [
#set enum(start: int(questioncounter.get().first()))
#if question.at("unnumbered", default: false) [
#parsequestion(question, number: questioncounter.display(), dropallboxes: dropallboxes, defaultpoints: defaultpoints)
] else [
+ #parsequestion(question, number: questioncounter.display(), dropallboxes: dropallboxes, defaultpoints: defaultpoints)
#if question.at("label", default: none) != none [
#place[
#figure([], supplement: "examit")
#label(question.label)
]
]
]
]
] else if question.at("answerbox", default: none) != none [
#writingbox(height: question.answerbox)
]
#if question.at("subquestion", default: none) != none [
#subquestioncounter.update(0)
#context [
#set enum(start: int(questioncounter.get().first()), numbering: "1.a.")
#enum([
#for subquestion in question.subquestion [
#subquestioncounter.step()
#set enum(start: int(subquestioncounter.get().first()), numbering: "1.a.")
#enum([
#q(subquestion, number: subquestioncounter.display("a"), dropallboxes: dropallboxes)
])
]
])
]
]
]
]
})
if extrapicturebox {
v(1fr)
"If you have time, draw a picture here."
writingbox(height: 1in)
}
body
}
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/RM/请假申请单/请假.typ | typst | #set text(font:("Times New Roman","STSong"),size: 13pt)
// #set text(font:"SimHei")
#align(center,[= 请假申请单])
#let data=csv("./分区赛表格-分区赛信息表.csv")
#v(1.5em)
尊敬的老师:
#v(1.5em)
#h(2em)您好!哈尔滨工程大学创梦之翼战队代表哈尔滨工程大学获得了参加RoboMaster全国大
学生机甲大师超级对抗赛的资格,时间为 5 月19日 -5 月25 日(见比赛通知),(将于5月16日出发,5月26日返校,27日到校)。
#h(2em) RoboMaster 机甲大师赛事是由大疆创新(DJI)主办的全国性大学生机器人竞技赛事,是国内最具影响力的大学生机器人赛事之一,同时也是校竞赛库中的一流竞赛。
#h(2em)比赛
侧重考察参赛队员对理工学科的综合应用与工程实践能力,充分融合了“机器视觉”、“嵌入式系统设计”、“机械控制”、“惯性导航”
、“人工智能”等众多机器人相
关技术学科,同时创新性地引入了机器人竞技的方式,使机器人对抗
更加直观激烈,吸引了众多的科技爱好者和社会公众的广泛关注。
#h(2em) 战队将全力以
赴,争取取得好成绩!
#h(2em) 由于全国大学生机甲大师超级对抗赛的时间与某些考试时间冲突,导
致参赛队员(见队员名单) 无法按时参加课程及考试。因此,希望批准参赛
队员的请假缓考申请,并在之后补考。
#h(2em)感谢您对创新创业的支持和理解!
#v(1em)
#h(22em)战队指导教师:
#pagebreak()
战队名单如下:
#v(1em)
#table(
columns: 4,
// [*Condition*], [*Result*],[*Condition*], [*Result*],
..data.flatten(),
)
// #grid(
// columns: (30%, 30%),
// // rows: (auto, 60pt),
// gutter: 1cm,
// [
// 智能科学与工程学院
// 智能科学与工程学院
// 智能科学与工程学院
// 智能科学与工程学院
// 智能科学与工程学院
// 智能科学与工程学院
// 智能科学与工程学院
// 智能科学与工程学院
// 智能科学与工程学院
// 智能科学与工程(探测)
// 信息与通信工程学院
// 物理与光电工程学院
// 物理与光电工程学院
// 计算机科学与技术学院
// 计算机科学与技术学院
// 计算机科学与技术
// 机电工程学院
// 机电工程学院
// 机电工程学院
// 核科学与技术学院
// 计算机科学与技术
// ],[
// 2023040931 李泽东
// 2022040605 蒋佳灏
// 2022041002 李天宇
// 2022040305 石恪
// 2023041008 胡新旺
// 2023040914 黄俊文
// 2022040704 李振旭
// 2022040610 杨雨轩
// 2022040728 程思涵
// 2022041018 张羽璇
// 2023080821 苗海涛
// 2021251124 古翱翔
// 2023251116 余新苒
// 2022201512 郑竣哲
// 2022201308 彭智超
// 2022065523 李彬
// 2022079805 黄金涛
// 2023072228 陈骏熔
// 2023079511 胡乾
// 2022108312 王盛博
// 2023201522 陈一鸣
// ])
#v(3em)
// #pagebreak()
比赛通知见下一页:
// #box(background-color: f0f0f0)[111]
// #set background-color: f0f0f0; |
|
https://github.com/fabian1409/typst-iaik-thesis-template | https://raw.githubusercontent.com/fabian1409/typst-iaik-thesis-template/master/README.md | markdown | # typst-iaik-thesis-template
This is a Typst template for a Master's Thesis at IAIK TU Graz
## Usage
You can use this template by using the `typst` command to init a new project based on this template.
For this to work, clone the this repo into `~/.local/share/typst/packages/local/iaik-thesis/0.1.0`
```bash
typst init @local/iaik-thesis:0.1.0
```
Typst will create a new directory with all the files needed to get you started.
## Configuration
The template will initialize your package with a sample call to the `thesis` function in a show rule.
```typ
#import "@local/iaik-thesis:0.1.0": *
#show: thesis.with(
title: "Title and \nSubtitle\nof the Thesis",
author: "Firstname Lastname, BSc",
degree: "Diplom-Ingenieur",
curriculum: "Computer Science",
supervisors: (
"Firstname Lastname, academic degrees of first supervisor",
"Firstname Lastname, academic degrees of next supervisor",
),
)
// Your content goes below.
```
|
|
https://github.com/danilasar/conspectuses-3sem | https://raw.githubusercontent.com/danilasar/conspectuses-3sem/master/ООП/240919.typ | typst | Раньше студентов клали в багажники и увозили в другие города за матпомощь. Однажды вошла в вагон вошла медсестра и начала докапываться по бутилированной воде и медицинским сопровождающим. Коллега Батраевой зовёт Семёна --- 21-летнего бородатого усатого четверокурсника крупного телосложения. Медсестра, увидев такого ребёнка, успокоилась.
Чтобы поржать в карантин 2020 года, Батраева сочинила сказку про ООП. В зоопарке есть программист. Мимо пролетал пегас, его покормили и начали прилетать другие пегасы. Возникла потребность вести учёт пегасов. У пегасов есть имя, цвет глаз, масть, возраст, вес и секретная вкусняшка.
Чтобы пегас появился, его нужно создать. Для этого есть конструктор. Поскольку вкусняшка секретная, она генерируется внутренним алгоритмом (был выбран rand).
Проблема состоит в том, что у пегасов нет документов, поэтому придётся их идентифицировать по имени. Это значит, что, встречая неуникальное имя, нам придётся уговаривать пегаса сменить имя. Для этого нужны геттер и сеттер методы.
Кроме того, для сравнения пегасов мы должны определить оператор сравнения.
Перегрузка вывода:
```cpp
friend ostream& operator<<(ostream& out, Pegas p)
```
`friend` --- независимые методы, которые при этом имеют доступ к разделу `private`.
История про человека из макдональса. Человек вышел из мака и пролил горячий кофе и засудил мак за свою травму.
История про кошку в микроволновке. Женщина высушила кошку в микроволновке и подала в суд на производителя за то, что в инструкции не запрещалось сушить животных. Суд она выиграла. |
|
https://github.com/An-314/Notes-of-Nuclear_Radiation_Physics_and_Detection | https://raw.githubusercontent.com/An-314/Notes-of-Nuclear_Radiation_Physics_and_Detection/main/chap2.typ | typst | #import"@preview/physica:0.9.2":*
= 原子核的放射性
== 放射性
- 伦琴:发现X射线
- 彭加勒(<NAME>) 对X射线来源的一个错误推测:是不是所有能强烈发荧光和磷光的物质都能发出 X 射线
- 贝克勒尔(<NAME>):铀盐放射性实验
发现放射性后,对射线进行研究,在磁场中发现,射线有三种成份:
- $alpha$射线是氦核,带正电荷,贯穿本领小;在磁场中偏转,与带正电荷离子流相同。
- $beta$射线是高速电子流,带负电,贯穿本领较大;在磁场中偏转,与带负电荷离子流相同。
- $gamma$射线是波长很短的电磁波,贯穿本领大;在磁场中不偏转。
=== 放射性的定义
*放射性*:原子核*自发地*发射*各种射线*而蜕变的现象。
*放射性核素*:能自发地发射各种射线而蜕变的核素。也称为*不稳定核素*。
放射性现象是由原子核的变化引起的,与核外电子状态的改变关系很小。放射性现象与原子核的衰变密切相关。
*原子核的衰变*:在没有外界影响的情况下,原子核自发地发射粒子并发生改变的过程。
=== 原子核衰变的表示
- 衰变表达式
$
alpha : ""^210 "Po" -> ""^206 "Pb" + ""^4 "He"
$
$
beta : ""^38 "K" -> ""^38 "Ar" + e^+ + nu
$
$
"EC" : ""^38 "K" + e^- -> ""^38 "Ar" + nu
$
$
gamma : ""^137 "Cs" -> ""^137 "Ba" + e^- + tilde(nu)
$
- 衰变纲图 (Decay Scheme)
#figure(
image("pic/2024-03-14-10-10-52.png", width: 80%),
caption: [
衰变纲图
],
)
#figure(
image("pic/2024-03-14-10-13-47.png", width: 80%),
caption: [
衰变纲图详解
],
)
- 两种线
- 横线——能级(自旋、宇称、能级能量、半衰期)
- 箭头线——衰变(5种——α、EC、β+、β-、γ)
- 两类符号
- 核素符号——母核/子核
- 衰变方式——6种(α、EC、β+、β-、γ e)
- 能量值——对应的粒子能量(α粒子、β+β-粒子最大、γ射线)
- 百分数——绝对强度(对应到母核衰变的百分数)
- 衰变能——到子核基态的
- 同位素表
== 放射性衰变的基本规律
基于统计的规律
- 放射源中的原子核数目巨大
- 放射性原子核是全同的
- 放射性衰变是一个统计过程
*统计规律*:我们不能预测某一原子核的衰变时刻,但可以统计得到放射源中总的放射性原子核数目的变化规律;每个放射性原子核的衰变是服从一定规律的随机事件,可以用*衰变概率表示*。
=== 单一放射性的指数衰减规律
由统计性,以放射源总体考虑衰减规律:
由于同类微观粒子的全同性, $- dd(N(t))$ 应该正比于$N(t)$和$dd(t)$,从而有:
$
- dd(N(t)) = lambda N(t) dd(t)
$
得到:
$
N / N_0 = e^(-lambda t)
$
其中$lambda$是衰变常数,$t$是时间,$N_0$是初始放射性核数目,$N$是时间$t$后的放射性核数目。
1. 单一放射性的指数衰减规律
$
N(t) = N_0 e^(-lambda t)
$
2. T 时间内一个放射性原子核不衰变的概率为:
$
N(T) / N_0 = e^(-lambda T)
$
3. T 时间内一个放射性原子核衰变的概率为:
$
1 - e^(-lambda T)
$
=== 放射性核素的特征量
==== 衰变常数
衰变常数#footnote[各放射性原子核都有特有的衰变常数,就像人的指纹一样,是放射性核素的特征量,可以通过测量衰变常数判断是什么核素。]:一个放射性原子核在单位时间内发生衰变的概率。
$
lambda = -(dd(N(t)) "/" ( dd(t)))/N(t)
$
- 分子:$t$时刻单位时间内发生衰变的核数目,称为衰变率$J(t)$
- 分母:$t$时刻放射性原子核总数
量纲为: $[t]^(-1)$
$T$时间内一个放射性原子核衰变的概率为: $1-e^(- lambda T)$
1. 衰变率——活度
$
J(t) = - dd(N(t)) "/" ( dd(t)) = lambda N(t)
$
2. 当一个原子核有几种衰变方式时:
$
lambda = sum_i lambda_i
$
分支比#footnote[区分衰变纲图中的绝对强度和分支比]为
$
R_i= lambda_i / lambda
$
是针对母核的衰变而言的。
==== 半衰期$T_"1/2"$
*半衰期*:放射性核的数目衰变一半所需的时间,记为$T_"1/2"$。
即:$N(t) = N_0 / 2$时,$t = T_"1/2"$。
可以得到:
$
T_"1/2" = ln(2) / lambda
$
量纲为:$[t]$
==== 平均寿命$tau$
平均寿命 = 总寿命 / 总核数——指数分布的均值。
$
tau = 1 / lambda = T_"1/2" / ln(2)
$
==== 衰变宽度$Gamma$
由放射性衰变的量子理论,原子核所处的能级具有一定的宽度, 如自然宽度$Gamma$,能级宽度不为零导致原子核状态不稳定。
由不确定关系:
$
Gamma approx hbar lambda\
Gamma tau approx hbar
$
特征量大小与放射性核总数衰减快慢的关系
#figure(
table(
columns: (auto, auto, auto, auto, auto),
inset: 10pt,
align: horizon,
[$lambda$], [$T_"1/2"$], [$tau$], [$Gamma$],[*放射性核总数衰减快慢*],
[大], [小], [小], [大], [快],
[小], [大], [大], [小], [慢],
),
caption: [
放射性核总数衰减快慢与特征量大小的关系
],
)
=== 放射性活度及其单位
==== 放射性活度 (Activity)
*活度*:单位时间内发生衰变的原子核的数目,以$A$表示,表征放射性的强弱。
$
A = - dd(N(t)) / dd(t) = lambda N(t)\
A(t) = A_0 e^(-lambda t)
$
==== 活度的单位
常用单位是居里(Ci):
$
1 "Ci" = 3.7 dot 10^10 "次核衰变/s"
$
国际单位制中,活度的单位是贝克勒尔(Bq):
$
1 "Bq" = 1 "次核衰变/s"
$
从而:
$
1 "Ci" = 3.7 dot 10^10 "Bq"
$
==== 射线强度
*射线强度*:放射源单位时间内放出某种射线的个数。
$
"射线强度" = "放射性活度" dot "衰变纲图上相应的%数"
$
量纲为:$[s]^(-1)$
放射源衰变时发出某种射线的多少,不仅与核衰变数有关,而且与核衰变的具体形式直接相关。通常,核衰变数不等于发出射线数。发出射线数等于核衰变数乘以一个百分数。
==== 比活度(Specific Activity)
*比活度*:*单位质量*的放射性核的活度。
$
a = A / m
$
量纲为:$"Bq"/g$ 或 $"Ci"/g$
*比活度*反映了放射源中放射性物质的*纯度*。
== 递次衰变规律
许多放射性核素的子核仍有放射性,会接着衰变···这就产生了多代连续放射性衰变,称为*递次衰变或级联衰变*。
$
N_n = sum_i N_i(t)
$
递次衰变的表示:
$
A ->^("衰变方式,半衰期") B ->^("衰变方式,半衰期") C ->^("衰变方式,半衰期") ... -> N("稳定")
$
=== 两次连续衰变规律
*对于母体$A$:*
$
N_1(t) = N_10 e^(-lambda_1 t)
$
A是单一放射性衰变,服从简单的指数衰减规律。
$t$时刻,$dd(t)$时间内,$A$的变化为:
$
- dd(N_1(t)) = lambda_1 N_1(t) dd(t)
$
*对于子体$B$:*
- 不断由A衰变而增加:$lambda_1 N_1(t) dd(t)$
- 不断衰变为C而减少:$- lambda_2 N_2(t) dd(t)$
$t$时刻,$dd(t)$时间内,$B$的变化为:
$
- dd(N_2(t)) = lambda_1 N_1(t) dd(t) - lambda_2 N_2(t) dd(t)
$
解得:
$
N_2(t) = N_10 (lambda_1 / (lambda_2 - lambda_1)) (e^(-lambda_1 t) - e^(-lambda_2 t))
$
*对于子体$C$:*
数目变化仅由 B 的衰变决定:
$
dd(N_3(t)) = N_(10) (lambda_1 lambda_2)/(lambda_2-lambda_1) (e^(-lambda_1 t) - e^(-lambda_2 t)) dd(t)
$
解得:
$
N_3(t) = N_10 (lambda_1 lambda_2)/(lambda_2-lambda_1) (1/lambda_1 (1 - e^(-lambda_1 t)) - 1/lambda_2 (1 - e^(-lambda_2 t)))
$
=== 多次连续衰变规律
$
N_n(t) = N_10 (sum_(i=1)^n c_i e^(-lambda_i t))
$
其中
$
c_i = product_(1 <= j <= n, j!=i) (lambda_j / (lambda_j - lambda_i))
$
在递次放射性衰变中:
- 只有母体衰变是单一放射性衰变,服从简单的指数衰减规律;
- 其余各代放射性子体的数目变化规律不再是简单的指数衰减规律,而与其前面各代的衰变常数都有关系。
=== 放射性平衡
研究在时间足够长之后,递次衰变的子体和母体的数目之比(或活度之比)。
对于两代连续:
$
(N_2(t)) / (N_1(t)) = lambda_1 / (lambda_2 - lambda_1) (1 - e^(-(lambda_2 - lambda_1) t))
$
==== 暂时平衡$lambda_1 < lambda_2$
母体 A 的半衰期不是很长,但比子体 B 的半衰期长,即$lambda_1 < lambda_2$。
观察时间内可看出母体 A 的核数目和放射性活度的变化;在时间足够长之后,子体 B 的核数目,将和母体 A 的核*数目*建立一固定的*比例关系*, 而且子体 B 的核数目*将按母体 A 的半衰期指数衰减*。这时建立的平衡叫*暂时平衡(Transient Equilibrium)*。
$
(N_2(t)) / (N_1(t)) approx lambda_1 / (lambda_2 - lambda_1)
$
平衡后,子体与母体的放射性活度之比为:
$
(A_2(t)) / (A_1(t)) approx lambda_2 / (lambda_2 - lambda_1) > 1
$
其中$lambda_2 / (lambda_2 - lambda_1)$被称为平衡因子。
物理过程:
+ 母体按自己的衰变常数指数衰减。
+ 子体从无到有增加,但增加速度会减慢,达到极大值后开始减少。
+ 母体数减少,其衰变率减少,即子体生成率减小
+ 子体数增加,衰变率增加
*$J_1(t_m) = J_2(t_m)$时,子体数目最大*,$A_1(t_m) = A_2(t_m)$:
$
t_m = ln(lambda_2 / lambda_1) / (lambda_2 - lambda_1)
$
#figure(
image("pic/2024-03-19-13-57-51.png", width: 80%),
caption: [
暂态平衡活度变化
],
)
对于*多代*连续放射性衰变:
只要母体$A_1$的衰变常数$lambda_1$最小,就会建立起按$A_1$的半衰期$T^((1))_(1/2)$进行衰变的暂时平衡体系。
建立平衡之后,各代放射体的数量及活度之比不随时间变化,且各代均按$lambda_1$进行衰变。
==== 长期平衡$lambda_1 << lambda_2$
当母体 A 的半衰期较长【观察时间$Delta t << T^((1))_(1/2)$】,且比子体 B 的半衰期长得多时,即$lambda_1 << lambda_2$。
在观察时间内,看不出母体 A 的核数目和放射性活度的变化;在相当长时间以后,子*体 B 的核数目和放射性活度会达到饱和*,并且*子母体的放射性活度相等*。这时建立的平衡叫*长期平衡(Secular Equilibrium)*。
$t$足够大时,有:
$
(N_2(t)) / (N_1(t)) approx lambda_1 / lambda_2
$
子体与母体的放射性活度之比为:
$
(A_2(t)) / (A_1(t)) approx 1
$
物理过程:
+ 母体在观测时间(如10天)内数目几乎不变;
+ 子体开始时从无到有增加,逐渐达到饱和。
+ 母体数几乎不变,其衰变率不变,即子体生成率不变
+ 子体数增加,衰变率增加,直到等于母体衰变率
在$J_1(t_m) = J_2(t_m)$时,子体数目饱和。其中$t_m = ln(lambda_2 / lambda_1) / (lambda_2 - lambda_1)$。
#figure(
image("pic/2024-03-19-14-08-07.png", width: 80%),
caption: [
长期平衡活度变化
],
)
对于多代连续放射性衰变:
只要母体$A_1$的衰变常数$lambda_1$足够小,就会建立起按$A_1$的半衰期$T^((1))_(1/2)$进行衰变的长期平衡体系。
平衡后,各代放射体的数量之比不随时间变化;各代子体的放射性活度都等于母体的放射性活度,且均按$lambda_1$进行衰变。
$
(N_i(t))/(N_1(t)) = lambda_1 / lambda_i
$
长期平衡后体系的*总活度*为$n A_1$,其中$n$是放射性子体的代数。
==== 不成平衡——逐代衰变$lambda_1 > lambda_2$
当母体 A 的半衰期比子体 B 的半衰期短,即$lambda_1 > lambda_2$。
这时不能建立平衡,母体 A 按指数规律较快衰减;而子体 B 的数目从零逐步增加, 过极大值后较慢衰减,当时间足够长时,母体 A 先衰减完,子体 B 则按自己的衰变常数 $lambda_2$ 衰变。这种情况也称为逐代衰变。
$
N_2(t) = N_10 (lambda_1 / (lambda_1 - lambda_2)) ( e^(-lambda_2 t))
$
$
A_2(t) &approx A_10 (lambda_1 lambda_2/ (lambda_1 - lambda_2)) ( e^(-lambda_2 t))\
A_1(t) &-> 0
$
+ 母体以衰变常数$lambda_1$按指数规律衰减,长时间后先衰变完了;
+ 子体开始时从无到有增加,长时间后母体衰变完,子体没有生成项,只以$lambda_2$按指数规律衰减。
$J_1(t_m) = J_2(t_m)$时,子体数目最大,其中$t_m = ln(lambda_2 / lambda_1) / (lambda_2 - lambda_1)$。
#figure(
image("pic/2024-03-19-14-24-12.png", width: 80%),
caption: [
逐代衰变活度变化
],
)
对于多代连续放射性衰变:
只要上代核素都比下代核素的衰变常数大,就会建立起逐代衰变体系。那么,随着时间的流逝,将会形成逐代衰变现象。首先是第一代衰变完,接着第二代,第三代,...,逐代衰变完,*而且各自按自己的衰变常数衰变*。
== 放射系——长期平衡
地球的年龄大约有46亿年。经过漫长的时间后,还能保存下来的天然放射系,其母体(或衰变链中的某子体)的半衰期都很长,要和地球年龄相近或更长,目前发现,地球上还存在着三个天然放射系,分别为:
#figure(
table(
columns: (auto, auto, auto),
inset: 10pt,
align: horizon,
[*钍系*],[*铀系*],[*锕系*],
[$""^232_"90""Th"$],[ $""^238_"92""U"$],[ $""^235_"92""U"$],
)
)
==== 钍系(4n系)
钍系从$""^232_"90""Th"$开始,经过连续10次衰变,最后到达稳定核素$""^208_"82""Pb"$。质量数是4的整数倍。
子体中半衰期最长为5.75a, 所以钍系建立起长期平衡需要几十年时间。
==== 铀系(4n+2系)
铀系从$""^238_"92""U"$开始,经过连续14次衰变,最后到达稳定核素$""^206_"82""Pb"$。质量数是4的整数倍加2。
子体中半衰期最长为2.455$×10^5$a,所以铀系建立起长期平衡需要几百万年时间。
==== 锕系(4n+3系)
锕系从$""^235_"92""U"$开始,经过连续15次衰变,最后到达稳定核素$""^207_"82""Pb"$。质量数是4的整数倍加3。
子体中半衰期最长为3.276$×10^4$a,所以锕系建立起长期平衡需要几十万年时间。
==== 镎系(4n+1系)
*天然放射系中缺少 $4n+1$ 放射系,人工造成。*
镎系从$""^237_"93""Np"$开始,经过连续11次衰变,最后到达稳定核素$""^209_"83""Bi"$。质量数是4的整数倍加1。
==== 分支衰变及分支比
*分支衰变*:核素的衰变方式不只一种的现象。
==== 铀-镭平衡(或钍-镭平衡、锕-镭平衡)
在测量天然矿物样品时,一般要求放射系处于平衡状态。
当测量的样品不密封时,各放射系中的放射性气体氡气会逸出而使长期平衡破坏。为了恢复被破坏的平衡,需要把样品密封起来达到氡气半衰期的$5 ~ 7$倍再进行测量。
放射系中的氡气,也称为
- 镭射气$""^222_"86""Rn"$
- 钍射气$""^220_"88""Ra"$
- 锕射气$""^219_"86""Ra"$
分别是铀系、钍系和锕系中镭的放射性气体子体。
== 放射性规律的应用
=== 放射性活度修正
_已知放射源某时的活度,求其它时刻的活度。_
根据
$
A(t) &= A_0 e^(-lambda t)\
A(t) &= A_0 2^(-t / T_"1/2")
$
若放射源已知,则$lambda$已知,根据已知条件 $A(0)$ 和$ t$ 可以求出现在或某时该源的*活度*。在已知衰变纲图的情况下,还可以求出其*射线强度*。
=== 确定放射源活度和制备时间
_人工制备放射源时,确定源的活度和最佳制备时间。_
地球上的近3000多种放射性核素大部分是人工制造的,如:核燃料$""^239"Pu"$、中子源$""^252"Cf"$。
若制备放射源时,带电粒子束或中子束的*强度和能量*是一定的,则放射性核素的*产生率* $P (P = N_t sigma Phi ) $是恒定的,但源在制备过程中同时又在衰变。
$
x + A("靶核") ->^P B("产生核") ->^(lambda N(t)) C
$
*放射性核素$B$*的数目变化率为:
$
- dd(N(t)) = P - lambda N(t) dd(t)
$
解得:
$
N(t) = P / lambda (1 - e^(-lambda t))
$
*活度*为:
$
A(t) = lambda N(t) = P (1 - e^(-lambda t))
$
$1 - e^(-lambda t)$称为*饱和因子*,用$S$表示。
一般在$S -> 99%$时,$t = 6.65 T_"1/2"$,即放射源的活度达到99%时的时间是6.65倍的半衰期。
不能通过照射时间来提高最大活度。
活度随照射时间的变化规律为:
$
A(t) = N_t sigma Phi (1 - e^(-lambda t)) = P (1 - e^(-lambda t))
$
其中$N_t$是靶核总数目,$sigma$是靶核的截面积,$Phi$是粒子束的强度。
=== 确定放射源性质
_在应用放射源时,确定源中放射性核素的组成是很重要的,因为这和源的放射性活度及辐射的粒子密切相关。_
例如$""^90_"38""Sr"$ 放射源:
$
""^90_"38""Sr" ->^(beta^-, 28.90a) ""^90_"39""Y" ->^(beta^-, 64.053h) ""^90_"40""Zr"("稳定")
$
该递次衰变会达到*长期平衡*,平衡后,原纯$""^90_"38""Sr"$放射源,将变为$""^90_"38""Sr"$和$""^90_"39""Y"$共存的放射源,并以$""^90_"38""Sr"$的半衰期衰变。这时源活度是纯$""^90_"38""Sr"$源的两倍,发射的粒子能量也有了变化。
=== 放射性鉴年法——确定远期年代
==== $""^14C$断代年代法
$""^14C$是一种放射性核素,半衰期为5730a,是地球上自然界中存在的放射性核素。
宇宙射线与大气层中的核发生反应,产生中子,中子和$""^14N$反应生成$""^14C$
$
n + ""^14N -> ""^14C + p
$
大气中:$""^12"C" : ""^14"C" = 1 : 1.2 dot 10^(-12)$。活生物体内的$""^12C$与$""^14C$含量之比与大气中相当。
$
n + ""^14N ->^(P = N_t sigma Phi) ""^14C -> ^(5730a) ""^14N
$
1g有生命机体的C中含$""^14C$约$6 dot 10^10$个,每分钟发生衰变的$""^14C$约14个。*当生命结束后,生物体停止与大气的C交换。*其体内14C不断衰变,数目不断减少,而其体内$""^12C$的数目保持不变。
通过测量:
- $""^14C$的$beta-$放射性活度
- $""^14C$核素数目#footnote[加速器质谱(AMS)方法测量]
都可以确定生物体的年代。将古代样品含量比与现代参考样品含量比(相当于0时刻的古代样品含量比)比较,可以确定生物体死亡距今的时间。
$
t = 1/lambda ln(((""^14C/""^12C)_"参考样品")/((""^14C/""^12C)_"测量样品"))
$
==== 地质放射性鉴年法—— 利用长寿命核素的衰变
早期利用铀系、锕系等放射系,母体半衰期与地球年龄相当;后来发展利用40K、87Rb等长寿命核素。
$
""^87"Rb" ->^(beta^- 4.75 dot 10^10a) ""^87"Sr"("稳定")
$
设岩石生成时刻为$t_0$,母核数$N_p(t_0)$,子核数$N_d(t_0)$,现在时刻为$t$,母核数$N_p(t)$,子核数$N_d(t)$。
$
cases(
N_p (t) = N_p (t_0) e^(-lambda (t - t_0)),
N_d (t) = N_p (t_0) - N_p (t)
)
$
从而:
$
N_p (t) =( N_p (t) + N_d (t)) e^(-lambda (t - t_0))
$
解得:
$
Delta t = 1 / lambda ln(1+(N_d (t)) / (N_p (t)))
$
可以通过测量$N_d (t)$和$N_p (t)$来确定岩石的年代。
$N_d (t_0) = 0$这一假设不一定成立,则:
$
N_d (t) + N_p (t) = N_d (t_0) + N_p (t_0)
$
$
N_p(t) = (N_p (t) + N_p (t)-N_d (t_0)) e^(-lambda Delta t)
$
考虑稳定子核$d$的另一稳定同位素$d'$,例如$""^86"Sr"$。要求:$d'$不能由其它长寿命核素衰变而来,因此:
$
N_d' (t) = N_d' (t_0)
$
于是:
$
(N_d (t) + N_p (t))/(N_d' (t)) &= (N_d (t_0) + N_p (t_0))/(N_d' (t_0))\
(N_d (t)) / (N_d' (t)) &= (N_p (t))/(N_d' (t))(e^(lambda Delta t) - 1) - (N_d (t_0))/(N_d' (t_0))
$
单个岩石样品测量得不到结果,需要测量不同岩石样品,进行数据拟合。
*利用天然放射系*,也可以测定地质年代。例如铀系:
$
""^238"U" -> ""^234"Th" -> ... ->""^206"Pb"
$
满足:
$
N_d (t) + sum_i N_i (t) = N_p (t_0) - N_d (t)
$
当放射系达到平衡后:
$
sum_i N_i (t) << N_p (t)
$
从而:
$
N_d (t) approx N_p (t_0) - N_p (t) = N_p (t_0) (1 - e^(-lambda (t - t_0)))
$
得到:
$
Delta t = 1 / lambda_(""^235 U) ln(1 + (N_(""^206 "Pb") (t)) / (N_(""^238 U) (t)))
$
为了降低系统误差的影响,可以联合两个放射系求时间,对于锕系同理:
$
(N_(""^238 U) (t) )/(N_(""^235 U) (t)) = (N_(""^206 "Pb") (t) )/(N_(""^207 "Pb") (t)) times (e^(lambda_(""^235 U) Delta t) - 1)/(e^(lambda_(""^238 U) Delta t) - 1)
$
一般地,
$
(N_(""^238 U) (t) )/(N_(""^235 U) (t)) = 138
$
则可求解$Delta t$。
=== 短寿命核素发生器
核医学、放射医学等需要短寿命的放射性核素,如$""^99m"Tc"$,$""^113"In"$等。
_无法及时将这些短寿命放射性核素运输到医院等需要它们的地方。_
*母牛*:利用连续衰变系列生产短寿命核素。
$
"母核" ->^("较长寿命核素") "子核" -> ...
$
*母牛原理*:寿命较长的核素不断衰变产生短寿命子体,需要时,将子体分离出来,而母体继续不断衰变生长出子体。
钼-锝($""^99"Mo" -> ""^99m"Tc"$)母牛:
$
""^99"Mo" ->^(beta^-,65.97h) ""^"99m""Tc" ->^(I T, 6.006h) ""^99"Tc" ->
$
*暂时平衡*:$t = t_m = ln(lambda_2 / lambda_1) / (lambda_2 - lambda_1)approx 23 h$时,子核放射性活度最大。
#figure(
image("pic/2024-03-21-10-33-00.png", width: 80%),
caption: [
母牛原理
],
) |
|
https://github.com/mariunaise/HDA-Thesis | https://raw.githubusercontent.com/mariunaise/HDA-Thesis/master/graphics/quantizers/two-bit-enroll-gray.typ | typst | #import "@preview/cetz:0.2.2": canvas, plot
#let line_style = (stroke: (paint: black, thickness: 2pt))
#let dashed = (stroke: (dash: "dashed"))
#canvas({
plot.plot(size: (8,6),
x-tick-step: 0.25,
y-label: $cal(Q)(2, 1, tilde(x))$,
x-label: $tilde(x)$,
y-tick-step: none,
y-ticks: ((0.25, [00]), (0.5, [01]), (0.75, [11]), (1, [10])),
axis-style: "left",
x-min: 0,
x-max: 1,
y-min: 0,
y-max: 1,{
plot.add(((0,0), (0.25,0.25), (0.5,0.5), (0.75,0.75), (1, 1)), line: "vh", style: line_style)
plot.add-hline(0.25, 0.5, 0.75, 1, style: dashed)
plot.add-vline(0.25, 0.5, 0.75, 1, style: dashed)
})
})
|
|
https://github.com/pku-typst/PKU-typst-template | https://raw.githubusercontent.com/pku-typst/PKU-typst-template/main/templates/通用/作业/themes/sketch.typ | typst | MIT License | #import "@preview/linguify:0.4.1": load_ftl_data, linguify
#let languages = (
"zh",
"en",
)
#let lgf_db = eval(load_ftl_data("../L10n", languages))
#let linguify = linguify.with(from: lgf_db)
#let logo_path = "../../../../utils/res/PKU.svg"
#let logo_str = read(logo_path).replace("920f14", "cccccc")
#let title(
course_name: none,
hw_no: none,
hw_week: none,
student_id: none,
student_name: none,
..args,
) = context {
// Logo size
let logo_size = 1. * page.width
// Info
let title = course_name
let course_title = box(
text(
title,
size: 36pt,
font: ("Courier New", "SimSun"),
baseline: -0.6em,
),
)
let subtitle = none
if hw_no != none {
subtitle = linguify("homeworkOrd", args: (ord: hw_no))
} else if hw_week != none {
subtitle = linguify("weekOrd", args: (weekNo: hw_week))
}
let info_text = [#subtitle ~ #student_name ~ #student_id]
let info = box([
#set text(
size: 20pt,
font: ("Courier New", "SimSun"),
baseline: 1em,
)
#set align(horizon)
#info_text
])
return [
#set page(
paper: "a4",
margin: 0pt,
)
// Logo
#place(
center + top,
dx: 0.4 * logo_size,
dy: 10pt,
)[
#image.decode(logo_str, width: logo_size)
]
// Info panel
#place(
bottom + left,
dx: 0pt,
dy: -20%,
rect(fill: rgb("cccccc"), width: 100%, height: 10pt),
)
#place(
bottom + left,
dx: 24pt,
dy: -20%,
course_title,
)
#place(
bottom + left,
dx: 24pt,
dy: -20%,
info,
)
#pagebreak(weak: true)
]
}
#let other(doc) = {
set text(
font: ("Sentinel Pro", "Songti SC"),
size: 10pt,
)
doc
}
|
https://github.com/NMD03/typst-uds | https://raw.githubusercontent.com/NMD03/typst-uds/main/thesis.typ | typst | #import "template.typ" : *
#show: thesis.with(
title: "Typst Template for UDS",
author: "<NAME>",
type: "Master Thesis",
student_id: "XXXXXXXXXXX",
date: datetime(
year: 1984,
month: 10,
day: 10,
),
time_period: "01.01.2023 - 00.00.2024",
confidentiality_clause: false,
language: "en",
supervisor: "Someone",
first_referee: "Someone else",
second_referee: "Someone else",
signature: "hide", // TODO
)
// NOTE: https://www.dhbw.de/fileadmin/user_upload/Dokumente/Dokumente_fuer_Studierende/191212_Leitlinien_Praxismodule_Studien_Bachelorarbeiten.pdf
// Requirements:
//
= Introduction
#include "./chapters/01-Introduction.typ"
#pagebreak()
= Technical Background
== Spell checking
You can use #link("https://github.com/crate-ci/typos")[Typos],
but I am too lazy to explain.
= Summary and Conclusion
#lorem(250)
|
|
https://github.com/HEIGVD-Experience/docs | https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S5/MAT3/docs/4-FormeExponentielle/forme-exponentielle.typ | typst | #import "/_settings/typst/template-note.typ": conf
#show: doc => conf(
title: [
Forme exponentielle
],
lesson: "MAT3",
chapter: "4 - Forme Exponentielle",
definition: "Ce document explique la forme exponentielle des nombres complexes, basée sur la formule d'Euler, qui relie les fonctions exponentielles et trigonométriques. Il illustre des cas particuliers, les propriétés de cette forme, et décrit comment effectuer des opérations telles que la multiplication, division, élévation à une puissance, et le calcul du conjugué pour les nombres complexes en utilisant cette représentation.",
col: 1,
doc,
)
= Forme exponentielle d'un nombre complexe
== Formule d'Euler
#align(center)[
#linebreak()
#box(
stroke: 1pt + color.black,
inset: 15pt,
)[
$
e^(j theta) = cos(theta) + j * sin(theta)
$
#align(left)[pour tout $theta$ réel.]
]
]
#image("/_src/img/docs/image copy 134.png")
Lorsque $theta$ varie, l'image du nombre complexe $e^(j theta)$ parcourt le cercle unité dans le plan
complexe.
=== Cas particuliers
1. $1 = e^(j 0) = e^0$
2. $j = e^(j pi/2)$
3. $-1 = e^(j pi)$
4. $-j = e^(j (3pi)/2)$
5. $e^z eq.not 0$ pour n'importe quel nombre complexe $z$
On remarque aussi que $e^(j theta)$ est $2k pi$ périodique ainsi pour tout entier $k$, on aura:
$
e^0 = e^(j 0) = e^(2pi k) = 1
$
== Forme exponentielle
#align(center)[
#linebreak()
#box(
stroke: 1pt + color.black,
inset: 10pt,
)[
$
z = "re"^(j theta)
$
]
]
pour $r$ représente le module et d'argument $theta$.
== Propriétés
- $z = a + "bj"$ alors $e^z = e^(a + "bj") = e^a (cos(b) + j sin(b))$
- $bar e^(a+"bj")bar = e^a$ et en particulier $bar e^(j b) bar = 1$
= Opération avec la forme exponentielle
Prenons $z_1 = r_1 e^(j theta_1)$ et $z_2 = r_2 e^(j theta_2)$ deux nombres complexes ainsi que $n$ un nombre entier. Alors :
#align(center)[
#linebreak()
#box(
stroke: 1pt + color.black,
inset: 15pt,
)[
1. $z_1 z_2 = r_1 r_2 e^(j(theta_1 + theta_2))$,
2. $frac(1,z_1) = frac(1,r_1) e^(-j theta_1)$,
3. $frac(z_1,z_2) = frac(r_1,r_2) e^(j(theta_1 - theta_2))$,
4. $(z_1)^n = (r_1)^n e^(j n theta_1)$,
5. $z_1^* = r_1 e^(-j theta_1)$.
]
] |
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/CPGE_MPSI.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: "CPGE MPSI",
authors: (
"<NAME>",
),
date: "12 Février, 2024",
)
#set heading(numbering: "1.1.")
=== MPSI
<mpsi>
- LLG
- Saint-Louis
- Stanislas
- Montaigne
- Fénelon
- Chaptal
- <NAME>
=== PCSI
<pcsi>
- LLG
- Montaigne
- <NAME>
- <NAME>
- Chateaubriand
=== INSA Toulouse
<insa-toulouse>
|