repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fletcher/0.4.3/src/layout.typ
typst
Apache License 2.0
#import "utils.typ": * #import "coords.typ": * #import "shapes.typ" /// Measure node labels with the style context and resolve node shapes. /// /// Widths and heights that are `auto` are determined by measuring the size of /// the node's label. #let compute-node-sizes(nodes, styles) = nodes.map(node => { // Width and height explicitly given if auto not in node.size { let (width, height) = node.size node.radius = vector-len((width/2, height/2)) node.aspect = width/height // Radius explicitly given } else if node.radius != auto { node.size = (2*node.radius, 2*node.radius) node.aspect = 1 // Width and/or height set to auto } else { // Determine physical size of node content let (width, height) = measure(node.label, styles) let radius = vector-len((width/2, height/2)) // circumcircle node.aspect = if width == 0pt or height == 0pt { 1 } else { width/height } if node.shape == auto { let is-roundish = max(node.aspect, 1/node.aspect) < 1.5 node.shape = if is-roundish { "circle" } else { "rect" } } // Add node inset if radius != 0pt { radius += node.inset } if width != 0pt and height != 0pt { width += 2*node.inset height += 2*node.inset } // If width/height/radius is auto, set to measured width/height/radius node.size = node.size.zip((width, height)) .map(((given, measured)) => map-auto(given, measured)) node.radius = map-auto(node.radius, radius) } if node.shape in (circle, "circle") { node.shape = shapes.circle } if node.shape in (rect, "rect") { node.shape = shapes.rect } node }) /// Convert an array of rects `(center: (x, y), size: (w, h))` with fractional /// positions into rects with integral positions. /// /// If a rect is centered at a factional position `floor(x) < x < ceil(x)`, it /// will be replaced by two new rects centered at `floor(x)` and `ceil(x)`. The /// total width of the original rect is split across the two new rects according /// two which one is closer. (E.g., if the original rect is at `x = 0.25`, the /// new rect at `x = 0` has 75% the original width and the rect at `x = 1` has /// 25%.) The same splitting procedure is done for `y` positions and heights. /// /// - rects (array): An array of rects of the form `(center: (x, y), size: /// (width, height))`. The coordinates `x` and `y` may be floats. /// -> array #let expand-fractional-rects(rects) = { let new-rects for axis in (0, 1) { new-rects = () for rect in rects { let coord = rect.center.at(axis) let size = rect.size.at(axis) if calc.fract(coord) == 0 { rect.center.at(axis) = calc.trunc(coord) new-rects.push(rect) } else { rect.center.at(axis) = floor(coord) rect.size.at(axis) = size*(ceil(coord) - coord) new-rects.push(rect) rect.center.at(axis) = ceil(coord) rect.size.at(axis) = size*(coord - floor(coord)) new-rects.push(rect) } } rects = new-rects } new-rects } /// Interpret #the-param[diagram][axes]. /// /// Returns a dictionary with: /// - `x`: Whether $u$ is reversed /// - `y`: Whether $v$ is reversed /// - `xy`: Whether the axes are swapped /// /// - axes (array): Pair of directions specifying the interpretation of $(u, v)$ /// coordinates. For example, `(ltr, ttb)` means $u$ goes $arrow.r$ and $v$ /// goes $arrow.b$. /// -> dictionary #let interpret-axes(axes) = { let dirs = axes.map(direction.axis) let flip if dirs == ("horizontal", "vertical") { flip = false } else if dirs == ("vertical", "horizontal") { flip = true } else { panic("Axes cannot both be in the same direction. Got `" + repr(axes) + "`, try `axes: (ltr, ttb)`.") } ( flip: ( x: axes.at(0) in (rtl, ttb), y: axes.at(1) in (rtl, ttb), xy: flip, ) ) } /// Determine the number and sizes of grid cells needed for a diagram with the /// given nodes and edges. /// /// Returns a dictionary with: /// - `origin: (u-min, v-min)` Coordinate at the grid corner where elastic/`uv` /// coordinates are minimised. /// - `cell-sizes: (x-sizes, y-sizes)` Lengths and widths of each row and /// column. /// /// - grid (dicitionary): Representation of the grid layout, including: /// - `flip` #let compute-cell-sizes(grid, nodes, edges) = { let rects = nodes.map(node => (center: node.pos, size: node.size)) rects = expand-fractional-rects(rects) // all points in diagram that should be spanned by coordinate grid let points = rects.map(r => r.center) points += edges.map(e => e.vertices).join() if points.len() == 0 { points.push((0,0)) } let min-max-int(a) = (calc.floor(calc.min(..a)), calc.ceil(calc.max(..a))) let (x-min, x-max) = min-max-int(points.map(p => p.at(0))) let (y-min, y-max) = min-max-int(points.map(p => p.at(1))) let origin = (x-min, y-min) let bounding-dims = (x-max - x-min + 1, y-max - y-min + 1) // Initialise row and column sizes let cell-sizes = bounding-dims.map(n => (0pt,)*n) // Expand cells to fit rects for rect in rects { let indices = vector.sub(rect.center, origin) if grid.flip.x { indices.at(0) = -1 - indices.at(0) } if grid.flip.y { indices.at(1) = -1 - indices.at(1) } for axis in (0, 1) { let size = if grid.flip.xy { rect.size.at(axis) } else { rect.size.at(1 - axis) } cell-sizes.at(axis).at(indices.at(axis)) = max( cell-sizes.at(axis).at(indices.at(axis)), rect.size.at(axis), ) } } (origin: origin, cell-sizes: cell-sizes) } /// Determine the centers of grid cells from their sizes and spacing between /// them. /// /// Returns the a dictionary with: /// - `centers: (x-centers, y-centers)` Positions of each row and column, /// measured from the corner of the bounding box. /// - `bounding-size: (x-size, y-size)` Dimensions of the bounding box. /// /// - grid (dictionary): Representation of the grid layout, including: /// - `cell-sizes: (x-sizes, y-sizes)` Lengths and widths of each row and /// column. /// - `spacing: (x-spacing, y-spacing)` Gap to leave between cells. /// -> dictionary #let compute-cell-centers(grid) = { // (x: (c1x, c2x, ...), y: ...) let centers = array.zip(grid.cell-sizes, grid.spacing) .map(((sizes, spacing)) => { array.zip(cumsum(sizes), sizes, range(sizes.len())) .map(((end, size, i)) => end - size/2 + spacing*i) }) let bounding-size = array.zip(centers, grid.cell-sizes).map(((centers, sizes)) => { centers.at(-1) + sizes.at(-1)/2 }) ( centers: centers, bounding-size: bounding-size, ) } /// Determine the number, sizes and relative positions of rows and columns in /// the diagram's coordinate grid. /// /// Rows and columns are sized to fit nodes. Coordinates are not required to /// start at the origin, `(0,0)`. #let compute-grid(nodes, edges, options) = { let grid = ( axes: options.axes, spacing: options.spacing, ) grid += interpret-axes(grid.axes) grid += compute-cell-sizes(grid, nodes, edges) // enforce minimum cell size grid.cell-sizes = grid.cell-sizes.zip(options.cell-size) .map(((sizes, min-size)) => sizes.map(calc.max.with(min-size))) grid += compute-cell-centers(grid) grid } #let apply-edge-shift-line(grid, edge) = { let (from-xy, to-xy) = edge.final-vertices let θ = vector-angle(vector.sub(to-xy, from-xy)) + 90deg let (δ-from, δ-to) = edge.shift let δ⃗-from = vector-polar-with-xy-or-uv-length(grid, from-xy, δ-from, θ) let δ⃗-to = vector-polar-with-xy-or-uv-length(grid, to-xy, δ-to, θ) edge.final-vertices.at( 0) = vector.add(from-xy, δ⃗-from) edge.final-vertices.at(-1) = vector.add(to-xy, δ⃗-to) edge } #let apply-edge-shift-arc(grid, edge) = { let (from-xy, to-xy) = edge.final-vertices let θ = vector-angle(vector.sub(to-xy, from-xy)) + 90deg let (θ-from, θ-to) = (θ + edge.bend, θ - edge.bend) let (δ-from, δ-to) = edge.shift let δ⃗-from = vector-polar-with-xy-or-uv-length(grid, from-xy, δ-from, θ-from) let δ⃗-to = vector-polar-with-xy-or-uv-length(grid, to-xy, δ-to, θ-to) edge.final-vertices.at( 0) = vector.add(from-xy, δ⃗-from) edge.final-vertices.at(-1) = vector.add(to-xy, δ⃗-to) edge } #let apply-edge-shift-poly(grid, edge) = { let end-segments = ( edge.final-vertices.slice(0, 2), // first two vertices edge.final-vertices.slice(-2), // last two vertices ) let θs = ( vector-angle(vector.sub(..end-segments.at(0))), vector-angle(vector.sub(..end-segments.at(1))), ) let ends = (edge.final-vertices.at(0), edge.final-vertices.at(-1)) let δs = edge.shift.zip(ends, θs).map(((d, xy, θ)) => { vector-polar-with-xy-or-uv-length(grid, xy, d, θ + 90deg) }) // the `shift` option is nicer if it shifts the entire segment, not just the first vertex // first segment edge.final-vertices.at(0) = vector.add(edge.final-vertices.at(0), δs.at(0)) edge.final-vertices.at(1) = vector.add(edge.final-vertices.at(1), δs.at(0)) // last segment edge.final-vertices.at(-2) = vector.add(edge.final-vertices.at(-2), δs.at(1)) edge.final-vertices.at(-1) = vector.add(edge.final-vertices.at(-1), δs.at(1)) edge } /// Apply #the-param[edge][shift] by translating edge vertices. /// /// - grid (dicitionary): Representation of the grid layout. This is needed to /// support shifts specified as coordinate lengths. /// - edge (dictionary): The edge with a `shift` entry. #let apply-edge-shift(grid, edge) = { if edge.kind == "line" { apply-edge-shift-line(grid, edge) } else if edge.kind == "arc" { apply-edge-shift-arc(grid, edge) } else if edge.kind == "poly" { apply-edge-shift-poly(grid, edge) } else { edge } }
https://github.com/wj461/operating-system-personal
https://raw.githubusercontent.com/wj461/operating-system-personal/main/HW3/hw3.typ
typst
#import "@preview/timeliney:0.0.1" #align(center, text(17pt)[ \u{1F995}*Operating-system homework\#3 * \u{1F996} ]) #(text(14pt)[ = Written exercises ]) = • Chap.7 - 7.8: The Linux kernel has a policy that a process cannot hold a spinlock while attempting to acquire a semaphore. Explain why this policy is in place.\ 預防deadlock ,與效能問題。 避免拿到A資源後又等待B資源,且B資源又必須等待A資源。 = • Chap.8 - 8.20: In a real computer system, neither the resources available nor the demands of processes for resources are consistent over long periods (months). Resources break or are replaced, new processes come and go, and new resources are bought and added to the system.\ – If deadlock is controlled by the banker’s algorithm, which of the following changes can be made safely (without introducing the possibility of deadlock), and under what circumstances? - (a) Increase Available (new resources added).\ 增加可用資源,不會造成deadlock。 - (b) Decrease Available (resource permanently removed from system).\ 如果減少的可用資源不會小於process的需求量,就不會造成deadlock。 - (c) Increase Max for one process (the process needs or wants more resources than allowed).\ 如果增加的Max沒有大於Available,就不會造成deadlock。 - (d) Decrease Max for one process (the process decides that it does not need that many resources).\ 漸少Max不會造成大於Available,不會造成deadlock。 - (e) Increase the number of processes.\ 只要增加後的need不會大於Available,不會造成deadlock。 - (f) Decrease the number of processes\ 減少process不會大於Available,不會造成deadlock。 - 8.27: Consider the following snapshot of a system : #align(center, table( columns: 4, table.header( [], [Allocation], [Max], [Need], ), [], [A B C D], [A B C D],[A B C D], [P0], [1 2 0 2], [4 3 1 6],[3 1 1 4], [P1], [0 1 1 2], [2 4 2 4],[2 3 1 2], [P2], [1 2 4 0], [3 6 5 1],[2 4 1 1], [P3], [1 2 0 1], [2 6 2 3],[1 4 2 2], [P4], [1 0 0 1], [3 1 1 2],[2 1 1 1] )) – Use the banker’s algorithm, determine whether or not each of the following states is unsafe. If the state is safe, illustrate the order in which the processes may complete. Otherwise, illustrate why the state is unsafe. #align(left, grid( columns: 2, gutter: 16pt, [- (a) Available=(2,2,2,3)\ P4: Available = (3,2,2,4)\ P0: Available = (4,4,2,6)\ P1: Available = (4,5,3,8)\ P2: Available = (5,7,7,8)\ P3: Available = (6,8,7,9)], [- (b) Available=(4,4,1,1)\ P2: Available = (5,6,5,1)\ P4: Available = (6,6,5,2)\ P1: Available = (6,7,6,4)\ P0: Available = (7,9,6,6)\ P3: Available = (8,9,6,7)] )) - 8.30: A single-lane bridge connects the two Vermont villages of North Tunbridge and South Tunbridge. Farmers in the two villages use this bridge to deliver their produce to the neighbor town.\ – The bridge can become deadlocked if a northbound and a southbound farmer get on the bridge at the same time. (Vermont farmers are stubborn and are unable to back up.)\ – Using semaphores and/or mutex locks, design an algorithm in pseudocode that prevents deadlock.\ – Initially, do not be concerned about starvation (the situation in which northbound farmers prevent southbound farmers from using the bridge, or vice versa)\ #show raw.where(block: true): block.with( fill: luma(240), inset: 10pt, radius: 4pt, ) #align(center, grid( columns: 2, gutter: 16pt, ```c semaphore mutex_biridge; semaphore mutex_north_count; semaphore mutex_south_count; // north while(true){ wait(mutex_north_count); north_pass_count++; if (north_pass_count == 1){ wait(mutex_biridge) } single(mutex_north_count); /* pass north bridge */ wait(mutex_north_count); north_pass_count--; if (north_pass_count == 0){ single(mutex_biridge) } single(mutex_north_count); } ```, ```c // south while(true){ wait(mutex_south_count); south_pass_count++; if (south_pass_count == 1){ wait(mutex_biridge) } single(mutex_south_count); /* pass south bridge */ wait(mutex_south_count); south_pass_count--; if (south_pass_count == 0){ single(mutex_biridge) } single(mutex_south_count); } ``` )) = • Chap.9 - 9.15: Compare the memory organization schemes of contiguous memory allocation and paging with respect to the following issues: - (a) external fragmentation\ paging: no external fragmentation\ contiguous fix memory: no external fragmentation\ contiguous variable parttition memory: external fragmentation\ - (b) internal fragmentation\ paging: internal fragmentation\ contiguous fix memory: internal fragmentation\ contiguous variable parttition memory: no internal fragmentation\ - (c) ability to share code across processes\ paging: can share code\ contiguous: cannot share code\ - 9.24: Consider a computer system with a 32- bit logical address and 8-KB page size. The system supports up to 1 GB of physical memory. How many entries are there in each of the following? - (a) A conventional, single-level page table\ $2^32 / 2^13 = 2^19$ - (b) An inverted page table\ $2^30 / 2^13 = 2^17$
https://github.com/brayevalerien/Learning-Typst
https://raw.githubusercontent.com/brayevalerien/Learning-Typst/main/tutorial/04_making_a_template/document.typ
typst
MIT License
#import "template.typ": template #show: doc => template( title: "Paper title", authors: ( ( name: "<NAME>", institute: "An Institute", email: "<EMAIL>" ), ( name: "<NAME>", institute: "Another Institute", email: "<EMAIL>" ) ), abstract: lorem(80), doc ) = Introduction #lorem(200) = Related work #lorem(25) == Paper 1 #lorem(40) == Paper 2 #lorem(30) == Paper 3 #lorem(50) = Method #lorem(20) == Subsection 1 #lorem(100) == Subsection 2 #lorem(150) == Subsection 3 #lorem(50) = Conclusion #lorem(100)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/circuiteria/0.1.0/gallery/test3.typ
typst
Apache License 2.0
#import "@preview/cetz:0.2.2": draw #import "../src/lib.typ": circuit, element, util, wire #set page(width: auto, height: auto, margin: .5cm) #circuit({ element.block( x: 0, y: 0, w: 2, h: 3, id: "block", name: "Test", ports: ( east: ( (id: "out0"), (id: "out1"), (id: "out2"), ) ) ) element.gate-and( x: 4, y: 0, w: 2, h: 2, id: "and1", inverted: ("in1") ) element.gate-or( x: 7, y: 0, w: 2, h: 2, id: "or1", inverted: ("in0", "out") ) wire.wire( "w1", ("block-port-out0", "and1-port-in0"), style: "dodge", dodge-y: 3, dodge-margins: (20%, 20%) ) wire.wire( "w2", ("block-port-out1", "and1-port-in1"), style: "zigzag" ) wire.wire( "w3", ("and1-port-out", "or1-port-in0") ) element.gate-and( x: 11, y: 0, w: 2, h: 2, id: "and2", inputs: 3, inverted: ("in0", "in2") ) for i in range(3) { wire.stub("and2-port-in"+str(i), "west") } element.gate-xor( x: 14, y: 0, w: 2, h: 2, id: "xor", inverted: ("in1") ) element.gate-buf( x: 0, y: -3, w: 2, h: 2, id: "buf" ) element.gate-not( x: 0, y: -6, w: 2, h: 2, id: "not" ) element.gate-and( x: 3, y: -3, w: 2, h: 2, id: "and" ) element.gate-nand( x: 3, y: -6, w: 2, h: 2, id: "nand" ) element.gate-or( x: 6, y: -3, w: 2, h: 2, id: "or" ) element.gate-nor( x: 6, y: -6, w: 2, h: 2, id: "nor" ) element.gate-xor( x: 9, y: -3, w: 2, h: 2, id: "xor" ) element.gate-xnor( x: 9, y: -6, w: 2, h: 2, id: "xnor" ) })
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/space_06.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test that trailing space does not force a line break. LLLLLLLLLLLLLLLLLL R _L_
https://github.com/fenjalien/metro
https://raw.githubusercontent.com/fenjalien/metro/main/tests/num/parse-numbers/test.typ
typst
Apache License 2.0
#import "/src/lib.typ": unit, metro-setup, num, qty #set page(width: auto, height: auto, margin: 1cm) $num(sqrt(2))$ $num(sqrt(2), e: sqrt(2), pw: sqrt(2), pm: sqrt(2))$ #num("1e n ^n") $qty(sqrt(2), m)$
https://github.com/Caellian/UNIRI_voxels_doc
https://raw.githubusercontent.com/Caellian/UNIRI_voxels_doc/trunk/content/raytrace.typ
typst
#import "../template.typ": formula = Egzaktne metode prikaza == Ray tracing - Osnove kako svijetlost putuje, što vidimo - Konstruktivne i destruktivne boje - Što je sjaj (engl. _radiance_) Svijetlost se može odbijati i ne završiti u kameri @Pharr2023-ex: #formula(caption: "osvjetljenje")[ $ L_0(p, omega_0) = underbrace(L_e (p, omega_0), "emitirani sjaj") + integral_(cal(S)^2) underbrace(f(p, omega_0, omega_i), "BDRF") underbrace(L_i (p,omega_i), "dolazeći sjaj") |cos(theta_i)| d omega_i $ ] <osvjetljenje> gdje je: - $p$ neka obasjana točka koju promatramo, - $omega_0$ fazor koji označava smjer iz kojeg je točka $p$ promatrana, - $L_0 (p, omega_0)$ ukupan sjaj koji napušta točku $p$ u smjeru $omega_0$ (engl. _outgoing radiance_), - $L_e (p, omega_0)$ sjaj kojeg sam materijal emitira (engl. _emitted radiance_) u smjeru $omega_0$, - integral $integral_(cal(S)^2)..d omega_i$ djeluje kao *težinski zbroj vrijednosti podintegralnog umnoška* za sve smjerove $d omega_i$ iz kojih može doprijeti svijetlost. Integrira po površini jedinične 2-kugle $cal(S)^2$, te se sastoji od: - $f(p, omega_0, omega_i)$ je dvosmjerna funkcija distribucije refleksije (engl. _Bidirectional Reflectance Distribution Function_, BRDF), koja je kasnije objašnjena, - $L_i (p,omega_i)$ je sjaj koji dolazi u točku $p$ od drugih izvora svijetlosti (engl. _incoming radiance_), te odbijanjem od reflektivnih površina, te konačno - $|cos(theta_i)|$ je geometrijsko prigušenje (engl. _geometric attenuation_) koje osigurava da je svijetlost koja se reflektira u smjeru $omega_0$ Koristi se jedinična 2-kugla $cal(S)^2 = {(x,y,z) | x^2 + y^2 + z^2 = 1}$ za integraciju jer su točke na njenoj površini uniformno raspoređene oko $p$ i podjednako udaljene od $p$. #figure(caption: "prikaz modela osvjetljenja")[ #set text(size: 10pt) #let width = 450pt #let height = 250pt #box(width: width, height: height)[ #let center_x = width / 2 #let center_y = height / -2 #align(center+horizon, image("../figure/observed_light.png")) #place(top+end, table( columns: (auto, auto), align: center+horizon, stroke: 1pt+gray.lighten(10%), [vektor], image("../figure/vektor.png"), [skalar], image("../figure/skalar.png") )) #place(dx: center_x + 4pt, dy: center_y + 13pt, $p$) #place(dx: center_x - 68pt, dy: center_y - 65pt, $omega_0$) #place(dx: center_x + 44pt, dy: center_y - 26pt, text(fill: yellow, $omega_i$)) #place(dx: center_x - 73pt, dy: center_y - 28pt, text(fill: blue, $L_e$)) #place(dx: center_x - 95pt, dy: center_y, text(fill: purple, $L_i$)) #place(dx: center_x + 28pt, dy: center_y + 58pt, $cal(S)^2$) #place(dx: center_x - 1.5pt, dy: center_y - 3pt, $theta$) ] ] <model-osvjetljenja> TODO Koristi @model-osvjetljenja Ako uzmemo u obzir samo $n$ izvora svijetlosti, integral možemo u potpunosti zamjeniti konačnim izrazom koji predstavlja njihov zbroj: #formula(caption: "zbroj svijetla")[ $ sum^n_(i = 0) f(p, omega_0, omega_i) L_i (p,omega_i) |cos(theta_i)| $ ] <zbroj-svijetlosti> No velik udio svijetla koje obasjava površine dolazi do njih odbijanjem od drugih površina te @zbroj-svijetlosti ne daje rezultate koji su vjerodostojni stvarnosti. Rezultat oslanjanja na takvo pojednostavljenje je značajno tamniji prikaz dijelova scene koji nije direktno obasjan. S druge strane, nije moguče izračunati stvarnu vrijednost integrala iz formule za @osvjetljenje, pa _ray tracing_ metode uz @zbroj-svijetlosti koriste i Monte Carlo metodu gdje prilikom svakog prikaza uzmu nekoliko nasumičnih uzoraka $omega_i$ pa te vrijednosti uključe u težinski zbroj. Problem s tim pristupom je što proizvede rezultate koji imaju veliku količinu buke (engl. _noise_). Taj problem nije rješiv bez potpunog rješavanja integrala za @osvjetljenje te postoje samo metode njegove mitigacije, ali primjetnost buke zavisi o broju nasumičnih uzoraka koji su uzeti kao i načinu odabira uzorkovanih $omega_i$. Popularnih metoda za mitigaciju buke su @nvidia-denoising: - prostorno filtriranje (engl. _spatial filtering_) - temporalno prikupljanje uzoraka (engl. _temporal accumulation_), te - rekonstrukcija metodama strojnog učenja (engl. _machine learning and deep learning reconstruction_). Svaka od mitigaciju buke ima prednosti i nedostatke, te ih se može kombinirati. U slučaju rasterizacije uniformno osvjetljenih voksela koji zauzimaju više piksela u krajnjem prikazu, prostorno filtriranje (korištenjem prosjeka sjaja uzoraka na površini istog voksela) pruža iznimno kvalitetno uklanjanje buke @douglas-voxel-denoising[#link("https://youtu.be/VPetAcm1heI&t=393")[6:33]], kao što je vidljivo na @denoising[slici], jer takav prosjek djeluje kao uvečavanje broja nasumičnih uzoraka onoliko puta koliko neka stranica voksela zauzima piksela bez troška koje bi stvarni dodatni uzorci zahtjevali. #figure( caption: [prikaz prije i nakon uklanjanja buke prostornim filtriranjem @douglas-voxel-denoising], kind: image, table( columns: (1fr, 1fr), inset: 0pt, stroke: none, image("../figure/big_voxel_noise.png", fit: "contain"), image("../figure/big_voxel_denoise.png", fit: "contain"), ) ) <denoising> == Ray marching Volumetrijski podaci zadani pravilima se na grafičke kartice šalju u obliku diskriminante tipa volumena i sukladnih podataka. Diskriminanta se u _shader_ kodu koristi za odabir grananja prilikom izvođenja pograma u sukladnu funkciju koja za neke ulazne koordinate i parametre lika vraća udaljenost tih koordinata od površine tijela koje je parametarski opisano. Takve funkcije su homotopično preslikavanje parametarski zadane topologije scene u polje skalara koje u svakoj točki sadrži udaljenost od razmatranog tijela, takav skalarni prostor nazivamo *polje udaljenosti s predznakom* (engl. _Signed Distance Field_, SDF). @sdf-shapes prikazuje SDF za 2D likove ili presjeke njihovih 3D analoga: koordinatama koje se nalaze unutar tijela SDF dodijeljuje negativne vrijednosti (plava boja), a koordinatama van tijela pozitivne (narančasta boja). Vrijednost u svakoj točki je jednaka njenoj udaljenosti od lika. #figure( caption: [prikaz SDFa likova @sdf-circle @sdf-triangle @sdf-square], kind: image, table( columns: (1fr, 1fr, 1fr), align: center+horizon, inset: (x: 0pt, y: 2pt), stroke: none, image("../figure/sdf_circle.png", fit: "contain"), image("../figure/sdf_triangle.png", fit: "contain"), image("../figure/sdf_square.png", fit: "contain"), [a) krug], [b) trokut], [c) kvadrat] ) ) <sdf-shapes> Iako se čini ograničavajuće što ray marching dozvoljava prikaz geometrije oslanjajući se samo na SDF, moguće je prijevremeno pretvoriti arbitrarne 3D modele izrađene u programima za modeliranje u SDF pomoću tehnika iz strojnog učenja (engl. _machine learning_, ML) @Park2019-vp. Također se često TODO - Dozvoljava fora efekte poput metaballs. - Brže od raytraceanja (u nekim slučajevima, npr. vokseli), no ograničenije jer zahtjeva da su sva prikazana tijela izražena formulama i shader onda mora rješavati sustave jednadžbi - Je li doista brže za voksele (e.g. Nvidia SVO) ili samo za loše slučajeve? Slabo se koristi. #pagebreak()
https://github.com/mhspradlin/wilson-2024
https://raw.githubusercontent.com/mhspradlin/wilson-2024/main/understanding-ai/unfinished-fable-of-the-sparrows.typ
typst
MIT License
#set par(justify: true) #set text(size: 13pt) #set page(footer: text(size: 10pt)[_<NAME>. In Superintelligence: Paths, Dangers, Strategies. Oxford: Oxford University Press, 2014_]) #align(center)[ = The Unfinished Fable of the Sparrows ] #v(1em) It was the nest-building season, but after days of long hard work, the sparrows sat in the evening glow, relaxing and chirping away. “We are all so small and weak. Imagine how easy life would be if we had an owl who could help us build our nests!” “Yes!” said another. “And we could use it to look after our elderly and our young.” “It could give us advice and keep an eye out for the neighborhood cat,” added a third. Then Pastus, the elder-bird, spoke: “Let us send out scouts in all directions and try to find an abandoned owlet somewhere, or maybe an egg. A crow chick might also do, or a baby weasel. This could be the best thing that ever happened to us, at least since the opening of the Pavilion of Unlimited Grain in yonder backyard.” The flock was exhilarated, and sparrows everywhere started chirping at the top of their lungs. Only Scronkfinkle, a one-eyed sparrow with a fretful temperament, was unconvinced of the wisdom of the endeavor. Quoth he: “This will surely be our undoing. Should we not give some thought to the art of owl-domestication and owl-taming first, before we bring such a creature into our midst?” Replied Pastus: “Taming an owl sounds like an exceedingly difficult thing to do. It will be difficult enough to find an owl egg. So let us start there. After we have succeeded in raising an owl, then we can think about taking on this other challenge.” “There is a flaw in that plan!” squeaked Scronkfinkle; but his protests were in vain as the flock had already lifted off to start implementing the directives set out by Pastus. Just two or three sparrows remained behind. Together they began to try to work out how owls might be tamed or domesticated. They soon realized that Pastus had been right: this was an exceedingly difficult challenge, especially in the absence of an actual owl to practice on. Nevertheless they pressed on as best they could, constantly fearing that the flock might return with an owl egg before a solution to the control problem had been found. It is not known how the story ends, but the author dedicates this book to Scronkfinkle and his followers.
https://github.com/sysu/better-thesis
https://raw.githubusercontent.com/sysu/better-thesis/main/lib.typ
typst
MIT License
// 中山大学学位论文 Typst 模板 modern-sysu-thesis // 基于 [南京大学学位论文模板](https://github.com/nju-lug/modern-nju-thesis) 重构中 // Repo: https://gitlab.com/sysu-gitlab/thesis-template/better-thesis // https://typst.app/universe/package/modern-sysu-thesis #import "/specifications/bachelor/lib.typ" as bachelor
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/attach-03.typ
typst
Other
// Test function call after subscript. $pi_1(Y), a_f(x), a^zeta(x) \ a^subset.eq(x), a_(zeta(x)), pi_(1(Y))$
https://github.com/Personal-Data-Acquisition/PDA_paperwork
https://raw.githubusercontent.com/Personal-Data-Acquisition/PDA_paperwork/main/scope_and_vision/scope_and_vision.typ
typst
#set align(center) #text(24pt, strong([Team 6 (Personal Data Aquisition])) <NAME> <NAME> <NAME> <NAME> *Project Partner:* <NAME> #set align(left) #pagebreak() #outline() #pagebreak() = Abstract The aim of this senior capstone project is to design and implement a versatile data logging system that integrates single board computers (SBCs), STM32 microcontrollers, and the Rust programming language. The system will be capable of collecting, storing, and processing data from various sensors and input sources, providing a flexible and reliable solution for a wide range of applications. The project will involve the development of software for both the SBCs and STM32 microcontrollers, leveraging the unique capabilities of each platform. The Rust programming language will be used for its safety, performance, and ease of use, allowing for efficient and reliable code development. + Selection and integration of sensors and input devices for data collection. + Design and implementation of communication protocols between SBCs and STM32 microcontrollers. + Development of data processing algorithms and storage mechanisms. + Creation of a user interface for system configuration and data visualization. The project will culminate in the deployment and testing of the data logging system in real-world scenarios, demonstrating its effectiveness and reliability. The system will be designed with scalability and modularity in mind, allowing for future expansion and customization. Overall, this project aims to provide a comprehensive solution for data logging applications, showcasing the capabilities of modern embedded systems and the Rust programming language in real-world applications. = Change Log No changes were made to any of the project requirements since the first term; we also haven't expanded the scope of the project as our team has been plauged with non-functional, counterfit and cloned chips(micro-controllers, CAN transceivers). = Product Requirements Document #strong[Authors:] <NAME>, <NAME>, <NAME>, <NAME> #strong[DATE:] 2023-11-23 == Problem Description Existing personal data acquisition devices are either too expensive or too DIY for most potential users. Many are designed for aerospace, automotive or research purposes, and are too expensive and unnecessarily complicated for casual users. The only other option is for users to build their own devices from prefabricated parts, which is too complicated and requires too much much prerequisite knowledge for most potential users. === Scope The scope of this project is to develop a prototype for a personal data acquisition device. This prototype will have the ability to collect real time data from a variety of sensors, including accelerometers, gyroscopes, GPS modules, and thermometers. These components will need to combined in a printed circuit board for the final prototype. The scope of this project also includes development of a web-based UI that both presents the data gathered by the prototype and sends commands to the physical device to record data and configure sensors. === Use Cases The user will take the product along with them on an outdoor activity and subject it to normal conditions for that activity. The user will connect the product to a phone or laptop they brought with them, and view the data stream and take samples using the user interface, and save the data locally. The user will choose and connect selected modules to the system using the CAN(controller area network) bus. == Purpose and Vision(Background) Our purpose is to develop a personal data acquisition system that records all the data a user might want, and is cheap and easy to set up and use. It should be able to record data on acceleration, force, position, etc. require minimal setup, and can be hooked up to bike, go-kart, etc. == Stakeholders #strong[Capstone Team] \ The capstone team are the main decision makers for the project, and will need extensive information for the product’s requirements and implementation details. They will also need oversight from the project partner and TA. #strong[Project Partner] \ The project partner will be working very closely with the capstone team, and will need to know the teams capabilities and status, and the status of the project. #strong[Project TA] \ The TA needs to be informed on project progress and any issues the team may be having. #strong[Capstone Instructors] \ The instructors require much of the same information as the TA, but because they are working less closely with the team there is less urgency. #strong[Users] \ Users will need to know the product’s capabilities, limitations and intended use. == Preliminary Context === Assumptions - We have a suitable power supply of 12v to power the system. - The end user has a device capable of connecting to an ad-hoc network. - The data to be logged doesn’t require more speed than the CAN 2.0 standard. - The environment it’s meant to be used in is electrically noisy. === Constraints - As undergraduate students, our team has limited experience in the field, so we will have to learn a lot to deliver the product. - Our budget is limited, so we will have to choose components carefully based on price. - We are limited to three terms to deliver our product. With these constraints factored, the biggest concerns for the feasibility of our project are the skills that need to be learned and limited time alloted to do so and complete the project. As an example, the team has primarily non-formal experience in hardware organization but has thus far worked efficiently in that aspect of the project. These risks are mitigated by the expertise and technical support offered by our project partner, and we consequently find the scope of our project realistic. === Dependencies - The rust language, (reduces bugs and helps with memory safety.) - C compiler(s), (C ABI is still used as a way to interface with libs.) - Rust Embassy Library. (Embedded rust lib to reduce boilerplate) - Rust Rocket(web server) - STM SDK and HAL (Good refences for the actual hardware.) - The CAN standard. - The Unix networking stack - SQLite and or rust file I/O - Rust Libraries available for individual sensor modules. Some possible bottlenecks that could occur given our current dependencies would be centered around sensor modules not having an existing library written in rust. This would add more development time to the project. However, we’ve researched workarounds and discovered tools to generate the needed interfaces for rust from a C header file. == Market Assessment and Competition Analysis #strong[RexGen:] Proprietary CAN bus based data logger, hard to find tutorial or documentation and is prohibitively expensive for hobbyists. Also unable to guarantee that their system is memory safe. #strong[CANedge1:] CANedge1: It has open source elements to it and documentation that is accessible, but still does not meet the requirements for its cost. DEWEsoft sells test and measurement equipment. Their products are not a good fit for our users because they are designed for industry, and therefore overkill and are prohibitively expensive for an individual. Omega Engineering sells data loggers that can record the data our users would want, can connect to a remote device over Bluetooth and have easy to use interfaces. However most of their data loggers only record one or two types of data, so a user would need to buy many of them, which would be inconvenient and expensive. An Apple Watch can track a user’s activity data, and send it to an iPhone with an easy to read interface. However, the Apple Watch is limited in what kind of data it can record, and would not be appropriate for our users due to its many other unneeded functions. There are guides on the internet that instruct a user on how to build their own data acquisition device using Arduino or Raspberry Pi microcontroller much more inexpensively than the other alternatives. However, this requires the user to have background knowledge in circuitry and programming, and requires a lot of time and effort to set up. == Target Demographics (User Persona) Terry is an amateur Go-kart enthusiast who was brought into the hobby 8 months ago by friends and has become entrenched in the hobby since then. They are looking for a way to improve their performance but need more information about their current racing habits to do that. Alice is a CTO of a large company that has decided to data log the forces and location their products experience during shipping through multiple contracted pilots and routes. She needs a system that isn’t cost prohibitive to deploy in large numbers and can be customized for her company’s other projects as needed. John is an extreme snowboarder looking to collect data from his downhill tricks in order to help his friend create realistic and smooth animations for a snowboarding video game. He needs a data logging system that can endure cold environments and is modular so he can keep down the bulk/weight of the system while carving toeside and hitting some sweet jumps. James is a competition mountain biker who wants to record and analyze data during rides for performance improvement. Uses a smartphone and needs an easy-to-use interface. He needs a system to compare data between runs. == Requirements === User Stories and Features (Functional Requirements) #figure( align(center)[#table( columns: 5, align: (col, row) => (auto,auto,auto,auto,auto,).at(col), inset: 6pt, [User Story], [Feature], [Priority], [GitHub Issue], [Dependencies], [As a mountain biker, I want to be able to view my instantaneous speed at any point in my journey.], [Gps], [Must Have], [TBD], [Common firmware.], [As a motorsport hobbyist, I want to be able to record the g-forces I experience while going around tight corners.], [Accelerometer.], [Must Have], [TBD], [Common firmware.], [As a winter sports enthusiast, I want to be able to track the turning speed of my snowboard.], [Yaw rate sensor.], [Must Have], [TBD], [Common firmware.], )] ) === Non-Functional Requirements - Delay on data transmission should be at an acceptable level - Code should be well documented, following coding standards and best practices - User interface should intuitive and fast to use - The product should use security best practices whenever possible === Data requirements - Analog data will be converted to digital. - Sensor data must be reliable, resistant to EMI - Sensor modules must adhere to the CAN protocol. === Integration requirements - All interfaces will be rust doc documented. - Tests will ensure API usage integrity. - All modules that are to use the interface must pass integration tests. === User interaction and design - Use a web server to interface with the user - Can display live data, configure sensors, and download data - Build using EGUI and Rust Rocket - Should focus on ease of use for less experienced users - Should be able to clearly provide all data and provide configurability #box(width: 300.0pt, image("mockup.jpg")) \ #emph[UI Mockup from project partner] === User Documentation The user documentation will be produced in markdown or LaTeX into a PDF or webpage. This documentation will cover the basic usage of the system and instructions on how to build it. === Testing and Quality Assurance Testing will be done through TDD(test driven development) using the supported testing frameworks for rust and C. These tests will allow us as developers to ensure the assumptions we make about our code matches the actual behavior of it. Quality assurance will mostly be handled by adhearance to style standards enforced by the lanuages LSP(language server protocol) servers. The two that will see extensive use in this project being: + Rust-analyzer + clangd Bug and issue tracking will all be handled by GitHub’s Issue and project system. This also serves as a way to allow public contributions in the future to the code base. == Milestones and Timeline #figure( align(center)[#table( columns: 3, align: (col, row) => (auto,auto,auto,).at(col), inset: 6pt, [Item], [Description], [Duration], [Schematics], [The wiring schematics], [2 months], [PCB], [PCB gerber files], [1 month], [uC], [Firmware for STM], [], [Sensor FW], [Sensor module firmware], [], [UI], [Web user interface], [], [Server], [The back end web server], [], )] ) == Open questions Currently, there are no open questions in the project. == Out of scope - Support for more than the listed sensors. - HAL development - Radiation Hardening - Full EMI sheilding - Full support for 10 channels saturated with sensor data at 5kHz - Water resistance at any depth or submersion - Documentation beyond rustdocs/doxygen and markdown/latex. - Wireless connectivity beyond ad-hoc wifi. = Software Design and Architecture Document (SDA) #strong[Authors:] <NAME>, <NAME>, <NAME>, <NAME> #strong[DATE:] 2023-12-03 == Introduction This document establishes the software and hardware architecture for a personal data acquisition system. Selecting the correct architecture improves development velocity and enables more robust functionality by having systems that support each other. Cohesive Software Architecture is particularly important for this project as our workflow has contributors split into two sub teams which are developing a frontend and backend that must communicate. In addition to that, designing an appropriate hardware architecture will reduce development costs and help our product find its place in the market. == Architectural Goals and Principles Our hardware and software architectures have the primary goal of being synergistic with each other and possessing libraries that interface with each other. Because our project covers layers ranging from hardware to a website, connection throughout the stack is critical. Additionally, as we work through the prototyping stage our architecture will practice modularity to be able to add new sensor hardware as we expand the capabilities of the product. Our architecture does not need to prioritize scalability as the final objective is only to develop a prototype. == System Overview #figure([#box(width: 300.0pt, image("SystemOverview.png"));], caption: [ image ] ) == Architectural Patterns Controller Responder: This pattern is useful as our hardware SBC can act as the controller which has a single responder in the user webpage. This pattern would help cache data generated by the controller to provide a seamless experience to the user in the face of latency issues. Additionally, the ability to access data in the responder without affecting the controller will allow for computation in an environment separate from the hardware board. Event Sourcing: This pattern works especially well with real-time data, which is what this project is all about. Our hardware controller can act as the producer and broadcast its data to a web server which will act as the event source for an y users that want to query the server and consume that data. The fail-safety of this design is also important to this project as data acquisition environments, such as racing or aeronautics, often cause damage to the controller while still requiring data to be accessible. == Component Descriptions #strong[Sensors:] Hardware components that acquire the raw data, such as accelerometers o r GPS devices. #strong[Microcontroller:] Small computer that is responsible for coordinating the sensors and collecting their data to be broadcast to the web server. #strong[Web server:] Acts as the intermediary between the user and the physical acquisition device. Communicates with the board, composed of the microcontroller and its sensors, to collect data which it then relays to the user interface when queried. #strong[User interface:] An HTTP webpage that requests data from the web server to present in useful ways to the user. == Data Management Sensor readings are transmitted over canbus in JSON format. Data is stored in a relational database on the Raspberry Pi. RESTful API endpoints are provided for CRUD operations on data. == Interface Definitions There will be a user interface to collect data from each sensor and display it to the user. There will be interactions to get event logs from each sensor, and to clear the event logs. The user interface will be hosted on a web server, which users will connect to over with their browser over HTTP. API endpoints for the web interface include: - `GET /data`: Returns a list of collected data from personal devices. \ - `GET /sensors`: Returns a list of sensor configurations. \ - `POST /data`: Allows the addition of new data. \ - `PUT /data/{id}`: Updates data with a specified ID. \ - `PUT /sensors/{id}`: Configure a sensor with a specific ID. \ - `DELETE /data/{id}`: Deletes data with a specified ID. == Considerations === Security The primary data security risk in this project is data loss due to physical conditions of the board. This includes both permanent damage through the elements or impacts as well as location preventing broadcast to the web server. A caching system on both the board and in the web server is the approach that will be used to mitigate this risk. The data security risks due to bad actors in this project are minimal as the data being processed is kinematic information. Regardless, our web server will require password authentication to access the RSA encrypted data. === Performance There are two primary performance concerns of the product. The first is the resolution of our data and how quickly we can poll our sensors, for which the current target is acquiring 10 data points per second. We plan to achieve this metric by screening hardware before they are implemented into the design to ensure it can meet this desired performance. The second concern is with the stability of the connection between the user interface and the board’s raw data. We plan to create a web server that will be able to cache the data produced by the board and present to the user at will to mitigate this concern. === Maintenance and Support Once the prototype is complete, maintenance and development will be inherited by <NAME>, the company partner for this project. The company has a background in aeronautics, competitive motor racing, and computer assisted physics, all of which are relevant to the project area. Their experience with the common end users of personal data acquisition devices makes them very capable of supporting users through the life cycle of the product. == Deployment Strategy As the ultimate objective for this project is to develop a prototype PCB that hosts a local webserver as a user interface, there is only deployment in a development environment. == Testing Strategy === Software (SBC side) Testing User testing will be done to ensure users can understand and use the interface effectively. These tests should be focused on confirming that functional requirements are met. Integration testing will be done with mock data until microcontrollers and sensors are operational. Further tests will be conducted when hardware is more complete. === Firmware Testing Our firmware testing methodology will make heavy usage of mocks for many of the hardware components so we tests can be run on development machines instead of on the embedded systems. A Red Green refactoring/testing cycle will ensure we always know the tests we write are both useful and logically possible to fail. Writing any tests that cannot fail would end up being dead or uncalled code. Many of the usual tests that would be prevalent for ensuring good memory management will be unnecessary from our use of the rust language. This along with the built in `rust-docs` will allow us to even use our tests as examples where needed as part of our documentation. Integration testing will mostly be handled as mocked interfaces replicating the physical hardware that will be required to collect the data. Further tests can added as needed should more sensors be added to the project at a later point in time. == Glossary - SBC: Single Board Computer - Rust: A modern compiled and memory safe language - PCB: Printed Circuit Board = Software Development Process(SDP) #strong[Authors:] <NAME>, <NAME>, <NAME>, <NAME> #strong[DATE:] 2023-11-16 = Principles - We will respond to asynchronous communication within 24 hours - We will be at meetings on time and pay attention - All changes need to be isolated to their own git branch - Each work item need a corresponding GitHub issue - Pull Requests have to be reviewed by at least one team member - We will use a kanban board to continuously work on the backlog - Once a work item is complete, a pull request is created - Blocks need to be discussed as soon as possible = Process Task Selection: \* Kanban style \* Select highest priority item within your role’s domain To Solve an Issue and Meet Acceptance Criteria: 1. Write failing tests. 2. Write code to pass tests. 3. Repeat. 4. Open a pull-request and merge == Steps in software development + Create a github issue/milestone. + Assign github task/issue. + Create fork of repo. + Write tests using the test framework. + Push the tests to the fork (optional). + Write Code to pass the tests. + Test the code. + Push to the fork repo. + Create a pull request with description. + Get approval for the PR(pull request). == Goals & Objectives Develop a personal data acquisition system that records all the data a user might want, and is cheap and easy to set up and use. \* Record data on acceleration, force, position, etc. \* Minimal setup \* Can be hooked up to bike, go-kart, etc. == Project Scope - Design of simple UI to display data. - Design of hardware/schematics for system. - Firmware for sensor modules in rust. - SBC with rust software to store/log sensor data over CAN. = Roles #figure( align(center)[#table( columns: 3, align: (col, row) => (auto,auto,auto,).at(col), inset: 6pt, [ROLE], [PERSON], [RESPONSIBILITIES], [UI], [Blake], [Develops the web page front end], [SBC/SW], [Aidian], [Develop logic to relay sensor data to UI], [FIRMWARE], [Patrick], [Develop firmware for microcontrollers], [HARDWARE], [Jake], [Design schematics, wiring diagrams & PCB files], )] ) These are the general outlines for the four different roles in the project. We have a verbal agreement at the moment that we will help out with parts of the project outside our roles as needed. = Tooling #figure( align(center)[#table( columns: 2, align: (col, row) => (auto,auto,).at(col), inset: 6pt, [Purpose], [Name], [Version Control], [Git], [Project Management], [GitHub Projects], [Documentation], [Rustdocs & MD], [Test framework], [Rust & Cmocka], [Editor], [ANY], [Schematics & PCB], [KiCAD], [Communication], [Discord/Teams/Email], [], [], )] ) == Version Control Git will allow our team to track changes in the projects files over time. Also prevents the loss of work from hardware failures. == Project Management GitHub projects is integrated into github organizations as well as git. The project management software makes the collaboration between developers easy and will make tracking milestones and issues for the entire project across multiple repositories a possibility. == Documentation Documentation will primaily be done through the built-in rust-docs feature. This is accesiable via the CLI(command line interface) tooling. This will encapsulate how the code itself and any interfaces are documented. Because the documentation is genreated as part of the code this will ensure that up to date and accurate documentatio is always availble. Secondary documentation meant for non-developers will be done using a combination of markdown and LaTex where needed. This will be availble usally in a PDF format. == Schematics & PCB The KiCAD program gives access to the schematics and PCB designs to all team members due to the software begin free and open-source. It will allow us to comment, label and design the needed circuits for the physical hardware of the system; providing a good troubleshooting resource as well. == Communication #strong[Discord:] \* Used to coordinate team meetings. \* To share ideas/brainstorm \* give updates on project. #strong[Teams:] \* TA meetings. #strong[GITHUB:] \* To discuss project issues. \* share documentation. = Definition of Done(DOD) - Acceptance criteria all satisfied by code changes - Changes have been merged to master after completing the Pull Request Process - A completed Pull Request has at least one approval and no marks for "Needs Work" - All tests pass with changes implemented and no reversion is required - Relevant documentation for the feature has been updated - Discussion points are prepared for next meeting == TESTING #strong[Rust:] The testing for all code repositories will be done using a testing harness or framework. For rust this takes the form of the `cargo test` command, which is part of the package managment system(tool-chain). These tests will be used as one of acceptance critera for a branch to be pulled into the main branch. #strong[C:] Some libraries or areas where the use of C code is needed we plan to use cmocka as the unit testing framework. This combined with Cmake as the build system will give us a host agnostic development cycle. === Quality Assurance Quality assurance will mostly be handled by adhearance to style standards enforced by the lanuages LSP(language server protocol) servers. The two that will see extensive use in this project being: + Rust-analyzer + clangd === Feedback Feedback on the work done will take place in the github projects. The issues and discussion boards are the main locations for this, with the weekly meetings and discord being a secondary and informal medium for minor feedback. = Release Cycle For the moment we will used semantic versioning with the standard Major.minor.patch format. This will help when it comes to dealing with any major changes that break APIs. == Contingency Plans Feedback can be shared during weekly standup with the TA, or over Discord if they are more time-sensitive, after which it should be reviewed by the whole team, and then incorporated. Changes to the whole process will require more comprehensive feedback and approval from the team before going into effect, after which related documents should be modified as soon as possible. In the event of unexpected challenges, the team should be notified immediately, and if serious enough should be brought up with the TA, project partner or instructor, otherwise they should be brought up during regular meetings. = Timeline - 12/15/2023: Version 0 complete with breadboard organized hardware and visual UI elements - 03/22/2023: Version 1 complete with functionality between firmware, SBC, and UI = Environments #figure( align(center)[#table( columns: 5, align: (col, row) => (auto,auto,auto,auto,auto,).at(col), inset: 6pt, [Environment], [Infrastructure], [Deployment], [What is it for?], [Monitoring], [Production], [Github releases], [Release], [Packaging install files.], [N/A], [Staging], [Github actions], [], [], [Github Pull requests], [Development], [Local], [Github commits], [Development and unit tests of microcontroller-based sensors], [Manual], )] ) = Jake Project Presentation #include"src/jake_project_presentation.typ" = Jake Retrospective #include "src/jake_retrospective.typ" = Jake Code Review Notes #include "src/jake_code_review_notes.typ"
https://github.com/cs-24-sw-3-01/typst-documents
https://raw.githubusercontent.com/cs-24-sw-3-01/typst-documents/main/report/chapters/foundation.typ
typst
#import "../custom.typ": * #import "../sources/DionInterview.typ" == Interview Process Overview The process of gathering information began by contacting KMD to arrange interviews with relevant employees. We were granted access to four individuals across different departments. Before the interviews, our team conducted a brainstorming session to generate as many relevant questions as possible. These questions were then documented and organized into a script. Next, the team was divided into smaller groups of 2-3 people. Each group was responsible for conducting 1-2 interviews. During these interviews, we diligently recorded the interviewees' responses, ensuring that we captured both their statements and feedback in detail. After the interview sessions, we regrouped to analyze the collected data. By comparing the responses, we compiled a list of pros and cons related to the current system, along with additional suggestions and feature requests made by the interviewees. == Feature Requests and Potential Problems This chapther defines both the potential problems that KMD have with their current solution, and the features required in the new one. #todo[add a table of feature requests specifically requested by people that have been interviewed. (niche requests - to further on get a in depth analysis and thereby a greater defined design, with greater begrundelse) -Si] The different finds in this chapter was aquired through interviews with three company employees, their lead developer, <NAME>, their project portfolio manager, <NAME> and their manager of modern workplace, <NAME>, respectivley. Transcriptions of said interviews can be found in @InterviewLinda, @InterviewDion, @InterviewMats and @InterviewCaroline To find out why KMD needs a new system for managing their holiday calender i was important to find the problems with the current solution. The interviews revealed problems with synchronizing with their current SAP system. system but surprisingly most of the problems with the current system is a lack of features due to the system being developed 10 years ago. The features that are missing can be seen in @missing-features-table. \ The absence of these features and the synchronizing problems with SAP have led to most of the employees using other programs to plan their holidays with most of the active users being employees that have worked at the company for a longer time. #figure( table( align: center, columns: (auto, auto), inset: 5pt, table.header([* Missing feature *],[* Desciption *]), [Holiday balance],[The program has to display the individual employees current available absence days. Prefereably there should be a function to loan absence days from the future which then are regained throughout the year. ], [Lookup specific team],[The current system is missing a way to quickly lookup a specific team in any department, there should be a function to search for the specific team and its members.], [Create teams across departments],[Too fully utilize the teams the company should be able to create teams with members across different departments.], [Viewable Holidays],[When looking up other teams, the user should be able to see what days the members of said team are absent.], [Toggleable UI],[The user should be able to switch between different calendar types, e.g. weekly, monthly, yearly.], [synchronizing with SAP],[The new program should be able to synchronize with SAP and vice versa. The program has to use their preset absence codes.], ), caption: ("Features that are missing in the current holiday planner at KMD.") ) <missing-features-table> == PACT The PACT analysis is a framework used to understand and design systems with a focus on four key areas: People, Activities, Context, and Technology. This approach ensures that the system being developed takes into consideration the users (People), what they need to do (Activities), the environments where the system will be used (Context), and the tools or platforms (Technology) required to make the system work effectively. By analyzing these four elements, a PACT analysis helps in designing systems that are user-centered, context-aware, and equipped with the right technology, ultimately enhancing the user experience and ensuring the system meets the needs of its intended audience @DEBBook. === People The users comprise all employees of KMD. This includes employees of various roles, such as software developers, financial analysts, human relations, administrative staff, and employees of different nationalities, mainly Danish and Polish. These users need to be able to intuitively record their vacation days, in a simple system. Furthermore they need to be able to compose teams of employees from different departments, for cross-department projects. At last, they need to be able to manually register vacation, since they sometimes do not have accrued enough vacation days in their SAP SucessFactors system. These users also have varying levels of technical proficiency. Therefore the systems interface must be intuitive for both technical and non-technical staff. === Activities The primary activities of the system, will that of recording vacations days accompanied by the vacation reason and being able to compose teams consisting of employees from different departments. Users will firstly log in with their company supplied Microsoft account, whereafter they can either register vaction, select a team to see their vacation days, or record new vacation days. The system will be engaged with regularly, especically during the peak vacation periods. Project managers usually check it multiple times a week, to know they status of their team. === Context The vacation planner will be accessible from all locations with internet connectivity, including at home, the office, or on the go with smartphones. This should happen trough a secure VPN with gives access to te local server. Furthermore the product will facilitate collaboration among employees of different departments, allowing them to get a better overview of their teams. The useres will consist of both Danish and Polish users, which arises some cultural differences, including the specific holidays of Denmark and Poland, as well as varying approaches to vacation planning, communication styles and workplace expectations. === Technologies The users are currently using a mix of the old vacation planner (the one being rewritten in this project), Outlook Calender, and SAP SuccessFactors. They will continue to use Outlook Calender for meetings, and SAP SuccessFactors for primary vacation planning. The vacation planner system will merely be a way of viewing the vacation registered in SAP SuccessFactors, with the ability to override by manually registering vacations, when not possible in SAP SuccessFactors. This system is built with C\# and a Microsoft SQL database. \ \ The new system will be built using Java with Spring Boot for the API, and React for the frontend, ensuring the ability to create a modern and responsive webapplication. For persistence, PostgreSQL will be used to efficiently and reliably store user data. It needs to integrate with SAP SuccessFactors to be able to show the vacation registered there. Furthermore it must also integrate with Microsoft Entra Id, to be able to authenticate the users. == FACTOR The FACTOR model has been applied to the absence calendar system to ensure a comprehensive analysis of the key components and requirements needed for successful implementation. The FACTOR model provides a structured approach to identifying the system’s functionality, the domain in which it operates, the conditions of development, the technologies involved, the objects that are central to the system, and the overall responsibilities @SUBook. By using this model, we aim to clearly define how our system will function within the organizational context of KMD. It is important to note that the T in Factor differs from the T in the PACT model. The T in the FACTOR model is the technologies used to develop the system aswell as the technology that the system will run on @SUBook, where the T in PACT can be broken down into four categories, Input, Output, Communcation and Content @DEBBook. === F - (Functionality) The system will be used by employees to register absence and view absence for themselves and their teams. In addition to this basic functionality, employees must be able to specify the type of absence, such as vacation, sick leave, or other reasons, as well as indicate the duration of the absence. The system will also allow employees to create, modify, and delete teams, enabling efficient organization of team members according to department or project requirements. Team members can view each other's absence schedules to help avoid overlapping leave periods and ensure optimal staffing levels. === A - (Application domain) The application falls under the domain of human resource management, specifically focusing on absence tracking and planning within an organization. It is designed to facilitate self-service absence management for employees while also providing oversight capabilities for managers. It supports both individual users who wish to manage their absences and managers who need to monitor the availability of their teams. === C - (Conditions) The system is being developed by a team of bachelor software students in cooperation with KMD employees, who provide the necessary knowledge and information regarding company-specific requirements. Additionally, the system must be versatile enough to accommodate users with varying levels of IT experience. It will be accessible from a variety of devices, including desktops, tablets, and mobile phones, allowing users to engage with the system in the most convenient manner possible. === T - (Technology) The system will be developed as a web application, with a client-side interface that runs on each user's device and communicates with a server, over a wireless private network. The server will host the system's logic and maintain the database. The backend application will utilize a RESTful API, implemented in Java using the popular framework "spring boot", while the frontend will be developed using frameworks like React to ensure a responsive and user-friendly interface. Data concerning employees, absences, and teams will be managed through a relational database named PostgreSQL. === O - (Objects) The objects within the system are Teams, Employees, Absence periods and Team members. === R - (Responsibility) The system is intended to ensure transparency in absence management across the organization. It provides a clear view of team members' absence schedules, helping to prevent scheduling conflicts and enabling better planning for upcoming work periods. The system has to be able to integrate with KMD's current SAP system. communcation between SAP and the system should go both ways, so the SAP data should be able to be imported to the system and vice versa. == System Definition The KMD Vacation Planner is a software solution that allows KMD employees to efficiently manage and track absences and vacations. It imports absence and vacation data from SAP SuccessFactors and displays it in the vacation planner. The system also enables users to manually register absences or vacations without requiring management approval. Teams can be created across different departments, facilitating cross-department collaboration. The system is accessible through authentication via Microsoft Entra ID and is built using Java Spring Boot for the backend and React/TypeScript for the frontend, with PostgreSQL used for data persistence. The system also accommodates cultural differences, particularly between Danish and Polish employees, by supporting Polish and Danish holidays. == Requirements == Functional and Non-Functional Requirements This section describes what the system should do, organized around specific functionalities, and provides a description of the essential functions and behaviors required @functionalRequirementsJama. The first User Management as each employee should already be registered in the system due to the integration that we will implement with KMD's internal system. That means that each employee can already access their own calendar and make teams from the get-go, they do not need to register. This also makes sure that every employee has access to their personal calendar and its functionalities as soon as they go on the application #todo("interview som source"). Next is Vacation & Sick Day Management where users submit time off by selecting the date and type of vacation that depends on whether the employee is danish or polish. Users should also be able to modify or cancel these inserts. Another requirement is Team Creation and Management within the calendar. A user can create a team by adding a group of employees they want as team members, where the creator automatically is assigned as the team administrator. This team allows all team members to view one another’s calendars in one—even if they belong to different departments. If a team creator no longer wants to hold the administrator role, they can transfer it to another team member. Additionally, employees can belong to multiple teams at the same time, so it is not limited to one team per employee for flexibility and management for those involved in more projects. Lastly, a requirement is that the count of vacation days should be visible for the employee so that they have an overview of how many days they are allowed to take off. This is where the loan comes in to play, as an employee might borrow vacation days that they will save up at a later time to pay be able to off eventually @InterviewDion . The system must also meet specific Non-Functional Requirements that describe its operational qualities, so this is an explanation of the quality attributes or performance criteria the system must meet @functionalRequirementsJama. Reliability is a primary consideration; the vacation system should handle several inputs without slowing down. This is especially important during peak times like holiday seasons. Response times for submitting requests should ideally remain under 2 seconds. Scalability is also important to accommodate future growth so this is also a requirement @Erb2012. The application should be able to support more users, teams, and departments as the company expands or changes.
https://github.com/HenkKalkwater/aoc-2023
https://raw.githubusercontent.com/HenkKalkwater/aoc-2023/master/aoc.typ
typst
#let year = 2023 #let stars = (body) => [ #set text(fill: rgb("#ffff66")) #body ] #let date-disp = (c) => datetime(year: year, month: 12, day: c).display("[weekday], [day padding:none] [month repr:long]") #let appendix-numbering = (..args) => [Appendix #numbering("A:", ..args)] #let appendix = (..args) => heading(supplement: [Appendix], numbering: appendix-numbering, ..args) #let day-part = (day, part, input-file, visualise: false) => [ #let story-file = "parts/day-" + str(day) + "-" + str(part) + "-story.typ" #let file = "parts/day-" + str(day) + "-" + str(part) + ".typ" #let input = read(input-file) == Part #{part} #include story-file #import file: solve #let answ = solve(input) #if type(answ) == dictionary and answ.at("value", default: none) != none [ My answer is: #raw(repr(answ.at("value"))) #if visualise [ #answ.at("visualisation", default: []) ] ] else [ My answer is: #raw(repr(answ)) ] The source code for the answer is: #raw(read(file), lang: "typ", block: true) ] #let day = (day, solved-parts: 0) => [ #pagebreak() #metadata(( day: day, input: solved-parts > 0 )) <day-meta> = #date-disp(day) #let input-file = "parts/day-" + str(day) + "-input.txt" #for part in range(1, solved-parts + 1) [ #day-part(day, part, input-file) ] #if solved-parts == 0 [ To begin, #link("https://adventofcode.com/" + str(year) + "/day/" + str(day) + "/input")[get your puzzle input] ] else { locate(loc => [ #let appendices = query(heading.where(supplement: [Appendix]), loc) #if appendices == () [ To begin, #link("https://adventofcode.com/" + str(year) + "/day/" + str(day) + "/input")[get your puzzle input] ] else [ #let number = numbering("A.", day) The puzzle input can be found in #link(appendices.at(day - 1).location())[Appendix #number] ] ]) } #if solved-parts == 1 { stars[The first half of this puzzle is complete! It provides one gold star: \*] } else if solved-parts == 2 { stars[Both parts of this puzzle are complete! They provide two gold stars: \*\*] } ] #let template = (title: "", year: 2023, body) => [ #set text( font: ("Source Code Pro", "monospace"), fill: rgb("#cccccc") ) #set page( background: rect(width: 100%, height: 100%, fill: rgb("#0f0f23")) ) #set heading(numbering: none) #show heading.where(level: 1): set text(fill: rgb("#00cc00")) #show heading.where(level: 2): it => [ #set text(fill: rgb("#ffffff")) \-\-\- #it.body \-\-\- ] #show outline.entry.where( level: 1 ): it => { v(12pt, weak: true) set text(fill: rgb("#009900")) it } #show link: set text(fill: rgb("#009900")) #show raw.where(block: false): box.with( fill: rgb("#10101a"), stroke: rgb("#333340"), inset: (x: 0.25em, y: 0.1em), outset: (x: 0.25em) ) #let raw-line-disp = it-line => style( styles => box( grid( columns: 2, rows: 1, column-gutter: 1em, box( width: measure([#it-line.count], styles).width, [ #set align(right) #set text(fill: rgb("#ffff88")) #(str(it-line.number) + " ") ] ), it-line.body ) ) ) #show raw.where(block: true): it-raw => block( fill: rgb("#10101a"), stroke: rgb("#333340"), inset: (x: 1em, y: 1em), if it-raw.lang != none [ #show raw.line: raw-line-disp #it-raw ] else [ #it-raw ] ) #heading(title, numbering: none, outlined: false) #body #pagebreak() #locate(loc => { for day-meta in query(<day-meta>, loc) { let input = day-meta.value.at("input", default: none) let day = day-meta.value.at("day") if input [ #appendix[Input for #date-disp(day)] #raw(read("parts/day-" + str(day) + "-input.txt"), block: true) ] } }) ]
https://github.com/giZoes/justsit-thesis-typst-template
https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/utils/hline.typ
typst
MIT License
// 一条水平横线 #let hline() = { line(length: 100%) }
https://github.com/MatejKafka/ctu-thesis-typst
https://raw.githubusercontent.com/MatejKafka/ctu-thesis-typst/main/README.md
markdown
# ctu-thesis-typst Typst template for an IT thesis at the Czech Technical University in Prague. Originally from FEE, might need some tweaking to meet the guidelines of other faculties. To use the template, just clone the repository locally or upload it to a new project in the Typst web app, copy `example.typ`, adjust the metadata block at the top and then start writing your thesis below. In the web app, everything should automatically work. For local compilation, you must set a path to the font directory used for the title page when compiling: ```sh typst compile --font-path ./template/res/fonts ./example.typ ``` If you don't, the title page will be mostly blank, except for the CTU logo. ## Example To view the output of the template, see [example.pdf](./example.pdf), which is compiled from `example.typ` using Typst v0.11.1. For a more complex example, see my thesis, which uses this template: https://typst.app/project/rlLOElGGPtW50kb2HFsT1- ## Issues You might be wondering what's up with the "assignment page 1" and "assignment page 2" in the output. I would prefer to insert the assignment of the thesis here, but Typst does not support embedding of other PDFs yet. Instead, when submitting the thesis, I exported the PDF and then used `qpdf` to replace the placeholder pages with the actual assignment, which works out OK since `qpdf` correctly preserves metadata such as the outline (unlike most other free PDF tools): ```sh qpdf typst-export.pdf --pages . 1 assignment.pdf 1-z . 5 . 7-z -- out.pdf ```
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-FF00.typ
typst
Apache License 2.0
#let data = ( (), ("FULLWIDTH EXCLAMATION MARK", "Po", 0), ("FULLWIDTH QUOTATION MARK", "Po", 0), ("FULLWIDTH NUMBER SIGN", "Po", 0), ("FULLWIDTH DOLLAR SIGN", "Sc", 0), ("FULLWIDTH PERCENT SIGN", "Po", 0), ("FULLWIDTH AMPERSAND", "Po", 0), ("FULLWIDTH APOSTROPHE", "Po", 0), ("FULLWIDTH LEFT PARENTHESIS", "Ps", 0), ("FULLWIDTH RIGHT PARENTHESIS", "Pe", 0), ("FULLWIDTH ASTERISK", "Po", 0), ("FULLWIDTH PLUS SIGN", "Sm", 0), ("FULLWIDTH COMMA", "Po", 0), ("FULLWIDTH HYPHEN-MINUS", "Pd", 0), ("FULLWIDTH FULL STOP", "Po", 0), ("FULLWIDTH SOLIDUS", "Po", 0), ("FULLWIDTH DIGIT ZERO", "Nd", 0), ("FULLWIDTH DIGIT ONE", "Nd", 0), ("FULLWIDTH DIGIT TWO", "Nd", 0), ("FULLWIDTH DIGIT THREE", "Nd", 0), ("FULLWIDTH DIGIT FOUR", "Nd", 0), ("FULLWIDTH DIGIT FIVE", "Nd", 0), ("FULLWIDTH DIGIT SIX", "Nd", 0), ("FULLWIDTH DIGIT SEVEN", "Nd", 0), ("FULLWIDTH DIGIT EIGHT", "Nd", 0), ("FULLWIDTH DIGIT NINE", "Nd", 0), ("FULLWIDTH COLON", "Po", 0), ("FULLWIDTH SEMICOLON", "Po", 0), ("FULLWIDTH LESS-THAN SIGN", "Sm", 0), ("FULLWIDTH EQUALS SIGN", "Sm", 0), ("FULLWIDTH GREATER-THAN SIGN", "Sm", 0), ("FULLWIDTH QUESTION MARK", "Po", 0), ("FULLWIDTH COMMERCIAL AT", "Po", 0), ("FULLWIDTH LATIN CAPITAL LETTER A", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER B", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER C", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER D", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER E", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER F", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER G", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER H", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER I", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER J", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER K", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER L", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER M", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER N", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER O", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER P", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER Q", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER R", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER S", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER T", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER U", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER V", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER W", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER X", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER Y", "Lu", 0), ("FULLWIDTH LATIN CAPITAL LETTER Z", "Lu", 0), ("FULLWIDTH LEFT SQUARE BRACKET", "Ps", 0), ("FULLWIDTH REVERSE SOLIDUS", "Po", 0), ("FULLWIDTH RIGHT SQUARE BRACKET", "Pe", 0), ("FULLWIDTH CIRCUMFLEX ACCENT", "Sk", 0), ("FULLWIDTH LOW LINE", "Pc", 0), ("FULLWIDTH GRAVE ACCENT", "Sk", 0), ("FULLWIDTH LATIN SMALL LETTER A", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER B", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER C", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER D", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER E", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER F", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER G", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER H", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER I", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER J", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER K", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER L", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER M", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER N", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER O", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER P", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER Q", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER R", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER S", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER T", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER U", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER V", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER W", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER X", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER Y", "Ll", 0), ("FULLWIDTH LATIN SMALL LETTER Z", "Ll", 0), ("FULLWIDTH LEFT CURLY BRACKET", "Ps", 0), ("FULLWIDTH VERTICAL LINE", "Sm", 0), ("FULLWIDTH RIGHT CURLY BRACKET", "Pe", 0), ("FULLWIDTH TILDE", "Sm", 0), ("FULLWIDTH LEFT WHITE PARENTHESIS", "Ps", 0), ("FULLWIDTH RIGHT WHITE PARENTHESIS", "Pe", 0), ("HALFWIDTH IDEOGRAPHIC FULL STOP", "Po", 0), ("HALFWIDTH LEFT CORNER BRACKET", "Ps", 0), ("HALFWIDTH RIGHT CORNER BRACKET", "Pe", 0), ("HALFWIDTH IDEOGRAPHIC COMMA", "Po", 0), ("HALFWIDTH KATAKANA MIDDLE DOT", "Po", 0), ("HALFWIDTH KATAKANA LETTER WO", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SMALL A", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SMALL I", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SMALL U", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SMALL E", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SMALL O", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SMALL YA", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SMALL YU", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SMALL YO", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SMALL TU", "Lo", 0), ("HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK", "Lm", 0), ("HALFWIDTH KATAKANA LETTER A", "Lo", 0), ("HALFWIDTH KATAKANA LETTER I", "Lo", 0), ("HALFWIDTH KATAKANA LETTER U", "Lo", 0), ("HALFWIDTH KATAKANA LETTER E", "Lo", 0), ("HALFWIDTH KATAKANA LETTER O", "Lo", 0), ("HALFWIDTH KATAKANA LETTER KA", "Lo", 0), ("HALFWIDTH KATAKANA LETTER KI", "Lo", 0), ("HALFWIDTH KATAKANA LETTER KU", "Lo", 0), ("HALFWIDTH KATAKANA LETTER KE", "Lo", 0), ("HALFWIDTH KATAKANA LETTER KO", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SA", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SI", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SU", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SE", "Lo", 0), ("HALFWIDTH KATAKANA LETTER SO", "Lo", 0), ("HALFWIDTH KATAKANA LETTER TA", "Lo", 0), ("HALFWIDTH KATAKANA LETTER TI", "Lo", 0), ("HALFWIDTH KATAKANA LETTER TU", "Lo", 0), ("HALFWIDTH KATAKANA LETTER TE", "Lo", 0), ("HALFWIDTH KATAKANA LETTER TO", "Lo", 0), ("HALFWIDTH KATAKANA LETTER NA", "Lo", 0), ("HALFWIDTH KATAKANA LETTER NI", "Lo", 0), ("HALFWIDTH KATAKANA LETTER NU", "Lo", 0), ("HALFWIDTH KATAKANA LETTER NE", "Lo", 0), ("HALFWIDTH KATAKANA LETTER NO", "Lo", 0), ("HALFWIDTH KATAKANA LETTER HA", "Lo", 0), ("HALFWIDTH KATAKANA LETTER HI", "Lo", 0), ("HALFWIDTH KATAKANA LETTER HU", "Lo", 0), ("HALFWIDTH KATAKANA LETTER HE", "Lo", 0), ("HALFWIDTH KATAKANA LETTER HO", "Lo", 0), ("HALFWIDTH KATAKANA LETTER MA", "Lo", 0), ("HALFWIDTH KATAKANA LETTER MI", "Lo", 0), ("HALFWIDTH KATAKANA LETTER MU", "Lo", 0), ("HALFWIDTH KATAKANA LETTER ME", "Lo", 0), ("HALFWIDTH KATAKANA LETTER MO", "Lo", 0), ("HALFWIDTH KATAKANA LETTER YA", "Lo", 0), ("HALFWIDTH KATAKANA LETTER YU", "Lo", 0), ("HALFWIDTH KATAKANA LETTER YO", "Lo", 0), ("HALFWIDTH KATAKANA LETTER RA", "Lo", 0), ("HALFWIDTH KATAKANA LETTER RI", "Lo", 0), ("HALFWIDTH KATAKANA LETTER RU", "Lo", 0), ("HALFWIDTH KATAKANA LETTER RE", "Lo", 0), ("HALFWIDTH KATAKANA LETTER RO", "Lo", 0), ("HALFWIDTH KATAKANA LETTER WA", "Lo", 0), ("HALFWIDTH KATAKANA LETTER N", "Lo", 0), ("HALFWIDTH KATAKANA VOICED SOUND MARK", "Lm", 0), ("HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK", "Lm", 0), ("HALFWIDTH HANGUL FILLER", "Lo", 0), ("HALFWIDTH HANGUL LETTER KIYEOK", "Lo", 0), ("HALFWIDTH HANGUL LETTER SSANGKIYEOK", "Lo", 0), ("HALFWIDTH HANGUL LETTER KIYEOK-SIOS", "Lo", 0), ("HALFWIDTH HANGUL LETTER NIEUN", "Lo", 0), ("HALFWIDTH HANGUL LETTER NIEUN-CIEUC", "Lo", 0), ("HALFWIDTH HANGUL LETTER NIEUN-HIEUH", "Lo", 0), ("HALFWIDTH HANGUL LETTER TIKEUT", "Lo", 0), ("HALFWIDTH HANGUL LETTER SSANGTIKEUT", "Lo", 0), ("HALFWIDTH HANGUL LETTER RIEUL", "Lo", 0), ("HALFWIDTH HANGUL LETTER RIEUL-KIYEOK", "Lo", 0), ("HALFWIDTH HANGUL LETTER RIEUL-MIEUM", "Lo", 0), ("HALFWIDTH HANGUL LETTER RIEUL-PIEUP", "Lo", 0), ("HALFWIDTH HANGUL LETTER RIEUL-SIOS", "Lo", 0), ("HALFWIDTH HANGUL LETTER RIEUL-THIEUTH", "Lo", 0), ("HALFWIDTH HANGUL LETTER RIEUL-PHIEUPH", "Lo", 0), ("HALFWIDTH HANGUL LETTER RIEUL-HIEUH", "Lo", 0), ("HALFWIDTH HANGUL LETTER MIEUM", "Lo", 0), ("HALFWIDTH HANGUL LETTER PIEUP", "Lo", 0), ("HALFWIDTH HANGUL LETTER SSANGPIEUP", "Lo", 0), ("HALFWIDTH HANGUL LETTER PIEUP-SIOS", "Lo", 0), ("HALFWIDTH HANGUL LETTER SIOS", "Lo", 0), ("HALFWIDTH HANGUL LETTER SSANGSIOS", "Lo", 0), ("HALFWIDTH HANGUL LETTER IEUNG", "Lo", 0), ("HALFWIDTH HANGUL LETTER CIEUC", "Lo", 0), ("HALFWIDTH HANGUL LETTER SSANGCIEUC", "Lo", 0), ("HALFWIDTH HANGUL LETTER CHIEUCH", "Lo", 0), ("HALFWIDTH HANGUL LETTER KHIEUKH", "Lo", 0), ("HALFWIDTH HANGUL LETTER THIEUTH", "Lo", 0), ("HALFWIDTH HANGUL LETTER PHIEUPH", "Lo", 0), ("HALFWIDTH HANGUL LETTER HIEUH", "Lo", 0), (), (), (), ("HALFWIDTH HANGUL LETTER A", "Lo", 0), ("HALFWIDTH HANGUL LETTER AE", "Lo", 0), ("HALFWIDTH HANGUL LETTER YA", "Lo", 0), ("HALFWIDTH HANGUL LETTER YAE", "Lo", 0), ("HALFWIDTH HANGUL LETTER EO", "Lo", 0), ("HALFWIDTH HANGUL LETTER E", "Lo", 0), (), (), ("HALFWIDTH HANGUL LETTER YEO", "Lo", 0), ("HALFWIDTH HANGUL LETTER YE", "Lo", 0), ("HALFWIDTH HANGUL LETTER O", "Lo", 0), ("HALFWIDTH HANGUL LETTER WA", "Lo", 0), ("HALFWIDTH HANGUL LETTER WAE", "Lo", 0), ("HALFWIDTH HANGUL LETTER OE", "Lo", 0), (), (), ("HALFWIDTH HANGUL LETTER YO", "Lo", 0), ("HALFWIDTH HANGUL LETTER U", "Lo", 0), ("HALFWIDTH HANGUL LETTER WEO", "Lo", 0), ("HALFWIDTH HANGUL LETTER WE", "Lo", 0), ("HALFWIDTH HANGUL LETTER WI", "Lo", 0), ("HALFWIDTH HANGUL LETTER YU", "Lo", 0), (), (), ("HALFWIDTH HANGUL LETTER EU", "Lo", 0), ("HALFWIDTH HANGUL LETTER YI", "Lo", 0), ("HALFWIDTH HANGUL LETTER I", "Lo", 0), (), (), (), ("FULLWIDTH CENT SIGN", "Sc", 0), ("FULLWIDTH POUND SIGN", "Sc", 0), ("FULLWIDTH NOT SIGN", "Sm", 0), ("FULLWIDTH MACRON", "Sk", 0), ("FULLWIDTH BROKEN BAR", "So", 0), ("FULLWIDTH YEN SIGN", "Sc", 0), ("FULLWIDTH WON SIGN", "Sc", 0), (), ("HALFWIDTH FORMS LIGHT VERTICAL", "So", 0), ("HALFWIDTH LEFTWARDS ARROW", "Sm", 0), ("HALFWIDTH UPWARDS ARROW", "Sm", 0), ("HALFWIDTH RIGHTWARDS ARROW", "Sm", 0), ("HALFWIDTH DOWNWARDS ARROW", "Sm", 0), ("HALFWIDTH BLACK SQUARE", "So", 0), ("HALFWIDTH WHITE CIRCLE", "So", 0), )
https://github.com/weeebdev/cv
https://raw.githubusercontent.com/weeebdev/cv/main/modules_ru/projects.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Проекты и ассоциации") #cvEntry( title: [Волонтер-переводчик], society: [WikigapKazakhstan, Wikipedia], date: [Мар 2021 - Апр 2021], location: [Алматы, Казахстан], description: list( [Участвовал в проекте \#WikigapKazakhstan для устранения гендерного неравенства на Википедии], ) ) #cvEntry( title: [Волонтер-переводчик], society: [notabenoid], date: [Июл 2026 - Настоящее время], location: [Удаленно], description: list( [Периодически перевожу шоу/книги/игры и т.д. в закрытом сообществе переводчиков notabenoid.org] ) ) #cvEntry( title: [Волонтер-разработчик], society: [GitHub], date: [Июл 2019 - Настоящее время], location: [Удаленно], description: list( [Регистрация багов и функций в различных проектах], [Решение этих задач], [Участие в обсуждениях], [Создание собственных проектов], ) )
https://github.com/kdog3682/mathematical
https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/examples/convex-hull-attempt-3.typ
typst
#import "@local/typkit:0.1.0": * #import "@preview/cetz:0.2.2" #let graham_scan(points) = { // Helper function to calculate cross product let cross_product(o, a, b) = { return (a.at(0) - o.at(0)) * (b.at(1) - o.at(1)) - (a.at(1) - o.at(1)) * (b.at(0) - o.at(0)) } // Sort points lexicographically let sorted_points = points.sorted(key: p => (p.at(0), p.at(1))) let n = sorted_points.len() if n <= 3 { return sorted_points } // Build lower hull let lower = () for p in sorted_points { while lower.len() >= 2 and cross_product(lower.at(-2), lower.at(-1), p) <= 0 { lower.pop() } lower.push(p) } // Build upper hull let upper = () for p in sorted_points.rev() { while upper.len() >= 2 and cross_product(upper.at(-2), upper.at(-1), p) <= 0 { upper.pop() } upper.push(p) } // Concatenate hulls lower.pop() upper.pop() return lower + upper } #let paired-points(hull) = { let store = () let l = hull.len() for i in range(l) { let p1 = hull.at(i) let p2 = hull.at(calc.rem(i + 1, l)) store.push((p1, p2)) } return store } #let angle-between-points(p1, p2) = { // the ordering of (p1 and p2) MATTERS let dx = p2.at(0) - p1.at(0) let dy = p2.at(1) - p1.at(1) let angle = calc.atan2(dy, dx) return angle } #let get-brace-content-angle(p1, p2) = { let angle = angle-between-points(p1, p2) - 90deg if angle < -180deg { angle += 180deg } return angle } #let offset_point(p1, p2, offset) = { let dx = p2.at(0) - p1.at(0) let dy = p2.at(1) - p1.at(1) let length = hyp(dx, dy) let ux = -dy / length let uy = dx / length return (p1.at(0) + offset * ux, p1.at(1) + offset * uy) } #let draw_flat_brace(p1, p2, offset: 0.5, side: "outside", rotate-content: true, end_length: 0.3, ..sink) = { // the offset is very important // otherwise it will overlap on the line let k = if side == "outside" { 1 } else { -1 } let m1 = offset_point(p1, p2, -k * offset) let m2 = offset_point(p2, p1, k * offset) // let perp1 = offset_point(m1, m2, end_length) // let perp2 = offset_point(m1, m2, -end_length) // let perp3 = offset_point(m2, m1, end_length) // let perp4 = offset_point(m2, m1, -end_length) // canvas.draw.line(perp1, perp2, stroke: green) // canvas.draw.line(m1, m2, stroke: green) // this stuff is for drawing a custom brace: |--------| let brace-attrs = sink.named() let content = resolve-sink-content(sink) cetz.decorations.brace(m1, m2, flip: true, name: "brace", ..brace-attrs) if content != none and rotate-content == true { let angle = get-brace-content-angle(m1, m2) content = typst.rotate(content, angle) } // cetz.draw.content("brace.content", content) } /// #example(``` /// line((0,0), (1,1), name: "l") /// get-ctx(ctx => { /// // Get the vector of coordinate "l.start" and "l.end" /// let (ctx, a, b) = cetz.coordinate.resolve(ctx, "l.start", "l.end") /// content("l.start", [#a], frame: "rect", stroke: none, fill: white) /// content("l.end", [#b], frame: "rect", stroke: none, fill: white) /// }) /// ```) /// /// - ctx (context): Canvas context object /// - ..coordinates (coordinate): List of coordinates /// - update (bool): Update the context's last position /// -> (ctx, vector..) Returns a list of the new context object plus the /// resolved coordinate vectors // /// input #let convex-hull-display(points) = { let hull = graham_scan(points) draw.canvas({ // Plot all points draw.points(points, fill: blue) draw.polygon(hull, stroke: red) // Draw braces for the hull let hull-points = paired-points(hull) for (i, pair) in hull-points.enumerate() { draw_flat_brace(..pair, i + 1) } }) } #let points = ( (0, 0), (1, 1), (2, 2), (3, 1), (4, 0), (3, 3), (2, 4), (1, 3), (2, 1), (10, 10) ) #convex-hull-display(points)
https://github.com/fufexan/cv
https://raw.githubusercontent.com/fufexan/cv/typst/modules/experience.typ
typst
#import "../src/template.typ": * #show link: underline #cvSection("Experience") #cvEntry( title: [Contracting], society: [NixOS Foundation], logo: "../src/logos/nixos.svg", date: [2021, 2022], location: [Remote], description: list( [Took part in a team of participants to package NGI (Next Generation Internet) applications with #link("https://nixos.org")[Nix] for the #link("https://summer.nixos.org")[Summer of Nix] program, as well as developing dream2nix and improving the overall Nix/NixOS documentation], [Improved documentation of several areas of the #link("https://nixos.wiki")[NixOS Wiki]], [Created publicly-available flakes accessible on the #link("https://github.com/ngi-nix")[NGI-Nix organization]], ) ) #cvEntry( title: [Apprenticeship], society: [Digital Nation], logo: "../src/logos/dn.jpg", date: [2019 - 2020], location: [Remote], description: list( [Participated as an apprentice in the #link("https://generatiatech.ro")[Generația Tech] program], [Learned PHP development using WordPress themes & plugins, under the guidance of skilled mentors], [Learned JavaScript back-end and front-end development, Firebase management and integration], [Was local ambassador for the Alba county regional group. Participated in team management, administration, logistics], ) )
https://github.com/galaxia4Eva/galaxia4Eva
https://raw.githubusercontent.com/galaxia4Eva/galaxia4Eva/main/typst/Buddhanov smiles — Akiyar is calling/album_cover.typ
typst
#set text(fill:white, size:96pt) #set image(width:941pt, height:1255pt) #set page(width:941pt, height:941pt, margin: 0pt, background: image("media/album_cover.jpeg")) #stack(dir:ttb)[ #v(42pt) #align(center)[ #text(font:"Samarkan", fill:rgb(255, 215, 0))[Buddha'nov smiles] ] #v(42pt) #v(42pt) #v(42pt) #v(42pt) #v(42pt) #align(center)[ #text(font:"Bulan Ramadhan", fill:rgb(0, 87, 183))[Akiyar is callinG] ] ]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/document-05.typ
typst
Other
#box[ // Error: 4-32 document set rules are not allowed inside of containers #set document(title: "Hello") ]
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2019/MS-04.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (1 - 32)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [1], [<NAME>], [CHN], [3647], [2], [<NAME>], [CHN], [3500], [3], [<NAME>], [CHN], [3301], [4], [<NAME>], [CHN], [3293], [5], [<NAME>], [JPN], [3269], [6], [<NAME>], [CHN], [3255], [7], [<NAME>], [GER], [3216], [8], [MIZUTANI Jun], [JPN], [3134], [9], [#text(gray, "<NAME>")], [CHN], [3104], [10], [<NAME>], [BRA], [3096], [11], [<NAME>], [KOR], [3095], [12], [<NAME>], [CHN], [3079], [13], [KANAMITSU Koyo], [JPN], [3077], [14], [<NAME>-Ju], [TPE], [3067], [15], [<NAME>], [BLR], [3051], [16], [FANG Bo], [CHN], [3036], [17], [YAN An], [CHN], [3027], [18], [OVTCHAROV Dimitrij], [GER], [3023], [19], [<NAME>], [SWE], [3016], [20], [<NAME>], [ENG], [3011], [21], [<NAME>], [CHN], [3002], [22], [JEOUNG Youngsik], [KOR], [2975], [23], [<NAME>], [CHN], [2970], [24], [<NAME>], [GER], [2966], [25], [LIM Jonghoon], [KOR], [2964], [26], [NIWA Koki], [JPN], [2964], [27], [<NAME>ihao], [CHN], [2955], [28], [<NAME>iyang], [CHN], [2955], [29], [<NAME>], [JPN], [2947], [30], [<NAME>], [CHN], [2934], [31], [<NAME>], [GER], [2931], [32], [#text(gray, "<NAME>")], [KOR], [2927], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (33 - 64)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [33], [<NAME>], [JPN], [2913], [34], [UEDA Jin], [JPN], [2910], [35], [<NAME>], [KOR], [2901], [36], [FREITAS Marcos], [POR], [2896], [37], [<NAME>], [BEL], [2894], [38], [OSHIMA Yuya], [JPN], [2888], [39], [<NAME>], [CRO], [2884], [40], [<NAME>], [JPN], [2881], [41], [CHUANG Chih-Yuan], [TPE], [2871], [42], [<NAME> Su], [KOR], [2863], [43], [<NAME>], [CHN], [2856], [44], [XU Chenhao], [CHN], [2853], [45], [<NAME>], [SWE], [2850], [46], [<NAME>], [GER], [2846], [47], [<NAME>], [AUT], [2838], [48], [<NAME>], [SLO], [2837], [49], [<NAME>], [JPN], [2837], [50], [<NAME>], [FRA], [2832], [51], [SHIBAEV Alexander], [RUS], [2832], [52], [<NAME>], [IRI], [2829], [53], [<NAME>], [CRO], [2827], [54], [<NAME>], [IND], [2822], [55], [<NAME>], [FRA], [2812], [56], [ZHAO Zihao], [CHN], [2812], [57], [<NAME>], [FRA], [2808], [58], [<NAME>], [KOR], [2806], [59], [CHEN Chien-An], [TPE], [2806], [60], [WONG Chun Ting], [HKG], [2806], [61], [<NAME>], [JPN], [2797], [62], [WANG Yang], [SVK], [2796], [63], [ZHAI Yujia], [DEN], [2795], [64], [IONESCU Ovidiu], [ROU], [2795], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (65 - 96)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [65], [<NAME>], [SWE], [2788], [66], [<NAME>], [IND], [2788], [67], [TAKAKIWA Taku], [JPN], [2787], [68], [<NAME>], [CZE], [2787], [69], [GIONIS Panagiotis], [GRE], [2782], [70], [<NAME>], [SWE], [2782], [71], [<NAME>], [SWE], [2781], [72], [<NAME>], [GER], [2779], [73], [XUE Fei], [CHN], [2772], [74], [ZHOU Kai], [CHN], [2771], [75], [OIKAWA Mizuki], [JPN], [2765], [76], [<NAME>], [GER], [2765], [77], [QIU Dang], [GER], [2761], [78], [MURAMATSU Yuto], [JPN], [2761], [79], [WANG Eugene], [CAN], [2760], [80], [LIND Anders], [DEN], [2759], [81], [KOU Lei], [UKR], [2759], [82], [MA Te], [CHN], [2750], [83], [JHA Kanak], [USA], [2749], [84], [LUNDQVIST Jens], [SWE], [2748], [85], [<NAME>], [NGR], [2747], [86], [WALKER Samuel], [ENG], [2746], [87], [<NAME>], [POL], [2743], [88], [<NAME>], [DEN], [2741], [89], [<NAME>], [SVK], [2741], [90], [AKKUZU Can], [FRA], [2736], [91], [<NAME>], [BRA], [2729], [92], [<NAME>], [KAZ], [2728], [93], [<NAME>], [SLO], [2727], [94], [<NAME>], [POR], [2727], [95], [<NAME>], [ECU], [2724], [96], [<NAME>], [SWE], [2723], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (97 - 128)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [97], [BADOWSKI Marek], [POL], [2721], [98], [<NAME>ya], [JPN], [2721], [99], [<NAME>], [IRI], [2717], [100], [<NAME>], [ESP], [2715], [101], [<NAME>], [JPN], [2714], [102], [<NAME>], [FIN], [2713], [103], [<NAME>], [AUT], [2709], [104], [KIM Donghyun], [KOR], [2709], [105], [<NAME>], [SWE], [2706], [106], [KIZUKURI Yuto], [JPN], [2706], [107], [HWANG Minha], [KOR], [2705], [108], [CHIANG Hung-Chieh], [TPE], [2705], [109], [NIU Guankai], [CHN], [2705], [110], [<NAME>], [JPN], [2703], [111], [<NAME>], [JPN], [2696], [112], [<NAME>], [RUS], [2695], [113], [#text(gray, "<NAME>")], [PRK], [2688], [114], [<NAME>], [KOR], [2687], [115], [<NAME>], [IND], [2686], [116], [<NAME>], [POL], [2684], [117], [KIM Minhyeok], [KOR], [2683], [118], [<NAME>], [ALG], [2683], [119], [<NAME>], [ROU], [2682], [120], [<NAME>], [KOR], [2681], [121], [<NAME>], [EGY], [2680], [122], [LIVENTSOV Alexey], [RUS], [2678], [123], [<NAME>], [ITA], [2678], [124], [<NAME>], [SLO], [2672], [125], [<NAME>], [JPN], [2668], [126], [XU Yingbin], [CHN], [2666], [127], [LIU Yebo], [CHN], [2666], [128], [DESAI Harmeet], [IND], [2665], ) )
https://github.com/loqusion/typix
https://raw.githubusercontent.com/loqusion/typix/main/docs/api/derivations/common/typst-opts.md
markdown
MIT License
<!-- markdownlint-disable-file first-line-h1 --> <!-- ANCHOR: head --> Attrset specifying command-line options to pass to the `typst` command. <!-- ANCHOR_END: head --> <!-- ANCHOR: tail --> Default: ```nix { format = "pdf"; } ``` <!-- ANCHOR_END: tail -->
https://github.com/505000677/2024SpringNote
https://raw.githubusercontent.com/505000677/2024SpringNote/main/2637/note-1.typ
typst
#import "../tizart.typ": * #show: project.with( title: "Foundations of Human Computer Interaction笔记", authors: (yuanxiang,), date: datetime.today() ) #show link: underline #outline() #set heading(numbering: "1.1.") = Day1 = Day2 #definition(name:"On Design")[ - Design is an iterative process: - To synthesize a solution from all the relevant constraints - To frame, or reframe, the problem and objective - To create and envision alternatives - To select from those alternatives - To visualize and prototype the intended solution ] $ S_A^("process") \u{21C4}S_B_("material") $ #definition(name:"Design as a process")[ - Design process is iterative and explorative, constantly involving users and investigating use, since we can't just trust our instincts - Group project – propose and carry out end-to-end design process ] #figure( image("day2.png", width: 80%) ) #clarification(name:"Design Process in a Nutshell")[ #figure( image("day2-1.png", width: 80%) ) ] #question(name:"Why do we need to center users in design?")[ #figure( image("day2-2.png", width: 80%) ) ] #question(name: "But how do we add users' input into our process?")[ #figure( image("day2-1-1.png", width: 80%) ) ] = Day3 = Day 4 #question(name:"Typical Goals in HCI Practice")[ - Usability: Ability to use a system to successfully complete a task - User experience: Thoughts, emotions, and perceptions that result from interactions with a system - Impact: How does the system influence the user's daily life? ] #definition(name:" Research Contributions in HCI")[ - Empirical Research Contributions: "provide new knowledge through findings based on observations and datagathering" - "arise from a variety of sources, including experiments, user tests, field observations, interviews, surveys, focus groups, diaries, ethnographies, sensors, log files, and many others" - Artifact Contributions: "reveal new possibilities, enable new explorations, facilitate new insights, or compel us to consider new possible futures" - "include new systems, architectures, tools, toolkits, techniques, sketches, mockups, and envisionments" - Methodological Contributions: "create new knowledge that informs how we carry out our work ... research or practice" - "may influence how we do science or how we do design. They may improve how we discover things, measure things, analyze things, create things, or build things" - Theoretical Contributions: "consist of new or improved concepts, definitions, models, principles, or frameworks" - "inform what we do, why we do it, and what we expect from it" - ] $ integral^a_b f(x)d x $
https://github.com/francescobortuzzo/Legionella
https://raw.githubusercontent.com/francescobortuzzo/Legionella/main/template.typ
typst
// FIXME: workaround for the lack of `std` scope #let std-bibliography = bibliography #let template( // Your thesis title title: [Modellazione e realizzazione di una base di dati per il monitoraggio del batterio legionella ], // The academic year you're graduating in academic-year: [2023/2024], // Your thesis subtitle, should be something along the lines of // "Bachelor's Thesis", "Tesi di Laurea Triennale" etc. course: [INFORMATICA], // The paper size, refer to https://typst.app/docs/reference/layout/page/#parameters-paper for all the available options paper-size: "a4", // Candidate's informations. You should specify a `name` key and // `matricola` key candidate: ( name: "<NAME>", matricola: 157430 ), // The thesis' supervisor (relatore) supervisor: "Professor <NAME>", // An array of the thesis' co-supervisors (correlatori). // Set to `none` if not needed co-supervisor: ( "<NAME>", "<NAME>" ), // Set to "it" for the italian template lang: "it", // The thesis' bibliography, should be passed as a call to the // `bibliography` function or `none` if you don't need // to include a bibliography bibliography: none, // Abstract of the thesis, set to none if not needed abstract: none, // Acknowledgments, set to none if not needed acknowledgments: none, // The thesis' content body ) = { // Set document matadata. set document(title: title, author: candidate.name) // Set the body font, "New Computer Modern" gives a LaTeX-like look set text(font: "New Computer Modern", lang: lang, size: 12pt) // Configure equation numbering and spacing. set math.equation(numbering: "(1)") show math.equation: set block(spacing: 0.65em) // Configure raw text/code blocks show raw.where(block: true): set text(size: 0.8em) show raw.where(block: true): set par(justify: false) show raw.where(block: true): set align(left) show raw.where(block: true): block.with( fill: gradient.linear(luma(240), luma(245), angle: 270deg), inset: 10pt, radius: 4pt, width: 100%, ) show raw.where(block: false): box.with( fill: gradient.linear(luma(240), luma(245), angle: 270deg), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) // Configure figure's captions show figure.caption: set text(size: 0.8em) // Configure lists and enumerations. set enum(indent: 10pt, body-indent: 9pt) set list(indent: 10pt, body-indent: 9pt, marker: ([•], [--])) // Configure headings set heading(numbering: "1.a.I.") show heading.where(level: 1): it => { if it.body not in ([References], [Riferimenti]) { block(width: auto, height: 20%)[ #set align(center + horizon) #set text(1.3em, weight: "bold") #smallcaps(it) ] } else { block(width: auto, height: 8%)[ #set align(center + horizon) #set text(1.1em, weight: "bold", hyphenate: true) #smallcaps(it) ] } } show heading.where(level: 2): it => block(width: 100%)[ #set align(center) #set text(1.1em, weight: "bold") #v(1em) #smallcaps(it) #v(1em) ] show heading.where(level: 3): it => block(width: 100%)[ #set align(left) #set text(1em, weight: "bold") #smallcaps(it) ] // Title page // Configure the page set page( paper: paper-size, margin: (right: 1.5cm, left: 2cm, top: 1cm, bottom: 3cm) ) set align(center) rect( fill: rgb("#0000FF"), width: 100%, height: 55pt, grid( columns: (140pt, 1fr), align: left + horizon, pad( left: 8pt, top: 4pt, bottom: 2pt, image("/img/logo.svg"), ), text(0.67em, font:"Arial", weight: 700, fill: white)[ DIPARTIMENTO DI SCIENZE MATEMATICHE, INFORMATICHE E FISICHE ] ) ) v(3fr) text(1.5em, [TESI DI LAUREA IN \ #course]) v(1.5fr, weak: true) text(2em, weight: 700, title) v(4fr) grid( columns: (1fr, 1fr), align: left, grid.cell( inset: (left: 40pt) )[ #if lang == "en" { smallcaps("candidate") } else { smallcaps("candidato") }\ *#candidate.name* ], grid.cell( inset: (right: 30pt) )[ #if lang == "en" { smallcaps("supervisor") } else { smallcaps("relatore") }\ *#supervisor* #if co-supervisor != none { if lang == "en" { smallcaps("co-supervisor") } else { smallcaps("correlatore") } linebreak() co-supervisor.map(it => [ *#it* ]).join(linebreak()) } ], ) v(5fr) text(1.2em, [ #if lang == "en" { "Academic Year " } else { "Anno Accademico " } #academic-year ]) pagebreak(to: "odd") set par(justify: true, first-line-indent: 1.25em) set align(center + horizon) // Configure the page set page( paper: paper-size, // Margins are taken from the university's guidelines margin: (right: 3cm, left: 3.5cm, top: 3.5cm, bottom: 3.5cm) ) // Abstract if abstract != none { heading( level: 2, numbering: none, outlined: false, "Abstract" ) abstract } pagebreak(weak: true, to: "odd") // Table of contents // Outline customization show outline.entry.where(level: 1): it => { if it.body != [References] { v(12pt, weak: true) link(it.element.location(), strong({ it.body h(1fr) it.page }))} else { text(size: 1em, it) } } show outline.entry.where(level: 3): it => { text(size: 0.8em, it) } outline(depth: 3, indent: true) pagebreak(to: "odd") // Main body show link: underline set page(numbering: "1") set align(top + left) counter(page).update(1) body pagebreak(to: "odd") }
https://github.com/seapat/markup-resume
https://raw.githubusercontent.com/seapat/markup-resume/main/example.typ
typst
Apache License 2.0
#import "markup-resume-lib/cv_core.typ" as core #import "markup-resume-lib/cv_head.typ": make_head #import "markup-resume-lib/cover_letter.typ": make_letter #import "markup-resume-lib/style.typ": init #let render_settings = ( font_body: "Linux Libertine", // Set font for body font_size: 11pt, // 10pt, 11pt, 12pt font_head: "Linux Libertine", // Set font for headings line_below: false, line_spacing: 0.65em, margin: 1.25cm, // 1.25cm, 1.87cm, 2.5cm number_align: center, //left, center, right numbering: "1 / 1", // Might not work as page-numbering in typst, please create an issue if you find such a case page_type: "a4", // a4, us-letter photo_height: 9em, // trial&error show_address: true, // true/false Show address in contact info show_phone: true, // true/false Show phone number in contact info show_photo: true, // whether or not to show the Photo ) #show: doc => init(doc, render_settings) #let cv_data = toml("./example.toml") #make_letter(cv_data) #make_head(cv_data, render_settings) #core.make_cv_core(cv_data) #core.foot_note // This example uses a single data file // alternatively you could also compose your cv from multiple files like so: // #let letter = toml("./letter.toml") // #let header = toml("./header.toml") // #let content = toml("./content.toml") // #make_letter(letter) // #make_head(header, render_settings) // #core.make_cv_core(content) // #core.foot_note // with a little bit more typst code (dictionary merges), you could compartemalize your data further
https://github.com/cadojo/correspondence
https://raw.githubusercontent.com/cadojo/correspondence/main/src/vita/src/socials.typ
typst
MIT License
#let socialslist = state("socialslist", ()) #let social( name, icon: none, ) = { let social = if icon == none { name } else { box(icon, baseline: 20%) h(1em) name } socialslist.update(current => current + (social,)) } #let socials(header: "Social Media") = { locate( loc => { let socialslist = socialslist.final(loc) if socialslist.len() > 0 { heading(level: 2, header) block( align(left)[#socialslist.join("\n")] ) } } ) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/github-pages/README.md
markdown
Apache License 2.0
## Online resources This directory contains files used to make online resources available for typst.ts.
https://github.com/touying-typ/touying
https://raw.githubusercontent.com/touying-typ/touying/main/README.md
markdown
MIT License
# ![logo](https://github.com/user-attachments/assets/58a91b14-ae1a-49e2-a3e7-5e3a148e2ba5) [Touying](https://github.com/touying-typ/touying) (投影 in chinese, /tóuyǐng/, meaning projection) is a user-friendly, powerful and efficient package for creating presentation slides in Typst. Partial code is inherited from [Polylux](https://github.com/andreasKroepelin/polylux). Therefore, some concepts and APIs remain consistent with Polylux. Touying provides automatically injected global configurations, which is convenient for configuring themes. Besides, Touying does not rely on `counter` and `context` to implement `#pause`, resulting in better performance. If you like it, consider [giving a star on GitHub](https://github.com/touying-typ/touying). Touying is a community-driven project, feel free to suggest any ideas and contribute. [![Book badge](https://img.shields.io/badge/docs-book-green)](https://touying-typ.github.io/) [![Gallery badge](https://img.shields.io/badge/docs-gallery-orange)](https://github.com/touying-typ/touying/wiki) ![GitHub](https://img.shields.io/github/license/touying-typ/touying) ![GitHub release (latest by date)](https://img.shields.io/github/v/release/touying-typ/touying) ![GitHub Repo stars](https://img.shields.io/github/stars/touying-typ/touying) ![Themes badge](https://img.shields.io/badge/themes-6-aqua) ## Document Read [the document](https://touying-typ.github.io/) to learn all about Touying. We will maintain **English** and **Chinese** versions of the documentation for Touying, and for each major version, we will maintain a documentation copy. This allows you to easily refer to old versions of the Touying documentation and migrate to new versions. **Note that the documentation may be outdated, and you can also use Tinymist to view Touying's annotated documentation by hovering over the code.** ## Gallery Touying offers [a gallery page](https://github.com/touying-typ/touying/wiki) via wiki, where you can browse elegant slides created by Touying users. You're also encouraged to contribute your own beautiful slides here! ## Special Features 1. Split slides by headings [document](https://touying-typ.github.io/docs/sections) ```typst = Section == Subsection === First Slide Hello, Touying! === Second Slide Hello, Typst! ``` 2. `#pause` and `#meanwhile` animations [document](https://touying-typ.github.io/docs/dynamic/simple) ```typst #slide[ First #pause Second #meanwhile Third #pause Fourth ] ``` ![image](https://github.com/touying-typ/touying/assets/34951714/24ca19a3-b27c-4d31-ab75-09c37911e6ac) 3. Math Equation Animation [document](https://touying-typ.github.io/docs/dynamic/equation) ![image](https://github.com/touying-typ/touying/assets/34951714/8640fe0a-95e4-46ac-b570-c8c79f993de4) 4. `touying-reducer` Cetz and Fletcher Animations [document](https://touying-typ.github.io/docs/dynamic/other) ![image](https://github.com/touying-typ/touying/assets/34951714/9ba71f54-2a5d-4144-996c-4a42833cc5cc) 5. Correct outline and bookmark (no duplicate and correct page number) ![image](https://github.com/touying-typ/touying/assets/34951714/7b62fcaf-6342-4dba-901b-818c16682529) 6. Dewdrop Theme Navigation Bar [document](https://touying-typ.github.io/docs/themes/dewdrop) ![image](https://github.com/touying-typ/touying/assets/34951714/0426516d-aa3c-4b7a-b7b6-2d5d276fb971) 7. Semi-transparent cover mode [document](https://touying-typ.github.io/docs/dynamic/cover) ![image](https://github.com/touying-typ/touying/assets/34951714/22a9ea66-c8b5-431e-a52c-2c8ca3f18e49) 8. Speaker notes for dual-screen [document](https://touying-typ.github.io/docs/external/pympress) ![image](https://github.com/touying-typ/touying/assets/34951714/afbe17cb-46d4-4507-90e8-959c53de95d5) 9. Export slides to PPTX and HTML formats and show presentation online. [touying-exporter](https://github.com/touying-typ/touying-exporter) [touying-template](https://github.com/touying-typ/touying-template) [online](https://touying-typ.github.io/touying-template/) ![image](https://github.com/touying-typ/touying-exporter/assets/34951714/207ddffc-87c8-4976-9bf4-4c6c5e2573ea) ## Quick start Before you begin, make sure you have installed the Typst environment. If not, you can use the [Web App](https://typst.app/) or the [Tinymist LSP](https://marketplace.visualstudio.com/items?itemName=myriad-dreamin.tinymist) extensions for VS Code. To use Touying, you only need to include the following code in your document: ```typst #import "@preview/touying:0.5.3": * #import themes.simple: * #show: simple-theme.with(aspect-ratio: "16-9") = Title == First Slide Hello, Touying! #pause Hello, Typst! ``` ![image](https://github.com/touying-typ/touying/assets/34951714/f5bdbf8f-7bf9-45fd-9923-0fa5d66450b2) It's simple. Congratulations on creating your first Touying slide! 🎉 **Tip:** You can use Typst syntax like `#import "config.typ": *` or `#include "content.typ"` to implement Touying's multi-file architecture. ## More Complex Examples In fact, Touying provides various styles for writing slides. For example, the above example uses first-level and second-level titles to create new slides. However, you can also use the `#slide[..]` format to access more powerful features provided by Touying. ```typst #import "@preview/touying:0.5.3": * #import themes.university: * #import "@preview/cetz:0.2.2" #import "@preview/fletcher:0.5.1" as fletcher: node, edge #import "@preview/ctheorems:1.1.2": * #import "@preview/numbly:0.1.0": numbly // cetz and fletcher bindings for touying #let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide.with(bounds: true)) #let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide) // Theorems configuration by ctheorems #show: thmrules.with(qed-symbol: $square$) #let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee")) #let corollary = thmplain( "corollary", "Corollary", base: "theorem", titlefmt: strong ) #let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em)) #let example = thmplain("example", "Example").with(numbering: none) #let proof = thmproof("proof", "Proof") #show: university-theme.with( aspect-ratio: "16-9", // config-common(handout: true), config-info( title: [Title], subtitle: [Subtitle], author: [Authors], date: datetime.today(), institution: [Institution], logo: emoji.school, ), ) #set heading(numbering: numbly("{1}.", default: "1.1")) #title-slide() == Outline <touying:hidden> #components.adaptive-columns(outline(title: none, indent: 1em)) = Animation == Simple Animation We can use `#pause` to #pause display something later. #pause Just like this. #meanwhile Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously. #speaker-note[ + This is a speaker note. + You won't see it unless you use `config-common(show-notes-on-second-screen: right)` ] == Complex Animation At subslide #touying-fn-wrapper((self: none) => str(self.subslide)), we can use #uncover("2-")[`#uncover` function] for reserving space, use #only("2-")[`#only` function] for not reserving space, #alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives. == Callback Style Animation #slide(repeat: 3, self => [ #let (uncover, only, alternatives) = utils.methods(self) At subslide #self.subslide, we can use #uncover("2-")[`#uncover` function] for reserving space, use #only("2-")[`#only` function] for not reserving space, #alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives. ]) == Math Equation Animation Equation with `pause`: $ f(x) &= pause x^2 + 2x + 1 \ &= pause (x + 1)^2 \ $ #meanwhile Here, #pause we have the expression of $f(x)$. #pause By factorizing, we can obtain this result. == CeTZ Animation CeTZ Animation in Touying: #cetz-canvas({ import cetz.draw: * rect((0,0), (5,5)) (pause,) rect((0,0), (1,1)) rect((1,1), (2,2)) rect((2,2), (3,3)) (pause,) line((0,0), (2.5, 2.5), name: "line") }) == Fletcher Animation Fletcher Animation in Touying: #fletcher-diagram( node-stroke: .1em, node-fill: gradient.radial(blue.lighten(80%), blue, center: (30%, 20%), radius: 80%), spacing: 4em, edge((-1,0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center), node((0,0), `reading`, radius: 2em), edge((0,0), (0,0), `read()`, "--|>", bend: 130deg), pause, edge(`read()`, "-|>"), node((1,0), `eof`, radius: 2em), pause, edge(`close()`, "-|>"), node((2,0), `closed`, radius: 2em, extrude: (-2.5, 0)), edge((0,0), (2,0), `close()`, "-|>", bend: -40deg), ) = Theorems == Prime numbers #definition[ A natural number is called a #highlight[_prime number_] if it is greater than 1 and cannot be written as the product of two smaller natural numbers. ] #example[ The numbers $2$, $3$, and $17$ are prime. @cor_largest_prime shows that this list is not exhaustive! ] #theorem("Euclid")[ There are infinitely many primes. ] #proof[ Suppose to the contrary that $p_1, p_2, dots, p_n$ is a finite enumeration of all primes. Set $P = p_1 p_2 dots p_n$. Since $P + 1$ is not in our list, it cannot be prime. Thus, some prime factor $p_j$ divides $P + 1$. Since $p_j$ also divides $P$, it must divide the difference $(P + 1) - P = 1$, a contradiction. ] #corollary[ There is no largest prime number. ] <cor_largest_prime> #corollary[ There are infinitely many composite numbers. ] #theorem[ There are arbitrarily long stretches of composite numbers. ] #proof[ For any $n > 2$, consider $ n! + 2, quad n! + 3, quad ..., quad n! + n #qedhere $ ] = Others == Side-by-side #slide(composer: (1fr, 1fr))[ First column. ][ Second column. ] == Multiple Pages #lorem(200) #show: appendix = Appendix == Appendix Please pay attention to the current slide number. ``` ![example](https://github.com/user-attachments/assets/3488f256-a0b3-43d0-a266-009d9d0a7bd3) ## Acknowledgements Thanks to... - [@andreasKroepelin](https://github.com/andreasKroepelin) for the `polylux` package - [@Enivex](https://github.com/Enivex) for the `metropolis` theme - [@drupol](https://github.com/drupol) for the `university` theme - [@pride7](https://github.com/pride7) for the `aqua` theme - [@Coekjan](https://github.com/Coekjan) and [@QuadnucYard](https://github.com/QuadnucYard) for the `stargazer` theme - [@ntjess](https://github.com/ntjess) for contributing to `fit-to-height`, `fit-to-width` and `cover-with-rect` ## Poster ![poster](https://github.com/user-attachments/assets/e1ddb672-8e8f-472d-b364-b8caed1da16b) [View Code](https://github.com/touying-typ/touying-poster) ## Star History <a href="https://star-history.com/#touying-typ/touying&Date"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=touying-typ/touying&type=Date&theme=dark" /> <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=touying-typ/touying&type=Date" /> <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=touying-typ/touying&type=Date" /> </picture> </a>
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/chordx/0.1.0/chordx.typ
typst
Apache License 2.0
#import "@preview/cetz:0.0.1" #let new-graph-chords(strings: 6, font: "Linux Libertine") = { return ( frets: 5, fret-number: none, capos: (), fingers: (), notes, chord-name ) => { box( cetz.canvas({ import cetz.draw: circle, content, line, rect, stroke let step = 5pt stroke(black + 0.5pt) let mute(col) = { let offset = col * step line((offset - 1.5pt, 2.5pt), (offset + 1.5pt, 5.5pt)) line((offset - 1.5pt, 5.5pt), (offset + 1.5pt, 2.5pt)) } // draws the grid let draw-grid(row, col, number) = { // Show or hide guitar nut if number == none or number == 1 { rect((0pt, -0.1pt), (col * step, 1.2pt), fill: black) } rect((0pt, 0pt), (col * step, -row * step)) let i = 1 while i < col { let x = i * step line((x, 0pt), (x, -row * step )) i += 1 } let i = 1 while i < row { let y = i * step line((0pt, -y), (col * step, -y)) i += 1 } } // draws notes: (x) for mute, (0) for air notes and (number) for finger notes let draw-notes(size, points) = { for (row, col) in points.zip(range(size)) { if row == "x" { mute(col) } else if row == 0 { circle( (col * step, 4pt), radius: 0.06, stroke: black + 0.5pt, fill: none ) } else if type(row) == "integer" { circle( (col * step, step / 2 - row * step), radius: 0.06, stroke: none, fill: black ) } } } // draw a capo list let draw-capos(size, points) = { for (fret, start, end) in points { if start > size { start = size } if end > size { end = size } line( ((size - start) * step, step / 2 - fret * step), ((size - end) * step, step / 2 - fret * step), stroke: (paint: black, thickness: 3.4pt, cap: "round") ) } } // draws the finger numbers let draw-fingers(size, points) = { for (finger, col) in points.zip(range(size)) { if type(finger) == "integer" and finger > 0 and finger < 6 { content((col * step, -(frets * step + 3pt)), text(6pt)[#finger]) } } } draw-grid(frets, strings - 1, fret-number) draw-notes(strings, notes) draw-capos(strings, capos) draw-fingers(strings, fingers) // shows the fret number content((-3pt, -2.25pt), anchor: "right", text(8pt)[#fret-number]) let space = 14pt if fingers.len() == 0 { space = 9pt } // shows the chord name content((step / 2 * (strings - 1), -(frets * step + space)), text(12pt, font: font)[#chord-name]) }) ) } } #let new-single-chords(..text-style) = { return (body, chord-name, body-char-pos) => { box( style(body-styles => { cetz.canvas({ import cetz.draw: content let offset = 0pt let anchor = "center" let content-to-array(content) = { if content.has("text") { return content.at("text").clusters() } if content.has("double") { return (content,) } if content.has("children") { for item in content.at("children") { content-to-array(item) } } if content.has("body") { content-to-array(content.at("body")) } if content.has("base") { content-to-array(content.at("base")) } if content.has("equation") { content-to-array(content.at("equation")) } } let body-array = content-to-array(body) // computes the width of the word until the pos index if body-char-pos.has("text") and int(body-char-pos.at("text")) != 0 { let body-chars-offset = 0pt let pos = int(body-char-pos.at("text")) - 1 for i in range(pos) { body-chars-offset += measure([#body-array.at(i)], body-styles).width } let body-width = measure(body, body-styles).width anchor = "left" // gets the char-offset to center the first character of the chord // with the selected character of the body let chord-char = content-to-array(chord-name).at(0) let chord-char-width = measure(text(..text-style)[#chord-char], body-styles).width let body-char-width = measure([#body-array.at(pos)], body-styles).width let char-offset = (chord-char-width - body-char-width) / 2 // final offset offset = body-chars-offset - (body-width / 2) - char-offset } content((offset, 16pt), text(..text-style)[#chord-name], anchor: anchor) content((0pt, 0pt), body) }) }) ) } }
https://github.com/ns-shop/ns-shop-typst
https://raw.githubusercontent.com/ns-shop/ns-shop-typst/main/chapter2.typ
typst
#import "template.typ": * #h1("Phân tích và thiết kế mô hình website TMĐT") #h2("Phân tích các yêu cầu nghiệp vụ và chức năng") Các tác nhân trong website: - Khách hàng. - Quản trị viên. // @startuml // left to right direction // actor "Khách hàng" as C // actor "Quản trị viên" as A // rectangle "Website TMĐT" { // usecase "Đăng nhập/Đăng ký tài khoản" as Register // usecase "Quản lý giỏ hàng cá nhân và thanh toán" as ManageCartAndPayment // usecase "Quản lý đơn hàng" as ManageOrder // usecase "Quản lý sản phẩm" as ManageProduct // usecase "Quản lý thông tin tài khoản cá nhân" as ChangeUserInfo // usecase "Quản lý tài khoản" as ManageAccount // usecase "Xem đơn hàng cá nhân" as ViewCustomOrder // C -- Register // C -- ManageCartAndPayment // C -- ChangeUserInfo // C -- ViewCustomOrder // A -- ManageOrder // A -- ManageProduct // A -- ManageAccount // ManageOrder <-- ViewCustomOrder: <<generalization>> // ManageAccount <-- ChangeUserInfo: <<generalization>> // } // @enduml #img("3image.png", cap: "Biểu đồ usecase tổng quát của hệ thống", width: 80%) #h3("Chức năng quản lý sản phẩm") Danh sách các chức năng con của chức năng quản lý sản phẩm: - Thêm sản phẩm. - Xem thông tin sản phẩm. - Sửa thông tin sản phẩm. - Xóa sản phẩm. - Quản lý danh mục sản phẩm. // @startuml // rectangle "Quản lý sản phẩm" as manage_product { // left to right direction // rectangle "Xem danh sách sản phẩm" as index_prod // rectangle "Xem danh sách danh mục sản phẩm" as index_cate // rectangle "Xem thông tin sản phẩm" as view // rectangle "Thêm sản phẩm mới" as add_product // rectangle "Xóa sản phẩm" as delete_product // rectangle "Cập nhật thông tin sản phẩm" as update_product // rectangle "Quản lý hình ảnh, mô tả, giá cả và số lượng tồn kho" as manage_details // rectangle "Thêm danh mục sản phẩm" as add_cate // rectangle "Cập nhật danh mục sản phẩm" as update_cate // rectangle "Xóa danh mục sản phẩm" as delete_cate // rectangle "Thêm sản phẩm vào danh mục" as add_prod_cate // rectangle "Xóa sản phẩm khỏi danh mục" as delete_prod_cate // rectangle "Xem danh mục sản phẩm" as view_cate // add_product --> manage_details // update_product --> manage_details // update_product --> add_prod_cate // update_product --> delete_prod_cate // update_product --> delete_product // index_prod --> view // update_cate --> delete_cate // index_cate --> view_cate // } // @enduml #img("4image.png", cap: "Biểu đồ phân rã chức năng quản lý sản phẩm", width: 70%) // @startuml // actor "Khách hàng" as user // actor "Quản trị viên" as admin // left to right direction // usecase "Xem danh sách sản phẩm" as index_prod // usecase "Xem danh sách danh mục sản phẩm" as index_cate // usecase "Xem thông tin sản phẩm" as view // usecase "Thêm sản phẩm mới" as add_product // usecase "Xóa sản phẩm" as delete_product // usecase "Cập nhật thông tin sản phẩm" as update_product // usecase "Quản lý hình ảnh, mô tả, giá cả và số lượng tồn kho" as manage_details // usecase "Thêm danh mục sản phẩm" as add_cate // usecase "Cập nhật danh mục sản phẩm" as update_cate // usecase "Xóa danh mục sản phẩm" as delete_cate // usecase "Thêm sản phẩm vào danh mục" as add_prod_cate // usecase "Xóa sản phẩm khỏi danh mục" as delete_prod_cate // usecase "Xem danh mục sản phẩm" as view_cate // add_product <-- manage_details: <<generalization>> // update_product <-- manage_details: <<generalization>> // update_product <-- add_prod_cate: <<include>> // update_product <-- delete_prod_cate: <<include>> // update_product <-- delete_product: <<extend>> // index_prod <-- view: <<extend>> // update_cate <-- delete_cate: <<extend>> // index_cate <-- view_cate: <<extend>> // view <-- add_product: <<extend>> // view_cate <-- add_cate: <<extend>> // user -- index_prod // user -- view // user -- index_cate // user -- view_cate // admin -- index_prod // admin -- view // admin -- index_cate // admin -- view_cate // admin -- add_product // admin -- update_product // admin -- delete_product // admin -- add_cate // admin -- update_cate // admin -- delete_cate // @enduml #img("5image.PNG", cap: "Biểu đồ usecase cho chức năng quản lý sản phẩm") #h3("Chức năng quản lý đơn hàng") Chức năng quản lý đơn hàng cho phép khách hàng xem lại các đơn hàng đã đặt trước đó và theo dõi trạng thái của từng đơn hàng. Khách hàng có thể xem chi tiết về sản phẩm đã đặt, số lượng, giá cả và thông tin vận chuyển. Ngoài ra, khách hàng cũng có thể hủy bỏ đơn hàng hoặc yêu cầu trả lại sản phẩm trong trường hợp sản phẩm không đáp ứng được yêu cầu của khách hàng. Danh sách các chức năng con của chức năng quản lý đơn hàng: - Tạo đơn hàng. - Xem đơn hàng. - Cập nhật trạng thái đơn hàng. // @startuml // rectangle "Quản lý đơn hàng" as manage_order { // rectangle "Tạo đơn hàng" as createOrder // rectangle "Xem danh sách đơn hàng" as viewListOrder // rectangle "Xem danh sách đơn hàng cá nhân" as viewListCustomOrder // rectangle "Xem đơn hàng cá nhân" as viewCustomOrder // rectangle "Cập nhật thông tin và trạng thái đơn hàng" as updateOrder // viewListOrder --> viewListCustomOrder // viewListOrder --> viewCustomOrder // viewListCustomOrder --> viewCustomOrder // } // @enduml #img("6image.png", cap: "Biểu đồ phân rã chức năng quản lý đơn hàng", width: 70%) // @startuml // actor "Khách hàng" as user // actor "Quản trị viên" as admin // usecase "Tạo đơn hàng" as createOrder // usecase "Xem danh sách đơn hàng" as viewListOrder // usecase "Xem danh sách đơn hàng cá nhân" as viewListCustomOrder // usecase "Xem đơn hàng cá nhân" as viewCustomOrder // usecase "Cập nhật thông tin và trạng thái đơn hàng" as updateOrder // viewListOrder <-- viewListCustomOrder: <<generalization>> // viewListOrder <-- viewCustomOrder: <<extend>> // viewListCustomOrder <-- viewCustomOrder: <<extend>> // createOrder --> viewListOrder: <<extend>> // updateOrder --> viewListOrder: <<extend>> // user -- viewListCustomOrder // user -- viewCustomOrder // admin -- createOrder // admin -- viewListOrder // admin -- updateOrder // admin -- viewCustomOrder // admin -- viewListCustomOrder // @enduml #img("image231313213123123123123123131312345345412313.png", width: 90%, cap: "Biểu đồ usecase cho chức năng quản lý đơn hàng") #h3("Chức năng đăng ký và đăng nhập tài khoản") Chức năng đăng ký tài khoản cho phép khách hàng có thể tạo một tài khoản mới trên trang web TMĐT. Người dùng cần cung cấp thông tin cá nhân như tên địa chỉ email, mật khẩu. Thông tin này sẽ được lưu trữ trong hệ thống của trang web để khách hàng có thể đăng nhập lại vào lần sau. Ngoài ra website còn được tích hợp tính năng đăng nhập bằng tài khoản Google sử dụng OAuth 2.0. Chức năng đăng nhập cung cấp cho khách hàng quyền truy cập vào các tính năng và dịch vụ của trang web TMĐT. Người dùng sẽ cần nhập tên đăng nhập và mật khẩu của mình để đăng nhập thành công. Sau khi đăng nhập thành công, khách hàng có thể thực hiện các hoạt động như xem lịch sử giao dịch, sửa đổi thông tin cá nhân, quản lý giỏ hàng và thanh toán đơn hàng. Ngoài ra, việc có chức năng đăng nhập và đăng ký tài khoản còn giúp cho trang web TMĐT có thể thu thập thông tin về khách hàng để có thể cung cấp các dịch vụ tốt hơn và phù hợp với nhu cầu của từng khách hàng. // @startuml // rectangle "Đăng nhập và đăng ký tài khoản" as manage_order { // rectangle "Đăng nhập" as login // rectangle "Đăng ký" as register // rectangle "Đăng nhập với email/password" as loginEmail // rectangle "Đăng ký với email/password" as registerEmail // rectangle "Đăng nhập bằng tài khoản Google" as googleLogin // rectangle "Đăng ký bằng tài khoản Google" as googleRegister // rectangle "Đăng xuất" as logout // login --> loginEmail // login --> googleLogin // register --> registerEmail // register --> googleRegister // register --> login // loginEmail --> logout // googleLogin --> logout // registerEmail --> logout // googleRegister --> logout // } // @enduml #img("8image.png", cap: "Biểu đồ phân rã chức năng của chức năng đăng ký và đăng nhập") // @startuml // actor "Khách hàng" as user // usecase "Đăng nhập" as login // usecase "Đăng ký" as register // usecase "Đăng nhập với email/password" as loginEmail // usecase "Đăng ký với email/password" as registerEmail // usecase "Đăng nhập bằng tài khoản Google" as googleLogin // usecase "Đăng ký bằng tài khoản Google" as googleRegister // usecase "Đăng xuất" as logout // login <-- loginEmail: <<generalization>> // login <-- googleLogin: <<generalization>> // register <-- registerEmail: <<generalization>> // register <-- googleRegister: <<generalization>> // register <-- login: <<include>> // loginEmail <-- logout: <<include>> // googleLogin <-- logout: <<include>> // registerEmail <-- logout: <<include>> // googleRegister <-- logout: <<include>> // user -- login // @enduml #img("imageq972193812931293.png", cap: "Biểu đồ usecase cho chức năng đăng nhập và đăng ký tài khoản") // @startuml // actor "Khách hàng" as customer // participant "Website TMĐT" as website // participant "OAuth 2.0 Provider" as oauth // participant "Email Provider" as email // == Quy trình đăng ký tài khoản bằng email/mật khẩu == // customer -> website: Truy cập trang đăng ký // activate website // website -> customer: Hiển thị biểu mẫu đăng ký // deactivate website // customer -> website: Gửi thông tin đăng ký // activate website // website -> website: Kiểm tra thông tin đăng ký // alt Tài khoản đã tồn tại // website --> customer: Trả về thông báo lỗi: Tài khoản đã tồn tại // else Tài khoản chưa tồn tại // website -> website: Tạo tài khoản mới // website -> email: Gửi email chứa link xác thực // activate email // email --> website: Thông báo đã gửi email thành công // deactivate email // website --> customer: Trả về thông báo tạo tài khoản thành công \n và yêu cầu xác thực email // deactivate website // customer -> website: Truy cập link xác thực // activate website // website -> website: Cập nhật trạng thái đã xác thực email // website --> customer: Thông báo đã xác thực email // deactivate website // end // == Quy trình đăng ký tài khoản bằng OAuth 2.0 == // customer -> website: Truy cập link đăng nhập bằng OAuth 2.0 // activate website // website -> customer: Chuyển hướng đến OAuth Provider // deactivate website // customer -> oauth: Xác thực đăng nhập OAuth // activate oauth // oauth --> website: Cung cấp mã truy cập (access token) // deactivate oauth // activate website // website -> oauth: Yêu cầu thông tin tài khoản dựa vào access token // activate oauth // oauth --> website: Trả về thông tin tài khoản // deactivate oauth // website -> website: Kiểm tra thông tin đăng ký // alt Tài khoản chưa tồn tại // website -> website: Tạo tài khoản mới // end // website --> website: Đăng nhập tài khoản // website --> customer: Trả về kết quả đăng nhập // deactivate website // @enduml #img("10image.png", cap: "Biểu đồ sequence thể hiện luồng xử lý của tính năng đăng ký", width: 100%) Một số cơ chế an toàn trong chức năng này: - Mã hóa mật khẩu: Mật khẩu của người dùng nên được mã hóa trước khi lưu trữ trong cơ sở dữ liệu. Một cách thông thường là sử dụng thuật toán băm (hashing) như bcrypt để mã hóa mật khẩu, đảm bảo rằng mật khẩu không thể được khôi phục ngược lại từ các giá trị được lưu trữ. - Bảo mật giao tiếp: Đảm bảo rằng thông tin đăng nhập và thông tin cá nhân của người dùng được bảo vệ trong quá trình truyền tải. Sử dụng kết nối an toàn qua HTTPS (SSL/TLS) để mã hóa dữ liệu giao tiếp giữa người dùng và hệ thống. - Kiểm tra mật khẩu mạnh: Yêu cầu người dùng sử dụng mật khẩu mạnh, bao gồm sự kết hợp của ký tự chữ hoa, chữ thường, chữ số và ký tự đặc biệt. - Bảo vệ thông tin cá nhân: Đảm bảo rằng thông tin cá nhân của người dùng được bảo vệ và không được tiết lộ cho bất kỳ bên thứ ba nào. Áp dụng các biện pháp bảo mật phù hợp như mã hóa dữ liệu, kiểm soát quyền truy cập và chứng thực đúng người dùng để bảo vệ thông tin cá nhân. #h3("Chức năng giỏ hàng và thanh toán") #img("11image.png", cap: "Giao dịch thanh toán trên internet") Đầu tiên, xác định các yêu cầu kinh doanh liên quan đến thanh toán điện tử của website. Website TMĐT trong báo cáo này hỗ trợ các phương thức thanh toán thông qua ví điện tử và thanh toán khi nhận hàng (COD). Đơn vị tiền tệ sử dụng Việt Nam Đồng. Lựa chọn cổng thanh toán cho ví điện tử: Dựa trên yêu cầu kinh doanh, chọn cổng thanh toán phù hợp để tích hợp vào website. Các cổng thanh toán phổ biến bao gồm PayPal, Stripe,... Sau quá trình khảo sát tác giả quyết định chọn Zalopay và Paypal là hai cổng thanh toán ví điện tử của website. Tiếp theo cần thiết kế cơ sở dữ liệu để lưu trữ thông tin liên quan đến thanh toán. Ở phần thiết kế danh sách các thực thể chính của website tác giả đã thiết kế thực thể "Payment Method" đại diện cho thông tin các cổng thanh toán được lưu trữ trong website. Từ đó có thể triển khai xây dựng cơ sở dữ liệu ở Chương 3. Tiếp theo cần thiết kế giao diện người dùng để hiển thị thông tin liên quan đến thanh toán, bao gồm các biểu mẫu nhập thông tin thanh toán, hiển thị đơn hàng, tóm tắt thanh toán và xác nhận thanh toán. Xử lý và xác thực thanh toán: Khi người dùng hoàn tất thông tin thanh toán, thực hiện xử lý và xác thực thanh toán. Điều này bao gồm gửi thông tin thanh toán đến cổng thanh toán, kiểm tra tính hợp lệ và xác nhận thanh toán từ cổng thanh toán. Nếu thanh toán thành công, cập nhật trạng thái đơn hàng và lưu trữ thông tin thanh toán. Ngoài ra cần xây dựng cơ chế để xử lý các lỗi thanh toán và quản lý giao dịch không thành công bao gồm xử lý các thông báo lỗi từ cổng thanh toán, gửi thông báo cho người dùng và cập nhật trạng thái đơn hàng tương ứng. Cuối cùng cần kiểm tra toàn bộ quy trình thanh toán để đảm bảo tính chính xác và hoạt động một cách trơn tru trên website. Sau đó, triển khai mô hình xử lý thanh toán vào website. Chức năng giỏ hàng cho phép người dùng lưu trữ các sản phẩm mà họ muốn mua vào trong giỏ hàng. Người dùng có thể thêm hoặc xóa bất kỳ sản phẩm nào từ giỏ hàng của mình và có thể xem toàn bộ giỏ hàng của mình trước khi hoàn tất đơn hàng. Sau khi đã chọn các sản phẩm mua, khách hàng cần thực hiện thanh toán để hoàn tất đơn hàng. Chức năng thanh toán cung cấp cho khách hàng các phương thức thanh toán khác nhau để lựa chọn, bao gồm thanh toán qua ví Zalopay, Paypal, thanh toán COD (thanh toán khi nhận hàng). Ngoài ra, trang web TMĐT cũng cần đảm bảo rằng các thông tin thanh toán của khách hàng được bảo mật và an toàn. Vì vậy, trang web TMĐT cần sử dụng các công nghệ bảo mật như SSL (Secure Sockets Layer) để mã hóa thông tin thanh toán và tránh các vấn đề bảo mật như lừa đảo hoặc giả mạo thông tin. Danh sách các chức năng con của chức năng giỏ hàng và thanh toán: - Thêm sản phẩm vào giỏ hàng. - Cập nhật số lượng sản phẩm. - Xóa sản phẩm ra khỏi giỏ hàng. - Thanh toán. // @startuml // top to bottom direction // rectangle "Giỏ hàng và thanh toán" { // rectangle "Xem giỏ hàng" as DisplayCart // rectangle "Thêm sản phẩm vào giỏ hàng" as AddToCart // rectangle "Cập nhật số lượng sản phẩm" as UpdateQuantity // rectangle "Xóa sản phẩm khỏi giỏ hàng" as RemoveFromCart // rectangle "Cung cấp thông tin thanh toán" as SelectPaymentMethod // rectangle "Thanh toán" as ConfirmPayment // DisplayCart --> UpdateQuantity // DisplayCart --> RemoveFromCart // AddToCart --> DisplayCart // SelectPaymentMethod --> ConfirmPayment // UpdateQuantity --> SelectPaymentMethod // RemoveFromCart --> SelectPaymentMethod // DisplayCart --> SelectPaymentMethod // } // @enduml #img("12image.png", cap: "Biểu đồ phân rã chức năng giỏ hàng và thanh toán", width: 70%) // @startuml // top to bottom direction // actor "Khách hàng" as user // usecase "Xem giỏ hàng" as DisplayCart // usecase "Thêm sản phẩm vào giỏ hàng" as AddToCart // usecase "Cập nhật số lượng sản phẩm" as UpdateQuantity // usecase "Xóa sản phẩm khỏi giỏ hàng" as RemoveFromCart // usecase "Thanh toán" as ConfirmPayment // DisplayCart <-- UpdateQuantity: <<include>> // DisplayCart <-- RemoveFromCart: <<include>> // AddToCart <-- DisplayCart: <<extend>> // UpdateQuantity --> AddToCart: <<include>> // DisplayCart <-- ConfirmPayment: <<include>> // user -- AddToCart // user -- UpdateQuantity // user -- RemoveFromCart // user -- ConfirmPayment // @enduml #img("13image22.png", cap: "Biểu đồ usecase cho chức năng giỏ hàng và thanh toán", width:70%) // @startuml // actor "Khách hàng" as cus // participant "Website TMĐT" as web // participant "Paypal" as pay // == Quy trình thanh toán giỏ hàng bằng Paypal == // cus -> web: Gửi thông tin thanh toán // activate web // web -> web: Kiểm tra thông tin thanh toán // web -> pay: Tạo đơn hàng thanh toán qua Paypal kèm link chuyển\nhướng về website TMĐT khi thanh toán thành công // activate pay // pay --> web: Trả về thông tin đơn hàng thanh toán qua Paypal\nkèm link chuyển hướng đến trang thanh toán Paypal // deactivate pay // web -> cus: Chuyển hướng sang trang thanh toán Paypal // deactivate web // cus -> pay: Thanh toán đơn hàng qua Paypal // activate pay // pay -> pay: Xử lý thanh toán đơn hàng // pay -> web: Gửi thông báo đã thanh toán đơn hàng // activate web // web -> web: Cập nhật trạng thái đơn hàng // deactivate web // pay -> cus: Chuyển hướng về website TMĐT // deactivate pay // @enduml #img("14image.png", cap: "Biểu đồ sequence thể hiện luồng thực hiện tính năng thanh toán với cổng thanh toán Paypal") #h3("Chức năng quản lý tài khoản") Chức năng quản lý tài khoản cho phép quản trị viên quản lý danh sách khách hàng trên website TMĐT và cho phép khách hàng cập nhật xem và sửa đổi thông tin cá nhân của mình, bao gồm tên, địa chỉ, số điện thoại và địa chỉ email. Khách hàng cũng có thể thay đổi mật khẩu để bảo mật tài khoản của mình. Danh sách các chức năng con của chức năng quản lý thông tin tài khoản: - Xem danh sách tài khoản. - Xem thông tin tài khoản. - Cập nhật thông tin tài khoản. - Xóa tài khoản. // @startuml // rectangle "Quản lý tài khoản" as manage_customer { // rectangle "Xem thông tin tài khoản" as view // rectangle "Cập nhật thông tin tài khoản" as update_customer_info // rectangle "Quản lý địa chỉ giao hàng và thanh toán" as manage_address // rectangle "Thay đổi mật khẩu" as change_password // rectangle "Xóa tài khoản" as delete // update_customer_info --> manage_address // update_customer_info --> change_password // } // @enduml #img("15image.png", cap: "Biểu đồ phân rã tinh năng quản lý tài khoản", width: 80%) // @startuml // actor "Khách hàng" as user // actor "Quản trị viên" as admin // usecase "Xem thông tin tài khoản" as view // usecase "Xem thông tin tài khoản cá nhân" as view_custom // usecase "Cập nhật thông tin tài khoản" as update_customer_info // usecase "Cập nhật thông tin tài khoản cá nhân" as update_customer_info_custom // usecase "Quản lý địa chỉ giao hàng và thanh toán" as manage_address // usecase "Quản lý địa chỉ giao hàng và thanh toán cá nhân" as manage_address_custom // usecase "Thay đổi mật khẩu cá nhân" as change_password // usecase "Xóa tài khoản" as delete // usecase "Xóa tài khoản cá nhân" as delete_custom // update_customer_info <-- manage_address: <<generalization>> // view <-- view_custom: <<generalization>> // delete <-- delete_custom: <<generalization>> // update_customer_info <-- update_customer_info_custom: <<generalization>> // update_customer_info_custom <-- manage_address_custom: <<include>> // manage_address <-- manage_address_custom: <<generalization>> // change_password --> update_customer_info_custom: <<extend>> // user -- delete_custom // user -- update_customer_info_custom // user -- view_custom // user -- change_password // admin -- view // admin -- update_customer_info // admin -- manage_address // admin -- delete // @enduml #img("16image22.png", cap: "Biểu đồ usecase của chức năng quản lý tài khoản") // #h3("Chức năng tìm kiếm sản phẩm") // #p Chức năng tìm kiếm sản phẩm cho phép người dùng nhập từ khóa tìm kiếm vào ô tìm kiếm và sau đó hiển thị các sản phẩm liên quan đến từ khóa tìm kiếm đó. Nếu có quá nhiều sản phẩm được tìm thấy, trang web TMĐT có thể sắp xếp chúng theo các tiêu chí khác nhau như giá cả, độ phổ biến, đánh giá của khách hàng hoặc thương hiệu sản phẩm. // Ngoài ra, trang web TMĐT cũng có thể cung cấp các công cụ lọc sản phẩm để giúp khách hàng thu hẹp phạm vi tìm kiếm của mình và tìm kiếm các sản phẩm phù hợp với nhu cầu của mình hơn. Các tiêu chí lọc sản phẩm phổ biến bao gồm màu sắc, kích thước, giá cả và thương hiệu. // Chức năng tìm kiếm sản phẩm cùng với các công cụ lọc sản phẩm giúp khách hàng dễ dàng tìm kiếm các sản phẩm mà họ đang quan tâm và giúp trang web TMĐT cung cấp cho khách hàng những trải nghiệm mua sắm thân thiện và tiện lợi. #h2("Thiết kế cơ sở dữ liệu") #h3("Lựa chọn hệ quản trị cơ sở dữ liệu") Lựa chọn hệ quản trị cơ sở dữ liệu (Database Management System - DBMS) trong thiết kế website thương mại điện tử là một yếu tố quan trọng và có ảnh hưởng đáng kể đến hiệu suất, bảo mật và khả năng mở rộng của hệ thống. Phân loại và đánh giá tổng quát của các loại cơ sở dữ liệu phổ biến: - Relational Database: - Đặc điểm: Cơ sở dữ liệu quan hệ sử dụng bảng và mối quan hệ để tổ chức dữ liệu thành các thực thể và quan hệ giữa chúng. Structured Query Language (SQL) là ngôn ngữ phổ biến để truy vấn và quản lý cơ sở dữ liệu quan hệ. - Ưu điểm: Dễ hiểu, dễ sử dụng, hỗ trợ các hoạt động truy vấn phức tạp, đảm bảo tính nhất quán và toàn vẹn dữ liệu. - Nhược điểm: Cần sử dụng quá nhiều liên kết giữa các bảng trong trường hợp dữ liệu phức tạp, có thể làm chậm hiệu suất truy vấn. - Non-Relational Database: - Đặc điểm: Các cơ sở dữ liệu không quan hệ, hay còn gọi là NoSQL, có cấu trúc linh hoạt hơn và không sử dụng mô hình quan hệ. Các loại cơ sở dữ liệu NoSQL bao gồm: cơ sở dữ liệu cột, cơ sở dữ liệu tài liệu, cơ sở dữ liệu đồ thị và cơ sở dữ liệu key-value. - Ưu điểm: Khả năng mở rộng tốt, hỗ trợ truy vấn nhanh, linh hoạt và có thể xử lý dữ liệu phi cấu trúc. - Nhược điểm: Không đảm bảo tính nhất quán dữ liệu như cơ sở dữ liệu quan hệ, hạn chế trong việc truy vấn phức tạp. - Graph Database: - Đặc điểm: Cơ sở dữ liệu đồ thị được sử dụng để lưu trữ dữ liệu có mối quan hệ phức tạp. Nó sử dụng các nút, cạnh và thuộc tính để biểu diễn dữ liệu và quan hệ giữa chúng. - Ưu điểm: Hiệu suất cao trong việc truy vấn và phân tích các mối quan hệ dữ liệu phức tạp. - Nhược điểm: Thường không phù hợp cho các dự án có dữ liệu đơn giản hoặc ít quan hệ. Dựa vào các phân tích và đánh giá được thực hiện trong Chương 1, kết hợp tìm hiểu trong quá trình xây dựng yêu cầu nghiệp vụ và chức năng của website, tác giả đánh giá rằng mô hình dữ liệu của website được liên kết với nhau một cách chặt chẽ và mạch lạc. Do đó, tác giả đã quyết định chọn SQL làm hệ quản trị cơ sở dữ liệu cho website, bởi SQL mang đến những ưu điểm quan trọng và phù hợp với yêu cầu của dữ liệu trong dự án. Bằng việc sử dụng SQL, website thương mại điện tử sẽ có khả năng xử lý dữ liệu một cách hiệu quả, đáng tin cậy và linh hoạt. SQL cung cấp một ngôn ngữ truy vấn mạnh mẽ cho phép thực hiện các truy vấn phức tạp và tùy chỉnh theo nhu cầu cụ thể của dự án. #h3("Thiết kế mô hình dữ liệu") <titlexx1> Trong quá trình phân tích thiết kế website thương mại điện tử, thiết kế mô hình dữ liệu đóng vai trò quan trọng để xác định cấu trúc và quan hệ giữa các bảng dữ liệu. Việc thiết kế mô hình dữ liệu cẩn thận và hợp lý là yếu tố quyết định thành công của hệ thống cơ sở dữ liệu, ảnh hưởng đến hiệu suất, tính nhất quán và quản lý dữ liệu. Dưới đây là phân tích và đánh giá chi tiết về thiết kế mô hình dữ liệu trong phân tích thiết kế website thương mại điện tử: - Xác định yêu cầu và mục tiêu: Trước khi thiết kế mô hình dữ liệu, cần xác định rõ yêu cầu và mục tiêu của website thương mại điện tử. Điều này bao gồm việc hiểu rõ các chức năng, quy trình kinh doanh, quyền hạn và yêu cầu về dữ liệu của hệ thống. - Xác định các thực thể (entities): Xác định các thực thể chính trong hệ thống, như sản phẩm, người dùng, đơn hàng, danh mục sản phẩm, v.v. Mỗi thực thể đại diện cho một tập hợp các đối tượng có liên quan trong thế giới thực. - Xác định các thuộc tính (attributes) của thực thể: Xác định các thuộc tính cần thiết để mô tả và lưu trữ thông tin về các thực thể. Ví dụ, thuộc tính của thực thể "sản phẩm" có thể bao gồm tên, mô tả, giá, hình ảnh, số lượng, v.v. Từ những đánh giá trên tác giả đã xây dựng danh sách các thực thể chính trong một website TMĐT như sau: - User: Đại diện cho người dùng của website, bao gồm thông tin như tên, email, mật khẩu, và các thông tin liên quan khác. - Product: Lưu trữ thông tin về các sản phẩm mà website đang bán, bao gồm tên, mô tả, giá, số lượng, mã SKU, và trạng thái có sẵn hay không. - Order: Đại diện cho đơn hàng được tạo bởi người dùng, bao gồm thông tin như người đặt hàng, phương thức thanh toán, địa chỉ giao hàng, tổng giá trị đơn hàng, ghi chú và trạng thái đơn hàng. - Order Item: Lưu trữ thông tin về các sản phẩm được đặt trong mỗi đơn hàng, bao gồm sản phẩm, số lượng và giá. - Cart Item: Lưu trữ thông tin về các sản phẩm trong giỏ hàng của người dùng, bao gồm sản phẩm, số lượng và người dùng tương ứng. - Shipping Provider: Đại diện cho các nhà cung cấp dịch vụ giao hàng mà website hỗ trợ. - Payment Method: Đại diện cho các phương thức thanh toán mà người dùng có thể sử dụng khi đặt hàng. - Address: Lưu trữ thông tin về địa chỉ của người dùng, bao gồm quốc gia, thành phố, tiểu bang/tỉnh, đường phố, và mã bưu điện. Sau khi đã xác định các thực thể chính trong website, dựa vào đó tác giả đã thiết kế mô hình ER cho cơ sở dữ liệu để triển khai trong Chương 3: // @startuml // entity User { // id: Integer // name: String // email: String // password: <PASSWORD> // } // entity Product { // id: Integer // name: String // price: Integer // quantity: Integer // } // entity Order { // id: Integer // user: User // orderDate: Date // address: Address // paymentMethod: PaymentMethod // } // entity OrderItem { // id: Integer // order: Order // product: Product // quantity: Integer // } // entity CartItem { // id: Integer // user: User // product: Product // quantity: Integer // } // entity ShippingProvider { // id: Integer // name: String // cost: Integer // } // entity PaymentMethod { // id: Integer // name: String // code: String // } // entity Address { // id: Integer // user: User // street: String // city: String // state: String // zipcode: String // } // User "1" -- "1" Order // User "1" -- "1..*" CartItem // Order "1" -- "1" ShippingProvider // Order "1" -- "1" PaymentMethod // Order "1" -- "1..*" OrderItem // CartItem "1" -- "1" Product // OrderItem "1" -- "1" Product // Address "1" -- "1" User // @enduml #img("17image.png", cap: "Biểu đồ ER của CSDL website TMĐT") #h3("Đảm bảo tính nhất quán và an toàn cho cơ sở dữ liệu") Đảm bảo tính nhất quán và an toàn cho cơ sở dữ liệu là một yếu tố quan trọng trong phân tích và thiết kế website thương mại điện tử. Điều này đảm bảo rằng dữ liệu được lưu trữ và truy cập một cách đáng tin cậy, đồng thời đảm bảo tính toàn vẹn và bảo mật của thông tin. Dưới đây là phân tích và đánh giá chi tiết về đảm bảo tính nhất quán và an toàn cho cơ sở dữ liệu trong phân tích thiết kế website thương mại điện tử: - Tính nhất quán của cơ sở dữ liệu. - Tính toàn vẹn dữ liệu. - Bảo mật dữ liệu. - Sao lưu và phục hồi dữ liệu. #h2("Phân tích thiết kế kiến trúc hệ thống") #h3("Xác định các thành phần hệ thống") Từ những phân tích trên kết hợp với việc ứng dụng mô hình MVC vào website TMĐT, ta có các thành phần chính như sau: - Model: Đại diện cho logic xử lý dữ liệu trong ứng dụng. Model thực hiện truy vấn, thêm, sửa đổi và xóa dữ liệu từ cơ sở dữ liệu. Nó quản lý lưu trữ và truy xuất dữ liệu thông qua truy vấn SQL hoặc Object Relational Mapping (ORM). - View: Đại diện cho giao diện người dùng của ứng dụng. View hiển thị dữ liệu cho người dùng và tương tác với họ. Nó chứa mã HTML, CSS và JavaScript để tạo giao diện người dùng. - Controller: Xử lý yêu cầu từ người dùng và tương tác với Model và View. Controller nhận yêu cầu qua Routes và gọi phương thức tương ứng để xử lý. Nó thực hiện lấy dữ liệu từ Model, xử lý logic và chuyển dữ liệu đến View. - Routes: Xác định các đường dẫn URL và kết nối chúng với phương thức trong Controller. Routes định nghĩa các điểm cuối (endpoints) của ứng dụng và quyết định điều hướng yêu cầu từ người dùng đến Controller. - Middleware: Là thành phần trung gian giữa yêu cầu và phản hồi của ứng dụng. Middleware cho phép xử lý trước và sau khi yêu cầu đi qua Controller. Nó kiểm soát quyền truy cập, xác thực người dùng, thực hiện xử lý logic và bổ sung thông tin vào yêu cầu. Thiết kế cấu trúc thư mục của website: - Thư mục `app` chứa các thành phần chính của ứng dụng như Controllers, Models, và Services. - Thư mục `config` chứa các tệp cấu hình của ứng dụng. - Thư mục `database` chứa các file migration và seeders. - Thư mục `public` chứa các file tĩnh như hình ảnh, CSS, và JavaScript. - Thư mục `resources` chứa các file nguồn của ứng dụng như views, assets, và ngôn ngữ. - Thư mục `routes` chứa các file định tuyến của ứng dụng. #h3("Các cơ chế an toàn") Cần xác định rõ các yêu cầu bảo mật của hệ thống. Bao gồm việc xác định các nguyên tắc bảo mật cần tuân thủ, các loại dữ liệu nhạy cảm cần được bảo vệ, và các rủi ro bảo mật tiềm ẩn. Xác định các yêu cầu bảo mật sẽ giúp xác định các khía cạnh cần thiết để bảo vệ thông tin của người dùng. Tiếp theo, cần thiết kế kiến trúc hệ thống hướng bảo mật. Bao gồm việc sử dụng các phương pháp mã hóa mạnh mẽ để bảo vệ thông tin, xác thực và ủy quyền để kiểm soát quyền truy cập, và các lớp bảo vệ phòng ngừa tấn công từ bên ngoài. Một phần quan trọng trong việc đảm bảo tính bảo mật là quản lý danh sách truy cập và phân quyền. Cần xác định các vai trò người dùng và quyền hạn tương ứng để kiểm soát quyền truy cập vào hệ thống và dữ liệu. Quản lý danh sách truy cập và phân quyền giúp đảm bảo rằng chỉ những người được ủy quyền mới có thể truy cập và thao tác với thông tin nhạy cảm. Cần thực hiện kiểm tra và xác minh bảo mật thường xuyên để đảm bảo tính bảo mật của hệ thống. Kiểm tra bảo mật bao gồm việc kiểm tra các lỗ hổng bảo mật và điểm yếu trong hệ thống, trong khi xác minh bảo mật đảm bảo rằng các biện pháp bảo mật đã được triển khai và hoạt động hiệu quả. Kiểm tra và xác minh bảo mật định kỳ giúp phát hiện và khắc phục các lỗ hổng bảo mật sớm trước khi chúng có thể bị tấn công. Cuối cùng, cần đảm bảo rằng nhân viên được đào tạo và có nhận thức về bảo mật. Đào tạo nhân viên về các quy trình bảo mật và các biện pháp bảo mật sẽ giúp nâng cao ý thức về bảo mật và đảm bảo rằng mọi người đều thực hiện các biện pháp bảo mật một cách đúng đắn. Một số phương pháp đảm bảo an toàn cho ứng dụng cho website TMĐT: - Sử dụng giao thức an toàn Secure Socket Layer (SSL): SSL/TLS tạo ra một kênh truyền thông an toàn giữa máy tính của người dùng và máy chủ của website, đảm bảo rằng dữ liệu không bị đánh cắp, thay đổi hoặc giả mạo trong quá trình truyền. Khi một trang web sử dụng SSL/TLS, địa chỉ URL sẽ bắt đầu bằng `https://` thay vì `http://`, và thông thường trình duyệt sẽ hiển thị một biểu tượng khóa hoặc dấu chấm than xanh lá để chỉ ra rằng kết nối là an toàn. Sử dụng giao thức HTTPS là một cách triển khai SSL. Một số nhà cung cấp chứng chỉ SSL miễn phí để sử dụng giao thức HTTPS cho website như Cloudflare và Let's Encrypt. Để cài đặt chứng chỉ cho website ta cần vào trang quản trị tên miền trỏ nameserver về nameserver của nhà cung cấp (đối với Cloudflare) hoặc cài đặt các khóa chứng chỉ của nhà cung cấp lên VPS mà tên miền đang trỏ về (đối với Let's Encrypt). - Mã hóa và xác thực với Tokenization: Thông tin thanh toán nhạy cảm của người sử dụng được thay thế bằng một tập hợp các ký tự được gọi là token và các token này sẽ không ảnh hưởng đến tính an toàn trong các giao dịch trực tuyến và di động. Các máy khách sẽ thực hiện truyền mã token, thay vì dữ liệu thông tin gốc quan trọng, điều này khiến dữ liệu sẽ không thể bị đánh cắp hoặc không có giá trị đối với kẻ tấn công khi đánh cắp được. Một trong số cách triển khai đó là xác thực người dùng sử dụng JSON Web Token (JWT) là một phương thức xác thực dựa trên mã thông báo (token) được tạo và ký bởi máy chủ. JWT hỗ trợ nhiều thuật toán mã hóa phổ biến như HS256 (HMAC SHA-256), RS256 (RSA SHA-256), và nhiều thuật toán khác dựa trên mã hóa đối xứng và bất đối xứng. - Thiết kế theo tiêu chuẩn Payment Card Industry Data Security Standard (PCI DSS): Để đạt được tuân thủ PCI DSS, website phải thực hiện theo một loạt các yêu cầu khắt khe, chẳng hạn như thực hiện bảo mật hệ thống và mạng để bảo vệ dữ liệu thẻ tín dụng, bảo vệ các thông tin xác thực của khách hàng bằng cách sử dụng các giải pháp mã hóa và thực hiện quản lý quy trình và chính sách bảo mật, đảm bảo rằng nhân viên được đào tạo và thực hiện theo tiêu chuẩn an ninh thông tin. - Xác thực với giao thức Open Authorization: Open Authorization (OAuth) là một giao thức xác thực và ủy quyền được sử dụng để cho phép người dùng cấp quyền truy cập tài khoản của mình cho các ứng dụng, dịch vụ và trang web khác. OAuth cho phép người dùng chia sẻ thông tin cá nhân và tài khoản của họ mà không cần tiết lộ mật khẩu của mình. Thay vào đó, OAuth sử dụng một mã truy cập để cung cấp quyền truy cập. Khi người dùng cấp quyền truy cập cho ứng dụng, dịch vụ hoặc trang web, mã truy cập sẽ được tạo ra. Mã này sau đó được sử dụng để xác thực yêu cầu truy cập từ ứng dụng, dịch vụ hoặc trang web đó. OAuth 2.0 là phiên bản tiếp theo của giao thức OAuth. OAuth 2.0 giúp cho việc ủy quyền truy cập dễ dàng hơn và cung cấp nhiều cấp độ quyền hơn so với phiên bản trước đó. - Quản lý phiên làm việc bằng việc triển khai session cho website. Framework Laravel đã hỗ trợ session cho user. - Chỉ lưu trữ mật khẩu đã mã hóa 1 chiều vào website nhằm giảm khả năng lộ lọt dữ liệu của cơ sơ dữ liệu, có thể sử dụng hàm mã hóa `bcrypt` của Laravel. - Kiểm tra và sửa lỗi bảo mật: Thực hiện kiểm tra bảo mật định kỳ, bao gồm kiểm tra lỗ hổng, kiểm tra xác thực, kiểm tra cấu hình, và kiểm tra mã nguồn để tìm và sửa các lỗi bảo mật tiềm ẩn. - Xây dựng các bộ kiểm thử input đầu vào. Ta có thể sử dụng class `Validator` được hỗ trợ bởi framework Laravel hoặc có thể xây dựng các kịch bản kiểm thử input đầu vào. Dưới đây là một số bộ kiểm thử input đầu vào có thể sử dụng trong website: ```php // Thông tin thanh toán đơn hàng $rules = [ 'name' => 'required', 'email' => 'required|email', 'country' => 'required', 'city' => 'required', 'state' => 'required', 'street' => 'required', 'postalCode' => 'required|postal_code', 'phone' => 'required|vn_phone_number', 'paymentMethodId' => 'required', 'cart' => 'required|array|min:1', ]; // Thông tin đăng ký $rules = [ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users', 'password' => '<PASSWORD>', ]; // Thông tin cập nhật tài khoản $rules = [ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users,email,'.$id, ]; ``` // #h2("Quản lý và bảo vệ thông tin khách hàng trên website TMĐT") // #h3("Quản lý thông tin cá nhân và dữ liệu khách hàng") // #h3("Bảo vệ thông tin giao dịch trên website TMĐT") // #h3("Các qui định pháp lý liên quan") #h2("Giải pháp xây dựng giao diện và trải nghiệm người dùng") #h3("Xây dựng giao diện với Tailwind") Tailwind một framework CSS utility-first được lựa chọn vì sự linh hoạt và hiệu quả trong việc thiết kế giao diện. Tailwind CSS đặc biệt hữu ích cho việc xây dựng giao diện web từ đầu, mang lại khả năng tùy chỉnh cao và sự linh hoạt trong việc tạo ra các thành phần giao diện. Một trong những ưu điểm của Tailwind CSS là phương pháp thiết kế utility-first. Thay vì tạo ra các class CSS đặc biệt cho từng thành phần, Tailwind CSS tập trung vào việc cung cấp các class utilitarian như `w-`, `h-`, `bg-`, `text-`,... cho phép xây dựng giao diện nhanh chóng bằng cách kết hợp các class này lại với nhau. Điều này giúp tiết kiệm thời gian viết CSS từ đầu và cho phép tập trung vào việc xây dựng giao diện một cách hiệu quả. Ngoài ra, Tailwind CSS cung cấp một design system rất phong phú với rất nhiều thành phần giao diện sẵn có. Các thành phần này bao gồm nút, thẻ, menu, biểu đồ, bảng và nhiều hơn nữa. Một khía cạnh quan trọng khác của việc sử dụng Tailwind CSS là khả năng áp dụng Responsive Web Design (RWD). Framework cung cấp các class CSS breakpoint như `sm`, `md`, `lg`, `xl` để giúp điều chỉnh giao diện theo kích thước màn hình khác nhau. Bằng cách sử dụng các class này, ta có thể dễ dàng điều chỉnh giao diện để nó hiển thị tốt trên điện thoại di động, máy tính bảng và máy tính để bàn. Đối với trải nghiệm người dùng, Tailwind CSS cung cấp một giao diện đẹp, dễ nhìn và dễ sử dụng. Các thành phần được thiết kế sao cho tương thích với nguyên tắc thiết kế giao diện hiện đại và hướng tới trải nghiệm người dùng tốt nhất. Ta có thể tùy chỉnh giao diện để phù hợp với thương hiệu và mục tiêu của mình, tạo nên một trải nghiệm độc đáo và chuyên nghiệp cho người dùng. #h3("Tối ưu hóa tốc độ load trang") Tối ưu hóa tốc độ load trang là một trong những yếu tố quan trọng để cải thiện trải nghiệm người dùng và tăng tương tác trên website TMĐT. Dưới đây là một số cách để tối ưu hóa tốc độ load trang: - Tối ưu hóa hình ảnh: Sử dụng các công cụ tối ưu hóa hình ảnh để giảm dung lượng của các hình ảnh trên trang web, đồng thời áp dụng kỹ thuật lazy loading để chỉ tải hình ảnh khi cần thiết. - Sử dụng cache: Sử dụng bộ nhớ cache để giảm thời gian tải lại trang web và cải thiện trải nghiệm người dùng. - Giảm số lượng yêu cầu HTTP: Giảm số lượng yêu cầu HTTP bằng cách sử dụng các kỹ thuật như gộp file CSS và JavaScript hoặc sử dụng các CDN (Content Delivery Network) để phân phối tài nguyên trên nhiều máy chủ. - Chọn hosting tốt: Lựa chọn một nhà cung cấp hosting tốt có thể giúp tăng tốc độ tải trang web. - Tối ưu hóa mã nguồn: Sử dụng các phương pháp tối ưu hóa mã nguồn, chẳng hạn như sử dụng minifier để giảm kích thước của mã HTML, CSS và JavaScript. - Sử dụng các công cụ đo lường hiệu suất: Sử dụng các công cụ đo lường hiệu suất như Google PageSpeed Insights để theo dõi và đánh giá tốc độ tải trang web. Tuy nhiên, việc tối ưu hóa tốc độ load trang là một quá trình liên tục và cần được thực hiện thường xuyên để đạt được hiệu quả tối đa. #h2("Kết chương") Trong chương 2 tác giả đã trình bày các bước xây dựng mô hình cơ sở dữ liệu, thiết kế kiến trúc dự án và các quy trình tích hợp cổng thanh toán cũng như quy trình cụ thể để đảm bảo an toàn dữ liệu cho website TMĐT. Việc phân tích và đánh giá trước khi bắt đầu xây dựng sản phẩm giúp cho việc xây dựng trở nên an toàn và hiệu quả, đạt được lợi ích lớn nhất. Từ những phân tích và đánh giá đó sẽ áp dụng vào việc xây dựng website sẽ được trình bày trong Chương 3.
https://github.com/Skimmeroni/Appunti
https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Metodi%20Algebrici/Metodi_appunti.typ
typst
Creative Commons Zero v1.0 Universal
#set text( font: "Gentium Plus", size: 10pt, lang: "it" ) #set page( paper: "a4", header: align(right)[_Metodi Algebrici per l'Informatica_], numbering: "1" ) #set par( justify: true ) #set heading( numbering: "1." ) #import "Metodi_defs.typ": * #show: thmrules.with(qed-symbol: $square$) #show par: set block(spacing: 0.55em) #outline(indent: auto) #pagebreak() = Insiemi == Definizione di insieme #include "Insiemi/Definizione.typ" == Corrispondenze e relazioni #include "Insiemi/Relazioni.typ" == Funzioni #include "Insiemi/Funzioni.typ" // == Insiemi numerici noti // #include "Insiemi/Insiemi.typ" #pagebreak() = Numeri interi == Principio di induzione #include "Interi/Induzione.typ" == Divisione euclidea #include "Interi/Divisione.typ" == Numeri in base $n$ #include "Interi/Basi.typ" // == Stime temporali // #include "Interi/Tempo.typ" // == Binomio di Newton // #include "Interi/Newton.typ" == Numeri primi #include "Interi/Primi.typ" == Equazioni Diofantee #include "Interi/Diofantee.typ" == Congruenza Modulo $n$ #include "Interi/Congruenza.typ" == Funzione di Eulero #include "Interi/Eulero.typ" == Teorema di Fermat-Eulero #include "Interi/Fermat.typ" == Metodo dei quadrati ripetuti #include "Interi/Quadrati.typ" #pagebreak() = Strutture algebriche == Semigruppi e monoidi #include "Strutture/Strutture.typ" == Gruppi #include "Strutture/Gruppi.typ" == Permutazioni #include "Strutture/Permutazioni.typ" == Classi di resto #include "Strutture/Resto.typ" == Insiemi di generatori #include "Strutture/Generatori.typ" == Sottogruppi normali #include "Strutture/Normale.typ" == Anelli e campi #include "Strutture/Anelli.typ" #pagebreak() = Polinomi == Polinomi su un campo #include "Polinomi/Polinomi.typ" == Radici di un polinomio #include "Polinomi/Radici.typ" == Costruzione di campi #include "Polinomi/Costruzione.typ" #pagebreak() = Crittografia == Introduzione alla crittografia #include "Crittografia/Introduzione.typ" == Algoritmo RSA #include "Crittografia/RSA.typ" == Firma digitale tramite RSA #include "Crittografia/Firma.typ" // == Logaritmo discreto // #include "Crittografia/Logaritmo.typ" == Test di primalitá #include "Crittografia/Primalita.typ" #pagebreak() = Teoria dei codici == Introduzione alla teoria dei codici #include "Codici/Introduzione.typ" == Codici a blocchi #include "Codici/Blocchi.typ" == Codici lineari #include "Codici/Lineari.typ" == Codifica e decodifica #include "Codici/Codifica.typ" == Codice duale #include "Codici/Duale.typ" == Sindrome #include "Codici/Sindrome.typ" == Codici ciclici #include "Codici/Ciclici.typ"
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/latedef/0.1.0/README.md
markdown
Apache License 2.0
# `latedef` *Use now, define later!* ## Basic usage This package exposes a single function, `latedef-setup`. ```typst #let (undef, def) = latedef-setup(simple: true) My #undef is #undef. #def("dog") #def("cool") ``` ![](example-images/1.png) Note that the definition doesn't actually have to come _after_ the usage, but if you want to define something beforehand, you're better off using a variable instead. ```typst #let (undef, def) = latedef-setup(simple: true) // Instead of #def("A") The first letter is #undef. // you should use #let A = "A" The first letter is #A. ``` ![](example-images/2.png) ## The `simple` parameter When `simple: false` (which is the default), `undef` becomes a function you have to call. It takes an optional positional or named parameter `id` of type `str`, which can be used to define things out of order. ```typst #let (undef, def) = latedef-setup() // or `latedef-setup(simple: false)` // Note that you can still call it without an id, which works just like when `simple: true`. My letters are #undef("1"), #undef(id: "2"), and #undef(). // `def` now takes one positional and either another positional or a named parameter. #def("C") #def(id: "2", "B") #def("1", "A") ``` ![](example-images/3.png) ## The `footnote` parameter This is a convenience feature that automatically wraps `undef` in `footnote`, either directly (when `simple: true`) or as a function (when `simple: false`). This corresponds to LaTeX's `\footnotemark` and `\footnotetext`, hence the different names in the example. ```typst #let (fmark, ftext) = latedef-setup(simple: true, footnote: true) Do#fmark you#fmark believe#fmark in God?#fmark #let wdym = "What do you mean" #ftext[#wdym "Do"?] #ftext[#wdym "you"?] #ftext[#wdym "believe"?] #ftext[And w#wdym.slice(1) "God"?] ``` ![](example-images/4.png) ## The `stand-in` parameter This is a function that takes a single positional parameter (`id`) of type `none | str` and produces a stand-in value that gets shown when a late-defined value is missing a corresponding definition. <!-- isolate-example --> ```typst #let (undef, def) = latedef-setup() // This is the default stand-in #undef() #undef("with an id") // Custom stand-in #let (undef, def) = latedef-setup(stand-in: id => emph[No #id!]) #undef() #undef("id") ``` ![](example-images/5.png) Since `stand-in` is a function, which is only called when a definition is actually missing, you can even set it to panic to enforce that all late-defined values have a definiton. <!-- fail-example --> ```typst #let (undef, def) = latedef-setup(stand-in: id => panic("Missing definition for value with id " + repr(id))) #undef() #undef("id") ``` The output will look something like ``` error: panicked with: "Missing definition for value with id none" ┌─ example.typ:1:50 │ │ #let (undef, def) = latedef-setup(stand-in: id => panic("Missing definition for value with id " + repr(id))) │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: panicked with: "Missing definition for value with id \"id\"" ┌─ example.typ:1:50 │ │ #let (undef, def) = latedef-setup(stand-in: id => panic("Missing definition for value with id " + repr(id))) │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``` And there is no error when everything has a definition: ```typst #let (undef, def) = latedef-setup(stand-in: id => panic("Missing definition for value with id " + repr(id))) #undef() is #undef("id"). #def("This") #def("id", "fine") ``` ![](example-images/6.png) ## The `group` parameter Sometimes you may want to use multiple instances of `latedef` in parallel. This is done using the `group` parameter, which can be `none` (the default) or any `str`. Note that using `footnote: true` sets the default group to `"footnote"` instead. ```typst // Use a group for the figure stuff... #let (caption-undef, caption) = latedef-setup(simple: true, group: "figure") #let figure = std.figure.with(caption: caption-undef) // ...so you can still use the regular mechanism in parallel. #let (undef, def) = latedef-setup(simple: true) #figure(raw(block: true, lorem(5))) #caption[The #undef _lorem ipsum_.] #def("classic") ``` ![](example-images/7.png)
https://github.com/pabsantos/anpet-typst
https://raw.githubusercontent.com/pabsantos/anpet-typst/main/main.typ
typst
#import "anpet-typst.typ": anpet-typst #show: anpet-typst.with( authors: ( ( name: "<NAME>", department: "Pesquisa, Desenvolvimento & Inovação", affiliation: "Observatório Nacional de Segurança Viária", email: "<EMAIL>", address: "Rua, 123, Centro, Curitiba, PR, Brasil" ), ( name: "<NAME>", department: "XYZ Department", affiliation: "ABC University", email: "<EMAIL>", address: "Rua, 456, Centro, Curitiba, PR, Brasil" ) ), title: "TEMPLATE EM TYPST PARA O CONGRESSO DA ANPET", agradecimentos: "Agradeço ao ONSV pelo financiamento dessa pesquisa.", bibliography: bibliography( "refs.bib", title: text(10pt, [REFERENCIAS BIBLIOGRÁFICAS]), style: "apa" ), ) = TEXTO #lorem(50) #lorem(50) @santosEstabelecimentoMetasReducao2022 == Heading 2 #lorem(50) @santosRoadtrafficdeathsRoadTraffic2023 === Heading 3 #lorem(50) = TABELAS A @tbl-test inclui a tabela no formato requerido pelo congresso. #figure( table( columns: 3, table.header([a], [b], [c]), [1], [2], [3], [4], [5], [6], [7], [8], [9], table.hline() ), caption: [Tabela formatada] ) <tbl-test> = FIGURAS A @fig-test inclui uma figura apresentada no formato do congresso. #figure( image("fig/taz_dist.png"), caption: [Inserção de figuras] ) <fig-test> = EQUAÇÕES A @eq-test apresenta uma equação no formato requerido. $ R = c_1 G + c_2 G V + c_a A V^2 + 10 G i $ <eq-test> #block( [ #show par: set block(spacing: 0.65em) em que: $R$: resistência total [N]; #h(1.5cm) $c_1$: constante; #h(1.5cm) $G$: peso bruto total combinado [kN]; #h(1.5cm) $c_2$: constante; #h(1.5cm) $V$: velocidade [km/h]; #h(1.5cm) $c_a$: constante de penetração aerodinâmica; #h(1.5cm) $A$: seção transversal do veículo [$m^2$]; e #h(1.5cm) $i$: declividade da rampa [m/100 m]. ] ) #lorem(25)
https://github.com/Ourouk/IOT_Bicycle_fleet
https://raw.githubusercontent.com/Ourouk/IOT_Bicycle_fleet/main/rapport/main.typ
typst
#import "template.typ": * #show: project.with( course-title: "IOT", title: "Vélos connectés", authors: ( ( first-name: "Andrea", last-name: "Spelgatti", cursus: "M. Ing. Ind. - Informatique", ), ( first-name: "\nMartin", last-name: "<NAME>", cursus: "M. Ing. Ind. - Informatique", ), ), bibliography-file: "ref.bib" ) = Introduction == Problématique Lors de nos diverses balades en ville, nous pouvons désormais constater l'apparition de plus en plus fréquente de vélos en libre-service. C'est ainsi que l'idée de gérer une flotte de vélos universitaires, disponibles pour les étudiants et le personnel sur un campus, nous est venue à l'esprit. Des problématiques apparaissent directement avec cette idée, comme l'exemple du campus de Google à Mountain View, où une succession de vols des vélos mis à disposition sur le site a eu lieu, avec près de 250 disparitions par semaine #cite(<ruggieroSecurityFlawGoogle2018>). On ne sait également pas qui utilise les vélos, si les règles d'utilisation sont respectées ou si les vélos sont en bon état. Il semble donc nécessaire de mettre en place un système de gestion de ces vélos pour éviter ce genre de désagrément. Cet ajout est aussi l'occasion de proposer une série de fonctionnalités qui pourraient être utiles pour les utilisateurs. == Objectif L'objectif de ce projet est de réaliser un système de gestion permettant de suivre l'activité des vélos en libre-service à l'intérieur d'un campus. Ce système devra permettre de gérer les vélos, les stations, les utilisateurs et les trajets. Nous ajouterons également quelques fonctionnalités intelligentes pour améliorer le confort de l'utilisateur. == Proposition Le projet consiste à réaliser trois objets connectés avec des capteurs différents. Ces objets sont les suivants : - Un vélo connecté avec un ESP32 compatible LORA, intégrant une gestion des lumières en fonction de la luminosité, un buzzer, un GPS et un lecteur RFID pour prévenir le vol; - Une station de sécurité/charge connectée avec un ESP32 compatible WIFI, comprenant une détection de la présence ou non d'un vélo et un système de déverrouillage par badge; - Une antenne connectée avec un edge processing basé sur un Raspberry Pi se connectant aux deux autres objets et agissant comme un point relais ou un hub. Le serveur de gestion sera réalisé en Python avec une base de données MongoDB. Un serveur sera présent côté client de notre produit, et un second sera géré de notre côté pour la distribution de mises à jour, le dépannage et la télémétrie. Les deux serveurs seraient basés sur Rocky Linux en utilisant une architecture containerisée avec Docker. == Diagramme #set page(flipped: true) #figure(image("./figures/IOT-diagramme.jpg",width: 100%),)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/gentle-clues/0.8.0/lib/predefined.typ
typst
Apache License 2.0
#import "clues.typ": clue, get-title-for, if-auto-then, increment_task_counter, get_task_number #import quote as typst_quote // needed for quote // Predefined gentle clues /* info */ #let info(title: auto, icon: "assets/info.svg", ..args) = clue( accent-color: rgb(29, 144, 208), // blue title: if-auto-then(title, get-title-for("info")), icon: icon, ..args ) /* success */ #let success(title: auto, icon: "assets/checkbox.svg", ..args) = clue( accent-color: rgb(102, 174, 62), // green title: if-auto-then(title, get-title-for("success")), icon: icon, ..args ) /* warning */ #let warning(title: auto, icon: "assets/warning.svg", ..args) = clue( accent-color: rgb(255, 145, 0), // orange title: if-auto-then(title, get-title-for("warning")), icon: icon, ..args ) /* error */ #let error(title: auto, icon: "assets/crossmark.svg", ..args) = clue( accent-color: rgb(237, 32, 84), // red title: if-auto-then(title, get-title-for("error")), icon: icon, ..args ) /* task */ #let task(title: auto, icon: "assets/task.svg", ..args) = { increment_task_counter() clue( accent-color: maroon, title: if-auto-then(title, get-title-for("task") + get_task_number()), icon: icon, ..args ) } /* tip */ #let tip(title: auto, icon: "assets/tip.svg", ..args) = clue( accent-color: rgb(0, 191, 165), // teal title: if-auto-then(title, get-title-for("tip")), icon: icon, ..args ) /* abstract */ #let abstract(title: auto, icon: "assets/abstract.svg", ..args) = clue( accent-color: olive, title: if-auto-then(title, get-title-for("abstract")), icon: icon, ..args ) /* conclusion */ #let conclusion(title: auto, icon: "assets/lightbulb.svg", ..args) = clue( accent-color: rgb(255, 201, 23), // yellow title: if-auto-then(title, get-title-for("conclusion")), icon: icon, ..args ) /* memorize */ #let memo(title: auto, icon: "assets/excl.svg", ..args) = clue( accent-color: rgb(255, 82, 82), // kind of red title: if-auto-then(title, get-title-for("memo")), icon: icon, ..args ) /* question */ #let question(title: auto, icon: "assets/questionmark.svg", ..args) = clue( accent-color: rgb("#7ba10a"), // greenish title: if-auto-then(title, get-title-for("question")), icon: icon, ..args ) /* quote */ #let quote(title: auto, icon: "assets/quote.svg", attribution: none, content, ..args) = clue( accent-color: eastern, title: if-auto-then(title, get-title-for("quote")), icon: icon, ..args )[ #typst_quote(block: true, attribution: attribution)[#content] ] /* example */ #let example(title: auto, icon: "assets/example.svg", ..args) = clue( accent-color: orange, title: if-auto-then(title, get-title-for("example")), icon: icon, ..args ) /* aim */ #let goal(title: auto, icon: "assets/flag.svg", ..args) = clue( accent-color: red, title: if-auto-then(title, get-title-for("goal")), icon: icon, ..args )
https://github.com/Sepax/Typst
https://raw.githubusercontent.com/Sepax/Typst/main/DIT323/Assignments/A1/main.typ
typst
#import "template.typ": * #show: template.with( title: [Finite automata and formal languages #linebreak() Assignment 1], short_title: "DIT084", description: [ DIT323 (Finite automata and formal languages)\ at Gothenburg University, Spring 2024 ], authors: ((name: "<NAME>"),), lof: false, lot: false, lol: false, paper_size: "a4", cols: 1, text_font: "XCharter", code_font: "Cascadia Mono", accent: "#000000", // black ) = _Question:_ Prove using induction that, for every finite alphabet, $Sigma, forall n in NN. |Sigma^n| = |Sigma|^n$. _Solution:_ Let $P(n) := |Sigma^n| = |Sigma|^n$. #proof[ By induction on $n$. _Basis:_ $P(0)$ is true since $|Sigma^0| = 1 = |Sigma|^0$. _Inductive step:_ Assume $P(n)$ is true for some arbitrary $n in NN$ _(i.h.)_. We want to show that $P(n+1)$ is true. Let $Sigma$ be a finite alphabet. Then, $|Sigma^{n+1}| = |Sigma| |Sigma^n|$ by definition of $Sigma^{n+1}$. By the induction hypothesis, $|Sigma^n| = |Sigma|^n => |Sigma^{n+1}| = |Sigma| |Sigma^n| = |Sigma| |Sigma|^n = |Sigma|^{n+1}$. $therefore forall n in NN. P(n)$. ] = Define a language $S$ containing words over the alphabet $Sigma = {a,b}$ inductively in the following way: - The empty word is in $S$: $epsilon in S$ - If $u, v in S$, then _auavb_ $in S$. - If $u, v, w in S$, then _buavaw_ $in S$. == _Question:_ Use recursion to define two functions $hash_a, hash_b ∈ Sigma^* -> NN$ that return the number of occurrences of $a$ and $b$, respectively, in their input. _Solution:_ $ hash_a (u v) = cases( 0 & quad "if" u v = epsilon, 1 + hash_a (v) & quad "if" u = a, hash_a (v) & quad "if" u eq.not a) $ #linebreak() $ hash_b (u v) = cases( 0 & quad "if" u v = epsilon, 1 + hash_b (v) & quad "if" u = b, hash_b (v) & quad "if" u eq.not b) $ #pagebreak() == _Question:_ Use induction to prove that $forall w in S. hash_a (w) = 2 hash_b (w)$. _Hint:_ You might want to show that $hash_a ( italic("auavb") ) = 2 + hash_a (u) + hash_a (v)$. How do you prove this? This property follows from a lemma that you can perhaps prove by induction: $forall u,v in Sigma^* . hash_a (u v) = hash_a (u) + hash_a (v)$ _Solution:_ ==== Proof of lemma from hint Lemma to prove: $l_1 := forall u,v in Sigma^* . hash_a (u v) = hash_a (u) + hash_a (v)$ Let $P(u) := hash_a (u v) = hash_a (u) + hash_a (v)$. #proof[ By induction on $u$. _Basis:_ $P(epsilon)$ is true since $hash_a (epsilon) = 0 = hash_a (epsilon) + hash_a (epsilon)$. _Inductive step:_ Assume $P(u)$ is true for some arbitrary $u in Sigma^*$ _(i.h.)_. We want to show that $P(a u)$ is true. Let $v in Sigma^*$. Then, $ hash_a (a u v) &= 1 + hash_a (u v) & & wide ("by definition of" hash_a) \ &= 1 + hash_a (u) + hash_a (v) & & wide ("i.h") \ &= hash_a (a u) + hash_a (v) & & wide ("by definition of" hash_a) $ $therefore forall u,v in Sigma^*. P(u)$. ] Because $hash_a$ and $hash_b$ are defined in the same way, the same proof can be applied to: $ forall u,v in Sigma^* . hash_b (u v) = hash_b (u) + hash_b (v) $ ==== Using lemma 1 to prove lemma 2 from hint _Lemma to prove:_ $l_2 := hash_a ( italic("auavb") ) = 2 + hash_a (u) + hash_a (v)$ #proof[ $ hash_a (a u a v b) &= 1 + hash_a (u a v b) & & wide ("by definition of" hash_a) \ &= 1 + hash_a (u) + hash_a (a v b) & & wide ("lemma" l_1) \ &= 1 + hash_a (u) + 1 + hash_a (v b) & & wide ("by definition of" hash_a) \ &= 2 + hash_a (u) + hash_a (v) + hash_a (b) & & wide ("lemma" l_1) \ &= 2 + hash_a (u) + hash_a (v) + hash_a (epsilon)& & wide ("by definition of" hash_a) \ &= 2 + hash_a (u) + hash_a (v) & & wide ("by definition of" hash_a) $ $therefore hash_a ( italic("auavb") ) = 2 + hash_a (u) + hash_a (v)$ ] Because $hash_a$ and $hash_b$ are defined in the same way, the same proof can be applied to: $ hash_b ( italic("bubva") ) = 2 + hash_b (u) + hash_b (v) $ #pagebreak() ==== Using statement to prove original question _Statement to prove:_ $forall w in S. hash_a (w) = 2 hash_b (w)$ Let $P(w) := hash_a (w) = 2 hash_b (w)$. #proof[ By induction on $w$. _Basis:_ $P(epsilon)$ is true since $hash_a (epsilon) = 0 = 2 hash_b (epsilon)$. _Inductive step:_ Assume $P(w)$ is true for some arbitrary $w in S$ _(i.h.)_. We want to show that $P(italic("auavb")) and P(italic("buavaw"))$ is true. Let $u,v,w in S$. Then, $ hash_a ( italic("auavb") ) &= 2 + hash_a (u) + hash_a (v) & & wide ("lemma" l_2) \ &= 2 + 2 hash_b (u) + 2 hash_b (v) & & wide ("i.h") \ &= 2 (1 + hash_b (u) + hash_b (v)) & & wide ("arithmetic") \ &= 2 hash_b ( italic("auavb") ) & & wide ("by definition of" hash_b) $ #linebreak() $ hash_a ( italic("buavaw") ) &= 2 + hash_a (u) + hash_a (v) & & wide ("lemma" l_2) \ &= 2 + 2 hash_b (u) + 2 hash_b (v) & & wide ("i.h") \ &= 2 (1 + hash_b (u) + hash_b (v)) & & wide ("arithmetic") \ &= 2 hash_b ( italic("buavaw") ) & & wide ("by definition of" hash_b) $ $therefore forall w in S. P(w)$. ] = _Question:_ Let $Sigma = {0}$ and define $f, g, h in Sigma^* -> NN$ recursively in the following way: - $g(epsilon) = 1$ #linebreak() $g(0w) = |w| + g(w) + -h(w)$ - $h(epsilon) = 0$ #linebreak() $h(0w) = |w| + g(w)$ - $f(epsilon) = 1$ #linebreak() $f(0w) = h(w) = 2g(w)$ == _Question:_ Compute the values of $f(00), g(00), h(00), f(000), g(000), h(000), f(0000), g(0000), h(0000)$ _Solution:_ $ &f(00) &= 3 quad &g(00) &= 1 quad &h(00) &= 2 \ &f(000) &= 4 quad &g(000) &= 1 quad &h(000) &= 3 \ &f(0000) &= 5 quad &g(0000) &= 1 quad &h(0000) &= 4 $ #pagebreak() == _Question:_ Prove that $forall n in NN. f(0^n) = 1+n$. _Hint:_ First prove that $forall n in NN. g(0^n) = 1 and h(0^n) = n$. _Solution:_ ==== Proof of lemma from hint _Lemma to prove:_ $l_3:$ $forall n in NN. g(0^n) = 1 and h(0^n) = n$. Let $P(n) := g(0^n) = 1 and h(0^n) = n$. #proof[ By induction on $n$. _Basis:_ $P(0)$ is true since $g(0^0) = g(epsilon) = 1 = 1 and h(0^0) = 1 and h(epsilon) = 1 and 1 = 1$. _Inductive step:_ Assume $P(n)$ is true for some arbitrary $n in NN$ _(i.h.)_. We want to show that $P(n+1)$ is true. Let $n in NN$. Then, $ g(0^{n+1}) &= |0^n| + g(0^n) + -h(0^n) & & wide ("by definition of" g) \ &= n + 1 + 1 + -n & & wide ("i.h") \ &= 1 & & wide $ $therefore forall n in NN. g(0^n) = 1 and h(0^n) = n$ ] ==== Proof of main statement _Statement to prove:_ $forall n in NN. f(0^n) = 1+n$. Let $P(n) := f(0^n) = 1+n$. #proof[ By induction on $n$. _Basis:_ $P(0)$ is true since $f(0^0) = f(epsilon) = 1 = 1 + 0$. _Inductive step:_ Assume $P(n)$ is true for some arbitrary $n in NN$ _(i.h.)_. We want to show that $P(n+1)$ is true. Let $n in NN$. Then, $ f(0^{n+1}) &= h(0^n) + 2 g(0^n) & & wide ("by definition of" f) \ &= n + 2 & & wide ("lemma" l_3) \ &= 1 + (n + 1) $ $therefore forall n in NN. f(0^n) = 1+n$ ]
https://github.com/bchaber/typst-template
https://raw.githubusercontent.com/bchaber/typst-template/main/slides/slides.typ
typst
#import "@preview/polylux:0.3.1": * #import themes.simple: * #set text(font: "Inria Sans") #show: simple-theme.with( footer: [Warsaw University of Technology], ) #title-slide[ = Keep it simple! #v(2em) <NAME> #footnote[Warsaw University of Technology] #h(1em) Jan 2024 ] #slide[ = Introduction #side-by-side(gutter: 0mm, columns: (4fr, 4fr))[ #lorem(20) ][ #figure(image("sample.png", height: 100%)) ] ] #focus-slide[ Basic rules: - structure your talk, - try being engaging, - use simple ideas. ] #centered-slide[ = Let's start a new section! ] #slide[ == Dynamic slide Did you know that... #pause ...you can see the current section at the top of the slide? ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/003%20-%20Gatecrash/009_Fblthp.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Fblthp", set_name: "Gatecrash", story_date: datetime(day: 25, month: 12, year: 2013), author: "<NAME>", doc ) The noise that escaped Fblthp's lips could best be described as a whimper. He didn't speak any language the citizens of Ravnica were familiar with, but that agonized sound of desperation was instantly recognizable. Unfortunately, the alley Fblthp found himself in was seemingly deserted, except for who caused the whimper in the first place. #figure(image("009_Fblthp/01.jpg", width: 100%), caption: [], supplement: none, numbering: none) Weathered fists seized the tiny homunculus by the arms and hoisted him up until he was face-to-eye with a wiry human. Pierced and severe, the human's face twisted in a sneer. Fblthp fell silent and instinctively started quivering. It was the most scared he'd ever been. It was also the highest he'd ever been off the ground. A laugh, like the scraping of boots on cobblestone, emerged from his captor. Tucking Fblthp under his arm as a courier would a missive, the human slinked off toward a neighborhood known to be controlled by the Cult of Rakdos. This wasn't how this was supposed to go. Fblthp started whimpering again. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Fblthp was immensely grateful his service to the Azorius Senate rarely required him to leave the safety and relative simplicity of the Magisters' Garden. His duties were also relatively simple: remove detritus from the wide pedestrian walkways that joined the various fountains and canals, polish the lower plaques adorning the statues of notable lawmakers, and alert the security officers of anything troubling. As ordinances forbade anything troubling on the grounds, the last duty had seldom been required. Like many in service to the senate, Fblthp enjoyed basic protections and allowances appropriate to his station as provided by law. In fact, he'd grown quite accustomed to the way he was treated by his masters—that is, to being ignored. He was given food and an unassuming home of sorts. Working with the flora in the garden sometimes aggravated his allergies, so the senate also provided a solution to prevent his eye from itching too badly. It was a safe, wonderful existence. It was unusual for members of other guilds to visit the Magisters' Garden, and the appearance of outsiders usually scared Fblthp. The leaf-covered druids of the Selesnya weren't too bad, although they did tend to pet him while uttering indecipherable prayers. Simic researchers sometimes mumbled among themselves about cross-breeding Fblthp with a bat or a sea anemone. At that point, Fblthp usually remembered some forgotten duty on the other side of the garden and skittered away. One day, as Fblthp walked the western edge of the garden, scooping up discarded scraps of food and other trash, he was approached by a human woman. He recognized the imposing figure by her attire—sigiled armor and cobalt trappings. She was an arrester. This was odd, indeed. Most arresters who visited the garden disregarded him completely, often accidentally kicking him if he were in their path. She leaned down and peered sternly into Fblthp's eye. #figure(image("009_Fblthp/02.jpg", width: 100%), caption: [], supplement: none, numbering: none) "You are Thbltpth?" she asked, the last word bringing a torrent of spittle upon the homunculus's face. Fblthp blinked twice and bobbed his head slightly. "I am <NAME>. I serve the Ninth Precinct. Pursuant to Provision IV.126.3 of Isperia's Edict, I require your assistance. Please come with me." She offered her hand. Fblthp whimpered. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Fblthp had never been inside any of the three majestic columns that comprised New Prahv. They were impossibly tall, gleaming, and immaculate. Without a word, he was deposited in a stark subchamber on the first floor by a slender vedalken male. Blinking slowly, Fblthp nervously absorbed his new surroundings; the barren walls and plain furniture that was too high up to be helpful. So he stood and waited. #figure(image("009_Fblthp/03.jpg", width: 100%), caption: [], supplement: none, numbering: none) Eventually, Parisha opened the wooden door and entered. Determined and efficient, but not unkind, she sat and placed two scrolls on the desk. She looked expectantly at Fblthp and glanced at the opposing chair. Realizing the impossibility of her silent request, she rose and lifted Fblthp into the chair. It was the highest he'd ever been off the ground. "This," Parisha proclaimed as she unfurled the first scroll, "is Vadax Gor. For months now, he's associated himself with a certain Rakdos establishment. A 'diversion club,' as I believe it is known." Parisha spat out the phrase distastefully. Fblthp shivered slightly at the image of the strange human. His face was ravaged with scars, piercings, and tattoos. Tattered scraps that barely qualified as clothing hung lazily from his malnourished frame. Fblthp had never encountered anything like him, and he earnestly wished not to. "<NAME> enjoys all manner of depravity," Parisha continued, "but lately his tastes have grown perversely specialized. He is no longer satisfied to keep his foolishness contained to the cult. He is suspected in the disappearance of two of our citizens. With your assistance, there won't be a third. Investigators have yet to find direct evidence of Gor's involvement in the kidnappings. We need to catch him in the act." Fblthp's eye grew wide, even for him. He briefly wondered if he could make it to the door before Parisha could catch him, but he knew this was foolish. He wouldn't be allowed to return to his duties if he disobeyed an arrester. Besides, he was still very high up on that chair. He wasn't sure he could jump down without hurting himself. Lacking other options, Fblthp whimpered softly. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "The previous two abductions have taken place within two blocks of this leatherworking shop," Parisha said, pointing at the map. "We believe the owner of that shop is somehow involved. Perhaps he is signaling Gor when a likely target appears. You are to travel to his shop to deliver these tax forms. They will need to be filled out immediately and in triplicate. If our suspicions are correct, Gor will make his move after you depart." If she had left it at that, Fblthp would surely have ran, beloved garden duties or no. But her eyes softened momentarily and she continued. "Do not fear, little one. My agents and I will be stationed throughout the area. We will never lose sight of you. You will be in no danger. Gor will not lay a hand on you. You'll be back in the Magisters' Garden in a few days. Isperia's Edict does not permit me to fail you. " She smiled slightly. Fblthp wasn't sure if he believed this, but he stopped quivering and nodded slowly. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Fblthp had always hated crowds. He scooted down the busy Ravnican thoroughfare, his eye darting quickly from passerby to passerby. No one was particularly paying him much attention, which he liked. No one was particularly making any effort to step around him, either. He was nearly kicked half a dozen times before he made it to his destination. #figure(image("009_Fblthp/04.jpg", width: 100%), caption: [Totally Lost | Art by <NAME>umbo], supplement: none, numbering: none) The leatherworker and proprietor was human, but only technically. Burly as an ogre and twice as ugly, he towered over Fblthp and grunted. Fblthp meekly presented his satchel. The man grunted again and opened it. Bits of food fell out of his scraggly beard as he began to read—an impressive feat, all things considered. A thunderous noise rumbled out of the man as he went to a back storeroom. Fblthp blinked and eyed the food on the floor suspiciously. After a time, the owner emerged and thrust the completed forms in Fblthp's direction. Fblthp bowed and turned to leave. The man rumbled again, but Fblthp wasn't sure why. As instructed, he turned toward the alleys behind the shop. Parisha, masquerading as a shopper at a nearby fruit market, briefly made eye contact with the homunculus as he disappeared into the alley. That made him feel better. Fblthp walked down the alley, slowly but with growing confidence. He imagined Parisha and her comrades would be making arrests any minute now, and he could go back to the garden. He thought of the gently flowing waters of the garden's canals when a terrible crashing sound rang out behind him. He whipped around, expecting to see Parisha or one of the arresters. Instead, the dreadful shape of <NAME>or emerged from the shadows. Fblthp dropped his satchel and whimpered. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Gor's confidence and speed both grew as he left the scene of the crime behind him. Fblthp closed his eye, not wanting to see the fate that awaited him. He felt Gor turn left at an intersection. Then right. And then, without warning, Gor stopped. Fblthp opened his eye slightly at the jolt. He squirmed around to get a look at Gor, now frozen. He opened his eye a little wider, not comprehending what was going on. #figure(image("009_Fblthp/05.jpg", width: 100%), caption: [], supplement: none, numbering: none) Parisha approached them from behind at a full sprint. "<NAME>," she shouted between heavy breaths, "you are under arrest." As she caught up to them, she dislodged Fblthp from the detainee's grip. Fblthp noticed a blue glow surrounding Gor, who was still immobile. "My apologies, little one," Parisha murmured. "That leatherworker must've suspected something and attacked one of my agents before we could begin our pursuit. It was a minor delay, but you were in no danger." They were quickly joined by several other arresters, who dragged the deadweight known as <NAME> back through the alley toward the square. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Fblthp stood in an antechamber on the sixth floor of the Lyev Column. It was the highest he'd ever been off the ground. Parisha stood beside him. Silently, she turned, bent slightly at the waist, and nodded to him. A marble door Fblthp hadn't realized was there swung out from unseen hinges, and a squat, robed official strode into the room. Parisha saluted. "Senator," she greeted him reverently. Fblthp blinked. "Arrester. Congratulations on a successful mission. This is the one you mentioned in your report?" He peered down at a piece of parchment. "Cthillcip?" "Yes, Senator." "Very well." The elder bureaucrat turned his gaze onto the foot-high homunculus. "Pursuant to Provision III.875.2b of Isperia's Edict, please accept my thanks on behalf of the senate and the lawful people of Ravnica. Although monetary reward is disallowed, your descendants may petition the senate to create a tablet recounting your honorable deeds upon your death." He turned and left the room. Parisha motioned to the room's southern exit. "Come, let us return you to your duties." Fblthp practically bounced to the door, eager to see the Garden again. "At least, until next time." Fblthp whimpered.
https://github.com/Chwiggy/thesis_bachelor
https://raw.githubusercontent.com/Chwiggy/thesis_bachelor/main/src/chapters/04_access.typ
typst
#import "../preamble.typ": * #set math.equation(numbering: "(1)") = Transit Access As seen in @related, there are plenty of ways to operationalise transit accessibility, as a local measure. For this thesis, I focused on local connectivity without a large focus on specific itinerary scenarios. As detailed in @data, data acquisition focused on travel time matrices to ascertain a measure of reach. As as i set up these these travel time matrices, they are an active measure of reach, that is they measure how easy or hard it may be to move from one cell to another, as oppossed how easy it is for a cell to be reached @levinson_towards_2020. This can obviously easily be reversed to measure passive reach. Travel time here is used as a common cost measure for transit accessibility. As discussed earlier @related this is of course not the only realistic measure of impedance. As Heidelbergs transit has generally integrated ticketing and a reasonably high degree of people with public transit subscriptions, it seems reasonable to ignore some cost measures like fare rules. With this approach to reach, I'm basically approximating the inverse of closeness centrality as formulated by @stamos_transportation_2023. Transit access, however, depends on temporal aspects as well, both because different destinations offer various time constraints as well as the transport network changing over the course of the day @levinson_towards_2020. As mentioned in @related, this represents a gap in current travel time datasets, and transit accessibility analyses @verduzco_torres_public_2024. By calculating travel time matrices for every hour of the day for this thesis, I try to fill this gap. == Post-Processing <processing> After travel time matrices were calculated with `r5py` @r5py as used in @tenkanen_longitudinal_2020, based on the conveyal engine @Conway_uncertainty_2018, average Travel Times $T_c$ were calculated as in @TravelTimeEq for each cell with $C_d$ as Travel Time Cost from cell to another destination cell divided by the Number of Cells $N_c-1$ for the cell itself. $ T_c = (sum C_d)/(N_c-1) $ <TravelTimeEq> Here $C_d$ describes the median travel time for a cell to cell connection at every point in time within the set 1 hour time interval given to `r5py`. These average travel times were calculated for 24 hours in a representative day for each cell. Capturing median travel times for each hour of that day from cell to cell, based on the Conveyal approach to travel time uncertainties @Conway_uncertainty_2018. This also represents `r5py`'s default behaviour, as `r5py` @r5py by default returns the median travel time over the supplied departure time window for the travel time matrix calculation. It can also supply other percentile travel times within this departure time window. I will make use of this fact in @planning. Using this median travel time for the average cell to cell travel times over the course of the departure time window of an hour can provide a more realistic measure than a single departure point in time, that would be inherently dependent on the whims of the schedule @levinson_towards_2020 @owen_modeling_2015. This measure has also been used in travel time datasets for metrics spanning the UK @verduzco_torres_public_2024 or Helsinki @tenkanen_longitudinal_2020. There is however a gap in temporal variability of transport choices across the course of a day @verduzco_torres_public_2024. One could obviously extend the whole departure time window to an entire day and compare various percentile outcomes. However, that approach limits insights into specific service patterns accross a day and their influence on connectivity. Therefore, it makes more sense to compute travel time matrices for multiple routing queries over the course of a day and to compare their results with each other. == Results Below I will talk about the resulting travel time matrices in two sections. The first concerns the raw insights from travel time calculations. primarily centered around discussions of the travel time matrix at 17:00 local time. The second section then summarises insights gained from the differences in travel time matrices over the course of the day. === Travel Times Looking of a map of the travel time matrix at 17:00 local time (see @map_17_tt), there is a clear pattern visible. The brightest spots with the lowest average cell to cell travel times centre around central locations within Heidelberg, specifically around the central station and the central interchange hubs Stadtbücherei / Römerkreis Süd and Bismarckplatz. Here average travel times to all cells are as low as 48 minutes. Notably at the central station there is a cell which lands in the middle of the western station throat, from which no other cells than the cell itself are reachable, and therefore technically has an average travel time of 0 minutes. This cell was discounted for analysis. #figure(image("../figures/Heidelberg_TravelTime_Map17.svg"), caption: [Map of average travel times in minutes in Heidelberg in the hour from 5 to 6 pm from h3 cell to h3 cell.], supplement: "Map", kind: "Map") <map_17_tt> The highest average travel times can be found on the outskirts of the administrative boundaries of Heidelberg in areas without much population or built up area. This includes the area around Grenzhof, an outlying farm complex, a landfill south of Patrick-Henry-Village, and forests to the West of Ziegelhausen and north east of Handschuhsheim. Here average travel times reach values of up to 95 minutes. Many of them include significant walks in their itineraries. Notably, the lowest travel times extend specifically along the tram lines of Heidelberg. The lowest median travel times can be found specifically along those tracks that carry more than one tram line. Those are the tracks between Hauptbahnhof / Betriebshof and Seegarten / Bismarkplatz, as well as the tracks extending north to Handshuhsheim from there. Another low travel time corridor extends then south from Römerkreis towards Rohrbach. Corridors like the line from Betriebshof to the university campus Im Neuenheimer Feld, show up as a low travel time corridor at peak times, but diminish in prominence off peak. As a whole the 1301 cells across Heidelberg, are hard to grasp. So I attempted to group them by neighbourhoods (compare @boxplot_17_tt). Unfortunately this results in a clear separation between boroughs that contain large unpopulated areas and those that do not. Bahnstadt, Bergheim, Pfaffengrund, Neuenheim, Rohrbach, Südstadt, and Weststadt all contain comparatively little unpopulated area. The range of travel times in these boroughs is all comparatively small and their median cells have travel times below 70 minutes. #figure(image("../figures/Heidelberg_TravelTime_BP17.svg"), caption: [Boxplots showing average travel times per cell grouped by the borough of the start location.]) <boxplot_17_tt> On the flip side, boroughs with large unpopulated areas like Altstadt, Handschuhsheim, Schlierbach, Wieblingen, Ziegelhausen show a large spread of travel times and exhibit median travel times up to 80 minutes. Their population density too then drops far below the values for the lower travel time boroughs. For this reason it seemed reasonable to exclude cells with a low population density below 5 people per square kilometre from the analysis (compare @clean_boxplot). #figure(image("../figures/Heidelberg_TravelTime_BP_cleaned.svg"), caption: [Boxplot showing average travel times per cell grouped by borough, ignoring cells with population densities lower than 5 / $"km"^2$.]) <clean_boxplot> Excluding low population cells like this reduces the amount of cells in consideration to about a third. This of course means the statistics for each borough might get more susceptible to outlier cells like Grenzhof in Wieblingen. Notable however is that now Altstadt joins the ranks of well connected neighbourhoods. Whereas, it becomes more clear that Boxberg, and Emmertsgrund are actually less well connected even after exclusion of the large forrested area to the east of their population centres (compare @borough_map). #figure(image("../figures/Boroughs_TravelTime_Map17.svg"), caption: [Chloropleth map of Heidelberg boroughs showing average travel times in minutes], kind: "Map", supplement: "Map") <borough_map> === Temporal Variability As I calculated travel times for all 24 hour slots of the day, we can look at the changes to these travel time patterns over the course of the day. Looking at a plot of all cells' average travel times then, it is hard to make out individual cells among the 1301 different locations (compare @daily_travel_time). There are however three distinct sections to the graph: + there appears to be a night section from midnight up until about 03:00 local time. The spread of travel times seems fairly low within this time span, but travel times are fairly high between 70 and 90 minutes. + between 04:00 and about 17:00 local time, the span of average travel times increases quite severely, now ranging from under 50 minutes to curiously about 100 minutes. Several locations seem to exhibit volatile changes within that span, while others remain steady. + after 17:00 local time, the spread of average travel times reduces again until midnight. Notably, well connected locations seem to gain travel times first. #box(grid(columns: 1, [#figure(image("../figures/Heidelberg_TravelTime_MT17.svg"), caption: [Plot of average travel times in Heidelberg from cell to cell, over the course of a weekday.], placement:auto) <daily_travel_time>], [#figure(image("../figures/clean_tt_summary_stats_all.svg"), caption: [Summary plot for all of Heidelberg.])<summary_plot>] )) A similar picture emerges when plotting, summary statistics for the cells above the population threshhold. @summary_plot shows the average travel time and a one standard deviation interval. Again, there seem to be multiple phases of travel time regimes: + Until 03:00 local time night time travel times are relatively high with a low spread ov travel times in different cells. + Again at around 04:00 local time the spread of travel times increases and travel times generally decrease over the course of the day. Curiously enough however at 04:00 local time, travel times are at their highest. Potentially indicating a gap between reduced night time services, and morning services kicking in. Notably, without the unpopulated cells, the spread of travel times is reduced and only a few cells exhibit longer travel times than during the night. + After 17:00 travel times increase again. Notably, for some unpopulated cells they decrease again between 23:00 and midnight. #figure(image("../figures/select_HD_TT_boroughs.svg"), caption: [Plot of average travel times in select neighbourhoods of Heidelberg across the day without low population cells.]) <borough_time> Grouping populated cells by borough reveals a similar general pattern. With 15 boroughs the plot still remains a bit hard to parse. Selecting a few representative boroughs for @borough_time, lets us make. Notably there seem to be two groups, low travel time boroughs like Altstadt or Weststadt. And boroughs which ove the course of the day do not lose as much travel time, like Wieblingen or Ziegelhausen. Curiously enough, the more central boroughs do not experience the 04:00 local time uptick in travel times, the less central boroughs experience. Another curiosity is the uptick in travel time in a few places like Emmertsgrund right around noon. <end_of_chapter> #locate(loc => bib_state.at(query(<end_of_chapter>, loc).first().location()))
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/布局/盒子/盒子.typ
typst
= box 调整内容大小的内联级容器。 除内联数学、文本和框之外的所有元素都是块级的,不能出现在段落内部。框功能可用于将此类元素集成到段落中。默认情况下,框采用其内容的大小,但也可以明确调整大小。 == 例子 #image("屏幕截图 2024-04-14 165213.png") width 盒子的宽度。 框可以具有分数宽度,如下面的示例所示。 注意:目前,只有框及其宽度可以在段落内以小数形式调整大小。将来可能会添加对小尺寸图像、形状等的支持。 默认:auto #image("屏幕截图 2024-04-14 165333.png") #image("屏幕截图 2024-04-14 165400.png") #image("屏幕截图 2024-04-14 165441.png") #image("屏幕截图 2024-04-14 165532.png") #image("屏幕截图 2024-04-14 165605.png") #image("屏幕截图 2024-04-14 165632.png")
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/multiline-07.typ
typst
Other
// Test single trailing line break. $ "abc" &= c \ $ One trailing line break.
https://github.com/BeiyanYunyi/Architectural-Technology-and-Art-Paper
https://raw.githubusercontent.com/BeiyanYunyi/Architectural-Technology-and-Art-Paper/main/nju-thesis/template.typ
typst
MIT License
// 南京大学学位论文模板 nju-thesis-typst // Author: https://github.com/OrangeX4 // Repo: https://github.com/nju-lug/nju-thesis-typst // 在线模板可能不会更新得很及时,如果需要最新版本,请关注 Repo #import "@preview/anti-matter:0.0.2": anti-inner-end as mainmatter-end #import "layouts/doc.typ": doc #import "layouts/preface.typ": preface #import "layouts/mainmatter.typ": mainmatter #import "layouts/appendix.typ": appendix #import "templates/fonts-display-page.typ": fonts-display-page #import "templates/bachelor-cover.typ": bachelor-cover #import "templates/master-cover.typ": master-cover #import "templates/bachelor-decl-page.typ": bachelor-decl-page #import "templates/master-decl-page.typ": master-decl-page #import "templates/bachelor-abstract.typ": bachelor-abstract #import "templates/master-abstract.typ": master-abstract #import "templates/bachelor-abstract-en.typ": bachelor-abstract-en #import "templates/master-abstract-en.typ": master-abstract-en #import "templates/bachelor-outline-page.typ": bachelor-outline-page #import "templates/list-of-figures.typ": list-of-figures #import "templates/list-of-tables.typ": list-of-tables #import "templates/notation.typ": notation #import "templates/acknowledgement.typ": acknowledgement #import "utils/custom-numbering.typ": custom-numbering #import "utils/custom-heading.typ": heading-display, active-heading, current-heading #import "utils/custom-tablex.typ": * #import "utils/indent.typ": indent #import "@preview/i-figured:0.2.2": show-figure, show-equation #import "utils/style.typ": 字体 #import "utils/style.typ": 字号 // 使用函数闭包特性,通过 `documentclass` 函数类进行全局信息配置,然后暴露出拥有了全局配置的、具体的 `layouts` 和 `templates` 内部函数。 #let documentclass( type: "bachelor", // "bachelor" | "master" | "doctor" | "postdoc",文档类型,默认为本科生 bachelor degree: "academic", // "academic" | "professional",学位类型,默认为学术型 academic nl-cover: false, // TODO: 是否使用国家图书馆封面,默认关闭 twoside: false, // 双面模式,会加入空白页,便于打印 anonymous: false, // 盲审模式 fonts: (:), // 字体,应传入「宋体」、「黑体」、「楷体」、「仿宋」、「等宽」 info: (:), ) = { // 默认参数 fonts = 字体 + fonts info = ( title: ("基于 Typst 的", "南京大学学位论文"), title-en: "NJU Thesis Template for Typst", grade: "20XX", student-id: "1234567890", author: "张三", author-en: "<NAME>", department: "某学院", department-en: "XX Department", major: "某专业", major-en: "XX Major", field: "某方向", field-en: "XX Field", supervisor: ("李四", "教授"), supervisor-en: "<NAME>", supervisor-ii: (), supervisor-ii-en: "", submit-date: datetime.today(), // 以下为研究生项 defend-date: datetime.today(), confer-date: datetime.today(), bottom-date: datetime.today(), chairman: "某某某 教授", reviewer: ("某某某 教授", "某某某 教授"), clc: "O643.12", udc: "544.4", secret-level: "公开", supervisor-contact: "南京大学 江苏省南京市栖霞区仙林大道163号", email: "<EMAIL>", school-code: "10284", degree: auto, degree-en: auto, ) + info ( // 页面布局 doc: (..args) => { doc( ..args, info: info + args.named().at("info", default: (:)), ) }, preface: (..args) => { preface( twoside: twoside, ..args, ) }, mainmatter: (..args) => { if type == "master" or type == "doctor" { mainmatter( twoside: twoside, display-header: true, ..args, fonts: fonts + args.named().at("fonts", default: (:)), ) } else { mainmatter( twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), ) } }, mainmatter-end: (..args) => { mainmatter-end( ..args, ) }, appendix: (..args) => { appendix( ..args, ) }, // 字体展示页 fonts-display-page: (..args) => { fonts-display-page( twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), ) }, // 封面页,通过 type 分发到不同函数 cover: (..args) => { if type == "master" or type == "doctor" { master-cover( type: type, degree: degree, nl-cover: nl-cover, anonymous: anonymous, twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), info: info + args.named().at("info", default: (:)), ) } else if type == "postdoc" { panic("postdoc has not yet been implemented.") } else { bachelor-cover( anonymous: anonymous, twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), info: info + args.named().at("info", default: (:)), ) } }, // 声明页,通过 type 分发到不同函数 decl-page: (..args) => { if type == "master" or type == "doctor" { master-decl-page( anonymous: anonymous, twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), ) } else if type == "postdoc" { panic("postdoc has not yet been implemented.") } else { bachelor-decl-page( anonymous: anonymous, twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), info: info + args.named().at("info", default: (:)), ) } }, // 中文摘要页,通过 type 分发到不同函数 abstract: (..args) => { if type == "master" or type == "doctor" { master-abstract( type: type, degree: degree, anonymous: anonymous, twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), info: info + args.named().at("info", default: (:)), ) } else if type == "postdoc" { panic("postdoc has not yet been implemented.") } else { bachelor-abstract( anonymous: anonymous, twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), info: info + args.named().at("info", default: (:)), ) } }, // 英文摘要页,通过 type 分发到不同函数 abstract-en: (..args) => { if type == "master" or type == "doctor" { master-abstract-en( type: type, degree: degree, anonymous: anonymous, twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), info: info + args.named().at("info", default: (:)), ) } else if type == "postdoc" { panic("postdoc has not yet been implemented.") } else { bachelor-abstract-en( anonymous: anonymous, twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), info: info + args.named().at("info", default: (:)), ) } }, // 目录页 outline-page: (..args) => { bachelor-outline-page( twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), ) }, // 插图目录页 list-of-figures: (..args) => { list-of-figures( twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), ) }, // 表格目录页 list-of-tables: (..args) => { list-of-tables( twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), ) }, // 符号表页 notation: (..args) => { notation( twoside: twoside, ..args, ) }, // 致谢页 acknowledgement: (..args) => { acknowledgement( anonymous: anonymous, twoside: twoside, ..args, ) }, ) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/video_00.typ
typst
Apache License 2.0
#import "/contrib/templates/xhtml/lib.typ": xhtml #set page(height: auto, width: auto) = Multi-media in Typst This is a embed video. #xhtml(outer-width: 640pt, outer-height: 360pt, ```html <iframe src="https://player.bilibili.com/player.html?aid=80433022&amp;bvid=BV1GJ411x7h7&amp;cid=137649199&amp;page=1&amp;danmaku=0&amp;autoplay=0" scrolling="no" border="0" width="100%" height="100%" frameborder="no" framespacing="0" allowfullscreen="true" ></iframe> ```) That is a embed video.
https://github.com/Zeng-WCh/SYSU-Typst-Internship-report-template
https://raw.githubusercontent.com/Zeng-WCh/SYSU-Typst-Internship-report-template/main/README.md
markdown
MIT License
# SYSU-Typst-Internship-report-template A Typst template for SYSU internship report for personal usage, not official one, use it at your own risk. 实习报告 Typst 模板,非官方模板,使用风险自负 # Usage 1. Install Typst 2. Install Fonts, please check the `template.typ` for details 3. Compile with `typst compile usage.typ` A example is provided in `usage.typ`, the output can be view in [usage.pdf](./usage.pdf)
https://github.com/akrantz01/resume
https://raw.githubusercontent.com/akrantz01/resume/main/template/experience.typ
typst
MIT License
#import "common.typ": date-range, icon, section #let entry( company, title, date, location: none, url: none, highlights: (), settings: (:), ) = { let link = if url != none { let text = if settings.full-links { url } else { url.trim("https://", at: start) } box( move(dx: 0.5em)[ #icon("website") #link(url, text) ], ) } set block(above: 0.95em, below: 0.95em) grid( columns: (60%, 40%), align(left)[ #strong(company), #emph(title) #link ], align(right)[ #if location != none and settings.locations [ #emph(location) -- ] #date-range(date) ], ) list(..highlights) } #let experience(title: "Experience", settings: (:), omit: (), ..entries) = { section(title) entries.pos().filter(((id, ..rest)) => id not in omit).map(( (id, company, title, date, ..rest), ) => entry( company, title, date, settings: settings, ..rest, )).join() }
https://github.com/devraza/warehouse
https://raw.githubusercontent.com/devraza/warehouse/main/README.md
markdown
MIT License
# Warehouse This is, as the repository's name suggests, a warehouse for all of my public documents. They're all written with Typst, and some of them might be found elsewhere, like [my blog](https://devraza.github.io). Here's an image of how these documents look after being compiled with `typst`: ![image sample](./assets/sample.png)
https://github.com/yhs0602/2024-1-mars
https://raw.githubusercontent.com/yhs0602/2024-1-mars/main/presentation.typ
typst
// Get Polylux from the official package repository #import "@preview/polylux:0.3.1": * // Make the paper dimensions fit for a presentation and the text larger #set page( paper: "presentation-16-9", fill: rgb(235, 253, 255) ) #set text( size: 25pt, font: "Pretendard", ) #set list(spacing: 2em, tight: true) #show heading: it => { it.body v(0.2em) } #let KL = math.op("KL") #let Uniform = math.op("Uniform") #let ReLU = math.op("ReLU") // Use #polylux-slide to create a slide and style it using your favourite Typst functions #polylux-slide[ #align(horizon + center)[ = Learning Fine-Grained Bimanual Manipulation with Low-Cost Hardware \ RSS 2023 양현서 July 12, 2024 ] ] #polylux-slide[ == About - Author: <NAME>, <NAME>, <NAME>, Chelsea Finn - Conference: RSS 2023 ] #polylux-slide[ == Motivation #list( tight: false, [*Fine manipulation tasks* such as #list( tight: true, [threading cable ties], [slotting a battery], ) #pause ], [*Requires* #list( tight: true, [precision], [careful coordination of contact forces], [closed-loop visual feedback] ) ] ) ] #polylux-slide[ == Low cost and imprecise hardware for fine manipulation tasks #block( fill: color.purple.lighten(80%), inset: 20pt, radius: 20%, width: 100%, [ #heading[Suggestion] #v(10pt) *Low-cost system* that performs end-to-end *imitation learning* directly from real demonstrations, collected with a custom teleoperation interface ] ) ] #polylux-slide[ == Introduction #list( tight: true, [Fine manipulation tasks require *precision and coordination* #pause], [Current systems are *expensive and complex* #pause], [Goal: Develop a low-cost, effective system for bimanual manipulation #pause], [Key contributions: #list( tight: true, [*Low-cost* hardware setup], [Novel imitation learning algorithm *(ACT)*], [Successful demonstration on various tasks] ) ] ) ] #polylux-slide[ == System Design - Low-cost hardware #list( tight: false, [ViperX 6-DoF robot arms], [3D printed “see-through” fingers, gripping tape], [*Cost: <\$20k*] ) ] #polylux-slide[ == System Design - Design principles #list( tight: false, [Versatile #pause], [User-friendly #pause], [Repairable #pause], [Easy-to-build] ) ] #polylux-slide[ == System Design - Design principles - Teleoperation setup #list( tight: false, [Joint-space mapping for control], [High-frequency control (50Hz)], ) ] #polylux-slide[ == Joint space mapping for control - Directly maps "Leader" joint angles to "Follower" joint angles - Solves IK failing problem #figure( image("images/robots.png", width: 85%), ) ] #polylux-slide[ == Imitation Learning Algorithm #pause #list( tight: false, [*Challenges*: #list( tight: true, [Compounding errors in policy], [Non-stationary human demonstrations] ) #pause ], [*Solution: Action Chunking with Transformers (ACT)*: #list( tight: true, [Predicts sequences of actions (chunks)], [Reduces effective horizon of tasks], [Uses temporal ensembling for smoothness] ) ] ) ] #polylux-slide[ == Training ACT on a New Task #list( tight: false, [Record leader joint positions as actions #pause], [Observations: follower joint positions, 4 camera feeds #pause], [Train ACT: predict future actions from observations #pause], [Test: use policy with lowest validation loss #pause], [*Challenge: Compounding errors*] ) ] #polylux-slide[ == Action Chunking #list( tight: false, [*Groups individual actions into units* for efficient storage and execution #pause], [Reduces the *effective horizon* of long trajectories #pause], [Every $k$ steps, the agent receives an observation and generates $k$ actions #pause], [Mitigates issues with non-stationary demonstrations] ) ] #polylux-slide[ == Action Chunking #figure( image("images/chunk.png", width: 70%), ) ] #polylux-slide[ == Temporal Ensemble #list( tight: false, [Creates *overlapping action chunks* #pause], [Queries the policy at *every step* for precise and smoother motions #pause], [*Combines* predictions using a weighted average #pause], [No additional training cost, only extra inference-time computation], ) ] #polylux-slide[ == Temporal Ensemble #figure( image("images/chunk.png", width: 70%), ) ] #polylux-slide[ == Modeling Human Data #list( tight: false, [Human demonstrations are *noisy and inconsistent* #pause], [*Different* trajectories can be used for the same observation #pause], [Human actions are more *stochastic* where precision matters less #pause], [Policy must *focus on high precision* areas] ) ] #polylux-slide[ == Conditional Variational Autoencoder (CVAE) #list( tight: false, [Train action chunking policy as a generative model #pause], [Only decoder (policy) used in deployment #pause], [Maximize log-likelihood of demonstration action chunks], ) ] #polylux-slide[ == Architecture #figure( image("images/arch.png", width: 100%), ) - typo: synthesizes images -> information ] #polylux-slide[ == Implementation of ACT: Encoder #list( tight: false, [CVAE encoder and decoder implemented with *transformers* #pause], [*BERT-like transformer* encoder used #pause], [Inputs: current joint positions and target action sequence #pause], [Outputs: mean and variance of "style variable" $z$ #pause], [Only used during training - $z$ set to 0 during test] ) ] #polylux-slide[ == Implementation of ACT: Decoder #list( tight: false, [Predicts next $k$ actions], [Inputs: current observations and $z$], [Observations: 4 RGB images and joint positions of 2 robot arms], [ResNet18 used for image processing], ) ] #polylux-slide[ == Implementation of ACT: Decoder #list( tight: false, [_Transformer_ encoder synthesizes information], [_Transformer_ decoder generates action sequence], [L1 loss used for precise action sequence modeling] ) ] #polylux-slide[ == Model architecutre: Training I #figure( image("images/1_training_1.png", width: 100%), ) ] #polylux-slide[ == Model architecutre: Training II #figure( image("images/2_training_2.png", width: 100%), ) ] #polylux-slide[ == Model architecutre: Training III #figure( image("images/3_training_3.png", width: 100%), ) ] #polylux-slide[ == Model architecutre: Testing #figure( image("images/4_testing.png", width: 95%), ) ] #polylux-slide[ == Experiment Tasks #list( tight: true, [Slide Ziploc: Grasp and open ziploc bag slider], [Slot Battery: Insert battery into remote controller slot], [Open Cup: Open lid of small condiment cup], [Thread Velcro: Insert velcro cable tie into loop], [Prep Tape: Cut and hang tape on box edge], [Put On Shoe: Put shoe on mannequin foot and secure velcro strap], [Transfer Cube (sim): Transfer red cube to other arm], [Bimanual Insertion (sim): Insert peg into socket in mid-air] ) ] #polylux-slide[ == Challenges #list( tight: false, [Requires fine-grained bimanual control #pause], [Perception challenges (e.g., transparency, low contrast) #pause], [Random initial placement of objects #pause], [Need for visual feedback to correct perturbations #pause], [Precise manipulation needed] ) ] #polylux-slide[ == Data Collection #list( tight: false, [Collected using ALOHA teleoperation for 6 real-world tasks #pause], [Each episode: 8-14 seconds (400-700 time steps at 50Hz) #pause], [50 demonstrations per task (100 for Thread Velcro) #pause], [Total: 10-20 minutes of data per task #pause], [Scripted policy / human demonstrations for simulated tasks], ) ] #polylux-slide[ == Human demonstrations are stochastic #list( tight: false, [Mid-air handover example: position varies each time #pause], [Policy must learn dynamic adjustments, not memorization] ) ] #polylux-slide[ == Experiment Comparison #list( tight: false, [Compared ACT with four methods: #list( tight: true, [BC-ConvMLP: Simple baseline with convolutional network], [BeT: Uses Transformers, no action chunking, separate visual encoder], [RT-1: Transformer-based, predicts one action from history], [VINN: Non-parametric, uses k-nearest neighbors] ) #pause ], [ACT directly predicts continuous actions] ) ] #polylux-slide[ == Experiment Results #pause #list( tight: false, [ACT outperforms all prior methods in both simulated and real tasks #pause], [Simulated tasks: ACT shows 20%-59% higher success rates #pause], [Real-world tasks: Slide Ziploc (88%), Slot Battery (96%) #pause], [ACT's performance in Thread Velcro was lower (20%) due to precision challenges] ) ] #polylux-slide[ == Experiment Results #figure( image("images/result.png", width: 95%), ) ] #polylux-slide[ == Ablation: Action Chunking and Temporal Ensembling #list( tight: false, [Action chunking reduces compounding errors by dividing sequences into chunks], [Performance improves with increasing chunk size, best at k = 100], [Temporal ensembling further improves performance by averaging predictions] ) ] #polylux-slide[ == Ablation: Training with CVAE #list( tight: false, [CVAE models noisy human demonstrations], [Essential for learning from human data, removing CVAE objective significantly drops performance #pause], [Human data success rate drops from 35.3% to 2% without CVAE] ) ] #polylux-slide[ == Ablation: Is High-Frequency Necessary? #list( tight: false, [Human shows higher performance at 50Hz compared to 5Hz #pause], [Tasks: threading zip cable tie and unstacking plastic cups #pause], [50Hz: faster and more accurate task completion #pause], [50Hz reduces teleoperation time by 62% compared to 5Hz] ) ] #polylux-slide[ == Ablation graphs #figure( image("images/abl.png", width: 100%), ) ] #polylux-slide[ == Limitations and Conclusion #list( tight: false, [Presented a low-cost system for fine manipulation], [Components: ALOHA teleoperation system and ACT imitation learning algorithm], [Enables learning fine manipulation skills in real-world], [Examples: Opening a translucent condiment cup, slotting a battery (80-90% success rate, ~10 min demonstrations)], [Limitations: Tasks beyond current capabilities, e.g., buttoning a dress shirt], [Hope: Important step and accessible resource for advancing fine-grained robotic manipulation] ) ] // #polylux-slide[ // == Experimental Results - Performance // #list( // tight: false, // [Success rates of 80-90%], // [Comparison with baselines: // #list( // tight: true, // [ACT significantly outperforms other methods], // [Effective in both simulated and real-world tasks] // ) // ] // ) // ] // #polylux-slide[ // == Conclusion and Future Work // #list( // tight: false, // [*Conclusion*: // #list( // tight: true, // [Developed a low-cost, effective system for fine manipulation], // [Proposed a novel imitation learning algorithm (ACT)] // ) // ], // [*Future Work*: // #list( // tight: true, // [Improving generalization to new tasks], // [Enhancing hardware precision], // [Exploring more complex manipulation tasks] // ) // ] // ) // ] // #polylux-slide[ // == Evaluation // #box(width: 100%, height: 87%, // columns(2, gutter: 0pt)[ // #set par(justify: true) // // #figure( // // image("images/eval.png", width: 100%), // // ) // #colbreak() // - CLIPDraw _performed best_, but *qualitative results are poor* // - Therefore, also use OpenCLIP score // - Effect of rejection sampling $tilde$ caption consistency // ] // ) // #table( // columns:(auto, 1fr, 1fr), // table.vline(x: 1, start: 0), // table.hline(y: 1, start: 0), // inset:(10pt), // fill:color.yellow.lighten(85%), // table.header[][Multimodal][Recurrent], // [kcc-husk-vision-dqn], [X], [X], // [kcc-husk-bimodal-dqn-final], [O], [X], // [kcc-husk-vision-drqn-final], [X], [O], // [kcc-husk-bimodal-drqn-final], [O], [O], //) // ] // #polylux-slide[ // == Qualitative Results // // #figure( // // image("images/results.png", width: 100%), // // // #table( // // // columns:(auto, 1fr, 1fr), // // // table.vline(x: 1, start: 0), // // // table.hline(y: 1, start: 0), // // // inset:(10pt), // // // fill:color.yellow.lighten(85%), // // // table.header[][Multimodal][Recurrent], // // // [kcc-husk-vision-dqn], [X], [X], // // // [kcc-husk-bimodal-dqn-final], [O], [X], // // // [kcc-husk-vision-drqn-final], [X], [O], // // // [kcc-husk-bimodal-drqn-final], [O], [O], // // ) // ] // #polylux-slide[ // == Discussion // - Utilizes pretrained diffusion models *without captioned SVG datasets* // - Effectively shows the *distillation of generative models* compared to contrastive models #pause // \ // - Computationally more *expensive* than CLIP-based approaches // - *Limited* by the quality and biases of the pretrained diffusion model // ] // #polylux-slide[ // == References // - DiffVG // - LIVE // - VectorFusion // ]
https://github.com/maxgraw/bachelor
https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/4-concept/userflow.typ
typst
Das Hauptmerkmal der Anwendung liegt in der erweiterten Interaktion mit dem Möbelsystem. Aus der Anforderungsanalyse ergeben sich klare Funktionen und Interaktionen, welche von der Anwendung umgesetzt werden müssen. Um die Interaktion und Entwicklung der Anwendung zu unterstützen, wird ein User Flow erstellt. Der User Flow ist hierbei aus drei Blöcken aufgebaut. Diese Blöcke sind Aktion (Kreis), Prozess (Rechteck) und Entscheidung (Raute). Diese Blöcke stellen die Abläufe und Entscheidungen dar, welche in der Anwendung getroffen werden. Die einzelnen Blöcke sind durch Pfeile miteinander verbunden, welche die Richtung der Interaktionen und Abläufe darstellen. Die Interaktion mit dem System lässt sich in zwei Bereiche unterteilen. Im ersten Bereich erfolgt die Interaktion über die Kameraposition und die Ausrichtung des Geräts. Das System sucht nach einer geeigneten Fläche zur Darstellung von Möbelstücken, die durch Anpassen der Kameraposition und der Ausrichtung des Geräts beeinflusst werden kann. Bei einer geeigneten Fläche erscheint ein Cursor, der weitere Interaktionen ermöglicht. Wird keine geeignete Fläche gefunden, wird der Prozess zurückgesetzt und die Suche erneut gestartet wie in @user-flow dargestellt. Falls der Cursor dargestellt wird, beginnt der zweite Bereich des User Flows. Hier wird die Interaktion über Tap-Events ermöglicht. Die Art des angetippten Elements entscheidet über den weiteren Verlauf im User Flow. Wird kein Element angetippt, wird zum Anfang des User Flows zurückgesprungen und alle Menüs werden nicht mehr angezeigt. Ein Sonderfall tritt ein, wenn die Szene leer ist und bisher kein Möbelstück platziert wurde. In diesem Fall wird das Menü "Auswahl" sichtbar. Dieser Sonderfall stellt den Startprozess der Anwendung dar und ermöglicht das Platzieren eines ersten Möbelstücks, das als Grundlage für die weitere Interaktion dient. Im Falle eines angetippten Elements wird zwischen einem Möbelstück und einem Menü unterschieden. Ist das angetippte Element ein platziertes Möbelstück, werden die Menüs "Löschen" und "Anhängen" sichtbar. Handelt es sich um ein Menü, wird zwischen drei unterschiedlichen Optionen unterschieden. Das Menü "Auswahl" ermöglicht es, einzelne Optionen auszuwählen und das entsprechende Möbelstück in der Umgebung zu platzieren. Danach wird der User Flow zurückgesetzt. Die Menüs "Löschen" und "Anhängen" sind nur sichtbar, wenn zuvor ein Möbelstück angetippt und somit ausgewählt wurde. Das Menü "Löschen" ermöglicht das Löschen des ausgewählten Möbelstücks. Das Menü "Anhängen" erlaubt es, ein weiteres Möbelstück an das ausgewählte Möbelstück anzuhängen. Hierfür wird das Menü "Auswahl" erneut angezeigt, um ein weiteres Möbelstück auszuwählen. #figure( image("../media/user_flow.svg", width: 100%), caption: [User Flow der Anwendung], ) <user-flow>
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/044%20-%20Innistrad%3A%20Crimson%20Vow/002_The%20Edge%20of%20the%20World.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Edge of the World", set_name: "Innistrad: Crimson Vow", story_date: datetime(day: 29, month: 10, year: 2021), author: "<NAME>", doc ) Lord Nellick's receiving room is cold. The parlor fire has been burning for hours, but Jacob's knuckles still ache with the chill. The heavy brocade drapes, the scroll-legged tables, and the many framed landscapes speak of comfort and wealth, but all the money on the Plane cannot combat the night crouching outside, scrabbling hungrily at the wall. If the Innistrad gentry could have bought themselves out of the darkness, they would have done it already. "Thank you for your punctuality, <NAME>." Lord Nellick does not appear bothered by the cold. With a high forehead and a patrician nose, he is handsome in a narrow sort of way. He lounges in a wide-backed chair, grand and languorous and smiling. Considering the current atmosphere in town, he is downright chipper. Jacob doesn't like it. He has the impression Nellick is telling a joke he is not in on. "No need to thank me," he says. "I was in the neighborhood." #figure(image("002_The Edge of the World/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) A lie, but he will add the stagecoach to the bill. He had to offer the driver a hefty bribe to even consider the trip. The villages along the Alrun River were inhospitable even before The Travails, but now~well, Jacob just wishes that when the Plane decided to plunge itself into permanent night, he could have been caught somewhere that didn't reek of fish and rotting infrastructure. But judging from what he's found since his arrival in Selhoff, the choking, heavy mantle of fear will feel the same no matter where he goes. "Detective Wicker here assures me you are the best in the business," Nellick goes on. The Detective Wicker in question gives Jacob a tight nod. He is surprised she even remembers him. They worked briefly together three years ago, but that was before The Travails, in the old Innistrad. He never even learned her first name. He recalls her as unfriendly, unusually severe for someone so young, and prone to rookie mistakes. He figured she hadn't thought very highly of him, either, but clearly, he was wrong if she's brought him in to consult. He's impressed she's even thinking that clearly. Nowadays all anyone wants to do is chop their firewood, earn their coin however they can, and bolt their doors behind them. "We'll have a few questions for you, <NAME>," Jacob says. "Of course." Nellick folds his hands. "What would you like to know?" "Let's begin with the dangerous horde of geists pillaging up and down Nephalia." Detective Wicker sits with her pen poised over her journal, back straight, curly hair pinned neatly. Jacob, who has been wearing the same jacket and waistcoat since he left the Alrun, feels shabby beside her. "<NAME>, correct me if I'm wrong, but the stories I've heard insist all the targets of these attacks have been the morally bankrupt. Didn't they knock the mayor of Havengul off this roof after he drove a block of families out of their homes?" Polite amusement flickers across Nellick's face, and he crosses his legs in interest. "I don't see what that has to do with me." He moves with sinuous deliberation, every motion considered. Jacob leans back in his own chair. "I believe she is asking what you think you've done to make yourself a target." "Hmm? Oh, I'm a businessman, Detective Wicker. When I make money, someone else loses it." That was rather more candor than Jacob was expecting. "But if you're asking if I've dumped anyone in the bay recently—" Nellick laughs. "You can rest assured, I'm innocent." Wicker's expression doesn't relax, but she nods and jots down a note. Jacob graciously allows Wicker to ask the preliminary questions. It gives him time to think. A swarm of unusually vicious geists roaming Nephalia, attacking politicians and merchants, draining their life energy to leave behind a desiccated husk. That's~odd, to say the least. But after The Travails there's been more than enough novelty to go around. The Plane has been picked up and shaken, and all of its pieces are jostled out of their proper places. Jacob wishes he were still young enough for it to fill him with a sense of adventure, rather than just bleak exhaustion tinged with cold terror. When Wicker's questions are finished, Jacob offers his own professional advice. "Stay inside, <NAME>, though I'm sure I don't have to tell you that nowadays. You should have someone set up wards." <NAME> rises from his chair. "You can't do that?" "No, unfortunately," Jacob lies. The last thing he is going to do is air out old, musty rituals for this man. "Better off going to the church for that. They'll charge you less than I would, anyway." Nellick laughs, although it wasn't a joke. His smile doesn't show his teeth. "Surely I can convince the two of you to stay the night. Well—so to speak, at least." He lets out a polite little chuckle, as if the end of Innistrad is just drawing-room banter. Jacob imagines spending one more minute in this chilly place and suppresses a shudder. Reminds him way too much of home. "That's very kind of you, my lord, but I wouldn't want to put you out. There's a public house close by. I don't predict any trouble." If night creatures have become bold enough to attack in the middle of a city, surrounded by wards and armed hunters, well, then there's really no hope for any of them anymore. Better to submit to fate. "I've lodgings elsewhere, as well," Wicker sniffs. "Suit yourselves," Nellick says. He turns to Wicker to shake her hand. "As Mr. Hauken suggested, an accredited mage would~" She breaks off, going still, before dropping his hand. Then, stiffly, she smiles. A strange feeling hovers at the base of Jacob's spine, but before he can dwell on it, Wicker turns on her heel. "Come on!" Perplexed, Jacob nods briefly at <NAME> before following Wicker down the hall. "Wicker, slow down!" Jacob catches her in the echoing grand foyer, the shapes of hulking busts of past Nellicks glaring at them from the shadows. Wicker looks up at him from beneath dark brows, leaning in like she has a secret. "You can call me Eloise," she says, before a servant opens the door and bows them out. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Selhoff is a city on the edge of the world, and winter bites like a mad wolf. Frost etches glittering patterns into glass windows, and the Bay of Vustrow yawns dark and endless beyond the docks, like a piece of the Plane scooped out and discarded. Even before the fall of permanent night, this wasn't a place for the frail. When the wind blows, the city holds its breath and bows its head. The tails of Jacob's coat dance around his legs, his hair whipping at his frozen cheeks. The cold seems to have sunk into Wicker's limbs as well, because her first few steps down the lane are unsteady. Jacob moves to catch her as she stumbles. "I'm fine, I'm fine." She looks up at Jacob. He's short enough that most people don't have to do that, not even women, but Wicker—Eloise—barely rounds out five feet tall. Her lips twitch. "Nice hair." Well, at least she's entertained. "I can take the investigation from here," Jacob says, as they start down the road. From this high up, the moonlight glimmers on rooftops glazed with ice, all their flags and ornaments lowered to wait for a spring that might never come. "Hmm?" Eloise glances back at him. "You don't want me anymore?" Jacob doesn't know how to answer that. She laughs. "What makes you think you're better suited to it than me? Your esoteric skillset?" "You're the one who referred Nellick to me," Jacob says, annoyed. He wishes she would walk faster. The local vampires are busy preparing for a wedding and most likely won't be hunting on city streets, but that doesn't make being out in the dark any more appealing. Jacob's shoulders are stiff with unease. "It's so ugly from the outside," Eloise says to herself. "What?" He follows her gaze. Climbing above the city are the towers of industry, where the elite make their home. Most of them are beautiful, but the largest is a huge greasy-gray stone monstrosity, punching up at the sky like a fist aimed at the gods. Looking at it makes him queasy; the malice pouring off it is intense. It would have to be, considering Jacob can pick it out from the ambient malice in the air. "Quite the eyesore," he agrees. "What is it?" "Oh, it's vacant. A necro-alchemist lived there, but not anymore. There was an incident a few months ago. A geistbomb misfired. Killed a bunch of people." #figure(image("002_The Edge of the World/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "A what?" Jacob isn't sure if he heard her right. "A geist bomb? What is that?" Eloise looks up from beneath her bangs. "Exactly what it sounds like. An explosive device fueled with dead souls." The queasiness intensifies. "That's~" He doesn't even know what to say. Whenever he thinks he has seen the very worst Innistrad has to offer, a whole new realm of horror opens before him. The wind whirls through the eaves, sending a crumpled, discarded ribbon tumbling across the street. A few market stalls are open despite the cold and the dark, their minders huddling behind them with heads bowed. Unsafe, but they likely have little choice. Even eternal darkness and the monsters that hunt inside it hasn't been enough to convince landlords to lower their rents. Food must be bought. Medical bills must be paid. Jacob remembers Selhoff in the height of summer—the colors and smells and drifting music. He's no tavern-crawler, but he likes to watch the crowd. Anything to remind him that Innistrad isn't dead. As they round a corner into a desolate stretch of alley, his stomach tightens. Not an unusual sensation; he always feels spectral activity in the gastric system first. But this is~strange. "Steady on." He touches Eloise's shoulder, feeling her go perfectly still under his hand. "Hm?" "Listen." The wind screams. Before, Jacob imagined Nellick's description of a "swarm of geists" to be an exaggeration. Artful hyperbole. Geists are solitary creatures by their very nature; they do not possess the intelligence or animal instinct necessary for cooperation. Every so often they will group, but never in the spirit of community, just shared interest in a spot or a source of power. This is not like that. The world around them explodes into the shivering fog of geists. They stream up from the ground, from inside the adjacent buildings, and down from the slate-gray sky. Cool, slithery magic paints over Jacob's skin, the smoky voices of emotion scrabbling to find a way inside him. Fear, regret, sorrow, excitement, and rage, rage, rage, burning bright and hot inside his chest. A shriek builds in Jacob until his very bones are rattling. It's only through instinct that he manages to plant his feet and force his fingers into a clumsy warding gesture, pushing magic into the palms of his hands. "Eloise, get behind me, just—" The geists flow up in front of them, coalescing for one trembling moment into a woman's screaming face. The gale slams into Eloise, knocking her backward against the alley wall. Jacob swears and thrusts his hands out again, summoning up every ounce of muscle memory. He hasn't met a spirit this powerful in years; usually all it takes is a few words and the twitch of a finger to settle things down. But that was before The Travails. Now all magic is harder. Everything is harder. "Leave," he shouts, putting all of himself into the banishing command. "NOW!" The screaming woman turns on him, finally solid enough for him to make out details. Wild hair, round eyes, strong shoulders, and a furious mouth. #figure(image("002_The Edge of the World/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Then she's gone. The wind calms and the silence presses in on his ears. Strength leaves him like heat escaping an oven, and he falls against the brickwork. Eloise groans. Blood pools at the corner of her mouth, and her eyes are hazy when she looks up at him. "Jacob~?" "I'm here." he says. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Luckily, there's an inn on the next corner. Neither of them is strong enough to carry the other in their current conditions. By the time they are installed in a parlor with a physician on the way, Eloise is more or less lucid again, if muddled. As Jacob helps her to an armchair by the hearth, she smiles at him, slow and curious. "How did you do that?" Jacob removes his gloves and overcoat, hunkering down in front of the fire. He feels like he's just come out of an ice bath. "Do what?" Eloise wipes at the blood on her mouth. "Command geists." "Oh. I grew up around them." Eloise laughs softly, a thoughtful noise. "You grew up around geists?" "No. Well, yes." Eloise tips her head to show she is listening. Jacob shouldn't have said anything. Misdirection is always the wiser course, but his logic center is not working at maximum capacity just now. His skin is still shivering with the shock of absorbing and expelling energy so quickly. Lights sparkle in the corners of his vision, a veil between himself and Innistrad. He looks into the fire. "The people who raised me~revered geists. Almost worshipped them. The dead are easier to contend with than the living. Predictable, and easy to control." The firelight glints off the pin in Eloise's hair. "I've never heard anyone talk about geists like pets." Jacob can't manage a smile. "Geists have knowledge no living creature ever can. Not even a vampire can see behind the veil. The people I grew up with were convinced that only the dead can reveal true wisdom." Eloise's eyes are very dark in the shadows. "Fascinating." Her fingers twitch. "And what made you decide to hunt geists, rather than worship them?" "I don't hunt geists," Jacob says, with a familiar pulse of annoyance. "I investigate geist-related incidents. I'll leave the hunting to the Keepers of the Pale. I'm not interested in the church." "I see." The injury makes Eloise's gaze sleepy and slow and just the slightest bit sinister. "Then why investigate geists?" "My friend. She—" The landlady arrives with tea and a plate of thick, raisin-studded cake. Jacob busies himself, pouring Eloise a cup. She takes it, but then just balances the saucer on her thighs. She gestures for Jacob to go on as soon as they are alone again. He shakes his head. "It isn't interesting." Eloise huffs. "You're the one who brought it up. You obviously want to keep talking." Jacob sighs. "My friend died when we were young. She was found strangled." The pain is so old he barely feels it, as familiar as any other bodily process. "Who killed her?" Jacob adds sugar to his tea. They brew it too bitter in the south. "I don't know. No one bothered to find out." Eloise's brow furrows. "I told you—my people revere the dead. My friend joined their ranks, who cared how? The elders gave it up as an accident." Eloise snorts. "Did they all rush to join her?" Jacob blows across the surface of his tea. "No." "Sounds like they weren't very dedicated to death, then." Jacob's laugh feels dragged from deep inside, leaving him raw, but he feels better when it's out. "Anyway, I realized I couldn't stay there. I~just couldn't look at them anymore. Any of them. I decided to go into business with the only knowledge I had. I thought~well, it sounds silly now, but I thought I could help people. And I did, I suppose. For a while." "Not anymore?" He snorts. "Are you serious? I haven't had a client in weeks. Surely you couldn't have seen much business yourself." Eloise looks confused for a moment, before her expression clears. "Ah. Yes. Eternal night. A bit inconvenient, agreed." "That's putting it mildly." "How would you put it, then?" Jacob puts his teacup down. "The end of Innistrad?" Eloise smiles. "Dramatic." "Not really." He shrugs. "It's only a matter of time before the vampire houses move in to pen us like cattle. And in the meantime, the night creatures pick us off one by one." It feels gauche to say it out loud. Like talking about sex, or childbirth, or taxes. Something everyone knows but doesn't speak about in polite company. The end of everything. "Then why are you still here?" Eloise asks. She's still holding onto her full teacup. Maybe her injury made her queasy. He looks down at the cake, but he doesn't much feel like eating either. "What do you mean?" "There's a whole bay out there. It's very cold. You could jump in." Her voice is slow, almost hypnotic. "Find out those hidden truths only available to the dead." Jacob stares at her. She isn't at all the way he remembered her. "I don't know," he says after a moment. "Habit, I guess. What about you? Things can't be much better in Selhoff than they are anywhere else." Eloise leans in like she is telling him a secret. "I'm going to keep living until they drag me under." He leans in, too, reflexively. She hasn't made any attempt to talk him out of his strangled pessimism, and it is strangely comforting. She understands. He can see it in her eyes. She touches cold fingertips to his face. "Thank you for telling me your story, <NAME>," she says, and Jacob feels~something. It slides beneath his skin, oily and slick like the film on a decaying corpse, moving through him. Searching, seeking. Forcing its way in. Jacob recoils, dropping the teacup. Eloise's eyes narrow. "Are you alright?" Before he can dredge together a response, the physician finally arrives, pushing Jacob aside. He almost forgot he sent for one. He leaves Eloise to get her head checked and goes out into the hallway to try to clear his own. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) It takes a few minutes of steady breathing for the slimy feeling in his bones to dissipate. He wonders if it could be a side effect of the dispelling charms he cast out on the street. Unusual, but magic's effect on the body changes as it ages, and Jacob isn't getting any younger. The physician emerges a quarter of an hour later, ashen, and rather unsteady. Maybe Eloise had suggested casual suicide to her as well. "How is she?" he asks. "Hmm? Oh, muddled." The physician's mouth quirks up. "Well, she would be. A geist slammed her head against a wall. She's sleeping now." "She told you that?" Bad form, to discuss an open investigation with someone who isn't an active participant, but he supposes allowances had to be made with an injury like this. "She told me all sorts of things," the physician says, with another half-smile. "Have we met?" he asks before he can help himself. Just the way she's looking at him. "Met?" The physician tilts her head. "No, I don't think so. Take care, Jacob." Despite the physician's words, when Jacob returns to the parlor, Eloise isn't asleep but rather sitting slumped in the armchair, slowly massaging her eyelids. "Eloise, did the physician leave you with any instructions?" She drops her hand to her lap. "I'm not sure, Jacob. Just sleep, I think." Her eyes dart from Jacob to the spilled tea to the uneaten cake. "What the hell happened to me?" Jacob steps closer to the fire. "What do you mean?" Eloise continues to rub a palm against her temple. "I remember~the merchant in the tower. His hands were cold. Then, nothing after that." "That's~concerning. We talked quite a bit." Eloise lets out a breath. "I have a concussion and a wrenched muscle in my back. I'll somehow manage to survive losing the memories of whatever thrilling banter the two of us shared." Jacob finds himself half-expecting her to suddenly break character and start laughing at him again. But whatever strange mood had taken hold of her after her injury appears to have departed with the doctor. Jacob tries to ignore the hint of disappointment. He'd almost started to like her. "Well, thrilling might be a bit of a—" Jacob breaks off as he feels a thrumming beneath his skin. No. It can't be. What the hell is going on? Being targeted by the very geists he's been summoned here to investigate could be written away as coincidence once. But twice? "What's wrong?" Eloise goes very still. "Hauken, what is it?" The geists howl into the parlor, pouring in through the walls and ceiling and up through the floors. Wind tears at Jacob's hair and sends the tableware flying through the room like artillery. Jacob narrowly manages to dodge a dinner knife. The geists don't attempt to scare or threaten this time but immediately resolve into the same screaming woman. And just like last time, she ignores Jacob and makes straight for Eloise. Eloise shrieks, shrinking back in the chair. "Don't let it touch you!" Jacob yells. "How am I supposed to do that?" Eloise yells back. The geist stops. Inside the tiny parlor, she seems to stretch from floor to ceiling, her edges indistinct. "Are you talking to me?" Jacob's veins tremble with her voice. "Yes." She tips her head. "No one talks to me." "Well~" He spreads his palms. "Surprise." With great deliberation, the geist looks at Eloise. "I thought this was the one I've been looking for. It was. But now it isn't." Eloise's eyes are round and huge. "Is this the geist that attacked me?" "Yes," says Jacob. "This is a lie," says the geist. "Is she talking?" Eloise asks. "It just sounds like the wind." Jacob swears. "I need paper—something to write on, anything—" Eloise pats at her coat, pulls out her journal, and rips a page out with careful deliberation. Jacob picks up the knife left with the cake and drags it across his palm. "What are you—" He paints a series of sloppy symbols, swaying as he forces power into the seal. He's scraping the bottom of his reserves at this point. Shaking a few more drops of blood off his palm, he finishes the last symbol and waves the paper to dry it. Then he holds it out to the geist. Jacob watches as she slowly realizes what he wants her to do with it. She takes it from him, fingers leaving an ethereal afterimage as she moves. Instantly, her edges become more solid, and she settles more heavily onto the ground. "That was a lie," she says again, her voice firmer. Eloise reacts visibly, her eyes getting even bigger. "Oh," she says. "I can hear her." "No~no, it was a lie, but now it's not." She looks back at Jacob. "Who are you?" "I'm called Jacob. Who are you?" The geist takes so long to answer that Jacob starts to think perhaps the spell isn't working after all. But then— "Millicent. That was my name. I was~someone, once." As she speaks, her form continues to shrink down on itself, becoming more fixed, the blood seal helping anchor her in her memories. "We all lived together in a place by the river. Until he came. He used us. Fresh spirits." "He? Who is he?" "Someone we shouldn't have trusted. He knew the dead. They listened to him." "Knew the dead~do you mean, a necro-alchemist?" Information begins to compile in Jacob's head, teasing the edges of his cognition, just out of reach. This used to be exhilarating, once upon a time, when the thrill of discovery was still new. Now he just feels tired. "Eloise, you told me a necro-alchemist lived in that tower. That he was the one whose geistbomb destroyed that town. What was his name?" Eloise scowls. "I never told you that." "Right—" her head. "Right, you don't remember, but you did tell me, on the way out of Nellick's house. You told me about a necro-alchemist that set off a geistbomb in a village nearby." Eloise continues to blink at him. "No, I didn't." Jacob shakes his head. "I know you don't remember, but—" "I never told you about a necro-alchemist who set off a geistbomb in a nearby village," Eloise says, "because I don't know anything about a necro-alchemist who set off a geistbomb in a nearby village. What the hell is a geistbomb?" The wind howls outside, and Jacob tenses, but it's just the ordinary kind. He forces himself to focus; he hasn't been this jumpy in years. "You don't know." "No, I don't. I'd heard something about a town going through a disaster, but not what, or who, caused it." Jacob thinks. "That doesn't make sense." He's missing a critical bit of information. "This necro-alchemist, where is he now?" "I told you—" "I'm not talking to you." Jacob looks at the geist in the center of the room. "He ended when we ended," she says slowly. "You mean he's dead?" Millicent hesitates. "I~don't know. He's here. I've seen him. He was~" Once again, she looks at Eloise. And Jacob understands. He thinks of Eloise's lazy smile and the squirming feeling of filth forcing itself beneath his skin when she touched him. The physician who hadn't even asked him to pay her. Nellick's cold eyes. "Oh," Jacob says. "Shit." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "What an unexpected delight." Nellick is just as elegant as he was this morning, still sitting in his cold parlor. The hollow-eyed servant who brought Jacob up says nothing, simply bows and leaves as fast as she can. "What brings you back so soon, <NAME>? Is this a social call?" The corner of a sharp canine gleams. "It's really too late for business." Jacob matches his smile. "Recently, it's always too late for business. Fortunately, these sorts of investigations rarely keep regular hours." The fire is unlit, and so are the candles. L<NAME> was sitting in the dark. "I was wondering what you could tell me about <NAME>." Nellick's smile doesn't droop. "Hm? I'm not sure, I haven't spent much time with necro-alchemists." "But you do know he's a necro-alchemist." "I'm sure I've heard his name, here and there. If he's someone important, mention of him will have crossed my desk." He steps forward, gold brocade robe tied loosely around his waist. He hadn't bothered to dress before meeting Jacob. "Seriously, you can't just be here to ask me that." Nellick's feet make no sound on the rug as he moves closer. His eyes look like ice floes. He raises a hand, brushing his fingers across Jacob's cheek. "So, tell me~what can I do for you?" At first Jacob feels nothing but soft, chilly fingertips and thinks that he must be wrong and will now need to find a way to extricate himself from a supremely awkward situation. But then he feels it. Oily, pressing fingers wiggling their way under his skin, coating his throat and the roof of his mouth with smoke. Instead of pushing Nellick away, he pulls him closer, hand on the back of his neck. "Have you ever possessed a geistmage before? I promise you won't like it." And then he pushes back. Nellick's body goes rigid before he staggers away with an inhuman hiss. His legs tangle in his heavy robe and he falls, barely catching himself on his elbows. He wipes at his mouth, which has begun to drip thick, black blood. "You didn't take many pains to hide it," Jacob says. "Still took you long enough. I thought you were a detective." Jacob doesn't show the hit on his face, but he feels it. He hadn't noticed, and he should have. Just, he'd been so shaken by Millicent's attacks, and, the truth is, no one in Innistrad has been at the peak of their powers in the last few years since The Travails. The changed magic unbalances the weather, which unbalances the Plane, which unbalances people. Still, he should have noticed that he's only truly spoken to one person since arriving in Selhoff. "This is rather awkward for me, I admit," Rav says, gesturing at himself, sprawled in the brocade gown on the floor. Jacob backs up a step. "Get up, then." "Hmm? Oh, no. I just meant, I hired you without even knowing I was speaking to one of the exalted Vizag Atum. The geist-talkers. Terribly rude of me." Jacob doesn't blink. "I left that group a long time ago." "Yes, because of your friend. Fascinating. How cruel people can be." "You would know, wouldn't you?" Another flash of rage flickers across Rav's face, the same one Jacob had seen in Eloise's eyes when he'd spilled the tea. "That was a mistake. An unfortunate misstep." "Was it?" Rav tugs the neck of his robe closed with great dignity. "Of course. I would much rather my geistbomb succeed than fail. Why would you think anything different? What, did that geist tell you something else?" "She wasn't killing corrupt officials, was she?" Jacob counters. "She was looking for you. That mayor you pushed off a roof—" "Oh, that. I didn't like that body; I don't think it suited me." "You only steal the forms of influential people." "How else would I influence anything?" Rav's eyes glint with humor. "And yes, she's been bent on revenge since that whole unfortunate affair. Can't imagine why. It's not as if I'm any less dead than she is." "Except she doesn't steal other people's bodies." Rav snorts. "That's because she can't. I have an affinity with death, much like you do. Most geists can't possess a living body, especially not without that body's permission. I'm simply exceptional." "Modest, too." "It was a statement without a value judgment. I am an exception, much like you are." He sighs, seemingly perfectly content to stay on the ground and keep looking up at Jacob. "Nevertheless, I wish you'd just destroyed Millicent, instead of listening to her list of grievances." "Bad luck, then. You shouldn't have possessed my colleague." Rav rises from the ground with unexpected grace. He seems to wear this body better than he did Eloise's or the physician's. "Well, yes. True. I just couldn't resist watching you work, Jacob. I like you. And that's why I'm glad you're here." "Am I supposed to be flattered?" Jacob asks faintly. "I wouldn't mind," the necro-alchemist says. "A little flattery never hurt anyone." "I'm not going to destroy Millicent," Jacob says. "You'll have to deal with her on your own." "Oh, I don't care about her anymore. I just took your advice and had someone from the church put up wards. Very kind of you." Another sharp-toothed grin. "No, you shouldn't be asking what you can do for me, but what I can do for you." He walks over to a dusty sideboard and selects a bottle seemingly at random, pouring a splash of liquor into an equally dusty glass. "Drink?" Jacob grits his teeth. "No, thank you." "Suit yourself." He settles in a chair beside the empty fireplace. "Why don't you sit down?" "I'll stand." Rav shrugs. "I think we should go into business together." Jacob waits for the punchline. "I can help you, <NAME>. With me by your side, you won't have to be afraid anymore." "I'm not afraid." "Of course, you are. You just spent an hour in that inn telling me all your fears. The night, the monsters, the yawning dark of the bay." He swirls the amber liquor in his glass but doesn't drink. His eyes look like jewels. "You should be careful who you open up to, in the future." Jacob says nothing. "The days of humanity are gone," Rav says. "And the night is getting colder. Imagine if you didn't have to worry. Let me help you. I can protect you. Just~come with me." Jacob blinks. "Where?" "Anywhere. I can set up a laboratory anywhere on Innistrad. You can solve your geist crimes, whatever you want." He looks up, thoughtful. "Or we can find the people who killed your friend, and we can make them pay. Together." Jacob stares at him, trying to tease some meaning from between the words. "Why? What's in it for you?" Rav rubs his fingertips across the shining wood of the chair. "I've been alone for a long time." Jacob can't explain why, but he believes him. "Why me?" "Why not?" He shakes his head, as if Jacob is bothering him with silly trifles. "I can't do anything to you. You're a geistmage. I can't take your body, and you can banish me if I do anything you don't like. What's the downside? If you don't like looking at this body, I can just take another one." Jacob thinks of all the things he should say, all the things he would have said only a few years ago. He doesn't make deals with killers. He has a duty. Or he did. Then the whole Plane broke. "Don't try to take a high road," Rav goes on. "You're from Innistrad, like me. You know better than to turn down power when it's offered to you. What do you do this job for? Justice? Please. You're too smart for that. Money? We can get money anywhere." Jacob closes his eyes. "I'm just tired." "I know," Rav says. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("002_The Edge of the World/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) <NAME>'s mansion looms out of the dark, stately and silent. Despite the danger, <NAME> is glad of the night. Her head hurts. Besides, it makes the ethereal form standing beside her easier to see. Millicent still clutches the blood seal Hauken made for her, staring at the house with a rage that would be terrifying even if she wasn't a geist. "I cannot enter," she says. Eloise sighs. "Well, I can. Wait here." She's only inside for a few minutes, as long as it takes to check the place from one end to the other. She finds two unconscious servants in the kitchen, and a body in the parlor: <NAME>. <NAME> is nowhere to be found. Eloise returns to the geist and tells Millicent what she found. Millicent stays quiet for so long that Eloise begins to fear the blood seal has stopped working. But then she says, "Rav must have taken him, after taking a new body." "I didn't find any sign of a struggle." Millicent looks at her sharply. "This is my job, after all. If he left, it was likely under his own power. Or, it's possible he never made it in the first place." She shrugs. "A lot of monsters roaming the street these days." Millicent smiles faintly. "Like me." Eloise knows she means it as a joke, but she doesn't find it funny. "You aren't a monster," she snaps, surprised by her own vehemence. "You just need someone to fight for you." Millicent is quiet for a moment. "Do you think he went willingly," she says at last. "Would he?" Eloise looks off into the gloom of Selhoff's streets, as if Hauken will show himself suddenly at her behest. "I don't know. I don't actually know him that well." Millicent nods, then she drops the blood seal. "Wait!" Eloise catches it before it can hit the ground, shoving it back into Millicent's hands. "What are you doing?" "I don't need this. I will continue my search." Eloise sighs, rubbing at her aching temples. "Keep the seal." Millicent looks at her, head tilted like a dark bird. "I've never worked for a geist before, but my rates are very reasonable."
https://github.com/jamesrswift/pixel-pipeline
https://raw.githubusercontent.com/jamesrswift/pixel-pipeline/main/src/utility/arguments.typ
typst
The Unlicense
#let map(args, fn) = arguments( ..for (key, value) in args.named() { (: (key): fn(value)) }, ..args.pos().map(fn), )
https://github.com/mitsuyukiLab/grad_thesis_typst
https://raw.githubusercontent.com/mitsuyukiLab/grad_thesis_typst/main/contents/acknowledgement.typ
typst
#heading(numbering: none)[謝辞] <acknowledgement> 神に感謝。世界に感謝。人生に感謝。
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/superb-pci/0.1.0/lib.typ
typst
Apache License 2.0
#import "formatters.typ": * // Workaround for the lack of a `std` scope. #let std-bibliography = bibliography #let pci( title: [Paper Title], authors: (), affiliations: (), abstract: none, doi: none, keywords: (), correspondence: none, numbered_sections: false, bibliography: none, pcj: false, // removes all unecessary bits // TODO line_numbers: false, doc, ) = { // housekeeping to allow use in quarto show regex("\\\\"): it => "" let sanitize_orcid(author) = { if author.at("orcid", default: none) != none { author.at("orcid") = author.at("orcid").replace("\\", "") } return author } if correspondence != none {correspondence = correspondence.replace("\\", "")} if doi != none {doi = doi.replace("\\", "")} authors = authors.map(sanitize_orcid) // color definitions let PCIdark = rgb("#346E92") let PCImedium = rgb("#77A4BF") let PCIlight = rgb("#9FBFD2") // document metadata set document( title: title, author: authors.map(author => author.name), ) // global configuration set page( paper: "a4", margin: 1in, numbering: if pcj {none} else {"1 / 1"}, header: if pcj {none} else {generate_header(authors, fill: PCIdark)}, footer: if pcj {none} else {generate_footer(fill: PCIdark)}, header-ascent: 13pt, footer-descent: .55em, ) set text( font: ("Lato", "Calibri", "Source Sans Pro", "Source Sans 3"), fallback: true, size: 11pt, lang: "en", region: "US", hyphenate: true, ) let line_spacing = 0.55em * 1.5 set par( first-line-indent: 1.5em, justify: true, leading: line_spacing, // 0.65 * 1.5 for onehalfspacing ) set block(spacing: line_spacing) show link: set text(fill: PCIdark) show ref: set text(fill: PCIdark) set enum(indent: 2em, numbering: "(1.a)") set list(indent: 2em) set math.equation( numbering: "(1)", number-align: top, supplement: [Eq.], ) // make sure Fira Math is installed on your system show math.equation: set text(font: ("Fira Math", "New Computer Modern Math")) // Headings set heading( numbering: if numbered_sections {"1."} else {none}, ) show heading.where(level: 1): it => [ #set align(center) #set text(size: 12pt, weight: "bold") #block(above: 2em, below: 1em)[ #if it.numbering != none [#counter(heading).display()#h(.5em)]#it.body ] ] show heading.where(level: 2): it => [ #set text(weight: "bold", size: 11pt) #block(above: 1.6em, below: 1em)[ #if it.numbering != none [#counter(heading).display()#h(.5em)]#it.body ] ] show heading.where(level: 3): it => [ #set text(style: "italic", size: 11pt) #v(1.6em) #if it.numbering != none [#counter(heading).display()#h(.5em)]#it.body.#h(.5em) ] // Figure and Table settings let caption_width = 21cm - 2in - 3cm // 21 - 5.08 - 3 for total margins show figure: set block(width: 100%, spacing: 1.6em) show figure.caption: it => [ #block(width: caption_width)[ #set align(left) #set text(9pt) *#it.supplement #it.counter.display(it.numbering)* -- #it.body ] ] set table(stroke: none) show figure.where( kind: table ): set figure.caption(position: top) // ========================= // Document // Frontpage if not pcj { set par(first-line-indent: 0pt) set block(spacing: 20pt) v(2cm) block()[ #text(size: 25pt, weight: "bold")[#title] ] display_authors(authors) display_affiliations(affiliations) if doi != none { block()[ #link(doi)[#doi] ] } display_abstract(abstract) if keywords.len() > 0 { block()[*Keywords:* #keywords.join(", ")] } if correspondence != none { block()[ *Correspondence:* #link("mailto:" + correspondence)[#correspondence] ] } pagebreak() } doc // bibliography settings if bibliography != none { show std-bibliography: set par(first-line-indent: 0pt) set std-bibliography(title: "References", style: "pci.csl") bibliography } }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/viewers/preview-incr_01.typ
typst
Apache License 2.0
#let text_base_size=10pt #let text_h1_size=20pt #let header_size_increment=3pt #set page( paper: "a4", header: align(right)[ Multi-purpose Combat Chassis ], numbering: "1", margin: (x:20mm, y:12.7mm) ) #set par(justify: true) #set text( font: "LXGW WenKai", size: text_base_size, lang: "zh", ) #let emp_block(body,fill:luma(230),stroke:orange) = { block( width:100%, fill: fill, inset: 8pt, radius: 0pt, stroke: (left:(stroke+3pt),right:(luma(200)+3pt)), body, ) } #let booktab() = { block( width: 100%, [ #line(length: 100%,stroke: 3pt+luma(140)) #move(line(length: 100%), dx: 0pt, dy: -9pt) ] ) v(0pt, weak: true) } #show heading: it => block[ #let heading_size=text_h1_size - (it.level - 1) * header_size_increment #set text(size: heading_size, font: "HarmonyOS Sans SC") #emph(it.body) ] #let img = "/assets/files/tiger.jpg" = Seed #outline(title:none, indent:auto, ) #booktab() Seed2 Seed4 Seed3 Seed4 #pagebreak() == #lorem(3) #emp_block()[ Seed4 Seed4 Seed4 Seed4 ] #booktab() Seed4 Seed4 Seed4 Seed4 Seed4 Seed4 Seed4 Seed4 Seed4 Seed4 Seed4 Seed4 Seed4 Seed4 #pagebreak() == 隼的轻武器 #booktab() Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed #let images_rkg3=("tiger.jpg","tiger.jpg") #align(center)[ #stack( dir: ltr, ..images_rkg3.map(n=>align(center)[#image(img, height:15%)]) ) ] Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed #let images_pistol=("tiger.jpg","tiger.jpg") #let cell = rect.with( inset: 8pt, fill: rgb("e4e5ea"), width: 100%, radius: 6pt ) #grid( columns: (1fr,1fr), rows: (), gutter: 3pt, ..images_pistol.map(n=>align(center)[#image(img, width:20%)]) ) Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed #figure( image(img, width: 50%) ) Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed #figure( image(img, width: 50%) ) Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed === 电磁枪 Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed #pagebreak() == 武器舱和背部重武器 #booktab() Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed #figure( image(img, width: 60%), caption: [30mm Rapid Railgun with Extended Barrel, also retrofitted as 2nd stage rail on Arclight] ) Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed #figure( image(img, width: 60%), caption: [TGLS/Tactical Graviton Laser(Lance) System] ) #lorem(1000) #figure( image(img, width: 60%), caption: [炮管展开60°的状态] ) Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed #figure( image(img, width: 80%), caption: [4Sure Ballistics Man-Portable ASAT Missile] ) Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed #pagebreak() == 辅助机 —— "FRAMER" #booktab() Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed Seed
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_complex/ordered_list/ordered_list_updated.typ
typst
+ The CLIMATE - Precipitation2 - Temperature + degree - cold - really hot - warm + rain + The GEOLOGY
https://github.com/MatheSchool/typst-g-exam
https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/src/g-solution.typ
typst
MIT License
#import"./global.typ": * /// Show solution of question. /// /// *Example:* /// ``` #g-solution( /// alternative-content: v(1fr) /// )[ /// I know the demostration, but there's no room on the margin. For any clarification ask <NAME>. /// ]``` /// /// /// - alternative-content (string, content): Alternate content when the question solution is not displayed. /// - show-solution: (true, false, "space", "spacex2", "spacex3"): Show the solutions. /// - body (string, content): Body of question solution #let g-solution( alternative-content: none, show-solution:none, body) = { // [#type(alternative-content) \ ] // assert(alternative-content == none or type(alternative-content) == "content", // message: "Invalid alternative-content value") context { let show-solution = __g-show-solution.final() if show-solution == true { body } else { hide[#body] [ \ ] hide[#body] [ \ ] hide[#body] [ \ ] // alternative-content } } }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/features-09.typ
typst
Other
// Error: 26-28 stylistic set must be between 1 and 20 #set text(stylistic-set: 25)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.0.1/gallery/3d-chart.typ
typst
Apache License 2.0
#import "@local/cetz:0.0.1": canvas, draw #set page(width: auto, height: auto) #canvas(length: 1cm, { import draw: * // Draw grid stroke((paint: black, dash: "dashed", thickness: .5pt)) // not on release yet for i in range(0, 6) { line((0, i, 0), (0, i, 1), (7, i, 1)) content((-.1, i, 0), [$#{i*20}$], anchor: "right") } stroke((paint: black, thickness: .5pt, dash: none, join: "round")) line((0, 0, 1), (0, 6, 1)) line((0, 6, 0), (0, 0, 0), (7, 0, 0)) // Draw data let draw-box(x, height, title) = { x = x * 1.2 let color = blue let (top, front, side) = (color.lighten(20%), color, color.lighten(10%)) let y = height / 20 fill(front) rect((x - .5, 0), (x + .5, y)) fill(side) line((x + .5, 0, 0), (x + .5, 0, 1), (x + .5, y, 1), (x + .5, y, 0), close: true) fill(top) line((x - .5, y, 0), (x - .5, y, 1), (x + .5, y, 1), (x + .5, y, 0), close: true) content((x, -.1), title+h(0.5em), anchor: "above", angle: -90deg) } // Draw data draw-box(1, 10)[very good] draw-box(2, 30)[good] draw-box(3, 40)[ok] draw-box(4, 30)[bad] draw-box(5, 0)[very bad] })
https://github.com/NOOBDY/formal-language
https://raw.githubusercontent.com/NOOBDY/formal-language/main/main.typ
typst
The Unlicense
#import "template.typ": * #import "q1.typ": q1 #import "q2.typ": q2 #import "q3.typ": q3 #import "q4.typ": q4 #import "q5.typ": q5 #import "q6.typ": q6 #import "q7.typ": q7 #import "q8.typ": q8 #import "q9.typ": q9 #import "q10.typ": q10 #import "q11.typ": q11 #show: project.with( title: "Formal Language HW1", authors: ( "資工三 110590003 黃政", ), date: "March 11, 2024", ) #q1 #q2 #q3 #q4 #q5 #q6 #q7 #q8 #q9 #q10 #q11 == References The entirety of this homework is mostly discussed with 劉蜆皓 #link("mailto:<EMAIL>") #link("https://www.overleaf.com/read/ztdgxxgscsny#0523f5")
https://github.com/WinstonMDP/math
https://raw.githubusercontent.com/WinstonMDP/math/main/exers/c.typ
typst
#import "../cfg.typ": * #show: cfg $ "Prove that" all(a in (0, 1)): lim_(x -> +oo) (log_a x)/x = 0 $ $(log_a x)/x = -(-log_a x)/a^(-(-log_a x))$ $lim_(x -> +oo) -x/a^(-x) = -lim_(x -> oo) x/a^(-x) = 0$ $all(x in (a^(-r), +oo)): -log_a x in (r, +oo)$ // $all(x\, y): x < y -> -log_a x < - log_a y$ // $all(c) ex(x') all(x > x'): -log_a x > c$
https://github.com/darkMatter781x/OverUnderNotebook
https://raw.githubusercontent.com/darkMatter781x/OverUnderNotebook/main/entries/structure/structure.typ
typst
#import "/packages.typ": notebookinator, gentle-clues, codly #import notebookinator: * #import themes.radial.components: * #import gentle-clues: * #import codly: * #import "/util.typ": qrlink #show: create-body-entry.with( title: "Decide: Structure", type: "decide", date: datetime(year: 2024, month: 1, day: 6), author: "<NAME>", ) = File Structure For my program, I organize code into many different files in order to enhance my ability to navigate the code. Here's a tree diagram of the code's organization: #[ #disable-codly() #box(fill: rgb("#ced4da"), radius: 2pt, inset: 10pt, [``` . ├── include │ ├── lemlib │ │ └── ... │ ├── pros │ │ └── ... │ ├── auton.h │ ├── catapult.h │ ├── fieldDimensions.h │ ├── lift.h │ ├── main.h │ ├── robot.h │ └── selector.h └── src ├── auton │ ├── autons │ │ ├── defensive.cpp │ │ ├── sixBall.cpp │ │ └── skills.cpp │ ├── selector.cpp │ └── util.cpp ├── robot-config │ ├── dimensions.cpp │ ├── motors.cpp │ ├── odom.cpp │ ├── pistons.cpp │ ├── sensors.cpp │ └── tunables.cpp ├── subsystems │ ├── catapult.cpp │ ├── initialize.cpp │ └── lift.cpp └── main.cpp ```]) ] == Whats the difference between .h and .cpp? - .h's are header files that declare variables, functions, and classes so that they can be used in the files. - .cpp's implement the declarations made in the headers. These implementations are called definitions For example: ```h // inside helloWorld.h void helloWorld(); // declares what helloWorld() is ``` ```cpp // inside helloWorld.cpp // tells the compiler to include the symbols from helloWorld.h #include "helloWorld.h" // defines the implementation of helloWorld() void helloWorld() { printf("Hello World \n"); } ``` ```cpp // inside main.cpp // tells the compiler to include the symbols from helloWorld.h #include "helloWorld.h" // the function that will be run at the start of the program int main() { // runs the helloWorld() function helloWorld(); } ``` == Include This folder contains a several headers, which are files that declare symbols (variables, functions, classes, etc.) so that they can be used in other files. - LemLib - offers tools for position tracking and motion algorithms. - PROS - declare how the user program can interact with the v5 devices - auton.h - the autonomous functions and the utility functions used by autons. - catapult.h - the catapult subsystem class and the methods for controlling the catapult - fieldDimensions.h - constants describing the dimensions of the field which is useful for autons. - lift.h - the lift subsystem class and the methods for controlling the lift - main.h - declares competition event functions (opcontrol, autonomous, initialize) - robot.h - declares all of the robot's devices, subsystems, dimensions, and tunables - selector.h - the autonomous selector class == SRC Short for source. Contains several source files which define the symbols declared in the headers. - auton - contains everything related to autonomous - autons - contains all the autons - defensive.cpp - auton that runs on the side of the field closest to our alliance station - sixBall.cpp - auton that runs on the side of the field furthest to our alliance station. Scores 6 triballs into the goal - skills.cpp - programming skills routine - selector.cpp - the auton selector class's methods - util.cpp - utility functions for autons that reduce the verbosity of the autonomous functions. - robot-config - dimensions.cpp - the dimensions of the robot, including the wheel diameters, gear ratios, and tracking wheel positions - motors.cpp - configures the robot's motors' ports, gear cartridges, and directions - odom.cpp - configures position tracking's tracking wheels and defines the lemlib chassis object - pistons.cpp - configures the robot's pistons' ports - sensors.cpp - configures the robot's sensors' ports and directions - tunables.cpp - controller settings and chasePower for the drive and PID constants for the lift - subsystems - catapult.cpp - catapult subsystem's state machine - initialize.cpp - starts subsystem update task and initializes the two subsystems. - lift.cpp - lift subsystem's pid controller and state machine - main.cpp - driver control, brain screen printing, program initialize, and runs the autonomous function
https://github.com/kotfind/hse-se-2-notes
https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/edu/homeworks/book_review/main.typ
typst
#set text(lang: "ru", size: 12pt) #set par(justify: true, leading: 1em, first-line-indent: 1cm) #align(center)[ #text(size: 20pt, weight: "bold")[Рефлексивное эссе\ по книге "<NAME>"\ Кендзиро Хайтани] #text(size: 18pt)[<NAME>\ БПИ233] ] #text(weight: "bold", size: 14pt)[ Какие подходы Котани применимы в реальном современном образовании? Какие ее поступки вдохновили вас как преподавателя? ] Больше всего в Котани меня вдохновила её приверженность работе. Сенсей посвящает школе не только официально отведенное, но и своё свободно время: она изучает хобби своих учеников, общается с ними, ходит к ним в гости и вместе с ребятами работает старьевщиком, когда те попадают в трудное финансовое положение. Своей целеустремленностью Котани и ещё трое учителей (Адачи, Ото и Орихаши) напомнили мне персонажа из аниме "Великий учитель Онидзука", в котором главный герой, учитель Онидзука, шел на всё возможное и даже несколько раз рисковал собственной жизнью, чтобы помочь ученикам в трудную минуту. Перед тем, как описать применимые в современности практики Котани-сенсей, хотелось бы сначала упомянуть те, что в эту категорию не входят. На протяжении книги Фуми много общалась со своими учениками вне школы, ходила к ним домой, временами оставаясь на ужин. Мне очень нравится эта идея, так как она помогала учительнице лучше понять своих воспитанников, тем не менее, сложно представить подобное в контексте современного мира, а тем более в контексте большого города. Несмотря на сказанное выше, стать другом для своих учеников всё ещё является хорошей идеей. Дети, знающие, что учитель на их стороне, более сговорчивы, чаще готовы идти преподавателю на встречу. Такое поведение я замечал на собственном опыте: если учитель-"друг" немного задерживал пару или давал домашнее задание на каникулы (что было запрещено), то я и мои одноклассники относились с пониманием; если же учитель-"враг" поступал аналогично, то его поведение мы встречали "в штыки". Пытаясь найти подход к молчаливому Тэцудзо, Котани-сенсей начала интересоваться его хобби: "Котани-сэнсей уже битый час сидела за столом, заваленным книгами [...]. А изучала она книги про насекомых. На ее столе были и энциклопедии с картинками, и разные справочники, но во всех этих книгах Котани-сэнсей интересовало лишь то, что касалось мух."#footnote[Гл. 6] Это позволило учительнице "наладить контакт" с мальчиком и помочь ему не только найти более научный подход к своим опытам с мухами, но и научиться читать и писать. Тратить столь много времени на каждого из учеников в современных реалиях было бы сложно. Ведь у одного учителя может быть несколько классов по 30+ человек в каждом. Тем не менее, хоть немного интересоваться увлечениями ребят несомненно стоит. Ещё один метод Котани-сенсей мы видим в эпизоде с открытым уроком#footnote[Гл. 21]. Учительница приносит в класс странную большую коробку, она открывает коробку и в ней оказывается другая коробка, а не то содержимое, о котором предполагали дети; этот процесс повторяется несколько раз. Таким необычным подходом Фуми *удивляет* ребят, тем самым вовлекая их в учебный процесс. Подобный прием актуален и может быть полезен и в наши дни. Ярким примером его применения являются лекции Уолтера Левина по физике. На своих занятиях профессор демонстрирует зрелищные опыты, например, катается на велосипеде на "огнетушительой тяге"#footnote[Фрагмент лекции Уолтера Левина по теме "Третий <NAME>" (#link("https://www.youtube.com/watch?v=rM0-7fCbEdQ"))] или отпускает шар для сноса зданий (wrecking ball) в нескольких миллиметрах от своего подбородка#footnote[Фрагмент лекции Уолтера Левина по теме "Механическая энергия" (#link("https://www.youtube.com/watch?v=77ZF50ve6rs"))]. Наконец одним из важнейших моментов является то, что Котани-сенсей знает, что у детей, так же, как и у взрослых, бывают умные мысли. Она уважает мнение ребят, советуется с ними (например, она прислушивается к мнению Джуна насчет "дежурства по Минако"). Умение прислушиваться к своим учениками --- очень важный навык в любое время, ведь учителя, как и все люди, несовершенны, а без обратной связи невозможно совершенствовать свои преподавательские навыки. Негативный пример мне довелось наблюдать в школьные годы: один из преподавателей математики в нашей школе плохо объяснял материал. Ученики говорили ему об этом и даже вносили предложения по улучшению учебного процесса. Преподаватель тем не менее отказывался вносить какие-либо корректировки и слушать ребят, аргументируя это тем, что он взрослый и образованный человек, а они ничего не смыслящие в вопросах образования дети. Впоследствии это привело к тому, что тот учитель был уволен, а его ученики плохо знали предмет. Несмотря на свою неопытность, Котани-сенсей показала себя понимающим, добрым, справедливым и целеустремленным преподавателем, примеру которого можно и даже нужно следовать.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/break-continue-02.typ
typst
Other
// Test continue. #let i = 0 #let x = 0 #while x < 8 { i += 1 if calc.rem(i, 3) == 0 { continue } x += i } // If continue did not work, this would equal 10. #test(x, 12)
https://github.com/elteammate/typst-compiler
https://raw.githubusercontent.com/elteammate/typst-compiler/main/src/ir-gen.typ
typst
#import "reflection-ast.typ": * #import "reflection.typ": * #import "pprint.typ": * #import "typesystem.typ": * #import "ir-def.typ": * #let ir_from_ast_(context) = { if context.errors.len() > 0 { return context } if context.ast.type == ast_node_type.content { let entry_point = context.counter == 0 context.ast.ty = types.content context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.const, ptype.content, "")); __a} for i, piece in context.ast.fields.pieces { let __a = context.ast context.ast = context.ast.fields.pieces.at(i) context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.pieces.at(i) = __b if context.ast.fields.pieces.at(i).ty == types.content { context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.join, ptype.content, context.ast.val, context.ast.fields.pieces.at(i).val)); __a} } else if context.ast.fields.pieces.at(i).ty != types.none_ { {context.errors.push("Type error when joining content pieces"); return context} } if flags.terminates_function in context.ast.fields.pieces.at(i) { context.ast.terminates_function = true break } } if entry_point { {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.return_, ptype.content, context.ast.val)); __a} } } else if context.ast.type == ast_node_type.content_block { context.ast.ty = types.content let __a = context.ast context.ast = context.ast.fields.content context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.content = __b context.ast.val = context.ast.fields.content.val } else if context.ast.type == ast_node_type.code_block { let block_type = types.none_ let val = none context.scope_stack.push((:)) for i, expr in context.ast.fields.statements { let __a = context.ast context.ast = context.ast.fields.statements.at(i) context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.statements.at(i) = __b block_type = type_of_join(block_type, context.ast.fields.statements.at(i).ty) if block_type == none { {context.errors.push("Type error when joining statements of block"); return context} } else if block_type.at(0) != ptype.none_ { if val == none { val = context.ast.fields.statements.at(i).val } else if context.ast.fields.statements.at(i).ty != types.none_ { val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.join, block_type.at(0), val, context.ast.fields.statements.at(i).val)); __a} } } if flags.terminates_function in context.ast.fields.statements.at(i) { context.ast.terminates_function = true break } } let scope = context.scope_stack.pop() for _, var in scope { let lvar = context.functions.at(context.current_function).locals.at(var.name) context.functions.at(context.current_function).stack_occupancy.at(lvar.stack_pos) = false } context.ast.ty = block_type context.ast.val = val } else if context.ast.type == ast_node_type.unknown { context.ast.ty = types.content context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.const, ptype.content, context.ast.fields.value)); __a} } else if context.ast.type == ast_node_type.literal_int { context.ast.ty = types.int context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.const, ptype.int, context.ast.fields.value)); __a} } else if context.ast.type == ast_node_type.literal_float { context.ast.ty = types.float context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.const, ptype.float, context.ast.fields.value)); __a} } else if context.ast.type == ast_node_type.literal_bool { context.ast.ty = types.bool context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.const, ptype.bool, context.ast.fields.value)); __a} } else if context.ast.type == ast_node_type.literal_string { context.ast.ty = types.string context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.const, ptype.string, context.ast.fields.value)); __a} } else if context.ast.type == ast_node_type.binary_add { let __a = context.ast context.ast = context.ast.fields.lhs context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.lhs = __b let __a = context.ast context.ast = context.ast.fields.rhs context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.rhs = __b if context.ast.fields.lhs.ty != context.ast.fields.rhs.ty or context.ast.fields.lhs.ty.at(0) not in (ptype.content, ptype.string, ptype.float, ptype.int, ptype.array, ptype.dictionary) { {context.errors.push("Type error when adding expressions (op add, allowed types: ptype.content, ptype.string, ptype.float, ptype.int, ptype.array, ptype.dictionary, got: " + repr(context.ast.fields.lhs.ty.at(0)) + " and " + repr(context.ast.fields.rhs.ty.at(0)) + ")"); return context} } context.ast.ty = context.ast.fields.lhs.ty context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.add, context.ast.ty.at(0), context.ast.fields.lhs.val, context.ast.fields.rhs.val)); __a} if flags.terminates_function in context.ast.fields.lhs { context.ast.terminates_function = true } if flags.terminates_function in context.ast.fields.rhs { context.ast.terminates_function = true } } else if context.ast.type == ast_node_type.binary_sub { let __a = context.ast context.ast = context.ast.fields.lhs context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.lhs = __b let __a = context.ast context.ast = context.ast.fields.rhs context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.rhs = __b if context.ast.fields.lhs.ty != context.ast.fields.rhs.ty or context.ast.fields.lhs.ty.at(0) not in (ptype.float, ptype.int) { {context.errors.push("Type error when adding expressions (op sub, allowed types: ptype.float, ptype.int, got: " + repr(context.ast.fields.lhs.ty.at(0)) + " and " + repr(context.ast.fields.rhs.ty.at(0)) + ")"); return context} } context.ast.ty = context.ast.fields.lhs.ty context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.sub, context.ast.ty.at(0), context.ast.fields.lhs.val, context.ast.fields.rhs.val)); __a} if flags.terminates_function in context.ast.fields.lhs { context.ast.terminates_function = true } if flags.terminates_function in context.ast.fields.rhs { context.ast.terminates_function = true } } else if context.ast.type == ast_node_type.binary_div { let __a = context.ast context.ast = context.ast.fields.lhs context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.lhs = __b let __a = context.ast context.ast = context.ast.fields.rhs context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.rhs = __b if context.ast.fields.lhs.ty != context.ast.fields.rhs.ty or context.ast.fields.lhs.ty.at(0) not in (ptype.float) { {context.errors.push("Type error when adding expressions (op div, allowed types: ptype.float, got: " + repr(context.ast.fields.lhs.ty.at(0)) + " and " + repr(context.ast.fields.rhs.ty.at(0)) + ")"); return context} } context.ast.ty = context.ast.fields.lhs.ty context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.div, context.ast.ty.at(0), context.ast.fields.lhs.val, context.ast.fields.rhs.val)); __a} if flags.terminates_function in context.ast.fields.lhs { context.ast.terminates_function = true } if flags.terminates_function in context.ast.fields.rhs { context.ast.terminates_function = true } } else if context.ast.type == ast_node_type.binary_mul { let __a = context.ast context.ast = context.ast.fields.lhs context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.lhs = __b let __a = context.ast context.ast = context.ast.fields.rhs context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.rhs = __b if context.ast.fields.lhs.ty.at(0) in ( ptype.content, ptype.string, ptype.array, ) and context.ast.fields.rhs.ty.at(0) == ptype.int { {context.errors.push("Not implemented"); return context} } if context.ast.fields.lhs.ty != context.ast.fields.rhs.ty or context.ast.fields.lhs.ty.at(0) not in (ptype.float, ptype.int) { {context.errors.push("Type error when adding expressions (op mul, allowed types: ptype.float, ptype.int, got: " + repr(context.ast.fields.lhs.ty.at(0)) + " and " + repr(context.ast.fields.rhs.ty.at(0)) + ")"); return context} } context.ast.ty = context.ast.fields.lhs.ty context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.mul, context.ast.ty.at(0), context.ast.fields.lhs.val, context.ast.fields.rhs.val)); __a} if flags.terminates_function in context.ast.fields.lhs { context.ast.terminates_function = true } if flags.terminates_function in context.ast.fields.rhs { context.ast.terminates_function = true } } else if context.ast.type == ast_node_type.stmt { if context.ast.fields.expr == none { context.ast.ty = types.none_ } else { let __a = context.ast context.ast = context.ast.fields.expr context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.expr = __b context.ast.ty = context.ast.fields.expr.ty if context.ast.ty != types.none_ { context.ast.val = context.ast.fields.expr.val } if flags.terminates_function in context.ast.fields.expr { context.ast.terminates_function = true } } } else if context.ast.type == ast_node_type.hash_expr { let __a = context.ast context.ast = context.ast.fields.expr context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.expr = __b if context.ast.fields.expr.ty == types.none_ { context.ast.ty = types.none_ } else { context.ast.ty = types.content if context.ast.fields.expr.ty.at(0) == ptype.content { context.ast.val = context.ast.fields.expr.val } else if context.ast.fields.expr.ty.at(0) == ptype.int { context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.cast, ptype.content, context.ast.fields.expr.val)); __a} } else { {context.errors.push("Not implemented (cast from " + repr(context.ast.fields.expr.ty.at(0)) + " to content)"); return context} } } if flags.terminates_function in context.ast.fields.expr { context.ast.terminates_function = true } } else if context.ast.type == ast_node_type.paren { let __a = context.ast context.ast = context.ast.fields.expr context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.expr = __b context.ast.ty = context.ast.fields.expr.ty if context.ast.ty != types.none_ { context.ast.val = context.ast.fields.expr.val } if flags.terminates_function in context.ast.fields.expr { context.ast.terminates_function = true } } else if context.ast.type == ast_node_type.ident { let pname = context.ast.fields.name let found = false for scope in context.scope_stack.rev() { if pname in scope { let var = scope.at(pname) if var.function == context.current_function { context.ast.ty = var.ty context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.load, var.ty.at(0), var.name)); __a} found = true break } else { {context.errors.push("Not implemented (captured variable from other function)"); return context} } } } if not found { {context.errors.push("Variable not found: " + pname); return context} } } else if context.ast.type == ast_node_type.type_cast { let __a = context.ast context.ast = context.ast.fields.expr context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.expr = __b context.ast.ty = type_from_string(context.ast.fields.type) if context.ast.ty not in ( types.none_, types.int, types.float, types.string, types.content, types.any, ) { {context.errors.push("Invalid type for cast"); return context} } if context.ast.fields.expr.ty != types.int { {context.errors.push("Not implemented (cast from " + repr(context.ast.ty) + ")"); return context} } context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.cast, context.ast.ty.at(0), context.ast.fields.expr.val)); __a} if flags.terminates_function in context.ast.fields.expr { context.ast.terminates_function = true } } else if context.ast.type == ast_node_type.let_ { if context.ast.fields.params == none { let __a = context.ast context.ast = context.ast.fields.expr context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.expr = __b { let pname = context.ast.fields.ident.fields.name let ty = context.ast.fields.expr.ty let name = "@" + pname + "." + str({ context.counter += 1; context.counter }) let stack_pos = context.functions.at(context.current_function).stack_occupancy.position(x => not x) if stack_pos == none { stack_pos = context.functions.at(context.current_function).stack_occupancy.len() context.functions.at(context.current_function).stack_occupancy.push(true) } else { context.functions.at(context.current_function).stack_occupancy.at(stack_pos) = true } context.functions.at(context.current_function).locals.insert( name, (ty: ty, stack_pos: stack_pos) ) context.scope_stack.last().insert(pname, ( ty: ty, function: context.current_function, name: name, )) {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.store_fast, ty.at(0), name, context.ast.fields.expr.val)); __a} } context.ast.ty = types.none_ } else { let old_function = context.current_function let pname = context.ast.fields.ident.fields.name let name = "@" + pname + "." + str({ context.counter += 1; context.counter }) context.functions.insert(name, mk_function()) context.current_function = name context.scope_stack.push((:)) let params = context.ast.fields.params.fields.args let positional_param_types = () for i, param in params { if param.sink { {context.errors.push("Not implemented (sink parameters)"); return context} } if param.key != none { {context.errors.push("Not implemented (keyword parameters)"); return context} } if param.value.type == ast_node_type.ident { let ty = types.any let pref = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.move_param, ty.at(0), i)); __a} { let pname = param.value.fields.name let ty = ty let name = "@" + pname + "." + str({ context.counter += 1; context.counter }) let stack_pos = context.functions.at(context.current_function).stack_occupancy.position(x => not x) if stack_pos == none { stack_pos = context.functions.at(context.current_function).stack_occupancy.len() context.functions.at(context.current_function).stack_occupancy.push(true) } else { context.functions.at(context.current_function).stack_occupancy.at(stack_pos) = true } context.functions.at(context.current_function).locals.insert( name, (ty: ty, stack_pos: stack_pos) ) context.scope_stack.last().insert(pname, ( ty: ty, function: context.current_function, name: name, )) {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.store_fast, ty.at(0), name, pref)); __a} } context.functions.at(name).params.push(( ty: ty, name: param.value.fields.name, index: i, )) positional_param_types.push(ty) } else if param.value.type == ast_node_type.type_cast { let ty = type_from_string(param.value.fields.type) let pref = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.move_param, ty.at(0), i)); __a} let param_name_ = param.value.fields.expr.fields.name { let pname = param_name_ let ty = ty let name = "@" + pname + "." + str({ context.counter += 1; context.counter }) let stack_pos = context.functions.at(context.current_function).stack_occupancy.position(x => not x) if stack_pos == none { stack_pos = context.functions.at(context.current_function).stack_occupancy.len() context.functions.at(context.current_function).stack_occupancy.push(true) } else { context.functions.at(context.current_function).stack_occupancy.at(stack_pos) = true } context.functions.at(context.current_function).locals.insert( name, (ty: ty, stack_pos: stack_pos) ) context.scope_stack.last().insert(pname, ( ty: ty, function: context.current_function, name: name, )) {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.store_fast, ty.at(0), name, pref)); __a} } context.functions.at(name).params.push(( ty: ty, name: param_name_, index: i, )) positional_param_types.push(ty) } else { {context.errors.push("Invalid parameter"); return context} } } let __a = context.ast context.ast = context.ast.fields.expr context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.expr = __b let ty = context.ast.fields.expr.ty let ret_ty = context.functions.at(name).return_ty if (flags.terminates_function not in context.ast.fields.expr and context.ast.fields.expr.ty != types.none_) { {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.return_, ty.at(0), context.ast.fields.expr.val)); __a} } else if ty != ret_ty and ret_ty != none { {context.errors.push("Return type mismatch: " + type_to_string(ty) + " != " + type_to_string(ret_ty)); return context} } context.functions.at(name).return_ty = if ty == none and ret_ty == none { types.none_ } else if ty == none { ret_ty } else { ty } let scope = context.scope_stack.pop() for _, var in scope { let lvar = context.functions.at(context.current_function).locals.at(var.name) context.functions.at(context.current_function).stack_occupancy.at(lvar.stack_pos) = false } context.current_function = old_function if context.functions.at(name).slots != (:) { {context.errors.push("Not implemented (slots)"); return context} } let fn_object = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.mk_function, ptype.none_, name, 0)); __a} // todo: loading slots here { let pname = pname let ty = mk_type( ptype.function, context.functions.at(name).return_ty, ..positional_param_types, slotless: true, // todo: slots positional_only: true, // todo: keyword parameters ) let name = "@" + pname + "." + str({ context.counter += 1; context.counter }) let stack_pos = context.functions.at(context.current_function).stack_occupancy.position(x => not x) if stack_pos == none { stack_pos = context.functions.at(context.current_function).stack_occupancy.len() context.functions.at(context.current_function).stack_occupancy.push(true) } else { context.functions.at(context.current_function).stack_occupancy.at(stack_pos) = true } context.functions.at(context.current_function).locals.insert( name, (ty: ty, stack_pos: stack_pos) ) context.scope_stack.last().insert(pname, ( ty: ty, function: context.current_function, name: name, )) {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.store_fast, ty.at(0), name, fn_object)); __a} } context.ast.ty = types.none_ } } else if context.ast.type == ast_node_type.call { let __a = context.ast context.ast = context.ast.fields.func context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.func = __b let func_ty = context.ast.fields.func.ty if not func_ty.at(2).positional_only or not func_ty.at(2).slotless { {context.errors.push("Not implemented (keyword parameters or slots)"); return context} } let return_ty = func_ty.at(1).at(0) let positional_param_types = func_ty.at(1).slice(1) let args = context.ast.fields.args.fields.args if args.len() != positional_param_types.len() { {context.errors.push("Invalid number of arguments: " + str(args.len()) + " != " + str(positional_param_types.len())); return context} } let arg_vals = () for i, arg in args { if arg.sink { {context.errors.push("Not implemented (sink parameters)"); return context} } if arg.key != none { {context.errors.push("Not implemented (keyword parameters)"); return context} } let __a = context.ast context.ast = arg.value context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a arg.value = __b let ty = arg.value.ty let param_ty = positional_param_types.at(i) if ty != param_ty { {context.errors.push("Type mismatch in argument: got " + type_to_string(ty) + " expected " + type_to_string(param_ty)); return context} } arg_vals.push(arg.value.val) } let val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.call_fast, return_ty.at(0), context.ast.fields.func.val, ..arg_vals)); __a} context.ast.ty = return_ty context.ast.val = val } else if context.ast.type == ast_node_type.return_ { if context.ast.fields.expr == none { {context.errors.push("Not implemented " + "(Valueless return is a nightmare and I hate the person who invented it)"); return context} } else { let __a = context.ast context.ast = context.ast.fields.expr context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.expr = __b context.ast.ty = types.none_ let prev_return_ty = context.functions.at(context.current_function).return_ty let new_ty = context.ast.fields.expr.ty if prev_return_ty != none and prev_return_ty != new_ty { {context.errors.push("Return type mismatch: previous: " + type_to_string(prev_return_ty) + " new: " + type_to_string(new_ty)); return context} } context.functions.at(context.current_function).return_ty = new_ty if new_ty != types.none_ { {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.return_, new_ty.at(0), context.ast.fields.expr.val)); __a} } context.ast.terminates_function = true } } else if context.ast.type == ast_node_type.assign { let __a = context.ast context.ast = context.ast.fields.rhs context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.rhs = __b context.ast.ty = types.none_ if context.ast.fields.lhs.type == ast_node_type.ident { {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.store_fast, context.ast.fields.rhs.ty.at(0), context.ast.fields.lhs.fields.name, context.ast.fields.rhs.val)); __a} } else { {context.errors.push("Not implemented"); return context} } if flags.terminates_function in context.ast.fields.rhs { context.ast.terminates_function = true } } else if context.ast.type == ast_node_type.add_assign { context.ast = mk_node( ast_node_type.assign, lhs: context.ast.fields.lhs, rhs: mk_node( ast_node_type.binary_add, lhs: context.ast.fields.lhs, rhs: context.ast.fields.rhs, ), ) let __a = context.ast context.ast = context.ast context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast = __b } else if context.ast.type == ast_node_type.sub_assign { context.ast = mk_node( ast_node_type.assign, lhs: context.ast.fields.lhs, rhs: mk_node( ast_node_type.binary_sub, lhs: context.ast.fields.lhs, rhs: context.ast.fields.rhs, ), ) let __a = context.ast context.ast = context.ast context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast = __b } else if context.ast.type == ast_node_type.mul_assign { context.ast = mk_node( ast_node_type.assign, lhs: context.ast.fields.lhs, rhs: mk_node( ast_node_type.binary_mul, lhs: context.ast.fields.lhs, rhs: context.ast.fields.rhs, ), ) let __a = context.ast context.ast = context.ast context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast = __b } else if context.ast.type == ast_node_type.div_assign { context.ast = mk_node( ast_node_type.assign, lhs: context.ast.fields.lhs, rhs: mk_node( ast_node_type.binary_div, lhs: context.ast.fields.lhs, rhs: context.ast.fields.rhs, ), ) let __a = context.ast context.ast = context.ast context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast = __b } else if context.ast.type == ast_node_type.if_ { let __a = context.ast context.ast = context.ast.fields.expr context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.expr = __b if context.ast.fields.expr.ty != types.bool { {context.errors.push("If condition must be a boolean"); return context} } let temp_var = ("@temp." + str({ context.counter += 1; context.counter })) let false_label = ".FALSE." + str({ context.counter += 1; context.counter }) let end_label = ".END." + str({ context.counter += 1; context.counter }) {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.goto_if_not, ptype.none_, context.ast.fields.expr.val, false_label)); __a} let __a = context.ast context.ast = context.ast.fields.block context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.block = __b context.ast.ty = types.none_ if context.ast.fields.else_ == none { if context.ast.fields.block.ty != types.none_ { {context.errors.push("If block can't return a value if there is no else block, returned: " + type_to_string(context.ast.fields.block.ty)); return context} } context.functions.at(context.current_function).labels.insert( false_label, context.functions.at(context.current_function).code.len() ) } else { if ( context.ast.fields.block.ty != types.none_ and flags.terminates_function not in context.ast.fields.block ) { {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.store_fast, context.ast.fields.block.ty.at(0), temp_var, context.ast.fields.block.val)); __a} context.ast.ty = context.ast.fields.block.ty } {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.goto, ptype.none_, end_label)); __a} context.functions.at(context.current_function).labels.insert( false_label, context.functions.at(context.current_function).code.len() ) let __a = context.ast context.ast = context.ast.fields.else_ context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.else_ = __b if ( context.ast.fields.else_.ty != context.ast.fields.block.ty and flags.terminates_function not in context.ast.fields.block and flags.terminates_function not in context.ast.fields.else_ ) { {context.errors.push("If and else blocks must return the same type, returned: " + type_to_string(context.ast.fields.block.ty) + " and " + type_to_string(context.ast.fields.else_.ty)); return context} } if ( context.ast.fields.else_.ty != types.none_ and flags.terminates_function not in context.ast.fields.else_ ) { {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.store_fast, context.ast.fields.else_.ty.at(0), temp_var, context.ast.fields.else_.val)); __a} context.ast.ty = context.ast.fields.else_.ty } context.functions.at(context.current_function).labels.insert( end_label, context.functions.at(context.current_function).code.len() ) if (flags.terminates_function in context.ast.fields.block and flags.terminates_function in context.ast.fields.else_) { context.ast.terminates_function = true } } if context.ast.ty != types.none_ { context.ast.val = {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.load, context.ast.ty.at(0), temp_var)); __a} let stack_pos = context.functions.at(context.current_function).stack_occupancy.position(x => not x) if stack_pos == none { stack_pos = context.functions.at(context.current_function).stack_occupancy.len() context.functions.at(context.current_function).stack_occupancy.push(true) } else { context.functions.at(context.current_function).stack_occupancy.at(stack_pos) = true } context.functions.at(context.current_function).locals.insert( temp_var, (ty: context.ast.ty, stack_pos: stack_pos) ) } } else if context.ast.type == ast_node_type.while_ { let start_label = ".WHILE_START." + str({ context.counter += 1; context.counter }) let end_label = ".WHILE_END." + str({ context.counter += 1; context.counter }) context.loop_stack.push((start: start_label, end: end_label)) // let temp_var = ("@temp." + str({ context.counter += 1; context.counter })) context.functions.at(context.current_function).labels.insert( start_label, context.functions.at(context.current_function).code.len() ) let __a = context.ast context.ast = context.ast.fields.expr context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.expr = __b if context.ast.fields.expr.ty != types.bool { {context.errors.push("While condition must be a boolean"); return context} } {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.goto_if_not, ptype.none_, context.ast.fields.expr.val, end_label)); __a} let __a = context.ast context.ast = context.ast.fields.block context = ir_from_ast_(context) if context.errors.len() > 0 { return context } let __b = context.ast context.ast = __a context.ast.fields.block = __b {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.goto, ptype.none_, start_label)); __a} context.functions.at(context.current_function).labels.insert( end_label, context.functions.at(context.current_function).code.len() ) let _ = context.loop_stack.pop() context.ast.ty = types.none_ } else if context.ast.type == ast_node_type.continue_ { if context.loop_stack.len() == 0 { {context.errors.push("Continue outside of loop"); return context} } let loop = context.loop_stack.last() {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.goto, ptype.none_, loop.start)); __a} context.ast.ty = types.none_ } else if context.ast.type == ast_node_type.break_ { if context.loop_stack.len() == 0 { {context.errors.push("Break outside of loop"); return context} } let loop = context.loop_stack.last() {let __a = "%" + str({ context.counter += 1; context.counter }); context.functions.at(context.current_function).code.push(mk_ir(__a, ir_instruction.goto, ptype.none_, loop.end)); __a} context.ast.ty = types.none_ } else { {context.errors.push("Unknown AST node type"); return context} } return context } #let ir_from_ast(ast) = ir_from_ast_(( ast: ast, functions: (entry: mk_function()), errors: (), scope_stack: ((:), ), loop_stack: (), counter: 0, current_function: "entry", )) #{ let ast = parse("#let f(/*int*/x, /*bool*/y) = { [base: ]; if y { [1] } else { return [2] } };#f(5,false)") // pprint(ast) let ir = ir_from_ast(ast) pprint(ir) }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/051%20-%20March%20of%20the%20Machine/004_Episode%204%3A%20Beneath%20Eyes%20Unblinking.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 4: Beneath Eyes Unblinking", set_name: "March of the Machine", story_date: datetime(day: 17, month: 04, year: 2023), author: "<NAME>", doc ) To battle and bravery born, to battle and bravery Tyvar Kell returns—with boasts upon his lips, and black tidings in his heart. Skemfar welcomes its wayward son with open arms. After the ozone-laden atmosphere of New Phyrexia and the acrid safe house swamp in Dominaria, it is a welcome thing to breathe good forest air into his lungs. But the moment he arrives he knows he is too late. It is not to welcoming cheers he returns but to the clatter of swords against metal, the howl of arrows in flight and the screams of the pierced. In the distance, a sanguine ophidian the size of a mountain strangles the World Tree. White armor, glacier thick, protects it. Pods fall—the shed scales of this foul serpent—and the ground trembles with every arrival, each one met with the hammer of war. War drums beat in time with his own wild heart as he pushes his way into the melee. Glory drives his limbs. He ducks the scythe-like limb of an enemy, changes his own arm to metal, drives it through the thing's head. An instant later he's swaying out of the way of an axe as it takes out another. A cheer ringing out behind him gladdens his heart—the end of days has come to Kaldheim, and the elves of Skemfar meet it head-on. Tyvar sees his brother fighting alongside his people, surrounded by skalds and banners. "Here for the dregs?" Harald calls to him. "There'll be plenty." "And more coming," Tyvar says. Something that was once a giant hurls a boulder toward them; the others scatter, but Tyvar plants his feet. From the earth he draws his strength—and with a single blow shatters the rock. He grins. "You must have been struggling before I returned." Harald shakes his head. "Enough of that. Do you know anything that can help us? Who are these creatures?" "Phyrexians," Tyvar answers. A scream takes his attention—one of the elves has found himself caught in the belly of a giant skeletal wolf. Tyvar winces. "See there—they'll bathe him in oil, and then he'll be more metal than elf. After that, the changes start. Won't be long before he'd tear off his own father's skin." A dozen warriors meet the hound, two coming in on each side to flank. Hammers ring against steel. "They won't stop until everything in Kaldheim's like they are. I've been to their home, brother—it is lifeless, without song." He swallows. The next part isn't easy to say, and yet it must be said: "This isn't an enemy the elves can vanquish alone." The Cosmos itself reinforces his grim warning. The ground roars and shakes beneath their feet, white light leaking up from the opening crevices. Tyvar knocks against his brother. Harald steadies him, then points to the opening doomskar. "It seems we won't be alone for long." Phyrexians and elves alike plummet into the hungry earth. Shifting lights render them silhouettes as the Cosmos claims them. Unsated, the light creeps higher and higher still—until at last torrents of water emerge. Tyvar scrambles, sinking to the ground, creating a platform for him and his people. His muscles strain under the force of his magic, shifting between rock and water, rock and water. When he sees the first of the longboats cresting the water, Tyvar knows he's going to be at this for a while. Maybe longer than he can manage. If he fails, the elves will be washed away as surely as the Phyrexians. The lives of his people are in his hands. He can't fail. <NAME> bellows a war cry. As his body battles the tides and the rock, he feels alive. And while he's doing the simple thing, his brother handles what's more complicated. Omenseekers aboard the ships call out to the stranded elves, their captain leading, "It is the end of all things. Will the elves come and join the fight?" "The elves will lead it!" is Harald's proud answer. "Onto the ships!" Tyvar's shoulders tremble with effort and yet he holds fast to the earth. Each pair of fleeing feet shrinks the platform. Smaller and smaller, until only he and Harald remain on the rock. He can hardly believe what he sees when he looks at the ships. Dwarves and humans, ghostly fallen heroes, undead warriors, <NAME>barians, fire giants wading through the seas, trolls beating war drums—has everyone on Kaldheim banded together? Tyvar can't recall seeing so many different faces in one place outside of a battlefield. New Phyrexia planted the seeds of doubt and fear deep within him. The oil, and the changing of his newfound comrades, nurtured it. But this? This true unity? This is an axe. Harald climbs onto the ship first. He stretches out a hand toward Tyvar, who instead leaps onto the longship of his own accord. Beneath them the platform crumbles away into Skemfar's new river. "Warriors!" Harald calls. The sigils and guides along the sides of the ship begin to glow. "Our grudges are ancient. A single battle shall not wipe clean the slate of old wrongs. When the morrow comes, all of us will once more be enemies!" Tyvar's heart thrums in time with the beating drums, the sounding horns. Ships pick up speed. When Harald spoke even his most hated enemies waited to hear what he had to say. He does not know where they are going, but he knows that wherever they land, glory awaits. White swallows them. For an instant, they enter the Cosmos, dazzling and infinite. Unearthly beasts lope alongside the boats—wolves, ravens, bears, even a squirrel. "But that is only if we live to greet the morrow, my brothers and sisters in arms. Today, the valkyries will have their choice of heroes; today is a day the skalds shall sing of for centuries. Will your descendants name you a hero, or a coward?" Light once more. Tyvar doesn't shut his eyes, no matter how the patterns sear at his irises. When at last the light recedes, they find themselves above a churning ocean. Somehow, they're airborne—he leaves no time to question it, only lets it thrill his blood. Valkyries fly alongside them toward the sharp barbs of the Invasion Tree, yet to find their home. Divine arrows streak light across the reddening sky. The World Tree looms, its foul mirror descending down, down, down. From here he can count every bump of its spine, every pod nestled within. There must be thousands. Tens of thousands, maybe, each with their own complement of soldiers, and each of those soldiers a fearsome foe. This was an enemy almost unstoppable: worse, those who died in defense of Kaldheim would rise, corrupted, to fight for the invaders who sought to destroy the land they once called home. The odds, he knows, are not good. #figure(image("004_Episode 4: Beneath Eyes Unblinking/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "If Kaldheim survives, let it survive because we fought! If it dies, let it die a warrior's death, axe in hand, a boast on its lips, and mead in its belly!" Beneath them the water bubbles. Just as the longboats erupt in a warrior's song, the seas too erupt. The tattoos on Tyvar's shoulders tingle. All elves grew in the shadow of Koma. Ever changing, ever growing, quick as lightning and wily besides—is there any better creature to emulate than a serpent? But that is not true of the serpent he sees now, the creature that rises from the depths of the sea. Sleek scales of metal, sharp bones along the ridges of its mouth, porcelain plating in place of eyes—whatever this creature once was, it is now unmistakably one of Elesh Norn's creations. Already the eyeless monstrosity has snapped a longship between its jaws. Wood groans and warriors cry, tumbling great distances to their deaths. From others, a hail of arrows, stones, thrown axes—whatever they might get ahold of. All bounce off the creature's strange carapace. Tyvar takes a step onto the boat's railing. In the flickering light of what might be Kaldheim's last war, the edge of his blade gleams bright. Below him, the mouth of the serpent: within it, New Phyrexia, and all his fears made manifest. He doesn't like being afraid. With the seething song of battle at his back and a cry from his chest, Tyvar leaps from the ship. However the story of this day ends, the sagas will tell he was no coward. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) <NAME> has spent the last ten years of her life fighting for a better Kaladesh. Most of that work's been undone in one day. No—the truth is it's been a week, at least. Saheeli warned her then that something like this might happen, that something was going to happen. The clouds held proof, she'd said. In place of the swirls that so often dominated the skies of Kaladesh, she'd shown Pia the new shape that had come to dominate them. "We have to be ready for an invasion," Saheeli had said. "Chandra and the others have a handle on it." She was so confident. So certain. She didn't want to believe that it could be otherwise. After all that had happened, after all the struggles and wars—the Gatewatch must understand what needs doing. They must be able to handle it. Then one morning Pia spilled ink on her desk. When she grabbed a cloth to clean up the mess, the symbol—like an unblinking eye—stared back up at her in viscous black. The memory was bad enough, but after the first spill she saw it everywhere she looked: in scrolls curled up on a shelf, in a plate of noodles she had not the stomach to finish, in trees and in currents of water. Every day she awoke hoping that they'd fade, that she'd not see them, that Chandra would stroll back into her home for their monthly tea appointment with another story about how they'd snapped victory from the jaws of defeat. But by the third day, she knew she had to act. She and Saheeli addressed the consulate—but how could they convey the severity of what they knew? After Ghirapur had won its own freedom and safety? Addressing this threat would stoke fear within the populace, and how could they be certain it was coming? The House of Knowledge had no records of any Phyrexians. Yet Saheeli and Pia were not raving madwomen, a fact the consulate knew well. If Pia allocated the resources to fight, then fight they would. Even if some of them had no heart in it. On the fourth day the sky darkened to a deep, rusty red. For the past three days Saheeli'd been working on something she called "Operation Golden Scales," something she said would keep the streets safe. Most citizens in Ghirapur had been evacuated, leaving only essential personnel behind. Skyships armed themselves with powerful experimental weaponry. Ghirapur's workshops and factories had never worked so hard in such a short time—but it was for the best. After all, if the enemy breached the aetherflux reservoir, there would no longer be a Ghirapur to defend. So the artisans hadn't slept, and Pia hadn't either. She'd fallen asleep in the entryway of her own home. Getting to bed was just too much effort. When at last the portals overhead opened, when the great spines of invasion descended from the holes they tore in reality, when the aether around them began to crackle dangerously against her skin—all of this was like letting out a breath. It was here. They were here. The time for preparation was long behind them. All they could do was hope it had been enough. Ghirapur's streets are clear—or as clear as they're ever going to get—as Pia leaves her home. Three buildings away, a pod obliterates a building's facade. Shattered glass, distant screams, weapons firing—the sounds are close to and yet altogether different from the sounds of revolution. There is no chanting here, there are no throaty slogans, no proud horns or resounding drums. Only fear and desperation. Skyships overhead fire their cannons at the invading branches and explosions paint the red sky gold. Shards of porcelain rain down upon the streets. She seeks cover beneath a statue's outstretched arms only to watch as the shards rend furrows down its sides. Pia looks back up at the sky—at the ship that so readily advanced against the questing branch. She met its captain two days ago. He swore that he'd do everything in his power to keep Ghirapur safe. A thousand and a half flights, he'd said, with no major losses to speak of. She watches as the branch wraps around the ship, watches as its windows shatter as easily as those down the street, watches the oil slick its surface. Pia closes her eyes. Her chest aches. A thousand thoughts fight to slip into her mind, but she walls them away. There's a rendezvous with Saheeli to get to. Speaking of—looks like her operation's off to a good start. Deployment chambers spring up from hatches all along the street, and from those chambers emerge the fruits of Operation Golden Scales. Saheeli must have taken inspiration from some fantastic kind of lizard: the one lumbering in front of Pia is as big as the house that crumbled moments ago. The shining teeth along its jaws are each the size of Pia's forearm. When it stomps its feet, the stones beneath crack. And it is only one of many—all along the streets other bronze attack lizards spring up from the earth. Some are the size of small dogs, some take to the skies like thopters, but all roar their defiance at the coming Phyrexians. And there are Phyrexians to deal with, even if the sight of these things is almost enough to distract Pia. From the broken house pour dozens of spindly porcelain soldiers—some of whom carry cages as big as they are. The two forces are about to clash. Pia doesn't want to be in the middle of it. She ducks under the bronze lizard's feet in time for a familiar face to pop up behind the Phyrexians. A cloud of thopters fly from Saheeli's cruiser. While the lizards descend upon the soldiers, the thopters conceal Pia's escape. "Get in!" Saheeli shouts. And she's right to hurry—the soldiers don't take their duties lightly. Within minutes they've swarmed the largest of the lizards and taken it down. Oil seeps from its split mouths. It won't be long before the lizard rises against them, too. Pia hops into the car. Saheeli's foot must be as leaden as the metal she's so fond of; the two of them jerk backward against the seats as the speed catches up to them. Wind whistles in Pia's ears—but they have to talk. "The flagship's down." "I know," Saheeli answers. An explosion to their right sends them swerving; Saheeli only barely manages to keep them from flipping. "The smaller ships are doing what they can. The tendrils can't grasp them quickly enough to stop them. Of course, their firepower is lacking in comparison~" Pia ducks as Saheeli takes them between the legs of a massive Phyrexianized lizard construct. Metal scrapes against metal; the cruiser's sides dent and distort despite Saheeli's best efforts. Oil drips onto the trunk's lid. Pia tries not to wonder how long it'll be before the cruiser is corrupted, too. "Do you know what the situation is at the aetherflux reservoir?" Pia asks. "We think the Phyrexians might understand its importance, or else feel a pull toward the aether stored there," Saheeli answers. "If you'll notice, they're all heading straight for it." #figure(image("004_Episode 4: Beneath Eyes Unblinking/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) They turn a corner, and Pia sees the guards. Her stomach wrenches at the sight. Like a sinister parody of Saheeli's design aesthetics, they are filigreed in white porcelain, half-metal and half-flesh. One of the men sports a large hole in the center of his head, one that Pia can see clear through. Only his ears, scalp, and chin remain. It looks as if he is a needle meant to be threaded—and the razor his arms have become only affirms the notion. Despite this hideous alteration, his chest rises and falls with unseen breath. His head, such as it is, is turned toward the reservoir. Pia covers her mouth. "We can't do anything to save them," Saheeli says. "There has to be something." "There might be, but whatever it is will take study, experimentation, iteration. Once the city's secure we can #emph[consider] what shapes that might take—but not now." Pia presses her eyes shut as the cruiser shoots over the newly converted Phyrexians. There are more of them to see when she opens her eyes again. Has she been ignoring them before now? There are so many, in so many different forms: Some share the same porcelain plating motif as the tendrils overhead, some have their organs replaced with glowing orange flame. She sees a street dog that has grown quills and tendrils twice its size. It'd be comical if the plane wasn't falling apart around her. "Have you heard from the others?" she asks, before she can stop herself. Saheeli's eyes don't leave the reservoir far ahead of them. "I have. The last time they saw Chandra, she was all right." Pia's been around politicians long enough to know when she isn't getting the whole story. "And when was that?" "Recently, very recently," Saheeli answers. She looks over her shoulder. "This might not be the best time." "There isn't a good time when it comes to bad news." "There are #emph[better] times than this." Pia frowns. "Please, just tell me what's going on." Saheeli glances around. "She's—" "Renegade Prime! Long time no see!" Pia turns. Along with the spritely voice comes the rumble of an engine. Hanging over the side of a skimmer above them is one of her old renegade contacts, Baji. "Need any help down there?" "We can use all the help we can get," she says. "We're headed to the reservoir." "Come on in, then!" calls the pilot. "You'll get there faster in this. And we've got better firepower, too." Saheeli looks up. "He's not joking. Those weapons aren't legal." The renegades were always great at securing contraband. Pia stands in the passenger seat of the cruiser, one hand on the seat and the other on the door. Saheeli doesn't slow down—not even when Pia offers her a hand. "There's only room for one more in that skimmer," Saheeli says. When one of the geniuses of Kaladesh tells you what she wants to do, it behooves you to listen. Besides, when it comes to revolutions and crises, you must be able to improvise. "Right," Pia says. "We'll cover you." As Baji swoops lower, he reaches out for Pia. The skimmer's not the most solid thing in the world, not by a long shot. Now that they're in it she wonders how it's flying at all—nuts and bolts rattle around them, and the seat's little more than a strip of leather on hard, hastily shaped metal. The back seat's so narrow that the sides bite against her shoulders. Baji angles the craft up, climbing higher, Ghirapur vanishing below the clouds as they rise into the sky. He flips a switch on his console and a glass dome slides over the open cockpit. "Helmet's under your seat," Baji says. Pia pulls the helmet on. She can't help but notice the chips and scraps on the cockpit glass. "Is this thing secure?" she asks. "It'll hold," Baji said. "I put it together myself. Used only the finest scrap, straight from—" Whatever he meant to say is lost in a gurgle when a javelin punches through the window and impales him through the chest to his seat, blood-soaked tip stopping only a hairsbreadth from Pia. Swooping through the air above them is something that might once have been a bird. Now it fights for Phyrexia. Realization sets in—that's no javelin, it's a #emph[quill] . Alarms howl, drowned out by the air screaming in through the hole in the ship's cockpit. Slowly, it begins to tip to the side, and then twist nose first, plummeting toward the ground. Pia's stomach lurches at the shift in momentum, the nauseating weightlessness. Without thinking she squeezes into the pilot's seat, wedging the quill free from the leather. Baji's body has her half-pinned. There's no room to navigate, the console's an incomprehensible hodgepodge of welded together parts, there are two Phyrexian birds on her flanks and more ships all around. This isn't good. And that's before factoring in that <NAME> has never even flown one of these things before. But she isn't about to give up here. Not when it comes to keeping Kaladesh safe, and not when it comes to her daughter. Chandra's going to come to tea next month. Pia's going to be there to meet her. If she can just get through this. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) From the second Atraxa arrived, New Capenna drew its nails down her pristine carapace. A city built reaching ever upward, the atmosphere crackling with a disgusting energy, crawling with a horribly diversity of life. Everything about it is anathema to her—to Phyrexia. How fortunate that her orders are to scour it. But Phyrexia is not a beast that eats without thought. In all things there is the seed of greatness, no matter how base the material. To be Phyrexian is to allow yourself to grow, to change, to become something greater than you once were. The spire that so vexes her can be stripped of its accoutrements and rendered anew. This is a place teeming with sin and filth, and Atraxa will be its savior. The work alone is enough to fill her with ecstasy. All along the rooftops the organics take up arms. Their weapons will not serve them here: there are no dents in Phyrexia's armor. Nor will climbing higher save them. A single thought from Atraxa summons swarms of flying servitors. Tiny though they may be, they are hungry beasts—soon, those that climb are nothing more than bones falling to the earth. Those that take to the streets instead rely on their muscle and sinew to fight back. They are ignorant to the weaknesses of flesh. The war engines crash through storefront after storefront to fulfill their will. As they reach the street, they unleash clouds of caustic gas. Flesh melts from bone. #emph[Harvest them. ] One glorious thought, echoed in a thousand minds. They take no prisoners here on New Capenna; there are no cages for the fleshlings. What the engines cannot melt with their gasses is shoveled back inside of them by servitors. Only these parts will remain. #emph[Harvest. Them. ] How loudly the words ring in her mind! The organics try to fool the Phyrexians, disappearing into the dark and reappearing behind them, but it is no use. Nothing is going to prevent what is to come. Neither will the spells hurled in desperation, or the blades driven between the ribs of centurions. Phyrexia can never be defeated. But flesh~ flesh will always yield, in the end. Norn's orders were clear: everything that draws wretched breath on this plane must be harvested for parts—and so they will be. But Atraxa sees a use for them before tearing them asunder. After all, somewhere within this monstrosity of a plane are the remains of her predecessors. Finding them is part of her assignment here. The minds of the newcomers open readily to her. Maestros, they call themselves. The thrill of their new bodies ripples through the entirety of the invading force, lending them strength against those who foolishly resist. Yet this is not the answer she seeks, not the answer Phyrexia needs. Deeper into their minds she ventures. Within them, Atraxa finds something curious. #emph[Beautiful.] #figure(image("004_Episode 4: Beneath Eyes Unblinking/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Over and over, that word. That idea. It never comes alone—always with images or sounds or tastes. Paint on canvas. Stone shaped by a studious hand. Flowers opening in the night. A keening creak from a wooden instrument. These things, she surmises, must be #emph[beautiful] , and what is #emph[beautiful ] must be important. Often it is the first thought they have when they look at their new forms, the first word that pops into their minds. But what is that? Why are they so preoccupied with it? The strength of their conviction's spread through the invading forces, each mind amplifying the last. The word rings within Atraxa's skull until she can no longer escape it. Norn warned her about this. She said there was something about this place that would try to infect her, something that her previous life might lend her resistance against. There are distant memories in her mind of #emph[beauty] , of a pale imitation of compleation she once reveled in. This is the face and name of her enemy—and those who spent so long worshipping this false divinity must know where it lives. Searching their minds provides another answer: #emph[museum] . The images that come along are clear enough. Surveying the city, she sees it not far from one of the conversion pods: a squat building festooned in marble shaped this way and that. She looks at it and wonders if it is #emph[beautiful] . Those who were once Maestros tell her that it is. The columns, the statues, the carefully curated ivy crawling upon its facade: how could she ever think it was anything but #emph[beautiful] ? The furor of their passion drives her on. Whatever it is they are hiding, she must be able to get a better idea of it there. As Phyrexia tears through the resistance, Atraxa lands upon the steps outside of the building. The doors are too small for her; with a touch, she corrects their already apparent failures. This place, too, shall embrace Phyrexia. Inside there are more incomprehensible works. Fleshy beings stare back from canvases or panels of wood—a testament to the frailty of natural materials. So great is the arrogance of these creatures that they have shaped stone and metal in their image. The wretched inversion rankles Atraxa. All of this does. Why would anyone bother with any of this? These "paintings" often portrayed only a single individual; even those with groups did not portray more than a dozen. Why extol the virtues of so few when it is by many hands that great work is done? And these statues! Even more individual than the paintings! Her spear makes short work of them. The newly formed scream in the recesses of the Phyrexian mind, but only for a moment; that part of them is dying and understands that this is for the best. All will be one. These works no longer matter. And yet something deep within that same mind tells her that she must keep going. There is something here. At the very least she can see to the destruction of the heresy around her. Deeper within there are more atrocities. Worse, if it can be believed. Here the works no longer represent anything at all: they are sharp, geometrical replications of organic creatures. Neither weapons nor bulwarks; she can imagine no purpose for them. These, too, she strikes down, her frustration growing. It is the last room which answers her questions. Here there are no strange objects, here there is no paint, no mortal loudly announcing their own individual self. Instead, the shapes she sees are pale imitations of glory. A lopsided axe upon the wall, a mock war hound carapace upon a plinth, images that occlude the glory of compleation~ Norn told her Phyrexians had once been here, but this speaks to the cruelty organics think themselves above. #emph[Beautiful] , that word again in her mind, that awful word, but there is nothing #emph[beautiful] about any of this. Do these people worship failure? Do they look upon the bodies of those that came before and marvel at them? The memories of the Maestros are a battering ram: groups gathered around these remains, drinking and eating and chittering with their wet lips and glistening tongues. #emph["Can you imagine being the guy swinging that thing around?"] #emph["I'll tell you something, I wish I could hire him to follow me around and just stand there looking intimidating."] #emph["Say, how much do you think it's worth . . . ? I've got half a mind to buy it myself."] #emph["C'mon, pal, there's no way you could afford it."] Her grip on her spear tightens. Wrong, wrong, wrong. This place, the Phyrexians who were too weak to see their mission through, the fleshlings who mock them. #emph[Beautiful] , that awful word they have for this, cannot mean other than #emph[wrongness] . Atraxa will strike it down. All of it, everything that bears the name, must be destroyed. To allow it to exist only invites further mockery—and Phyrexia shall not be mocked. As phyresis creeps over the building's facade, she obliterates everything within it. What purpose it will serve is not for her to decide. What is useful of them will linger and what is not will be stripped away. Tail, claw, spear, and scream: her weapons are unerring and untiring. Scrap and rubble are all that remain when she is done. What inhabitants she encounters are smeared across the rocks. In their last moments, they might imagine that they are beautiful. But she never wants to hear the word again. If she could scour it from the mind of Phyrexia, she would, but that is a thing only the Mother of Machines may decree. Still, <NAME> appointed her to lead these forces, which means she can strike down beauty here, if she pleases. Atraxa needs only think the order for it to go out. To her satisfaction, as she emerges from the museum, she hears weapons striking stone all around. The satisfaction does not last long. Across the courtyard there are angels staring at her—angels with faces of stone. It is not a conscious thing that happens next—it is not a thought she has, but an instinct. At once she realizes that the stone seraphs of the cathedral are indeed beautiful, and that she hates them more than she has ever hated anything, more than she knew it was possible to hate. The chorus of minds falls away to the resounding note of anger hammering throughout her being. In a blur of white, she strikes the heads from the statues. When they crumble to the ground, she does not stop attacking them but continues bringing her spear down, over and over, again and again, heedless of the hazy energy that emerges from the rock. Though it sears her carapace and her sinews are alight with agony, she cannot bring herself to stop until nothing remains of the heads but a fine dust. Only then does she stop. Only then does she hear Phyrexia again. #emph[There are fleshlings climbing the tower. What must be done with them?] One voice speaks, and then another: #emph[harvest them, harvest them.] #emph[But this vapor pains us, and we ache.] #emph[Phyrexia does not ache. Harvest them.] Atraxa looks up at the headless figures. A deep calm comes over her. Beauty is dead, and she can turn her attentions once more to the front—to the beings on the outside of the tower, and what they might be planning. She leaves the platform. But the seraphs remain, watching her go, with their visitor hovering among them in a haze of color. They, too, speak among themselves. #emph[Why not stop her? ] asks the visitor. #emph[It is not yet time.] It does not feel like the right answer—but the visitor cannot disprove it. #emph[Have faith. It's almost here, the end. You'll know what to do when we've gotten there.]
https://github.com/DieracDelta/presentations
https://raw.githubusercontent.com/DieracDelta/presentations/master/polylux/tests/alternatives.typ
typst
#import "../polylux.typ": * #set page(paper: "presentation-16-9") #polylux-slide[ == Test that `repeat-last` works #alternatives[abc ][def ][ghi ] #alternatives(repeat-last: true)[jkl ][mno ][this stays ] #uncover(5)[You can go now.] ] #polylux-slide[ == Test that `alternatives-match` works #alternatives-match(position: center, ( "-2": [beginning], "3, 5": [main part], "4": [short break], "6-" : [end] )) #uncover("1-8")[I am always here, for technical reasons.] ] #polylux-slide[ == Test that `alternatives-cases` works #alternatives-cases(("1,3,4", "2,5", "6"), case => { set text(fill: lime) if case == 1 lorem(10) }) ] #polylux-slide[ == Test that `alternatives-fn` works #alternatives-fn(count: 5, subslide => numbering("(i)", subslide)) ]
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/044.%20hiring.html.typ
typst
hiring.html Hiring is Obsolete Want to start a startup? Get funded by Y Combinator. May 2005(This essay is derived from a talk at the Berkeley CSUA.)The three big powers on the Internet now are Yahoo, Google, and Microsoft. Average age of their founders: 24. So it is pretty well established now that grad students can start successful companies. And if grad students can do it, why not undergrads?Like everything else in technology, the cost of starting a startup has decreased dramatically. Now it's so low that it has disappeared into the noise. The main cost of starting a Web-based startup is food and rent. Which means it doesn't cost much more to start a company than to be a total slacker. You can probably start a startup on ten thousand dollars of seed funding, if you're prepared to live on ramen.The less it costs to start a company, the less you need the permission of investors to do it. So a lot of people will be able to start companies now who never could have before.The most interesting subset may be those in their early twenties. I'm not so excited about founders who have everything investors want except intelligence, or everything except energy. The most promising group to be liberated by the new, lower threshold are those who have everything investors want except experience.Market RateI once claimed that nerds were unpopular in secondary school mainly because they had better things to do than work full-time at being popular. Some said I was just telling people what they wanted to hear. Well, I'm now about to do that in a spectacular way: I think undergraduates are undervalued.Or more precisely, I think few realize the huge spread in the value of 20 year olds. Some, it's true, are not very capable. But others are more capable than all but a handful of 30 year olds. [1]Till now the problem has always been that it's difficult to pick them out. Every VC in the world, if they could go back in time, would try to invest in Microsoft. But which would have then? How many would have understood that this particular 19 year old was <NAME>?It's hard to judge the young because (a) they change rapidly, (b) there is great variation between them, and (c) they're individually inconsistent. That last one is a big problem. When you're young, you occasionally say and do stupid things even when you're smart. So if the algorithm is to filter out people who say stupid things, as many investors and employers unconsciously do, you're going to get a lot of false positives.Most organizations who hire people right out of college are only aware of the average value of 22 year olds, which is not that high. And so the idea for most of the twentieth century was that everyone had to begin as a trainee in some entry-level job. Organizations realized there was a lot of variation in the incoming stream, but instead of pursuing this thought they tended to suppress it, in the belief that it was good for even the most promising kids to start at the bottom, so they didn't get swelled heads.The most productive young people will always be undervalued by large organizations, because the young have no performance to measure yet, and any error in guessing their ability will tend toward the mean.What's an especially productive 22 year old to do? One thing you can do is go over the heads of organizations, directly to the users. Any company that hires you is, economically, acting as a proxy for the customer. The rate at which they value you (though they may not consciously realize it) is an attempt to guess your value to the user. But there's a way to appeal their judgement. If you want, you can opt to be valued directly by users, by starting your own company.The market is a lot more discerning than any employer. And it is completely non-discriminatory. On the Internet, nobody knows you're a dog. And more to the point, nobody knows you're 22. All users care about is whether your site or software gives them what they want. They don't care if the person behind it is a high school kid.If you're really productive, why not make employers pay market rate for you? Why go work as an ordinary employee for a big company, when you could start a startup and make them buy it to get you?When most people hear the word "startup," they think of the famous ones that have gone public. But most startups that succeed do it by getting bought. And usually the acquirer doesn't just want the technology, but the people who created it as well.Often big companies buy startups before they're profitable. Obviously in such cases they're not after revenues. What they want is the development team and the software they've built so far. When a startup gets bought for 2 or 3 million six months in, it's really more of a hiring bonus than an acquisition.I think this sort of thing will happen more and more, and that it will be better for everyone. It's obviously better for the people who start the startup, because they get a big chunk of money up front. But I think it will be better for the acquirers too. The central problem in big companies, and the main reason they're so much less productive than small companies, is the difficulty of valuing each person's work. Buying larval startups solves that problem for them: the acquirer doesn't pay till the developers have proven themselves. Acquirers are protected on the downside, but still get most of the upside.Product DevelopmentBuying startups also solves another problem afflicting big companies: they can't do product development. Big companies are good at extracting the value from existing products, but bad at creating new ones.Why? It's worth studying this phenomenon in detail, because this is the raison d'etre of startups.To start with, most big companies have some kind of turf to protect, and this tends to warp their development decisions. For example, Web-based applications are hot now, but within Microsoft there must be a lot of ambivalence about them, because the very idea of Web-based software threatens the desktop. So any Web-based application that Microsoft ends up with, will probably, like Hotmail, be something developed outside the company.Another reason big companies are bad at developing new products is that the kind of people who do that tend not to have much power in big companies (unless they happen to be the CEO). Disruptive technologies are developed by disruptive people. And they either don't work for the big company, or have been outmaneuvered by yes-men and have comparatively little influence.Big companies also lose because they usually only build one of each thing. When you only have one Web browser, you can't do anything really risky with it. If ten different startups design ten different Web browsers and you take the best, you'll probably get something better.The more general version of this problem is that there are too many new ideas for companies to explore them all. There might be 500 startups right now who think they're making something Microsoft might buy. Even Microsoft probably couldn't manage 500 development projects in-house.Big companies also don't pay people the right way. People developing a new product at a big company get paid roughly the same whether it succeeds or fails. People at a startup expect to get rich if the product succeeds, and get nothing if it fails. [2] So naturally the people at the startup work a lot harder.The mere bigness of big companies is an obstacle. In startups, developers are often forced to talk directly to users, whether they want to or not, because there is no one else to do sales and support. It's painful doing sales, but you learn much more from trying to sell people something than reading what they said in focus groups.And then of course, big companies are bad at product development because they're bad at everything. Everything happens slower in big companies than small ones, and product development is something that has to happen fast, because you have to go through a lot of iterations to get something good.TrendI think the trend of big companies buying startups will only accelerate. One of the biggest remaining obstacles is pride. Most companies, at least unconsciously, feel they ought to be able to develop stuff in house, and that buying startups is to some degree an admission of failure. And so, as people generally do with admissions of failure, they put it off for as long as possible. That makes the acquisition very expensive when it finally happens.What companies should do is go out and discover startups when they're young, before VCs have puffed them up into something that costs hundreds of millions to acquire. Much of what VCs add, the acquirer doesn't need anyway.Why don't acquirers try to predict the companies they're going to have to buy for hundreds of millions, and grab them early for a tenth or a twentieth of that? Because they can't predict the winners in advance? If they're only paying a twentieth as much, they only have to predict a twentieth as well. Surely they can manage that.I think companies that acquire technology will gradually learn to go after earlier stage startups. They won't necessarily buy them outright. The solution may be some hybrid of investment and acquisition: for example, to buy a chunk of the company and get an option to buy the rest later.When companies buy startups, they're effectively fusing recruiting and product development. And I think that's more efficient than doing the two separately, because you always get people who are really committed to what they're working on.Plus this method yields teams of developers who already work well together. Any conflicts between them have been ironed out under the very hot iron of running a startup. By the time the acquirer gets them, they're finishing one another's sentences. That's valuable in software, because so many bugs occur at the boundaries between different people's code.InvestorsThe increasing cheapness of starting a company doesn't just give hackers more power relative to employers. It also gives them more power relative to investors.The conventional wisdom among VCs is that hackers shouldn't be allowed to run their own companies. The founders are supposed to accept MBAs as their bosses, and themselves take on some title like Chief Technical Officer. There may be cases where this is a good idea. But I think founders will increasingly be able to push back in the matter of control, because they just don't need the investors' money as much as they used to.Startups are a comparatively new phenomenon. Fairchild Semiconductor is considered the first VC-backed startup, and they were founded in 1959, less than fifty years ago. Measured on the time scale of social change, what we have now is pre-beta. So we shouldn't assume the way startups work now is the way they have to work.Fairchild needed a lot of money to get started. They had to build actual factories. What does the first round of venture funding for a Web-based startup get spent on today? More money can't get software written faster; it isn't needed for facilities, because those can now be quite cheap; all money can really buy you is sales and marketing. A sales force is worth something, I'll admit. But marketing is increasingly irrelevant. On the Internet, anything genuinely good will spread by word of mouth.Investors' power comes from money. When startups need less money, investors have less power over them. So future founders may not have to accept new CEOs if they don't want them. The VCs will have to be dragged kicking and screaming down this road, but like many things people have to be dragged kicking and screaming toward, it may actually be good for them.Google is a sign of the way things are going. As a condition of funding, their investors insisted they hire someone old and experienced as CEO. But from what I've heard the founders didn't just give in and take whoever the VCs wanted. They delayed for an entire year, and when they did finally take a CEO, they chose a guy with a PhD in computer science.It sounds to me as if the founders are still the most powerful people in the company, and judging by Google's performance, their youth and inexperience doesn't seem to have hurt them. Indeed, I suspect Google has done better than they would have if the founders had given the VCs what they wanted, when they wanted it, and let some MBA take over as soon as they got their first round of funding.I'm not claiming the business guys installed by VCs have no value. Certainly they have. But they don't need to become the founders' bosses, which is what that title CEO means. I predict that in the future the executives installed by VCs will increasingly be COOs rather than CEOs. The founders will run engineering directly, and the rest of the company through the COO.The Open CageWith both employers and investors, the balance of power is slowly shifting towards the young. And yet they seem the last to realize it. Only the most ambitious undergrads even consider starting their own company when they graduate. Most just want to get a job.Maybe this is as it should be. Maybe if the idea of starting a startup is intimidating, you filter out the uncommitted. But I suspect the filter is set a little too high. I think there are people who could, if they tried, start successful startups, and who instead let themselves be swept into the intake ducts of big companies.Have you ever noticed that when animals are let out of cages, they don't always realize at first that the door's open? Often they have to be poked with a stick to get them out. Something similar happened with blogs. People could have been publishing online in 1995, and yet blogging has only really taken off in the last couple years. In 1995 we thought only professional writers were entitled to publish their ideas, and that anyone else who did was a crank. Now publishing online is becoming so popular that everyone wants to do it, even print journalists. But blogging has not taken off recently because of any technical innovation; it just took eight years for everyone to realize the cage was open.I think most undergrads don't realize yet that the economic cage is open. A lot have been told by their parents that the route to success is to get a good job. This was true when their parents were in college, but it's less true now. The route to success is to build something valuable, and you don't have to be working for an existing company to do that. Indeed, you can often do it better if you're not.When I talk to undergrads, what surprises me most about them is how conservative they are. Not politically, of course. I mean they don't seem to want to take risks. This is a mistake, because the younger you are, the more risk you can take.RiskRisk and reward are always proportionate. For example, stocks are riskier than bonds, and over time always have greater returns. So why does anyone invest in bonds? The catch is that phrase "over time." Stocks will generate greater returns over thirty years, but they might lose value from year to year. So what you should invest in depends on how soon you need the money. If you're young, you should take the riskiest investments you can find.All this talk about investing may seem very theoretical. Most undergrads probably have more debts than assets. They may feel they have nothing to invest. But that's not true: they have their time to invest, and the same rule about risk applies there. Your early twenties are exactly the time to take insane career risks.The reason risk is always proportionate to reward is that market forces make it so. People will pay extra for stability. So if you choose stability-- by buying bonds, or by going to work for a big company-- it's going to cost you.Riskier career moves pay better on average, because there is less demand for them. Extreme choices like starting a startup are so frightening that most people won't even try. So you don't end up having as much competition as you might expect, considering the prizes at stake.The math is brutal. While perhaps 9 out of 10 startups fail, the one that succeeds will pay the founders more than 10 times what they would have made in an ordinary job. [3] That's the sense in which startups pay better "on average."Remember that. If you start a startup, you'll probably fail. Most startups fail. It's the nature of the business. But it's not necessarily a mistake to try something that has a 90% chance of failing, if you can afford the risk. Failing at 40, when you have a family to support, could be serious. But if you fail at 22, so what? If you try to start a startup right out of college and it tanks, you'll end up at 23 broke and a lot smarter. Which, if you think about it, is roughly what you hope to get from a graduate program.Even if your startup does tank, you won't harm your prospects with employers. To make sure I asked some friends who work for big companies. I asked managers at Yahoo, Google, Amazon, Cisco and Microsoft how they'd feel about two candidates, both 24, with equal ability, one who'd tried to start a startup that tanked, and another who'd spent the two years since college working as a developer at a big company. Every one responded that they'd prefer the guy who'd tried to start his own company. <NAME>, who's in charge of engineering at Yahoo, said: I actually put more value on the guy with the failed startup. And you can quote me! So there you have it. Want to get hired by Yahoo? Start your own company.The Man is the CustomerIf even big employers think highly of young hackers who start companies, why don't more do it? Why are undergrads so conservative? I think it's because they've spent so much time in institutions.The first twenty years of everyone's life consists of being piped from one institution to another. You probably didn't have much choice about the secondary schools you went to. And after high school it was probably understood that you were supposed to go to college. You may have had a few different colleges to choose between, but they were probably pretty similar. So by this point you've been riding on a subway line for twenty years, and the next stop seems to be a job.Actually college is where the line ends. Superficially, going to work for a company may feel like just the next in a series of institutions, but underneath, everything is different. The end of school is the fulcrum of your life, the point where you go from net consumer to net producer.The other big change is that now, you're steering. You can go anywhere you want. So it may be worth standing back and understanding what's going on, instead of just doing the default thing.All through college, and probably long before that, most undergrads have been thinking about what employers want. But what really matters is what customers want, because they're the ones who give employers the money to pay you.So instead of thinking about what employers want, you're probably better off thinking directly about what users want. To the extent there's any difference between the two, you can even use that to your advantage if you start a company of your own. For example, big companies like docile conformists. But this is merely an artifact of their bigness, not something customers need.Grad SchoolI didn't consciously realize all this when I was graduating from college-- partly because I went straight to grad school. Grad school can be a pretty good deal, even if you think of one day starting a startup. You can start one when you're done, or even pull the ripcord part way through, like the founders of Yahoo and Google.Grad school makes a good launch pad for startups, because you're collected together with a lot of smart people, and you have bigger chunks of time to work on your own projects than an undergrad or corporate employee would. As long as you have a fairly tolerant advisor, you can take your time developing an idea before turning it into a company. <NAME> and <NAME> started the Yahoo directory in February 1994 and were getting a million hits a day by the fall, but they didn't actually drop out of grad school and start a company till March 1995.You could also try the startup first, and if it doesn't work, then go to grad school. When startups tank they usually do it fairly quickly. Within a year you'll know if you're wasting your time.If it fails, that is. If it succeeds, you may have to delay grad school a little longer. But you'll have a much more enjoyable life once there than you would on a regular grad student stipend.ExperienceAnother reason people in their early twenties don't start startups is that they feel they don't have enough experience. Most investors feel the same.I remember hearing a lot of that word "experience" when I was in college. What do people really mean by it? Obviously it's not the experience itself that's valuable, but something it changes in your brain. What's different about your brain after you have "experience," and can you make that change happen faster?I now have some data on this, and I can tell you what tends to be missing when people lack experience. I've said that every startup needs three things: to start with good people, to make something users want, and not to spend too much money. It's the middle one you get wrong when you're inexperienced. There are plenty of undergrads with enough technical skill to write good software, and undergrads are not especially prone to waste money. If they get something wrong, it's usually not realizing they have to make something people want.This is not exclusively a failing of the young. It's common for startup founders of all ages to build things no one wants.Fortunately, this flaw should be easy to fix. If undergrads were all bad programmers, the problem would be a lot harder. It can take years to learn how to program. But I don't think it takes years to learn how to make things people want. My hypothesis is that all you have to do is smack hackers on the side of the head and tell them: Wake up. Don't sit here making up a priori theories about what users need. Go find some users and see what they need.Most successful startups not only do something very specific, but solve a problem people already know they have.The big change that "experience" causes in your brain is learning that you need to solve people's problems. Once you grasp that, you advance quickly to the next step, which is figuring out what those problems are. And that takes some effort, because the way software actually gets used, especially by the people who pay the most for it, is not at all what you might expect. For example, the stated purpose of Powerpoint is to present ideas. Its real role is to overcome people's fear of public speaking. It allows you to give an impressive-looking talk about nothing, and it causes the audience to sit in a dark room looking at slides, instead of a bright one looking at you.This kind of thing is out there for anyone to see. The key is to know to look for it-- to realize that having an idea for a startup is not like having an idea for a class project. The goal in a startup is not to write a cool piece of software. It's to make something people want. And to do that you have to look at users-- forget about hacking, and just look at users. This can be quite a mental adjustment, because little if any of the software you write in school even has users. A few steps before a Rubik's Cube is solved, it still looks like a mess. I think there are a lot of undergrads whose brains are in a similar position: they're only a few steps away from being able to start successful startups, if they wanted to, but they don't realize it. They have more than enough technical skill. They just haven't realized yet that the way to create wealth is to make what users want, and that employers are just proxies for users in which risk is pooled.If you're young and smart, you don't need either of those. You don't need someone else to tell you what users want, because you can figure it out yourself. And you don't want to pool risk, because the younger you are, the more risk you should take.A Public Service MessageI'd like to conclude with a joint message from me and your parents. Don't drop out of college to start a startup. There's no rush. There will be plenty of time to start companies after you graduate. In fact, it may be just as well to go work for an existing company for a couple years after you graduate, to learn how companies work.And yet, when I think about it, I can't imagine telling <NAME> at 19 that he should wait till he graduated to start a company. He'd have told me to get lost. And could I have honestly claimed that he was harming his future-- that he was learning less by working at ground zero of the microcomputer revolution than he would have if he'd been taking classes back at Harvard? No, probably not.And yes, while it is probably true that you'll learn some valuable things by going to work for an existing company for a couple years before starting your own, you'd learn a thing or two running your own company during that time too.The advice about going to work for someone else would get an even colder reception from the 19 year old <NAME>. So I'm supposed to finish college, then go work for another company for two years, and then I can start my own? I have to wait till I'm 23? That's four years. That's more than twenty percent of my life so far. Plus in four years it will be way too late to make money writing a Basic interpreter for the Altair.And he'd be right. The Apple II was launched just two years later. In fact, if Bill had finished college and gone to work for another company as we're suggesting, he might well have gone to work for Apple. And while that would probably have been better for all of us, it wouldn't have been better for him.So while I stand by our responsible advice to finish college and then go work for a while before starting a startup, I have to admit it's one of those things the old tell the young, but don't expect them to listen to. We say this sort of thing mainly so we can claim we warned you. So don't say I didn't warn you. Notes[1] The average B-17 pilot in World War II was in his early twenties. (Thanks to <NAME> for pointing this out.)[2] If a company tried to pay employees this way, they'd be called unfair. And yet when they buy some startups and not others, no one thinks of calling that unfair. [3] The 1/10 success rate for startups is a bit of an urban legend. It's suspiciously neat. My guess is the odds are slightly worse.Thanks to <NAME> for reading drafts of this, to the friends I promised anonymity to for their opinions about hiring, and to <NAME> and the Berkeley CSUA for organizing this talk.Russian TranslationRomanian TranslationJapanese Translation If you liked this, you may also like Hackers & Painters.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/string-13.typ
typst
Other
// Test the `match` method. #test("Is there a".match("for this?"), none) #test( "The time of my life.".match(regex("[mit]+e")), (start: 4, end: 8, text: "time", captures: ()), ) // Test the `matches` method. #test("Hello there".matches("\d"), ()) #test("Day by Day.".matches("Day"), ( (start: 0, end: 3, text: "Day", captures: ()), (start: 7, end: 10, text: "Day", captures: ()), )) // Compute the sum of all timestamps in the text. #let timesum(text) = { let time = 0 for match in text.matches(regex("(\d+):(\d+)")) { let caps = match.captures time += 60 * int(caps.at(0)) + int(caps.at(1)) } str(int(time / 60)) + ":" + str(calc.rem(time, 60)) } #test(timesum(""), "0:0") #test(timesum("2:70"), "3:10") #test(timesum("1:20, 2:10, 0:40"), "4:10")
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/blockchain/weeks/week2.typ
typst
#import "../../utils.typ": * #section("Ethereum") - Generalized Blokchain - turing complete programming language for smart contracts etc. - proof of work previously, soon proof of stake - block creation time 14-15s - during forks -> (updates) chain will be made read-only - read-only via making new blocks *extremely expensive* #subsection("GAS") This refers to the *fees* that you pay when using transactions or smart contracts.\ GAS is handled by time, which means you have to pay a certain amount of ETH to make a contract work.\ Should you not be able to pay enough GAS for the transaction or smart contract to complete, then your transaction is lost and no ETH will be refunded. #subsection("Bitcoin UTXO vs Ethereum Account") #align( center, [#image("../../Screenshots/2023_09_25_02_05_56.png", width: 70%)], ) - ETH works like a bank account -> enough balance, then it's fine - Bitcoin works with a flag in the bitcoin -> spent flag #section("Smart Contract") - *program must be deterministic*, each block must calculate the same result - random numbers via current time can't be used - special ways of using random numbers exist - blockchain specific language, or compatible must be used - either develop everything yourself (not recommended) - or use *standards* in order to provide interblockchain functionality as well - ERC (Ethereum Request for Comments)\ Standards for ethereum with which you can also create your own cryptocurrency via ethereum.\ Aka the root of all shitcoins\ *solidity* is made with this Example for a smart contract using *solidity* for ethereum ```sol pragma solidity ^0.8.21; contract Notary { mapping (address => mapping (bytes32 => uint256)) stamps; function store(bytes32 hash) public { stamps[msg.sender][hash] = block.timestamp; } function verify(address recipient, bytes32 hash) public view returns (uint) { return stamps[recipient][hash]; } } ``` #subsection("Non Fungible Token (NFT)") - defined in ERC21 - unique in the blockchain - guarantees that a digital asset is unique and not interchangeable - Can be any digital data that can be hashed -> only hash is stored on the chain - with NFT: proof of ownership (you can copy the data, but the ownership remains)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/emphasis_04.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Ends at paragraph break. // // Error: 1-2 unclosed delimiter // _Hello // // World
https://github.com/xrarch/books
https://raw.githubusercontent.com/xrarch/books/main/xrcomputerbook/chapether.typ
typst
#import "@preview/tablex:0.0.6": tablex, cellx, colspanx, rowspanx = Ethernet Controller == Introduction To Be Designed: A simple Ethernet controller
https://github.com/AHaliq/CategoryTheoryReport
https://raw.githubusercontent.com/AHaliq/CategoryTheoryReport/main/chapters/chapter3/notes.typ
typst
#import "../../preamble/lemmas.typ": * #import "../../preamble/catt.typ": * #import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge #definition(name: "Duality")[@sa[Proposition 3.1, 3.2] / Formal Duality: if $Sigma$ follows from the axioms of categories, then so does its dual $Sigma^*$ $ ("CT" => Sigma) => ("CT" => Sigma^*) $ specifically, if for a category $bold(C)$ that $Sigma$ holds, then in its dual $op(bold(C))$ the interpretation $Sigma^*$ holds. $ (bold(C) => Sigma) => (op(bold(C)) => Sigma^*) $ / Conceptual Duality: moreover if $Sigma$ holds for all categories $bold(C)$, then it also holds in all $op(bold(C))$. Thus $ forall bold(C). (bold(C) => Sigma) => (op(bold(C)) => Sigma) $ with both we can conclude that $ => (op((op(bold(C)))) => Sigma^*) => (bold(C) => Sigma^*) $ ]<defn-duality> #definition(name: "Coproducts")[@sa[Definition 3.3] $ "UMP"_"coproduct" (x_1,x_2,u,q_1,q_2) = forall x_1, x_2. exists! u. x_1 = u comp q_1 and x_2 = u comp q_2 $ #figure( diagram( cell-size: 10mm, $ & #node($X$, name: <X>) edge("dl", x_1, <-) edge("d", u, "<--") edge("dr", x_2, <-) \ #node($A$, name: <A>) & #node($P$, name: <P>) edge("l", q_1, <-) edge("r", q_2, <-) & #node($B$, name: <B>) $, ), ) notice the UMP is dual to products; flipped arrows and composition Examples of Coproducts: #figure( table( columns: 4, align: (right, left, left, left), [category], [equation], [description], [example of], $Set$, $A + B = A times 1 union B times 2$, [disjoint union of sets], [from definition], [*Monoids*], $M(A+B) iso M(A) + M(B)$, [monoid of $A+B$], [preserves coproducts], [*Top/Powerset*], $cal(P)(X + Y) iso cal(P)(X) times cal(P)(Y)$, [$2^(X+Y) iso 2^X times 2^Y$], [dual in underlying], [*Posets*], $p + q = p or q$, [least upper bound], [from definition], [*Proofs*], $phi + psi = phi or psi$, [disjunction], [from definition], [*Free Monoids*], $A + B iso M(|A| + |B|) slash ~$, [quotient unit & mul], [underlying quotient], [*Abelian Groups*], $A + B iso A times B$, [commutative], [self dual], ), ) ]<defn-coproducts> #grid( columns: (1fr, 1fr), align: (left + horizon, left + horizon), definition(name: "Equalizers")[@sa[Definition 3.13, 3.16] $"UMP"(f,g,z) = u$, notice $e$ is monic by uniqueness of $u$ #figure( diagram( cell-size: 10mm, $ E edge("r", e, >->) & A #edge("r", $f$, "->", shift: 3pt) #edge("r", $g$, "->", shift: -3pt, label-anchor: "north", label-sep: 0em) & B \ Z edge("u", u, "-->") edge("ur", z, ->) $, ), ) equalizers as subsets as two outgoing morphisms $f,g$ are equalized to one $e$ ], definition(name: "Coequalizers")[@sa[Definition 3.18, 3.19] $"UMP"(f,g,z)=u$, notice $q$ is epic by unqiueness of $u$ #figure( diagram( cell-size: 10mm, $ A #edge("r", $f$, "->", shift: 3pt) #edge("r", $g$, "->", shift: -3pt, label-anchor: "north", label-sep: 0em) & B edge("r", q, ->>) edge("dr", z, ->) & Q edge("d", u, "-->") \ & & Z $, ), ) coequalizers as quotients as two incoming morphisms $f,g$ are coequalized to one $q$ ], ) $ "UMP"_"equalizer" (e,f,g) = forall z. exists! u. f comp z = g comp z => e comp u = z \ "UMP"_"coequalizer" (q,f,g) = forall z. exists! u. z comp f = z comp g => u comp q = z $ #figure( table( columns: 3, align: (right, left, left), [UMP], [existence], [uniqueness], [equalizer], $forall f, g. exists e. f comp e = g comp e$, $forall z. exists! u. e comp u = z$, [coequalizer], $forall f, g. exists q. q comp f = q comp g$, $forall z. exists! u. u comp q = z$, ), )<defn-co-equalizer> #definition(name: "Presentation of Algebras")[@sa[Definition 3.24] - Given a finite set, let it be the *generators* of the *free algebra* - $F(3) = F(x,y,z)$ where $x,y,z$ are generators. - the relations it must hold are defined by coequalizers - $x y = z$ is quotiented by $q$ if $"UMP"(x y, z, q) = id_q$ - more generally the morphisms can be the relations themselves; $r_1 |-> x y = z, r_2 |-> y^2 = 1$ - this is called a *presentation* of the algebra; they are not unique ]
https://github.com/UntimelyCreation/typst-neat-cv
https://raw.githubusercontent.com/UntimelyCreation/typst-neat-cv/main/README.md
markdown
MIT License
# Neat CV **Neat CV** is a set of templates to produce modern, minimal and elegant CVs and cover letters using [Typst](https://github.com/typst/). This project is an adaptation of the very nice [Brilliant CV](https://github.com/mintyfrankie/brilliant-CV) project, with inspiration from the LaTeX template [Alta CV](https://fr.overleaf.com/latex/templates/altacv-template/trgqjpwnmtgv) or [its Typst equivalent](https://github.com/GeorgeHoneywood/alta-typst). Document examples can be found in the `output` directory. ## Features The set of available features is about the same as [Brilliant CV](https://github.com/mintyfrankie/brilliant-CV)'s. - **Style and content separation**: The documents' contents is defined in the `src/modules` directory, and can be changed independently of the styling. - **Multilingual support**: Define different versions of your documents in your `src/modules` directory, and configure the targeted language at compilation in `src/metadata.typ`. Some additional features included but not shown in the example documents are **company and organization logos**, as well as **choosing whether to display the title or the organization's name first in a CV entry**. ## Getting started ### Installation Everything needed to use the templates is contained in the `src` directory. You may clone this repository and modify the files directly, or you can copy the `src` directory into an existing Typst project. Any part of the templates can then be modified according to your needs and desires. ## Usage ### Compile documents Use the following `typst` commands to produce the documents from the templates. ```bash typst compile src/cv.typ path/to/cv.pdf --font-path src/fonts/ typst compile src/letter.typ path/to/letter.pdf --font-path src/fonts/ ``` ## License Distributed under the MIT License.
https://github.com/RaphGL/ElectronicsFromBasics
https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap6/4_kirchoffs_current_law.typ
typst
Other
#import "../../core/core.typ" === Kirchhoff\'s Current Law (KCL) Let\'s take a closer look at that last parallel example circuit: #image("static/00120.png") Solving for all values of voltage and current in this circuit: #image("static/10116.png") At this point, we know the value of each branch current and of the total current in the circuit. We know that the total current in a parallel circuit must equal the sum of the branch currents, but there\'s more going on in this circuit than just that. Taking a look at the currents at each wire junction point (node) in the circuit, we should be able to see something else: #image("static/00121.png") At each node on the negative \"rail\" (wire 8-7-6-5) we have current splitting off the main flow to each successive branch resistor. At each node on the positive \"rail\" (wire 1-2-3-4) we have current merging together to form the main flow from each successive branch resistor. This fact should be fairly obvious if you think of the water pipe circuit analogy with every branch node acting as a \"tee\" fitting, the water flow splitting or merging with the main piping as it travels from the output of the water pump toward the return reservoir or sump. If we were to take a closer look at one particular \"tee\" node, such as node 3, we see that the current entering the node is equal in magnitude to the current exiting the node: #image("static/00122.png") From the right and from the bottom, we have two currents entering the wire connection labeled as node 3. To the left, we have a single current exiting the node equal in magnitude to the sum of the two currents entering. To refer to the plumbing analogy: so long as there are no leaks in the piping, what flow enters the fitting must also exit the fitting. This holds true for any node (\"fitting\"), no matter how many flows are entering or exiting. Mathematically, we can express this general relationship as such: $ I_"exiting" = I_"entering" $ Mr. Kirchhoff decided to express it in a slightly different form (though mathematically equivalent), calling it #emph[Kirchhoff\'s Current Law] (KCL): $ I_"entering" + (-I_"exiting") = 0 $ Summarized in a phrase, Kirchhoff\'s Current Law reads as such: #quote[ *The algebraic sum of all currents entering and exiting a node must equal zero* ] That is, if we assign a mathematical sign (polarity) to each current, denoting whether they enter (+) or exit (-) a node, we can add them together to arrive at a total of zero, guaranteed. Taking our example node (number 3), we can determine the magnitude of the current exiting from the left by setting up a KCL equation with that current as the unknown value: $ I_2 + I_3 + I &= 0 \ 2 "mA" + 3 "mA" + I &= 0 \ $ $ &... "solving for " I ...& \ I &= -2 "mA" - 3 "mA" \ I &= -5 "mA" \ $ The negative (-) sign on the value of 5 milliamps tells us that the current is #emph[exiting] the node, as opposed to the 2 milliamp and 3 milliamp currents, which must were both positive (and therefore #emph[entering] the node). Whether negative or positive denotes current entering or exiting is entirely arbitrary, so long as they are opposite signs for opposite directions and we stay consistent in our notation, KCL will work. Together, Kirchhoff\'s Voltage and Current Laws are a formidable pair of tools useful in analyzing electric circuits. Their usefulness will become all the more apparent in a later chapter (\"Network Analysis\"), but suffice it to say that these Laws deserve to be memorized by the electronics student every bit as much as Ohm\'s Law. #core.review[ Kirchhoff\'s Current Law (KCL): #quote[The algebraic sum of all currents entering and exiting a node must equal zero] ]
https://github.com/MaxAtoms/T-705-ASDS
https://raw.githubusercontent.com/MaxAtoms/T-705-ASDS/main/content/week8.typ
typst
#import "../template.typ": example, exercise #import "../boxes.typ": definition #import "../tags.typ": week, barron = Statistics == Inferences about variances #week("8") #barron("9.5") Confidence Intervals & Hypothesis Tests for - population variance: $sigma^2=text("Var")(X)$ - comparison of two variances $sigma_X^2$ and $sigma_Y^2$ == Variance estimator and $chi^2$-Distribution We estimate a population variance $sigma^2$ from a sample $X=(X_1,dots,X_n)$ with $ s^2 = 1/(n-1) sum_n^(i=1) (X_i - X)^2 $ The sample variance $s^2$ is unbiased and consistent. Note that the differences $X_i - accent(X,macron)$ are not independent! When $X_1,dots,X_n$ are independent and Normaly distributed, with $text("Var")(X_i)=sigma^2$ $ ((n-1)s^2) / sigma^2 ~ chi_((n-1))^2 $ is Chi-squared distribution with $(n-1)$ degrees of freedom. $chi^2$ is a continous distribution with density $ f(x) = 1 / (2^(nu \/ 2) Gamma (nu \/ 2)) x^(nu\/2-1) e^(-x\/2) $ with expected value $E(X)=nu$ and variance $text("Var")(X)=2 nu$ == Confidence Interval for $sigma^2$ Let us construct a $(1-alpha) 100%$ Confidence Interval for $sigma^2$. Assume sample size $n$. We start with the estimator $s^2$. We need to find critical values from $chi_(n-1)^2$-dist such that $1-alpha$ is "in the middle". So $ 1-alpha &= P(chi_(1-alpha/2)^2 < ((n-1)s^2) / sigma^2 < chi_(alpha/2)^2) \ &= P(((n-1)s^2) / (chi^2_(alpha/2)) < sigma^2 < ((n-1)s^2) / chi^2_(1-alpha/2)) $ Therefore a $(1-alpha) 100%$ CI for $sigma^2$ is $ [ ((n-1)s^2) / chi^2_(alpha/2); ((n-1)s^2) / chi^2_(1-alpha/2) ] $ And a CI for $sigma$ is $ [ sqrt(((n-1)s^2) / chi^2_(alpha/2)); sqrt(((n-1)s^2) / chi^2_(1-alpha/2)) ] $ == Testing variances It is useful to test properties of variances: - uncertainty, risk, stability - we want to be sure that they are not too big === Level $alpha$ test for $sigma^2$ To test the null hypothesis $H_0: sigma^2 = sigma^2_o$ we use the test statistic $chi_text("obs")^2 = ((n-1)s^2) / (sigma_o^2) ~ chi^2$ with $n-1$ degrees of freedom. Where the alternative hypothesis can be: 1) Right sided $H_A: sigma^2 > sigma^2_o$, reject $H_0$ if $chi_text("obs")^2 > chi_alpha^2$ 2) Left sided $H_A: sigma^2 < sigma^2_o$, reject $H_0$ if $chi_text("obs")^2 < chi_(1-alpha)^2$ 3) Two-sided $H_A: sigma^2 eq.not sigma^2_o$, reject $H_0$ if $chi_text("obs")^2 gt.eq chi_(alpha\/2)^2$ or $chi_text("obs")^2 lt.eq chi_(1-alpha\/2)^2$ === Using p-Values instead 1) Right sided $p = P(chi^2 gt chi^2_text("obs")) = 1 - P(chi^2 lt.eq chi^2_text("obs")) = 1 - F(chi^2_text("obs"))$ where $F$ is the cdf of $chi^2$\~dist 2) Left sided $p = P(chi^2 lt.eq chi^2_text("obs")) = F(chi^2_text("obs"))$ 3) Two-sided p-Value corresponds to the highest significance level $alpha$ that yields an acceptance of $H_0$. In this two-sided case we must consider both the upper #underline("and") lower bound. upper: $p = alpha = 2 dot.op alpha/2 = 2P(chi^2 gt.eq X_text("obs")^2) = 2(1-F(chi_text("obs")^2))$ lower: $p = alpha = 2 dot.op alpha/2 = 2P(chi^2 lt X_text("obs")^2) = 2 dot.op F(chi_text("obs")^2)$ $=> p = 2 dot.op text("min")(1-F(chi_text("obs")^2);F(chi^2_text("obs")))$ == Comparing two variances Assume we have two independent samples: $ accent(X, arrow) = (X_1,dots,X_n)\ accent(Y, arrow) = (Y_1,dots,Y_n) $ We want to compare $sigma_X^2$ with $sigma_Y^2$. Because $sigma^2$ is a scale parameter (not location like $mu$) we look at the ratio between $sigma_X^2$ and $sigma_Y^2$. That is the param $Theta = sigma_X^2 / sigma_Y^2$ (\*). Often we are interested to know whether $sigma_X^2 = sigma_Y^2$. In which case $Theta = sigma_X^2 / sigma_Y^2 = 1$. To estimate the ratio in (\*) we use the entities we know already: $ accent(Theta, hat) = S_X^2 / S_Y^2 ~ F(n-1, m-1) $ For independent $(X_1,dots,X_n)$ from $X_i~N(mu_x, sigma_x)$ and $(Y_1,dots,Y_n)$ from $Y_i~N(mu_y, sigma_y)$ the standard ratio of the variances is: $ F= (s_X^2 \/ sigma_X^2) / (s_Y^2 \/ sigma_Y^2) ~ F(n-1, m-1) $ What we know about the $F$-dist: i) We know that $s_X^2 / sigma_X^2~chi^2 (n-1)$ and $s_Y^2 / sigma_Y^2~chi^2 (m-1)$ so the $F$-dist is a ratio of two $chi^2$-dist. ii) $F$ is non-negative and continous iii) $sigma_X^2 / sigma_Y^2 = 1/(sigma_Y^2 \/ sigma_X^2)$ so if $F ~ F(n-1, m-1)$ then $1/F~F(m-1, n-1)$ // TODO: Graphics // TODO CI for the ratio of population variances
https://github.com/fenjalien/mdbook-typst-doc
https://raw.githubusercontent.com/fenjalien/mdbook-typst-doc/main/example/src/f/a.md
markdown
Apache License 2.0
# next ```typ,example This is a nested example ``` ![](/a/mdbook-typst-doc/525af.svg)
https://github.com/mrknorman/evolving_attention_thesis
https://raw.githubusercontent.com/mrknorman/evolving_attention_thesis/main/main.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: "Evolving Attention", subtitle: "Exploring the Use of Genetic Algorithms and Attention for Gravitational Wave Data Science", authors: ( "<NAME>", ), logo: "cardiff_logo.png" ) // We generated the example code below so you can see how // your document will look. Go ahead and replace it with // your own content! #include "01_intro/01_introduction.typ" #pagebreak() #include "02_gravitation/02_gravitational_waves.typ" #pagebreak() #include "03_machine_learning/03_machine_learning.typ" #pagebreak() #include "04_application/04_application.typ" #pagebreak() #include "05_parameters/05_the_problem_with_parameters.typ" #pagebreak() #include "06_skywarp/06_skywarp.typ" #pagebreak() #include "07_crosswave/07_crosswave.typ" #pagebreak() #include "09_conclusion/09_conclusion.typ" #pagebreak()
https://github.com/Seasawher/typst-cv-template
https://raw.githubusercontent.com/Seasawher/typst-cv-template/main/README.md
markdown
# README これは,[Typst](https://github.com/typst/typst) による履歴書・職務経歴書のテンプレートです. プレヴューを確認するには,[resume.pdf](./resume.pdf) をご覧ください.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/list-06.typ
typst
Other
// This doesn't work because of mixed tabs and spaces. - A with 2 spaces - B with 2 tabs
https://github.com/altaris/typst-symbols-a4
https://raw.githubusercontent.com/altaris/typst-symbols-a4/master/README.md
markdown
MIT License
# typst-symbols-a4 [![Typst](https://img.shields.io/badge/typst-blue)](https://typst.app/docs/) [![License](https://img.shields.io/badge/license-MIT-green)](https://choosealicense.com/licenses/mit/) This repository contains a table [typst symbols](https://typst.app/docs/reference/symbols/sym/) (mostly mathematical) and their LaTeX equivalents. Contributions warmly welcome.
https://github.com/AliothCancer/AppuntiUniversity
https://raw.githubusercontent.com/AliothCancer/AppuntiUniversity/main/capitoli_fisica/esercizi/esercitazione4.typ
typst
#import "../../custom_functions.typ": c // diminutivo di energy mass #let em() = $"kJ"/"kg"$ #set math.equation(numbering: "1.1") = Esercitazione 4: Miscele bifasiche == Problema n.4 #image("immagini/E4P4_obscured.png", width: 115%) === D01) Potenza meccanica prima trasf. Formula: $ w_t = integral_(p_1)^(p_2) v space dif p \ \ $<eq1> oppure $ w = h_2 - h_1 $<eq2> - Si nota che $v_1 = v_("ls")$ quindi x=0: - Siccome è liquido e viene compresso, il volume massico non varia(variazione trascurabile) $=> v_1 = v_2$. - La potenza meccanica si calcola con il lavoro tecnico perchè un fluido incomprimibile non può subire lavoro volumico. Compressione da liquido saturo $=>$ liquido sottoraffreddato, si sceglie quindi la @eq1, poichè non abbiamo tabelle per liquidi sottoraffreddati. $ w_t = v_1 dot (p_2 - p_1)\ \ = 0.0010434 m^3/"kg" dot (10 - 1)"bar" dot 100"kPa"/("bar") dot 1000 J/"kJ" \ \ = #c({0.0010434 * (10-1)*100 * 1000}) "J"/"kg" \ \ #v(1cm) dot(W) = w dot dot(m) = 939.06 "J"/"kg" dot 1 "kg"/s = 939.06 W $ Risultato: 936.1 W (errore accettabile?) #set math.equation(numbering: none) === D02) Potenza termica scambiata 2° trasf. *trasformazione*\ 2 → 3: riscaldamento isobaro fino a T3 = 300°C; #table( columns: 3, "","2", "3", "p","1000 kPa","1000 kPa", "T","99.632C°","300 C°" ) - $T_"sat"$ = 179.88 C° $ q = h_"3 surr." - h_2 = h_"3 surr." - (h_1 + w_"t 1→2") $ $ dot(Q) = q dot dot(m) = (3052.1 - (417.51 + 0.93906))dot 1 = #c({3052.1 - (417.51 + 0.93906)}) space k W $ === D03) Determinare la potenza prodotta durante la prima espansione. #grid(columns: 2, rows: 3, circle(stroke: black)[ #set align(center + horizon) 3 ], box(grid(columns: 2,h(1em), [ p = 1000 kPa \ T = 300 C° \ Vapore surriscaldato ])), box(v(.5cm)), box(), circle(stroke: black)[ #set align(center + horizon) 4 ], box(grid(columns: 2,h(1em), [ p = 500 kPa \ T($s_3$ = 7.1251) = 200C°(7.0592) < T < 250C°(7.2721)\ Vapore surriscaldato ])), ) Espansione isoentropica fino a p4 = 5bar = 500 kPa - Di un vapore surriscaldato fino $ "Isoentropica" => q = 0 => d q = 0\ d u = d q - p dot d v \ d u = - p dot d v $ $ d h = d u + p dot d v + v dot d p\ d h = -cancel(p dot d v) + cancel(p dot d v) + v dot d p \ d h = v dot d p = w_t $ Il motivo per cui si usa $Delta h$ è che questo è pari al lavoro tecnico, ed esso è il lavoro prodotto dalla turbina. Nella turbina viene le due sezioni differiscono per pressione,
https://github.com/Wh4rp/Presentacion-Typst
https://raw.githubusercontent.com/Wh4rp/Presentacion-Typst/master/ejemplos/3_text.typ
typst
#text(blue)[Typst] es un lenguaje de #text(style:"italic")[tipografía] de código abierto para escribir documentos de #text(font:"Ubuntu Mono")[alta calidad tipográfica].
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/CLD/docs/TE/TE2.typ
typst
#import "/_settings/typst/template-note.typ": conf #show: doc => conf( title: [ Résumé CLD - TE2 ], lesson: "CLD", chapter: "PaaS, Storage as a Service, NoSQL, Container cluster management, IaaS and labs", definition: "", col: 1, doc, ) = PaaS Platform-as-a-Service (PaaS) permet aux développeurs de déployer des applications scalables dans le cloud, en se concentrant sur le code de l'application et en déléguant le reste au fournisseur de services cloud. #image("/_src/img/docs/image copy 94.png") Dans un PaaS nous avons donc la main uniquement sur l'application et les données, le reste est géré par le fournisseur de service cloud. Le PaaS existe aussi pour l'*IoT* ainsi que l'*IA*. Le cloud provider gère donc tout ce qui concerne : - provisionnement automatique des machines virtuelles (VM) - maintenance du système d'exploitation - installation et maintenance du serveur d'applications web - installation de l'application et déploiement des mises à jour de l'application - provisionnement des load-balancers, vérification de l'état des VM - mise à l'échelle automatique avec ajustement adaptatif - bases de données et data stores gérés == Risque de verrouillage des fournisseurs Dans de nombreux cas les solutions de PaaS sont propriétaires (architectures et API) et ne sont pas compatibles entre elles. Il est donc difficile de migrer d'un fournisseur à un autre. Il est donc important de bien choisir son fournisseur de PaaS ou d'opter pour une solution open-source. == Google App Engine Google App Engine est un PaaS qui permet de déployer des applications web et mobiles. Il est possible de déployer des applications web et mobiles sans se soucier de la gestion des serveurs. #image("/_src/img/docs/image copy 99.png") === Architecture - *Multi-tenant* : La plateforme de Google déploie automatiquement le code de votre application et ajuste l'échelle pour s'adapter à la charge. - Pas de contrôle des serveurs, équilibreurs de charge ou groupes de mise à l'échelle automatique. - La plateforme contrôle et partage les ressources entre tous les locataires. - *Frontend* : Reçoit les requêtes HTTP, identifie le locataire et l'application, et route la requête. - Effectue des vérifications de l'état des instances d'application et assure l'équilibrage de la charge. - *Serveurs d'application* : Exécutent le code de l'application dans des instances contenaires ou machines virtuelles. - Fournit le système d'exploitation et l'environnement d'exécution (Java, Python, etc.). - *App master* : Gère les instances d'application, déploie le code, remplace les instances défaillantes et ajuste automatiquement le nombre d'instances. #columns(2)[ === Request handler - Request Handler : Code responsable de créer une réponse HTTP à une requête HTTP. - Exemple : Java servlet. - Cycle de vie dans App Engine : 1. Une requête arrive. 2. Le Request Handler est créé et reçoit la requête. 3. Le Request Handler crée la réponse, en utilisant éventuellement d'autres services cloud et stockage cloud. 4. Une fois la réponse envoyée, App Engine peut supprimer le Request Handler de la mémoire. - Le Request Handler doit être sans état pour que ce cycle de vie fonctionne (sauf en cas de mise à l'échelle manuelle). #image("/_src/img/docs/image copy 100.png") ] - Lorsque le nombre de requêtes augmente, App Engine alloue des Request Handlers supplémentaires. - Tous les Request Handlers traitent les requêtes en parallèle (mise à l'échelle automatique). === App instance - App Instance : Conteneur ou machine virtuelle qui exécute le code de l'application. #image("/_src/img/docs/image copy 101.png") - Le cycle de vie du Request Handler peut être satisfaisant, mais il n'est pas pratique d'instancier et de détruire un programme pour chaque requête. - L'initialisation d'un programme est coûteuse en temps, surtout pour la mémoire locale. - Les instances sont des conteneurs dans lesquels vivent les Request Handlers. - Une instance conserve la mémoire locale initialisée pour les requêtes suivantes. - Une application a un certain nombre d'instances allouées pour traiter les requêtes. - Le front-end distribue les requêtes parmi les instances disponibles. - Si nécessaire, App Engine alloue de nouvelles instances. - Si une instance n'est pas utilisée pendant un certain temps, App Engine la libère. On peut voir les app instances dans le tableau de bord de Google Cloud Platform. *Prix*: vous êtes facturé en fonction du temps d'allocation d'une instance (parmi d'autres frais). === Type de scaling Lors du téléchargement d'une application, vous spécifiez le type de mise à l'échelle dans un fichier de configuration. Le type de mise à l'échelle contrôle comment la plateforme crée les instances. - *Mise à l'échelle manuelle* : Vous spécifiez manuellement le nombre d'instances à instancier. Les instances fonctionnent en continu, permettant à l'application d'effectuer une initialisation complexe et de s'appuyer sur l'état de sa mémoire au fil du temps (elles peuvent *stateful*). - *Mise à l'échelle basique* : La plateforme commence avec zéro instance et crée une instance lorsqu'une requête est reçue. L'instance est arrêtée lorsque l'application devient inactive. L'application doit être *stateless*. Le développeur contrôle directement deux paramètres : le *nombre maximum d'instances* et le *délai d'inactivité* pour supprimer les instances. - *Mise à l'échelle automatique* : La plateforme décide quand créer et supprimer des instances en utilisant des algorithmes prédictifs basés sur le taux de requêtes, les latences de réponse, et d'autres métriques de l'application. Le développeur n'a qu'un contrôle indirect en ajustant certains paramètres. L'application doit être stateless. Ce type de mise à l'échelle est celui par défaut. = Storage as a Service Le stockage en tant que service (STaaS) est un modèle de stockage de données dans le cloud, où les données sont stockées sur des serveurs distants accessibles via Internet. Les services de stockage en tant que service peuvent être utilisés pour stocker des données structurées, non structurées ou semi-structurées. Il existe 3 catégories bien distinctes de STaaS : - *Block storage* : Stockage de blocs, utilisé pour stocker des données brutes, généralement utilisé pour les bases de données. - *Object storage* : Stockage d'objets, utilisé pour stocker des objets (fichiers, images, vidéos, etc.), généralement utilisé pour les applications web. - *Database as a Service* : Stockage de données structurées, utilisé pour stocker des données structurées, généralement utilisé pour les applications web. == Base de données relationnelle - *Stockage de données persistantes* : - Permet de stocker de grandes quantités de données sur le disque, tout en permettant aux applications d'accéder aux données nécessaires via des requêtes. - *Intégration d'applications* : - De nombreuses applications au sein d'une entreprise ont besoin de partager des informations. - En utilisant la base de données commune, on assure que toutes ces applications disposent de données cohérentes et à jour. - *Principalement standardisé* : - Le modèle relationnel est largement utilisé et compris. - L'interaction avec la base de données se fait avec SQL, un langage (principalement) standard. - Ce degré de standardisation permet de maintenir une familiarité pour éviter d'apprendre de nouvelles choses. - *Contrôle de la concurrence* : - De nombreux utilisateurs accèdent aux mêmes informations en même temps. - Gérer cette concurrence est difficile à programmer, donc les bases de données fournissent des transactions pour garantir une interaction cohérente. - *Reporting* : - Le modèle de données simple et la standardisation de SQL en font une base pour de nombreux outils de reporting. === Problèmes des bases de données relationnelles - Impedance mismatch : La différence entre les structures de données en mémoire (objets) du programme et le modèle relationnel de la base de données. - Modèle relationnel : Ensemble de tuples avec des valeurs simples. - Structure de données du programme : Hiérarchie d'objets. - Source de frustration pour les développeurs. === Problèmes de scalabilité - Les bases de données relationnelles sont conçues pour fonctionner sur une seule machine, donc pour les mettre à l'échelle, vous devez acheter une machine plus puissante. - Cependant, il est moins cher et plus efficace de mettre à l'échelle horizontalement en achetant de nombreuses machines. - Les machines dans ces grands clusters sont individuellement peu fiables, mais le cluster dans son ensemble continue de fonctionner même lorsque des machines tombent en panne, donc le cluster global est fiable. - *Les bases de données relationnelles ne fonctionnent pas bien sur des clusters.* #colbreak() === Pourquoi les bases relationnelles continuent d'être utilisées - *Le modèle relationnel reste pertinent* : le modèle tabulaire convient à de nombreux types de données, notamment lorsque vous devez analyser les données et les réassembler de différentes manières pour différents usages. - *Transactions ACID* : Pour fonctionner efficacement sur un cluster, la plupart des bases de données NoSQL ont une capacité transactionnelle limitée. Souvent, cela suffit... mais pas toujours. - *Outils* : La longue domination de SQL signifie que de nombreux outils ont été développés pour fonctionner avec les bases de données SQL. Les outils pour les systèmes de stockage de données alternatifs sont beaucoup plus limités. - *Familiarité* : Les systèmes NoSQL sont encore récents, donc les gens ne sont pas familiers avec leur utilisation. Par conséquent, nous ne devrions pas les utiliser dans des projets utilitaires où leurs avantages auraient moins d'impact. == Object-oriented databases - Invention au milieu des années 1990, les bases de données orientées objet promettaient de résoudre le problème du déséquilibre d'impédance. - Contrairement aux attentes, elles n'ont pas connu beaucoup de succès. - Les bases de données SQL sont restées dominantes. - La principale raison : elles sont utilisées comme bases de données d'intégration entre différentes applications. = NoSQL NoSQL signifie "Not Only SQL". Il s'agit d'une catégorie de bases de données qui ne suivent pas le modèle de base de données relationnelle traditionnel. Les bases de données NoSQL sont conçues pour les applications web modernes, qui nécessitent une scalabilité horizontale, une faible latence et une disponibilité élevée. == Caractéristiques - Ils n'utilisent pas le modèle de données relationnel, et par conséquent, n'utilisent pas le langage SQL. - Ils sont généralement conçus pour fonctionner sur un cluster. - Ils n'ont pas de schéma fixe, ce qui vous permet de stocker n'importe quelle donnée dans n'importe quel enregistrement. - Ils ont tendance à être open source (lorsqu'ils sont proposés en tant que logiciel). == Modèle clé-valeur #columns(2)[ - La base de données permet de stocker des objets arbitraires (un nom, une image, un document, ...) et de les récupérer avec une clé. - C'est le principe d'une table de hachage, mais stockée de manière persistante sur un disque. #colbreak() #image("/_src/img/docs/image copy 103.png") ] == Modèle de colonnes #columns(2)[ - *Clé de ligne* : - Clé unique pour chaque ligne. - Une ligne contient plusieurs familles de colonnes. - Accessible via la clé. - *Famille de colonnes* : - Une combinaison de colonnes qui vont ensemble. - A un nom. - Contient plusieurs paires de clés de colonne / valeurs de colonne. - *Clé de colonne / Valeur de colonne* : - Paire clé/valeur contenant les données. #colbreak() #image("/_src/img/docs/image copy 102.png") ] #colbreak() == Modèle de documents Ce modèle de base de données permet de stocker des documents, la ou chaque document peut avoir sa propre structure. La structure est souvent représentée en JSON. Cela permet au développeur de faire des requêtes directement sur la structure de données. ```json {"id":1001, "customer_id":7231, "line8items":[ {"product_id":4555,"quantity":8}, {"product_id":7655,"quantity":4}, ], "discount8code":Y } {"id":"1002, "customer_id":9831, "line8items":[ {"product_id":4555,"quantity":3}, {"product_id":2155,"quantity":4}, {"product_id":6384,"quantity":1}, ], } ``` == Modèle de graphe #columns(2)[ - *Structure d'un graphe avec des sommets et des arêtes* : - Peut être orienté ou non. - Bien adapté pour suivre les relations entre les objets. - Les bases de données relationnelles ne fonctionnent pas bien dans ce cas. Il faut faire des jointures qui peuvent devenir très complexes. - Le terme "relationnel" vient de la théorie des ensembles. - *Langage de requête adapté à la structure du graphe*. #colbreak() #image("/_src/img/docs/image copy 104.png") ] #colbreak() == Comment utiliser NoSQL Prenons l'exemple d'une plateforme de E-Commerce, traditionnellement nous aurions opté pour une base de donnée relationnelle. L'avantage du NoSQL est qu'il peut s'adapter au différents types de données que nous avons à stocker. #image("/_src/img/docs/image copy 105.png") === Utilisation recommandée D'accord, voici la correction : - *Modèle de données clé-valeur* - Stockage des données de session web - Profils et préférences utilisateur - Données du panier d'achat - *Modèle de données document* - Journalisation des événements - Gestion de contenu d'entreprise, plateformes de blogs - Collecte de données pour l'analyse web - *Modèle de données en famille de colonnes* - Gestion de contenu d'entreprise, plateformes de blogs - Compteurs - *Modèle de données graphique* - Réseaux sociaux - Applications de livraison et de routage basées sur la géolocalisation - Moteurs de recommandation = Base de données distribuée Dimensions selon lesquelles une base de données peut avoir besoin de s'étendre : - *Capacité de stockage* - Nombre d'objets stockés - Moteur de recherche : métadonnées de 2 milliards de pages du World Wide Web - Réseaux sociaux : profils d'utilisateurs de 1 milliard d'utilisateurs - Suivi des comportements - Internet des objets - *Capacité de débit des requêtes de lecture* - Nombre de requêtes de lecture par seconde - Commerce électronique - Jeux en ligne : jusqu'à 100 000 lectures par seconde - *Capacité de débit des requêtes d'écriture* - Nombre de requêtes d'écriture par seconde - Jeux en ligne : jusqu'à 100 000 écritures par seconde - Internet des objets : jusqu'à 1 million d'écritures par seconde == Sharding vs Replication #columns(2)[ - *Sharding* : Partitionnement des données sur plusieurs machines. #image("/_src/img/docs/image copy 106.png") #colbreak() - *Replication* : Duplication des données sur plusieurs machines. #image("/_src/img/docs/image copy 107.png") ] #colbreak() === Repliacation Lors ce que les données sont repliquées il existe deux modèles de réplication : #columns(2)[ - *Master-slave* : Un serveur est le maître et les autres sont des esclaves. Les esclaves sont synchronisés avec le maître. #image("/_src/img/docs/image copy 108.png") #colbreak() - *Peer-to-peer* : Chaque serveur est un pair et les données sont synchronisées entre les pairs. #image("/_src/img/docs/image copy 109.png") ] === Sharding #columns(3)[ Au lieu de traiter la base de données comme un conteneur monolithique, elle est divisée en fragments (shards). #colbreak() Supposons que les données soient organisées sous forme de paires clé-valeur, par exemple des photos d'utilisateur (valeur) identifiées par leur nom (clé). #colbreak() La question est de savoir comment subdiviser l'espace clé entre les machines pour répartir uniformément la charge. ] #image("/_src/img/docs/image copy 110.png") Les *load balancers* sont utilisés pour rediriger les requêtes vers les bons serveurs. Ils doivent prendre une décision très rapidement, donc ils utilisent souvent des tables de hachage. #colbreak() ==== Tables de hachage - Une table de hachage distribue des objets dans une table à l'aide d'une fonction de hachage qui est calculée à partir de la clé. - Une bonne fonction de hachage distribue les objets de manière plus ou moins uniforme pour minimiser les collisions. - *Seul problème* : Lorsqu'une machine est ajoutée, les positions de presque tous les objets changent. Cela entraînerait un trafic réseau inacceptable pour migrer les objets ! ==== Consistant hashing - Le hachage cohérent évite de déplacer les objets lors de l'ajout ou de la suppression de machines. - Les clés sont mappées par la même fonction de hachage, puis les valeurs de hachage sont mappées sur un cercle. - Les machines sont également mappées dans le cercle en utilisant leur nom comme clé. - Une convention est établie : chaque objet est attribué à la machine suivante dans le cercle dans le sens horaire. #columns(3)[ Situation initiale. #colbreak() Ajouter une machine n'affecte que les objets se trouvant entre la nouvelle machine et la précédente. #colbreak() Retirer une machine n'affecte que les objets se trouvant entre la machine retirée. ] #image("/_src/img/docs/image copy 111.png") ==== Ecritures concurrentes Dans un système distribué, les écritures concurrentes peuvent poser problème. Par exemple, si deux utilisateurs modifient le même objet en même temps, comment résoudre le conflit ? #colbreak() ===== Transactions lecture-écriture La première solution consiste à envelopper la lecture et l'écriture de chaque utilisateur dans une transaction. La base de données détectera le conflit, exécutera avec succès l'une des deux transactions et annulera l'autre. Cependant, un problème majeur est que le* maintien d'une transaction* sur une aussi longue période peut entraîner une *dégradation des performances*. #image("/_src/img/docs/image copy 112.png") #colbreak() ===== Transactions écriture La deuxième solution consiste à envelopper uniquement l'écriture dans une transaction. Cela garantira que l'écriture est exécutée complètement ou pas du tout (pas d'écriture à moitié). Cependant, ni la *base de données* ni l'*application* ne seront conscients d'un *conflit entre les utilisateurs*. De plus l'ajout d'une *version* sur le champ de données permet de vérifier si la donnée a été modifiée. Avant de modifier la donnée, on vérifie si la version est la même que celle que l'on a en mémoire. Nous pouvons donc détecter s'il y a eu un problème de concurrence. #image("/_src/img/docs/image copy 113.png") ==== Consistance avec de la réplication #columns(2)[ - *Le théorème CAP* aborde les compromis dans les bases de données distribuées. Il stipule que parmi les objectifs de Cohérence (Consistency - C), Disponibilité (Availability - A) et Tolérance aux partitions réseau (Partitions - P), seuls deux peuvent être atteints simultanément. - Conjecturé par <NAME> en 2000, preuve formelle par <NAME> et <NAME> en 2002. #colbreak() #image("/_src/img/docs/image copy 114.png") ] ===== Tolerance à la réplication - *Problèmes de réseau* : peuvent mener à des partitions dites partitions réseau. - Avec deux ruptures dans les lignes de communication, le cluster de la base de données se partitionne en deux groupes. - Un système est tolérant aux partitions s'il continue de fonctionner en présence d'une partition. ==== Consistance forte avec commit à deux phases #columns(2)[ #image("/_src/img/docs/image copy 115.png") #colbreak() #image("/_src/img/docs/image copy 116.png") ] ==== Disponibilité sans consistance forte #columns(2)[ #image("/_src/img/docs/image copy 117.png") #colbreak() #linebreak() #image("/_src/img/docs/image copy 118.png") ] = Conteneurs logiciels == Conteneurs vs Machines virtuelles - Les conteneurs offrent une alternative légère aux machines virtuelles en partageant le noyau du système d'exploitation hôte tout en maintenant des espaces utilisateurs isolés. - Les conteneurs sont plus efficaces en termes d'utilisation des ressources comparés aux machines virtuelles traditionnelles. #image("/_src/img/docs/image copy 84.png") == Création et téléchargement d'images de conteneurs - Le processus implique la création d'une image de conteneur, généralement avec Docker, et son téléchargement dans un registre de conteneurs. - Les registres populaires incluent Docker Hub, GitHub Container Registry, Amazon Elastic Container Registry, Azure Container Registry et Google Artifact Registry. = Gestion des clusters de conteneurs == Introduction - La gestion des clusters de conteneurs est essentielle pour déployer des applications sur plusieurs hôtes afin d'assurer la robustesse et la continuité du service. - Les besoins clés incluent la surveillance de la santé des conteneurs, le placement optimal des conteneurs et la gestion efficace des pannes. == Orchestration des conteneurs - L'orchestration détermine le placement des conteneurs d'application sur les nœuds du cluster en fonction des besoins en ressources et des contraintes comme l'affinité et l'anti-affinité. - Les objectifs sont d'augmenter l'utilisation du cluster tout en répondant aux exigences des applications. == YAML (Yet Another Markup Language) - L'opérateur peut créer des objets K8s avec la ligne de commande ou décrire les objets dans des fichiers manifestes. - `kubectl` create -f file.yaml - Le format de fichier est JSON, qui peut également être écrit en YAML === Structure - Seulement deux structures de données de base : tableaux et dictionnaires, qui peuvent être imbriqués - YAML est un sur-ensemble de JSON - Plus facile à lire et écrire pour les humains que JSON - L'indentation est significative - Spécification à http://yaml.org/ === Exemple de YAML ```yaml apiVersion: v1 kind: Pod metadata: name: redis labels: component: redis app: todo spec: containers: - name: redis image: redis ports: - containerPort: 6379 resources: limits: cpu: 100m args: - redis-server - --requirepass ccp2 - --appendonly yes ``` = Kubernetes == Introduction - Kubernetes est une plateforme open-source pour automatiser le déploiement, la mise à l'échelle et la gestion des applications conteneurisées. - Développé à l'origine par Google, il est maintenant maintenu par la Cloud Native Computing Foundation (*CNCF*). #colbreak() == Anatomie d'un cluster #image("/_src/img/docs/image copy 85.png") === Composants du nœud maître - *etcd* : Un magasin clé/valeur pour les données de configuration du cluster. - *API Server* : Sert l'API de Kubernetes. - *Scheduler* : Décide des nœuds sur lesquels les pods doivent fonctionner. - *Controller Manager* : Exécute les contrôleurs principaux comme le Replication Controller. === Composants du nœud de travail - *Kubelet* : Gère l'état des conteneurs sur un nœud. - *Kube-proxy* : Gère le routage réseau et l'équilibrage de charge. - *cAdvisor* : Surveille l'utilisation des ressources et la performance. - *Réseau superposé* : Connecte les conteneurs entre les nœuds. == Concepts principaux - *Cluster* : Un ensemble de machines (nœuds) où les pods sont déployés et gérés. - *Pod* : La plus petite unité déployable, composée d'un ou plusieurs conteneurs. - *Controller* : Gère l'état du cluster. - *Service* : Définit un ensemble de pods et facilite la découverte de services et l'équilibrage de charge. - *Label* : Paires clé-valeur attachées aux objets pour la gestion et la sélection. == Concepts communs - Les objets Kubernetes peuvent être créés et gérés en utilisant des fichiers YAML ou JSON. - YAML est un format lisible par l'homme utilisé pour décrire les objets Kubernetes dans les fichiers de configuration. == Déployer une application : IaaS vs Kubernetes - L'IaaS traditionnel implique des étapes manuelles comme le lancement de VMs, leur configuration et la mise en place d'équilibreurs de charge. - Kubernetes simplifie ce processus avec des images de conteneur et des manifestes, permettant un déploiement et une mise à l'échelle automatisés. == Exemple de YAML Kubernetes #columns(2)[ - Chaque description d'objet Kubernetes commence par deux champs : - *kind* : une chaîne qui identifie le schéma que cet objet doit avoir - *apiVersion* : une chaîne qui identifie la version du schéma que l'objet doit avoir - Chaque objet a deux structures de base : Métadonnées de l'objet et Spécification (ou Spec). - La structure des Métadonnées de l'objet est la même pour tous les objets dans le système - *name* : identifie de manière unique cet objet dans l'espace de noms actuel - *labels* : une carte de clés et de valeurs de chaîne qui peut être utilisée pour organiser et catégoriser les objets - *Spec* est utilisé pour décrire l'état désiré de l'objet #colbreak() ```yaml apiVersion: v1 kind: Pod metadata: name: redis labels: component: redis app: todo spec: containers: - name: redis image: redis ports: - containerPort: 6379 resources: limits: cpu: 100m args: - redis-server - --requirepass ccp2 - --appendonly yes ``` ] == Pods *Le pod est l'unité atomique de déploiement dans Kubernetes.* - L'unité atomique de déploiement dans Kubernetes est le Pod. - Un Pod contient un ou plusieurs conteneurs, le cas le plus courant étant un seul conteneur. *Si un Pod a plusieurs conteneurs :* - Kubernetes garantit qu'ils sont programmés sur le même nœud du cluster. - Les conteneurs partagent le même environnement du Pod : - Espace de noms IPC, mémoire partagée, volumes de stockage, pile réseau, etc. - Adresse IP. - Si les conteneurs doivent communiquer entre eux au sein du Pod, ils peuvent simplement utiliser l'interface *localhost*. === Loosely vs Tightly Coupled Containers #columns(2)[ *Loosely Coupled Containers* *Définition* : - Les conteneurs faiblement couplés fonctionnent de manière indépendante, avec peu ou pas de dépendances directes entre eux. Ils sont conçus pour effectuer des tâches autonomes et ne nécessitent pas une interaction continue avec d'autres conteneurs pour fonctionner correctement. #colbreak() #image("/_src/img/docs/image copy 119.png") ] #colbreak() *Caractéristiques* : - *Indépendance* : Chaque conteneur peut être géré, mis à l'échelle et redéployé indépendamment des autres. - *Isolation* : Moins de partage de ressources, comme la mémoire et le stockage, ce qui minimise l'impact des erreurs d'un conteneur sur les autres. - *Flexibilité* : Adapté aux microservices où chaque service peut être développé, déployé et mis à jour indépendamment. - *Communication* : Les conteneurs communiquent souvent via des réseaux internes ou des API externes. *Exemples d'utilisation* : - Services de microservices où chaque service a sa propre base de code, cycle de déploiement et peut évoluer indépendamment des autres services. - Applications où des composants indépendants traitent des tâches distinctes, comme un service de facturation séparé d'un service de gestion des utilisateurs. *Tightly Coupled Containers* *Définition* : - Les conteneurs étroitement couplés travaillent ensemble de manière plus intégrée et partagent souvent des ressources communes. Ils sont conçus pour collaborer étroitement, où l'un peut dépendre directement de l'autre pour fournir une fonctionnalité complète. *Caractéristiques* : - *Interdépendance* : Les conteneurs sont fortement dépendants les uns des autres pour accomplir leurs tâches. - *Partage de ressources* : Les conteneurs partagent des ressources telles que l'espace de noms IPC, la mémoire, les volumes de stockage et la pile réseau. - *Coordination* : Souvent utilisés dans des scénarios où une application principale est assistée par des conteneurs secondaires qui fournissent des services supplémentaires comme le traitement des journaux ou la mise à jour du contenu. - *Communication locale* : Les conteneurs peuvent utiliser l'interface localhost pour une communication rapide et directe. *Exemples d'utilisation* : - Un serveur web conteneurisé qui dépend d'un conteneur d'assistance pour mettre à jour dynamiquement le contenu ou gérer les journaux. - Une application où un conteneur exécute l'application principale tandis qu'un autre conteneur gère des tâches auxiliaires telles que la surveillance ou la sauvegarde des données en temps réel. #table( columns: (0.5fr, 1fr, 1fr), [*Caractéristique*], [*Faiblement couplés (Loosely Coupled)*], [*Étroitement couplés (Tightly Coupled)*], "Indépendance", "Haute", "Faible", "Partage de ressources", "Minimum", "Élevé", "Flexibilité de déploiement", "Haute", "Moyenne", "Communication", "Réseau ou API externe", "Interface localhost", "Utilisation typique", "Microservices", "Applications complexes et intégrées", ) == Volumes Un pod peut avoir besoin de stockage persistant ou pas pour stocker des données. Kubernetes fournit des volumes pour gérer le stockage. *Stockage supportés* - *emptyDir*: an empty directory the app can put files into, erased at Pod deletion - *hostPath*: path from host machine, persisted with machine lifetime - gcePersistentDisk, awsElasticBlockStore, azureFileVolume: cloud vendor volumes, independent lifecycle - *secret*: used to pass sensitive information, such as passwords, to Pods. You can store secrets in the Kubernetes API and mount them as files for use by Pods without coupling to Kubernetes directly. secret volumes are backed by tmpfs (a RAM-backed filesystem) so they are never written to nonvolatile storage - *nfs*: network file system, persisted - Many more: iscsi, flocker, glusterfs, rbd, gitRepo ... === Monter un volume persistant K8s propose 2 manières de monter un volume persistant : - *Directement* - Avec *PersistentVolumeClaim (PVC)* #image("/_src/img/docs/image copy 120.png") == Replication Controller Permet de déploier automatiquement un nombre spécifique de réplicas identiques d'un pod. Si un pod échoue, le Replication Controller en crée un nouveau pour le remplacer. Cependant les *Replication Controllers* sont gentiement remplacés par les deploiements. == Services Un service Kubernetes est une abstraction qui définit un ensemble de pods et une politique d'accès à ces pods. Les services permettent de définir un ensemble de pods et de les exposer au sein du cluster. - L'interface utilisateur communique avec l'adresse IP fiable du Service. - Le Service dispose également d'un nom de domaine identique à son nom. - Le Service répartit la charge de toutes les requêtes sur les Pods de l'arrière-plan qui le composent. - Le Service garde une trace des Pods qui se trouvent derrière lui. === Type de services - *ClusterIP* : Expose le Service sur une adresse IP interne du cluster. C'est le type de Service par défaut. - *NodePort* : Expose le Service sur un port statique sur chaque nœud du cluster. - *LoadBalancer* : Expose le Service via un équilibreur de charge externe.
https://github.com/HKFoggyU/hkust-thesis-typst
https://raw.githubusercontent.com/HKFoggyU/hkust-thesis-typst/main/hkust-thesis/layouts/doc.typ
typst
LaTeX Project Public License v1.3c
#import "../imports.typ": * // 文稿设置,可以进行一些像页面边距这类的全局设置 #let doc( // documentclass 传入参数 config: (:), info: (:), // 其他参数 it, ) = { // 1. 默认参数 config = ( twoside: true, ) + config info = ( title: ("基于 Typst 的", "香港科技大学学位论文"), author: "张三", ) + info // 2. 对参数进行处理 // 2.1 如果是字符串,则使用换行符将标题分隔为列表 if (is.str(info.title)) { info.title = info.title.split("\n") } // 3. 基本的样式设置 set text( font: "Times New Roman", size: 12pt, ) set page( paper: "a4", margin: constants.pagemargin, number-align: center, numbering: "i", ) // Spacing: // The official pdf is 1.73 line spacing // #set par(leading: 1.05em) // #set par(leading: 1.03em) set par( leading: constants.linespacing, justify: true ) // 4. PDF 元信息 set document( title: (("",)+ info.title).sum(), author: info.author, ) it }
https://github.com/SillyFreak/typst-packages-old
https://raw.githubusercontent.com/SillyFreak/typst-packages-old/main/tidy-types/docs/manual.typ
typst
MIT License
#import "@preview/tidy:0.2.0" #import "template.typ": * #import "../src/lib.typ" as tt #let package-meta = toml("../typst.toml").package #let date = none // #let date = datetime(year: ..., month: ..., day: ...) #show: project.with( title: "Tidy Types", // subtitle: "...", authors: package-meta.authors.map(a => a.split("<").at(0).trim()), abstract: [ Helpers for writing complex types in tidy documentation and rendering types like tidy outside of tidy-generated signatures. ], url: package-meta.repository, version: package-meta.version, date: date, ) // the scope for evaluating expressions and documentation #let scope = (tt: tt) #set table(stroke: 0.5pt) #let style = tidy.styles.minimal #show raw.where(lang: tt.lang): it => style.show-type(it.text) = Introduction <intro> This package contains helpers for documenting the types of values with tidy, just as tidy itself shows them in function signatures. For example, this lets you write documentation such as this: #pad(x: 5%)[ The result of ```typc range(5).enumerate()``` is a #tt.arr(tt.tuple(tt.int, tt.int)). ] To do so, it produces raw blocks with language #raw(repr(tt.lang)), which can be then styled using a show rule as follows: ```typ #import "@preview/tidy:0.2.0" #import "@preview/tidy-types:0.1.0" as tt // using the default style with default colors #let style = tidy.styles.default #show raw.where(lang: tt.lang): it => { style.show-type(it.text, style-args: (colors: style.colors)) } // using the minimal style #let style = tidy.styles.minimal #show raw.where(lang: tt.lang): it => style.show-type(it.text) ``` For example, the raw block #raw("```" + tt.lang + " content```", lang: "typ") would be displayed as #{ let style = tidy.styles.default show raw.where(lang: tt.lang): it => { style.show-type(it.text, style-args: (colors: style.colors)) } tt.content } in the default style, or #{ let style = tidy.styles.minimal show raw.where(lang: tt.lang): it => style.show-type(it.text) tt.content } in the minimal style. This can be more easily written using the basic function of this package, #ref-fn("tt.type()"): ```typ #tt.type("content")```. In practice, you will not need to use this function directly but instead use the utility functions and variables built on top. = Built-in Typst types There are constants for all the built-in types that Typst provides. Note how two of them are prefixed with `"t-"` as their names are keywords -- ```typc none``` and ```typc auto``` -- and another because its name is taken by a tidy types function -- ```typc type```: #{ let type-names = ( "t-none", "bool", "int", "float", "str", "bytes", "array", "dictionary", "t-type", "function", "t-auto", "datetime", "duration", "regex", "version", "content", "symbol", "length", "ratio", "relative", "fraction", "angle", "color", "stroke", "alignment", "location", "styles", "label", "selector", "module", "plugin", "arguments", ) table( columns: (1fr,)*6, ..for name in type-names { (raw(name, lang: "typc"), eval("tt." + name, scope: (tt: tt))) } ) // [TODO: some types are missing, update to current typst version] } #pagebreak(weak: true) = Module reference == `tidy-types` #{ let module = tidy.parse-module( read("../src/lib.typ"), label-prefix: "tt.", scope: scope, ) tidy.show-module( module, sort-functions: none, style: tidy.styles.minimal, ) }
https://github.com/cu1ch3n/karenda
https://raw.githubusercontent.com/cu1ch3n/karenda/main/date.typ
typst
#import "nord.typ": * #let weekday-names = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") #let month-first-days = range(1, 13).map(month => datetime(year: 2024, month: month, day: 1)) #let month-short-text = month-first-days.map(date => date.display("[month repr:short]")) #let month-long-text = month-first-days.map(date => date.display("[month repr:long]")) #let get-dates(year, begin-weekday) = { let first-day = datetime(year: year, month: 1, day: 1) let next-weekday = calc.rem(begin-weekday - 1, 7) + 1 let dates-by-week = () let dates-by-week-temp = () let current-date = first-day - duration(days: first-day.weekday() - calc.rem(begin-weekday, 7)) while current-date.year() <= year or current-date.weekday() != next-weekday { if current-date.weekday() == next-weekday and dates-by-week-temp.len() > 0 { dates-by-week.push(dates-by-week-temp) dates-by-week-temp = () } dates-by-week-temp.push(current-date) current-date = current-date + duration(days: 1) } if dates-by-week.len() > 0 { dates-by-week.push(dates-by-week-temp) } let dates-by-month-week = () let dates-by-month-week-temp = () let month = 1 for i in range(dates-by-week.len()) { let week = dates-by-week.at(i) let begin-month = week.at(0).month() let end-month = week.at(-1).month() if month == begin-month or month == end-month { dates-by-month-week-temp.push((i, week)) } if month != end-month { dates-by-month-week.push(dates-by-month-week-temp) dates-by-month-week-temp = ((i, week),) month = end-month } } if dates-by-month-week-temp.len() > 0 { dates-by-month-week.push(dates-by-month-week-temp) } return dates-by-month-week }
https://github.com/mumblingdrunkard/mscs-thesis
https://raw.githubusercontent.com/mumblingdrunkard/mscs-thesis/master/src/discussion/index.typ
typst
#import "../utils/utils.typ": * = Discussion <ch:discussion> In this chapter, we discuss the results and try to reason about them. == Interpreting Results Similar to the results in @bib:doppelganger, the benefits are quite small. At best, we would hope for the doppelganger loads to increase performance as much as speculative load wakeups. In most cases, address prediction can at best make loads behave _as if_ speculative load wakeups were enabled. That is: the performance of *ldpred-no-spec-ld* should likely fall somewhere between *base-no-spec-ld* and *base*. This is also largely what we observe: very small improvements with varying levels of success. Most interesting is perhaps the cases where the combination of speculative wakeups and load address prediction lead to a worse result than any one technique applied in isolation. We do not have a hypothesis for this behaviour. Most likely it is down to luck in execution because these tests are so short that a few cycles improvement can lead to drastically different final IPC values. One thing of note when looking only at the IPC is that the predictor seems to do better with workloads that iterate through arrays like *vvadd* and *median* and worse for the quicksort programs *rsort* and *qsort* where the access patterns depend heavily on the input data. It seems to do nothing in the recursive *towers* application, which does look better than the performance reduction when adding speculative load wakeups. Why speculative load wakeups may ever reduce performance is unclear to us, but it is possible that a speculative wakeup marks an IQ slot as ready and schedules it, taking up available issue-capacity for that cycle, only to be killed in the next cycle. Bringing accuracy and coverage into the mix muddies the picture significantly. The *vvadd* test which seems to benefit greatly from address prediction in the MediumBoomConfig case has a coverage of less than 50% in the SmallBoomConfig, and lower than 25% in the MediumBoomConfig. Additionally, the accuracy for *vvadd* is nothing short of abysmal. Our hypothesis is that *vvadd* has such a tight loop that multiple iterations of the same load instruction are being observed by the predictor, without any commits to update the previous address, causing the predictor to issue incorrect predicted values for later loads. The fact that *median* gets a much better coverage and accuracy supports the hypothesis as it has a munch longer loop. *median* also has a much lower IPC in the first place, meaning each loop takes longer. As for coverage in general, we observe that the total coverage (predictions made/total number of loads committed) varies only slightly between the SmallBoom and MediumBoom configurations, with the latter having a slightly lower coverage overall. For the effective coverage (predictions used/total number of loads committed), there is a more severe reduction. Most likely, this is due to there simply being more conflicts where a prediction is made, but cannot be issued because some other operation is given priority. The same number of actions must be performed by the LSU in around half the time, leading to a higher utilisation factor with fewer opportunities to insert predictions. Both the SmallBoom and MediumBoom configurations have only a single port to the L1d, which supports the hypothesis of contention. == Evaluating Hardware Cost Without a working synthesis process, it is difficult to evaluate the definitive hardware cost. The most important thing to know is whether adding the code for doppelgangers increases the length of the critical path and how much hardware is needed to implement the predictor. Because of the banking strategy, the complexity of the predictor storage should be considerably lower than that of the PRF. Additionally, the predictor storage has some cycles of latency for access, meaning implementation can feasibly be done with SRAM blocks as opposed to flip-flop type registers. Thus, the critical path is likely unchanged. As for how much hardware is needed to implement the entire scheme, the added bits to track doppelgangers in the LSU are largely irrelevant, requiring only one bit per LDQ entry, and the major cost is likely to be the predictor storage itself which requires storing the tag, the previous accessed address, the stride, and the confidence for each entry. With the current implementation, there is a lot of waste, but for the planned architecture this should not be a problem. The planned architecture does seem feasible to implement with additional time and better knowledge of the working components of the BOOM. Without any obvious indication of anything to the contrary, we claim similar hardware cost as @bib:doppelganger: One additional bit per entry in the LDQ and the predictor storage itself. == Problems There are some obvious problems with the current implementation, some of which are outlined and explained here. === `debug_pc` is Used `debug_pc` is a signal in the uOP bundle in the BOOM. As the name implies, it is the program counter value (instruction address) of the uOP intended for debug purposes and should not be required in a real implementation. This signal is used at various points in the predictor. The use with the most impact is on the commit-side when the predictor is being trained as this forces the ROB to store the full PC value for every single instruction. It is less bad to use it on the prediction side as the instruction passed in has not yet even entered decode and passing the PC value on for a a few stages is not too much of an impact. It is also used in the LSU to compare the incoming predictions with the incoming (dispatching) uOPs. This is slightly worse as it requires passing the full width PC through both stages. The ROB already stores the PC per instruction, but in a format that saves storing the upper bits more than once per row. It should be simple to reconstruct the PCs/addresses of uOPs that leave the ROB. We mistakenly believed in @bib:nodland-paper that reading from the ROB to reconstruct the PC would be better in all cases. Upon reflection, we have determined that this would only serve to increase the pressure on the ROB and that passing the address on for a few stages is preferable to adding extra ports to the ROB in terms of complexity. === Incorrect Printout From Tests As shown in the previous chapter, the output from the tests have missing characters. It looks like the first few lines print fine, or close to fine, but then get messed up. Normal programs would write to the terminal by using system calls or environment calls. These tests do not do that and instead use a different protocol to interact with a sort of "hidden" system in the BOOM. The programs do this by writing a value at a specific address, then setting a flag at another address referred to as `tohost`, then entering a loop until another flag at another address referred to as `fromhost` is raised. This hidden system is referred to as a _test virtual machine_ (TVM) @bib:riscv-tests. With the way the printing behaves, our working hypothesis is that there is some sort of ordering failure arising when predicted loads are added. The LSU can have ordering failures on loads, but these seem to be checked in relation to the real load. If the doppelganger load would incur an ordering violation but the real load does not, the value that is written back is possibly inconsistent. This might make the `fromhost` flag being visible too early, or there may be something in the TVM that gets an incorrect value when checking available buffer capacity for a serial port. This issue is very difficult to debug. Attempts at debugging this issue yielded little and the effects of the TVM appear to be invisible in waveforms and debug print logs, making the results of our investigations inconclusive. == Future Work We outline the future work that should be done for a proper implementation of doppelganger loads in the BOOM core. The ordering here is thought to be a reasonable order of steps for actual implementation. === Implement Doppelganger Loads Alongside Secure Speculation Schemes Ultimately, the performance improvements are meagre when compared to speculative load wakeups. This is not a surprising result and seems mostly in line with the results from the original paper on doppelganger loads @bib:doppelganger. Instead, doppelganger loads should be seen in relation to secure speculation schemes such as NDA, STT, and DoM. This requires some modifications to how doppelganger loads are performed such as allowing doppelgangers to execute despite ordering violations and store-forwarding as these mechanisms can reveal information about other load and store instructions in flight. It may also require delaying changes to the cache replacement policy. === Detecting and Compensating for Tight Loops We hypothesised that the poor accuracy displayed in simple applications like *vvadd* and *multiply* comes mainly from the predictor's current inability to detect when there are very tight loops, causing it to issue predictions for additional load instructions without being updated by a commit. Said in a different way: the LDQ holds multiple iterations of the same load instruction, meaning the predictor is not updated with new training data. Solving this problem requires first detecting when a tight loop occurs and then deciding what to do when in such a loop. Detecting such a loop can be done by incrementing a counter each time an instruction address is used to make a prediction, and decrementing the counter when the same address is committed. That gives a reasonable estimate for how many instructions are in flight and thus how many times the stride should be added. This requires a multiplier, though likely not a large one. Another option is to track how far off the prediction is from the real address and storing that in the LDQ. This increases the cost of the LDQ because it requires storing the stride. However, on the commit-side, the predictor can store the new stride and make new predictions using that. Assuming the tight loop reaches some sort of steady state, this should be sufficient to ensure the predictions are ahead by the correct amount. However, the steady state might easily flip-flop between having $n$ loads in flight and $n plus.minus 1$ loads in flight, which would make the appropriate offset change accordingly. This might warrant a more complex predictor to detect such flip-flopping. Calculating an appropriate confidence value also becomes more complicated in this scenario. === Making Predictor Storage Set-Associative Currently, the predictor storage acts like a direct-mapped cache. Changing this to an associative implementation is likely to result in fewer evictions and better coverage with an equal number or fewer entries. === Storing Values in the Physical Register File First, the values should be sent to the PRF as responses arrive from the L1d, just as for real loads. This requires some mechanism to hold off dependent instructions until the address is confirmed, and a way to wake them up when the address is confirmed. It may be possible to re-use the writeback logic as wakeup logic to avoid adding additional ports to the IQ slots, though this also means confirmed addresses sometimes have to wait. The other alternative is to add an entirely different port for waking up dependents, but this adds pressure on each IQ slot. It may also be possible to re-use the speculative wakeup port as a dual-purpose port, prioritising signalling correctly predicted doppelgangers. === Removing the Dependency on `debug_`-Signals In its current form, the code makes use of the `debug_pc` signal of the MicroOp bundle in various locations. This signal should not exist in a final deployment and the PC either has to be explicitly added or reconstructed from other available information. For the prediction side, it is likely fine to pass the PC through the initial stages instead of potentially adding more ports to the FTQ to read the high-order bits of the PC. On the commit side, the PC should be reconstructed from the low-order bits contained in the uOP and the high-order bits from the FTQ. === Buffering Predictions to Fill More Cycles There is potential to fill unused cycles with more predictions. For example, when a prediction is made in the same cycle as an address arriving from the AGUs, the LSU prioritises issuing operations to the L1d based on the data from the AGU and the prediction is dropped. If predictions were not dropped but put in a buffer-like structure instead, the LSU could prioritise issuing loads for predicted addresses when it has available capacity. Keeping predictions around for 1-2 cycles seems reasonable to fill more cycles. === Allow Other Operations to Execute Upon Correct Predictions When a correct prediction is made, the `will_fire_load_incoming` signal is high, causing the LSU to "think" that the L1d is being accessed, even if the operation is intercepted. This leaves room for other operations that access the L1d, such as more predictions, or waking up loads that have already had their address translated. === Compressing Predictor Entries Currently the predictor uses full-width tags, previous addresses, and strides. In the case of the BOOM, the max address width is 39 bits. This makes for very large entries in the predictor. Strides likely tend toward smaller values and can likely be compressed to something closer to 10-12 bits. The previous address is more difficult to compress, but likely has a lot of bits in common with other addresses registered in the predictor. For this case, it might be possible to store low-order bits and a reference to a smaller table for storing shared high-order bits, similar to how the PC is stored for each instruction in the ROB. This approach likely requires an additional cycle of latency, but that may be a worthwhile tradeoff. === More Complex Predictors When the delay from prediction to receiving the real address is greater than the normal L1d access latency, there is room for having a predcitor that detects more advanced patterns but uses more cycles to perform the prediction to increase accuracy. It may also justify deeper pipelines to access predictor storage, which may in turn allow for storing more predictions overall. One such predictor might be using _delta-correlating prediction tables_ (DCPT) in which individual load instructions do not exhibit purely strided patterns, but still have patterns of offsets @bib:dcpt. ==== Hybrid Predictor As only ~20% of predictions are compared to the real address within 10 cycles, there is a good possibility of using additional slower predictors to get more accuracy for longer loads. One intriguing option is the possibility of issuing multiple doppelgangers per load using fast and slow predictors. Similar to how some branch prediction structures work where IF is redirected with a fast, low-accuracy prediction first, and only later redirected if the high-accuracy predictor disagrees, this could work to increase accuracy at the cost of some latency. We only collected statistics for load instructions that are already covered, but there is also a great possibility of increasing coverage with these predictor structures. === Test Predictor with Proper Benchmarking Suites and on Shared Systems A glaring weakness of the tests we have run is that they are all very small programs that likely fit fully within the instruction cache and only run one at a time. A useful predictor should be resilient to an OS switching tasks and should accomodate many tasks running within the same space of time and possibly with similar virtual address spaces. With this, it should be considered whether sharing the predictor between many applications poses a security risk. Intuitively, information in the predictor is only based on commited information and it should not be possible to extract information that is not already possible to extract through the cache side-channel. Entries should likely still be tagged with information specifying which application they belong to to prevent interferring with each other's prediction performance. === Handle Changes to Virtual Memory RISC-V has the instruction `SFENCE.VME` to signal that a change has occured to the virtual memory mapping and that the processor should invalidate some entries in structures like the TLB. This is common when unmapping pages in virtual memory. Similarly, corresponding entries in the predictor may need flushing as normal predictions bypass the TLB entirely and thus bypass permission checks on the assumption that subsequent accesses to a page are OK without permission checks. This may also be entirely fine as the permission check is still be performed when the real address arrives, causing the processor to raise an exception if the prediction is correct and the address falls outside of mapped memory. == Miscellaneous Musings Here are a few of our musings on different relevant topics. === On the Possibility of Merging With the L1d Prefetcher One of the ideas proposed in @bib:doppelganger is to merge the address predictor for doppelganger loads with that of the L1d prefetcher. This makes sense in the cases where the L1d prefetcher is predicting which address will be needed soon. Instead of predicting the next address, the predictor should determine the current address. This can be feasible with L1d prefetchers that use strided patterns or DCPT which still have a semblance of predicting what the next load address is going to be. State of the art prefetchers like best-offset @bib:best-offset would be considerably more difficult to integrate with. Best-offset does not predict the next address, but an offset that is calculated to be a few accesses ahead to ensure timely prefetches. The stride between accesses need only be a factor of the offset used by the prefetcher. An additional issue is that the L1d prefetcher generally has different design requirements for the storage. With the address predictor for doppelgangers, we know things about concurrent accesses that allow us to efficiently bank accesses. The guarantees we rely upon for this strategy are lost at the point the L1d prefetcher is employed. Adding ports to the L1d prefetcher could be costly. If the two structures are physically far apart on the chip, that introduces additional issues, but can potentially be compensated for by allowing more latency for predictions. === Following Through on L1d Misses for High-Confidence Doppelganggers We have decided to drop doppelgangers that miss in the L1d. Our reasoning here is that in a system with an L1d prefetcher, predictable addresses will practically always hit. Because our predictor uses a simple strided scheme, it is fair to say the addresses generated by the predictor are highly predictable. Thus, by allowing misses to start fetching from deeper cache levels, there is a very low likelihood of those data being useful. However, there is an interesting opportunity of a symbiotic relationship between the L1d prefetch predictor and the load address predcitor where they both detect different patterns and doppelganger loads appear almost like software prefetches to the L1d. Additionally, it is obvious to us that L1d misses must be serviced for any MLP to be regained under certain secure speculation schemes such as DoM. === United Nations Sustainability Goals This work is relevant to the United Nations Sustainability Goals by creating more performant processors that perform the same amount of work using less energy.
https://github.com/csimide/cuti
https://raw.githubusercontent.com/csimide/cuti/master/demo-and-doc/otr/utils.typ
typst
MIT License
#import "@preview/sourcerer:0.2.1": code #let example(source, sd: true) = { block( //breakable: false, { { code( radius: 0pt, inset: 10pt, line-offset: 10pt, text-style: (font: ("Fira Code", "Source Han Sans SC")), stroke: 0.5pt+luma(180), source ) } if sd { v(-1.2em) block( fill: rgb("dcedc8"), stroke: 0.5pt + luma(180), inset: 10pt, width: 100%, eval("#import \"../../lib.typ\": * \n" + source.text, mode: "markup") ) } } ) } #let typebox(fill: "default", s) = { set text(size: 10pt) let fillcolor = if fill == "default" { ( "int": rgb("#e7d9ff"), "str": rgb("#d1ffe2"), "bool": rgb("#ffedc1"), "none": rgb("#ffcbc4"), "content": rgb("#a6ebe6"), "angle": rgb("#e7d9ff"), "relative": rgb("#e7d9ff"), ).at(s.text, default: luma(220)) } else {fill} box( inset: 3pt, fill: fillcolor, radius: 3pt, baseline: 3pt, raw(s.text) ) }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/016%20-%20Fate%20Reforged/006_No%20End%20and%20No%20Beginning.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "No End and No Beginning", set_name: "Fate Reforged", story_date: datetime(day: 11, month: 02, year: 2015), author: "<NAME>", doc ) #emph[Several years have passed since Sarkhan Vol ] altered the fate of Tarkir #emph[by saving Ugin from the villainous Nicol Bolas and encasing the ailing Spirit Dragon in a cocoon of stone. Since then, the dragon tempests that spawn young dragons on Tarkir have not only continued—they have intensified—as though enraged at Ugin's injury.] #emph[Few on Tarkir know the reason for the storms' fury, but all can see the effects. What was once a delicate balance between clans and dragons is becoming an all-out rout. Every month brings new dragons and new losses.] #emph[In the Shifting Wastes, the Abzan Houses face off against foes at least as adept at desert survival as they are: the great dragon Dromoka and her brood. With nowhere to hide, the Abzan have lost more to the dragons' renewed assault than any other clan.] #emph[Daghatar, khan of the Abzan, must choose his course wisely if his people are to endure.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The winds howled over the stone citadel of Mer-Ek, seat of the Abzan khan. The storms had become more frequent over the last year, and there was rarely much of a respite between them. The winds were constant, and in the desert, they were deadly. At their strongest, the winds and sand could flay the flesh from an ibex, or an unprotected person. The fortresses moved less often. Food and water reserves were at their lowest level in the clan's history. But no storm could ever be crisis enough to bring the Abzan elders from the corners of the empire back to their seat of power. Daghatar, khan of the Abzan, sat at the head of a long marble table. It was scratched and scored, stained and worn by the generations of councils that had been held on the spot. Every seat was filled; twenty of the clan's finest and wisest were in attendance, and per the tradition that he had reinstated from Burak Khan, Daghatar did not speak until he had heard the words of each of his advisors in full. He would speak last, and his would be the final words on the matter. #figure(image("006_No End and No Beginning/01.jpg", width: 100%), caption: [Daghatar the Adamant | Art by <NAME>], supplement: none, numbering: none) Knowing that, his advisors had been talking and arguing for two hours. It was an existential crisis for the clan, and none wanted a decision to be made without the surety that they had been heard in full. Daghatar rested his chin on his hand, weary but attentive, as the battle raged in front of him. "What you suggest is absurd! You speak of Dromoka's brood as if they were force of nature. In the last six months alone, my warriors have brought down three dragons. That's in addition to the two that our khan struck down himself with that mace of his! I'm not talking about whelps, either—the one they called Korolar had a wingspan of twenty yards! Yes, we've had losses, but we can win this fight!" The speaker was Reyhan, joint commander of the forces of three Houses, and the only military leader to achieve any consistent success in the past two years. "Assuming you cowards don't decide to give up on us." She glared around the table. Fewer and fewer people were able to meet her gaze. The man at Daghatar's right began to clap, slowly. "Yes, well done. Well done! And did you hang your trophies across your gates like some Mardu savage? Twenty yards! A mighty victory. Five in six months! An amazing feat. Yet in that time, how many dragons were birthed from the storms?" This was Merel, Daghatar's uncle—a man who refused the khanship himself in his younger days. "My scouts have identified sixteen. And those are just #emph[my] scouts. Dromoka perches not twenty-five miles from here, and she summons more and more through the storms to her side. She doesn't just command the other dragons' obedience, she commands an #emph[army] . And I don't think I need to remind anyone of what happened when we faced her directly. Reyhan, you are a master of the war of attrition. My math may be a little rusty, but please, enlighten me as to why you think this could possibly turn in our favor?" Daghatar's frown deepened. He had held out hope that the Abzan leaders could all come together, and that their collective wisdom would provide a path that he had not already conceived. But instead, they seemed only to confirm his deepest fears. Reyhan glared. "I've heard a lot of criticism out of you, old man, and no solutions. None of you have offered a better plan than resistance. My solution is simple. We pool our remaining forces, and we go straight to the source. We call up all of our fighting men and women, we call up every ancestor willing to listen, and we strike at the brood's heart. We bring down Dromoka, and her brood will scatter. The rest of Tarkir can fend for itself until the storms relent and the winds change. As we have always done." Merel's retort was barely a whisper. His eyes shone with regret. "You weren't there, Reyhan. You didn't see what she did to us. We lost over a thousand soldiers, and we never scratched her. What you advocate is the end of the Abzan." #figure(image("006_No End and No Beginning/02.jpg", width: 100%), caption: [Citadel Siege | Art by <NAME>], supplement: none, numbering: none) Silence fell over the room. Reyhan's face softened, and she hung her head. "I have heard nothing today that does not lead to that destination, old friend. I'm trying to offer us a fragment of hope, or failing that, an end we can be proud of." Nobody spoke. All that needed to be said had been said, and the truth lay bare on the table before them. Daghatar stood, and everyone straightened in their seats. "I have heard your wise counsel, and I thank each of you for it. On one hand, we have a war we are unlikely to win. On the other, we have a siege we are unlikely to survive. I will not understate this: we may be facing the end of the Abzan. As such, I will not act hastily. The ancestors must be consulted. But whatever is decided, I will be with you until the end. You are dismissed." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The khan's chambers were austere. Daghatar was a wealthy man from a powerful family, but none of that was on display in the one space he did not have to share with anyone else. No servants cleaned his room, and no visitors ever saw the inside of it. It was an oddity for a people that prided themselves so much on community, but he was the khan, and he was due his occasional eccentricity. Still, he was not truly alone there. Not with the Remembrance. It watched him enter, and he felt its glare upon him. It was the burden of every khan, going back a dozen generations. It rested in a place of honor, and it was an inspiration to the people that beheld it. Not so to the handful who had borne it. To them, it was a terrifying burden. But in dark times, it was a weapon and a resource like none other. The Remembrance. It was said that it came from one of the first kin-trees, bound up with the spirits of some of the very first Abzan, the ones who survived, the ones who learned, the ones who persevered when life itself seemed impossible. These great spirits nurtured that sapling into a mighty, towering tree. Those branches rose higher than the walls of Mer-Ek, higher, it was said, than the far-away spires of the Jeskai, a veritable mountain of wood and bark and leaves, growing, thriving, despite the harshness of the desert. Daghatar often thought it must have been an affront to the heavens, and so the heavens finally brought it low. In the middle of a great storm, lightning struck, shattering the tree to its core. There, they found it. The tree's ancient amber heart, pulsing with the power of the long-dead, merged into a single consciousness. The amber heart was forged into the head of a mace, and it had been carried by the Abzan khans ever since. If he had known what it truly was, Daghatar might have never accepted the title. The amber swirled and pulsed with a fluid light—its movement quickened as it sensed his approach. He reached out for it and hesitated slightly before he gripped the hide-wrapped handle. The voice pounded his mind like a stampeding beast. "Coward. Weakling. You have been avoiding us. Do you fear your duty so much?" Daghatar respectfully lifted the mace and cradled the amber head in his left hand. The elders had not provided the guidance he needed, but the ancestors had never failed him. He sat down, took a deep breath, and tried to keep the weariness and resentment out of his voice. "On the contrary. I fear what might happen if my duty is left undone. But yes, I have been contenting myself with the wise counsel of the living." "The living. Yes. So afraid of what you might lose, you lose sight of what you are responsible for. Your duties are larger than a life, or ten thousand lives. Your duties are to every Abzan who will ever live." #figure(image("006_No End and No Beginning/03.jpg", width: 100%), caption: [Abzan Ascendancy | Art by <NAME>], supplement: none, numbering: none) Daghatar closed his eyes. "With the way we are headed, that will not be a terribly large number." He felt a wave of contempt from the amber heart. "Only if you fail. Have you already softened to the idea of failure? Will it comfort you as you die, as you reconcile the annihilation that you have consigned your people to, that your road was a #emph[hard one] ?" "I am willing to accept your abuse in return for your advice. There are two options available to us, and neither seems to have much of a chance. Dromoka and her brood are like no other dragons. They are powerful, yes, but they also protect each other. They work in concert, and they are inured to the harshness of the desert. We are at war with a foe that possesses our own strengths in greater quantity than we do. We can do what we have always done, keep our defenses tight, but the dragons are growing in both number and power, and our supplies will not last forever. Or, we can strike at the leader of their brood, and hope that the rest will scatter to other regions. "But I wonder if even that would be enough. I have heard from some of the other khans, and there is nowhere in Tarkir that has been spared the dragon tempests. We might repel one brood, but another would almost certainly take its place in time. If there is a third option, I have not yet discovered it. So what would you have me do?" There was a brief silence from the Remembrance. "The first crisis you came to me with. Such a trifling matter. You had lost a patrol, it was captured by the Sultai, and you wanted to mount a rescue effort. You wept when I forced the truth upon you, that the hardest thing a khan must do is lose, and survive to win the next battle. You would have lost five times the number in the recovery than you lost to the Sultai. You punished them in the next season, and the spirits of the fallen were brought home again. That is what it means to be Abzan. To suffer a defeat and yet lose none of your strength. You will do this again. The strength of the Abzan is enough to overcome this #emph[beast] , and no matter how many you lose, you will ensure that there is a future for those who remain. <NAME>, are you prepared to do what must be done?" The khan pondered the words of the Remembrance for a long time. "Yes. I believe I am." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The skies were clear, but the wind was strong. Daghatar's helm echoed with the constant beating of sand against the steel. His mask kept out the worst of it, but he still had to squint as he and his company approached the meeting place. A large outcropping of rocks came into view. Merel's posture changed, but he kept up alongside his nephew—it was the site of the first battle with Dromoka. A thousand Abzan had fallen on these dunes, but time and the desert had washed away any trace of the dead. Still, it was a sacred place; a momentous place. Daghatar could feel it. #figure(image("006_No End and No Beginning/04.jpg", width: 100%), caption: [Plains | Art by <NAME>], supplement: none, numbering: none) As they approached, he could see a handful of people waiting for them among the stones. Most of them dressed in Abzan fashion, although they no longer bore the insignia of any house. An instinctive hatred of these men welled up in the khan, but he knew it for what it was. He gripped the Remembrance, and kept marching into the oncoming gale. The stones provided some shelter from the wind, and Daghatar's men loosened their masks and helms enough to take a drink of water. The khan looked at the faces of the envoys, and kept his face a blank. The envoys bowed low, and Daghatar returned the gesture. "Daghatar, khan of the Abzan. On behalf of the Eternal, we welcome you. I am Sohemus." "You welcome me to my own land, Sohemus. Although given the circumstances, I accept. But I'm not here to speak with you. Where is your master?" Sohemus bowed his shaven head low. He had the look of a Jeskai pilgrim about him. "She will be joining us when it suits her. But in the meantime, I will let you know of the protocols that must be followed. When you speak, look at her. She will speak only Draconic, and I will translate. Do not look at or address me in any way." Daghatar cocked his head slightly, then nodded. "Very well. Anything else?" "I wish only to remind you that she has not granted any state of truce for this meeting. Given what she accuses your people of, we make no guarantee of your safety." "What?" Daghatar's heart raced as fury washed over him. "What she accuses #emph[us] of?" Sohemus bowed low, extending his empty palms. "It is not for me to discuss." Sohemus flinched, and a strange smile crossed his face. "Ah. You will not need to wait any longer. She comes." #figure(image("006_No End and No Beginning/05.jpg", width: 100%), caption: [Dromoka, the Eternal | Art by <NAME>], supplement: none, numbering: none) Daghatar looked to the sky and saw nothing but the blinding light of the sun. Then, the light relented. A giant form descended from above, wings so large that they eclipsed the windstorm. The men below felt pulse after pulse of air forced down from above, as the dragon landed in front of them. Dromoka was enormous, easily three times the size of the largest Ivorytusk Daghatar had ever seen. Her scales were thick, ranging from bronze to pearl, and not a single one seemed to bear a scratch. Thousands of arrows, spears and swords had broken against those scales. #emph[Here they were] , Daghatar thought, #emph[completely unmarred for the effort] . The khan stepped out and bowed. The dragon lowered her head slightly in return. She seemed to be studying him, like a person might upon seeing an unfamiliar kind of beetle. The dragon spoke, a rumbling, scraping sound unlike any he had ever heard before. He resisted the instinct to turn toward Sohemus as he translated. "I grant you this audience, Daghatar of the Abzan, although I do not understand what you hope to achieve by it." Daghatar stared up at the dragon. He felt like he was addressing a fortress. "Great and powerful Dromoka. I have come here to seek an end to the hostilities between the Abzan and your brood." The dragon made a sound, a rumble that felt like an earthquake in his chest. It took a moment for Daghatar to realize it was #emph[laughter] . Sohemus translated what followed. "That will not be possible. Your tribe of necromancers is a stain on her land that she cannot tolerate." "What? Necromancers? I don't understand. You speak of the Sultai, Dromoka. We have never practiced their foul arts." The dragon lowered her enormous head down to look Daghatar almost in the eye. Her expression seemed curious. When she spoke, the heat from her mouth eclipsed the burning sun. "You bind your dead to serve you. Necromancy. You even bring such a dark spirit into her presence, and you look at her and deny it? Yet you seem earnest. Explain this contradiction." #figure(image("006_No End and No Beginning/06.jpg", width: 100%), caption: [Rally the Ancestors | Art by <NAME>], supplement: none, numbering: none) Daghatar looked down at the Remembrance. "You misunderstand. These are our honored ancestors. Their wisdom helps guide us. It is tradition, our way. We cannot—" She cut him off, the Draconic speech a bellow of noise. Sohemus cringed before her outburst, and paused before translating. "The living serve the living, and the dead pass from us. This is the natural way, and…she has strong objections to those who defy it." The dragon continued, in a softer voice. "Dromoka wishes you to know that she has studied your people, and she finds much to respect. You serve one another with courage and are stronger together than apart. You understand sacrifice and strength. Even your tradition of #emph[krumar] is not unlike what she has instituted among those humans who have pledged ourselves to her. But as long as your people are tainted by necromancy, our brood will continue to wipe yours clean from the desert." Daghatar stared into the eyes of the dragon for a long time. The Remembrance's voice assaulted Daghatar's mind. "Fool. You will #emph[not] let this opportunity pass you by. You are not here under a banner of truce, and this beast has promised to kill us all. You will never get this close again. Raise me up. Strike your enemy down, #emph[now.] " Daghatar gripped the Remembrance's hilt. He steadied himself, and stepped forward. "Dromoka, our ancestors have guided us for centuries. And I will share with you the truest advice that they have ever given me. They reminded me that a khan's duties are larger than a life, or ten thousand lives. I have a responsibility to the lives of every one of our descendants, until the end of days. That to be Abzan, we must suffer a defeat, and yet lose none of our strength. That we must do what is necessary, even if it is hard. Even if it is unthinkable." He strode up to the dragon, fearless. Dromoka did not flinch, even as he walked up within an arm's length. He could feel the Remembrance, pulsing with power and anticipation. He whispered under his breath as he raised the mace. "Forgive me." Daghatar slammed the head of the mace down on the stone beneath his feet. The amber cracked, and the voice of the Remembrance exploded into a thousand screams of agony and rage. He slammed it down again, and again, until it shattered into a thousand shimmering shards. The voice went silent. The ancestors were gone. #figure(image("006_No End and No Beginning/07.jpg", width: 100%), caption: [Shatter | Art by <NAME>], supplement: none, numbering: none) He released a slow breath, and bent his knee. "Merel. You will take word to every house. Uproot every kin-tree. The practice of necromancy is hereby forbidden." He looked up at Dromoka. "I trust this will be sufficient?" The dragon nodded. Merel suddenly looked much older. "Son, entire Houses will rebel. You're talking about turning our backs on all our traditions. The destruction of our ancestors! About civil war!" "Yes. But there will be a future for those of us who remain." He looked down at the shards of the Remembrance in silence. As the wind blew, the shards were carried away, shining motes lost to the sand. In just minutes, there was no trace to be found.
https://github.com/christopherkenny/ctk-article
https://raw.githubusercontent.com/christopherkenny/ctk-article/main/README.md
markdown
# ctk-article Format The `ctk-article` Quarto template is a general purpose article template, designed for academic papers and preprints. <!-- pdftools::pdf_convert('template.pdf', pages = 1) --> ![[template.qmd](template.qmd)](template_1.png) ## Installing ```bash quarto use template christopherkenny/ctk-article ``` This will install the format extension and create an example qmd file that you can use as a starting place for your document. ## Using `ctk-article` This extension builds your Quarto documents using a Typst backend. [Typst](https://github.com/typst/typst) is a newer (~5 years old), but relatively developed approach to typsetting technical documents. This is substantially faster than LaTeX but is likely less familiar. I recommend using Typst for social sciences, as it gives sufficient control over formatting while being far more intuitive than LaTeX (even as a decade+ regular user of LaTeX). This template is what I am using for the job market in 2024. By the beauty of Quarto, this should not change your experience in any meaningful negative ways. You can use LaTeX equations, Quarto callouts, etc. But, you may want to save any images as `.png` or `.svg` files as Typst's main drawback (right now) is the lack of `.pdf` image support. This template has many custom options and optimizes for generic preprints. Some options you can set: - `title`: Your article's title - `subtitle`: Your article's subtitle - `running-title`: A short title to include in the article's header - `author`: Author and affiliation information, following [Quarto's schema](https://quarto.org/docs/journals/authors.html).+ - `orcid`: Ids are displayed as a green ORCIDiD logo link - `email`: Emails are listed as links under authors. - Departments, affiliation names, and locations are also listed in a compact fashion. - `thanks`: Acknowledgements to add as a footnote to the first page. - `keywords`: [An, array, of, keywords, to, list] - `margins`: These default to a sensible 1in all-around margin - `mainfont`: See the fonts discusison below - `fontsize`: Set the default font size. Default is 11pt. - `linestretch`: line spacing. In academic fashion, the default is `1` (single-spaced). I recommend `1.25`. - `linkcolor`: Add a splash of colors to your link. - `title-page`: Add a separate title page - `blind`: Blinds the document, hiding the authors and running author information. - `biblio-title`: Title for the reference section While writing, you can also identify the start of the appendix. This resets the counters and updates the "supplements" for figures, so the first appendix figure becomes "Figure A1" instead of continuing the count from the main paper. Simply add the `{.appendix}` tag to the first appendix section to start this switch, like so: ```md ## Some Title for First Appendix Section {.appendix} ``` ### Fonts By default, the `ctk-article` format uses the Spectral font. This can be installed from [Google Fonts](https://fonts.google.com/specimen/Spectral). To check that it is installed, run: ``` quarto typst fonts ``` If no font by the name "Spectral" is found, it falls back to Crimson Text. This can be installed from [Google Fonts](https://fonts.google.com/specimen/Crimson+Text). If no font by the names "Spectral", "Crimson Text", or "Crimson" is found, the template falls back to Linux Libertine. This backup font of Crimson Text is chosen to look like [Cory McCartan's cmc-article](https://github.com/corymccartan/cmc-article) which uses Cochineal. ### Running Headers Running titles and authors alternate on the left and right of the header. The title is placed on the right-hand side of odd pages and the author on the left-hand side of even pages. Nothing is added to the header on the first page of the document. By default, the running title is taken as the title. To override this, provide a `running-title` metadata field in the YAML frontmatter. The author running header is taken from the `author` metadata field. They are formatting according to the following pattern: - One author: `Last-Name-1` - Two authors: `Last-Name-1 and Last-Name-2` - Three authors: `Last-Name-1, Last-Name-2, and Last-Name-3` - Four authors: `Last-Name-1, Last-Name-2, Last-Name-3, and Last-Name-4` - Five or more authors: `Last-Name-1 et al.`
https://github.com/maxi0604/typst-builder
https://raw.githubusercontent.com/maxi0604/typst-builder/main/directory/two_deep/deeper.typ
typst
MIT License
And even if they are in nested directories.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.0.1/draw.typ
typst
Apache License 2.0
#import "vector.typ" #import "matrix.typ" #import "cmd.typ" #import "util.typ" #import "path-util.typ" #import "coordinate.typ" // #import "collisions.typ" #import "styles.typ" #let typst-rotate = rotate #let set-style(..style) = { assert.eq(style.pos().len(), 0, message: "set-style takes no positional arguments" ) (( style: style.named() ),) } #let fill(fill) = { (( style: (fill: fill) ),) } #let stroke(stroke) = { (( style: (stroke: stroke) ),) } // Move to coordinate `pt` // @param pt coordinate #let move-to(pt) = { let t = coordinate.resolve-system(pt) (( coordinates: (pt, ), render: (ctx, pt) => (), ),) } // Rotate on z-axis (default) or specified axes if `angle` is of type // dictionary #let rotate(angle) = { let resolve-angle(angle) = { return if type(angle) == "angle" { matrix.transform-rotate-z(angle) } else if type(angle) == "dictionary" { matrix.transform-rotate-xyz( angle.at("x", default: 0deg), angle.at("y", default: 0deg), angle.at("z", default: 0deg), ) } else { panic("Invalid angle format '" + repr(angle) + "'") } } return (( push-transform: if type(angle) == "array" and type(angle.first()) == "function" { ctx => resolve-angle(coordinate.resolve-function(coordinate.resolve, ctx, angle)) } else { resolve-angle(angle) } ),) } // Scale canvas // @param factor float #let scale(f) = (( push-transform: matrix.transform-scale(f) ),) // Translate #let translate(vec) = { let resolve-vec(vec) = { let (x,y,z) = if type(vec) == "dictionary" { ( vec.at("x", default: 0), vec.at("y", default: 0), vec.at("z", default: 0), ) } else if type(vec) == "array" { if vec.len() == 2 { vec + (0,) } else { vec } } else { panic("Invalid angle format '" + repr(vec) + "'") } return matrix.transform-translate(x, -y, z) } (( push-transform: if type(vec) == "array" and type(vec.first()) == "function" { ctx => resolve-vec(coordinate.resolve-function(coordinate.resolve, ctx, vec)) } else { resolve-vec(vec) }, ),) } // Sets the given position as the origin #let set-origin(origin) = { return (( push-transform: ctx => { let (x,y,z) = vector.sub(util.apply-transform(ctx.transform, coordinate.resolve(ctx, origin)), util.apply-transform(ctx.transform, (0,0,0))) return matrix.transform-translate(x, y, z) } ),) } // Register anchor `name` at position. #let anchor(name, position) = { let t = coordinate.resolve-system(position) (( name: name, coordinates: (position,), custom-anchors: (position) => (default: position), after: (ctx, position) => { assert(ctx.groups.len() > 0, message: "Anchor '" + name + "' created outside of group!") ctx.groups.last().anchors.insert(name, ctx.nodes.at(name).anchors.default) return ctx } ),) } // Group #let group(name: none, anchor: none, body) = { (( name: name, anchor: anchor, default-anchor: "center", before: ctx => { ctx.groups.push(( ctx: ctx, anchors: (:), )) return ctx }, children: body, custom-anchors-ctx: ctx => { let anchors = ctx.groups.last().anchors for (k,v) in anchors { anchors.insert(k, util.revert-transform(ctx.transform, v)) } return anchors }, after: (ctx) => { let self = ctx.groups.pop() let nodes = ctx.nodes ctx = self.ctx if name != none { ctx.nodes.insert(name, nodes.at(name)) } return ctx } ),) } #let mark(from, to, ..style) = { assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos())) let style = style.named() let t = (from, to).map(coordinate.resolve-system) (( coordinates: (from, to), render: (ctx, from, to) => { let style = styles.resolve(ctx.style, style, root: "mark") cmd.mark(from, to, style.symbol, fill: style.fill, stroke: style.stroke) } ),) } #let line(..pts-style, close: false, name: none) = { // Extra positional arguments from the pts-style sink are interpreted as coordinates. let (pts, style) = (pts-style.pos(), pts-style.named()) // Coordinate check let t = pts.map(coordinate.resolve-system) (( name: name, coordinates: pts, custom-anchors: (..pts) => { let pts = pts.pos() ( start: pts.first(), end: pts.last(), ) }, render: (ctx, ..pts) => { let pts = pts.pos() let style = styles.resolve(ctx.style, style, root: "line") cmd.path(close: close, ("line", ..pts), fill: style.fill, stroke: style.stroke) if style.mark.start != none or style.mark.end != none { let style = style.mark if style.start != none { let (start, end) = (pts.at(1), pts.at(0)) let n = vector.scale(vector.norm(vector.sub(end, start)), style.size) start = vector.sub(end, n) cmd.mark(start, end, style.start, fill: style.fill, stroke: style.stroke) } if style.end != none { let (start, end) = (pts.at(-2), pts.at(-1)) let n = vector.scale(vector.norm(vector.sub(end, start)), style.size) start = vector.sub(end, n) cmd.mark(start, end, style.end, fill: style.fill, stroke: style.stroke) } } } ),) } #let rect(a, b, name: none, anchor: none, ..style) = { // Coordinate check let t = (a, b).map(coordinate.resolve-system) // No extra positional arguments from the style sink assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos())) let style = style.named() (( name: name, default-anchor: "center", anchor: anchor, coordinates: (a, b), render: (ctx, a, b) => { let style = styles.resolve(ctx.style, style, root: "rect") let (x1, y1, z1) = a let (x2, y2, z2) = b cmd.path(close: true, fill: style.fill, stroke: style.stroke, ("line", (x1, y1, z1), (x2, y1, z2), (x2, y2, z2), (x1, y2, z1))) }, ),) } #let arc(position, start: auto, stop: auto, delta: auto, name: none, anchor: none, ..style) = { // Start, stop, delta check assert((start,stop,delta).filter(it=>{it == auto}).len() == 1, message: "Exactly two of three options start, stop and delta should be defined.") // No extra positional arguments from the style sink assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos())) let style = style.named() // Coordinate check let t = coordinate.resolve-system(position) let start-angle = if start == auto {stop - delta} else {start} let stop-angle = if stop == auto {start + delta} else {stop} (( name: name, anchor: anchor, default-anchor: "start", coordinates: (position,), custom-anchors-ctx: (ctx, position) => { let style = styles.resolve(ctx.style, style, root: "arc") let (x, y, z) = position let (rx, ry) = util.resolve-radius(style.radius).map(util.resolve-number.with(ctx)) ( start: position, end: ( x - rx*calc.cos(start-angle) + rx*calc.cos(stop-angle), y - ry*calc.sin(start-angle) + ry*calc.sin(stop-angle), z, ), origin: ( x - rx*calc.cos(start-angle), y - ry*calc.sin(start-angle), z, ) ) }, render: (ctx, position) => { let style = styles.resolve(ctx.style, style, root: "arc") let (x, y, z) = position let (rx, ry) = util.resolve-radius(style.radius).map(util.resolve-number.with(ctx)) cmd.arc(x, y, z, start-angle, stop-angle, rx, ry, mode: style.mode, fill: style.fill, stroke: style.stroke) } ),) } // Render ellipse #let circle(center, name: none, anchor: none, ..style) = { // No extra positional arguments from the style sink assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos())) let style = style.named() // Coordinate check let t = coordinate.resolve-system(center) (( name: name, coordinates: (center, ), anchor: anchor, render: (ctx, center) => { let style = styles.resolve(ctx.style, style, root: "circle") let (x, y, z) = center let (rx, ry) = util.resolve-radius(style.radius).map(util.resolve-number.with(ctx)) cmd.ellipse(x, y, z, rx, ry, fill: style.fill, stroke: style.stroke) } ),) } // Render content // NOTE: Content itself is not transformed by the canvas transformations! // native transformation matrix support from typst would be required. #let content( pt, ct, angle: 0deg, anchor: none, name: none, ..style ) = { // No extra positional arguments from the style sink assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos())) let style = style.named() // Coordinate check let t = coordinate.resolve-system(pt) (( name: name, coordinates: (pt,), anchor: anchor, default-anchor: "center", render: (ctx, pt) => { let (x, y, ..) = pt let style = styles.resolve(ctx.style, style, root: "content") let padding = util.resolve-number(ctx, style.padding) let size = measure(ct, ctx.typst-style) let tw = size.width / ctx.length let th = size.height / ctx.length let w = (calc.abs(calc.sin(angle) * th) + calc.abs(calc.cos(angle) * tw)) + padding * 2 let h = (calc.abs(calc.cos(angle) * th) + calc.abs(calc.sin(angle) * tw)) + padding * 2 // x += w/2 // y -= h/2 cmd.content( x, y, w, h, move( dx: -tw/2 * ctx.length, dy: -th/2 * ctx.length, typst-rotate(angle, ct) ) ) } ),) } /// Draw a quadratic or cubic bezier line /// /// - start (coordinate): Start point /// - end (coordinate): End point /// - ..ctrl (coordinate): Control points #let bezier(start, end, ..ctrl-style, name: none) = { // Extra positional arguments are treated like control points. let (ctrl, style) = (ctrl-style.pos(), ctrl-style.named()) // Control point check let len = ctrl.len() assert(len in (1, 2), message: "Bezier curve expects 1 or 2 control points. Got " + str(len)) let coordinates = (start, end, ..ctrl) // Coordiantes check let t = coordinates.map(coordinate.resolve-system) return (( name: name, coordinates: (start, end, ..ctrl), custom-anchors: (start, end, ..ctrl) => { let a = (start: start, end: end) for (i, c) in ctrl.pos().enumerate() { a.insert("ctrl-" + str(i), c) } return a }, render: (ctx, start, end, ..ctrl) => { let style = styles.resolve(ctx.style, style, root: "bezier") ctrl = ctrl.pos() cmd.path( (if len == 1 { "quadratic" } else { "cubic" }, start, end, ..ctrl), fill: style.fill, stroke: style.stroke ) } ),) } /// NOTE: This function is supposed to be REPLACED by a /// new coordinate syntax! /// /// Create anchors along a path /// /// - path (path): Path /// - anchors (positional): Dictionaries of the format: /// (name: string, pos: float) /// - name (string): Element name, uses paths name, if auto #let place-anchors(path, ..anchors, name: auto) = { let name = if name == auto and "name" in path.first() { path.first().name } else { name } assert(type(name) == "string", message: "Name must be of type string") (( name: name, children: path, custom-anchors-drawables: (drawables) => { if drawables.len() == 0 { return () } let out = (:) let s = drawables.first().segments for a in anchors.pos() { assert("name" in a, message: "Anchor must have a name set") out.insert(a.name, path-util.point-on-path(s, a.pos)) } return out }, ),) } /// NOTE: This function is supposed to be removed! /// /// Put marks on a path /// /// - path (path): Path /// - marks (positional): Array of dictionaries of the format: /// (mark: string, /// pos: float, /// scale: float, /// stroke: stroke, /// fill: fill) #let place-marks(path, ..marks, size: auto, fill: none, stroke: black + 1pt, name: none) = { (( name: name, children: path, custom-anchors-drawables: (drawables) => { if drawables.len() == 0 { return () } let anchors = (:) let s = drawables.first().segments for m in marks.pos() { if "name" in m { anchors.insert(m.name, path-util.point-on-path(s, m.pos)) } } return anchors }, finalize-children: (ctx, children) => { let size = if size != auto { size } else { ctx.style.mark.size } let p = children.first() (p,); for m in marks.pos() { let scale = m.at("scale", default: size) let fill = m.at("fill", default: fill) let stroke = m.at("stroke", default: stroke) let (pt, dir) = path-util.direction(p.segments, m.pos, scale: scale) if pt != none { cmd.mark(vector.add(pt, dir), pt, m.mark, fill: fill, stroke: stroke) } } } ),) } /// Merge multiple paths /// /// - body (any): Body /// - close (bool): If true, the path is automatically closed /// - name (string): Element name #let merge-path(body, close: false, name: none, ..style) = { // No extra positional arguments from the style sink assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos())) let style = style.named() (( name: name, children: body, finalize-children: (ctx, children) => { let segments = () let pos = none let segment-begin = (s) => { return s.at(1) } let segment-end = (s) => { let type = s.at(0) if type == "line" { return s.last() } else { return s.at(2) } } while children.len() > 0 { let child = children.remove(0) assert("segments" in child, message: "Object must contain path segments") if child.segments.len() == 0 { continue } // Revert path order, if end < start //if segments.len() > 0 { // if (vector.dist(segment-end(child.segments.last()), pos) < // vector.dist(segment-begin(child.segments.first()), pos)) { // child.segments = child.segments.rev() // } //} // Connect "jumps" with linear lines to prevent typsts path impl. // from using weird cubic ones. if segments.len() > 0 { let end = segment-end(segments.last()) let begin = segment-begin(child.segments.first()) if vector.dist(end, begin) > 0 { segments.push(("line", segment-begin(child.segments.first()))) } } // Append child segments += child.segments // Sort next children by distance pos = segment-end(segments.last()) children = children.sorted(key: a => { return vector.len(vector.sub(segment-begin(a.segments.first()), pos)) }) } let style = styles.resolve(ctx.style, style) cmd.path(..segments, close: close, stroke: style.stroke, fill: style.fill) } ),) } // Render shadow of children by rendering them twice #let shadow(body, ..style) = { // No extra positional arguments from the style sink assert.eq(style.pos(), (), message: "Unexpected positional arguments: " + repr(style.pos())) let style = style.named() (( children: ctx => { let style = styles.resolve(ctx.style, style, root: "shadow") return ( ..group({ set-style(fill: style.color, stroke: style.color) translate((style.offset-x, style.offset-y, 0)) body }), ..body, ) }, ),) } // Calculate the intersections of two named paths // #let intersections(path-1, path-2, name: "intersection") = { // (( // name: name, // custom-anchors-ctx: (ctx) => { // let (ps1, ps2) = (path-1, path-2).map(x => ctx.nodes.at(x).paths) // let anchors = (:) // for p1 in ps1 { // for p2 in ps2 { // let cs = collisions.poly-poly(p1, p2) // if cs != none { // for c in cs { // anchors.insert(str(anchors.len()+1), util.revert-transform(ctx.transform, c)) // } // } // } // } // anchors // }, // ),) // } #let grid(from, to, step: 1, name: none, help-lines: false, ..style) = { let t = (from, to).map(coordinate.resolve-system) (( name: name, coordinates: (from, to), render: (ctx, from, to) => { let style = styles.resolve(ctx.style, style.named()) let stroke = if help-lines { 0.2pt + gray } else { style.stroke } let (x-step, y-step) = if type(step) == "dictionary" { ( if "x" in step {step.x} else {1}, if "y" in step {step.y} else {1}, ) } else { (step, step) }.map(util.resolve-number.with(ctx)) if x-step != 0 { for x in range(int((to.at(0) - from.at(0)) / x-step)+1) { x *= x-step x += from.at(0) cmd.path(("line", (x, from.at(1)), (x, to.at(1))), fill: style.fill, stroke: style.stroke) } } if y-step != 0 { for y in range(int((to.at(1) - from.at(1)) / y-step)+1) { y *= y-step y += from.at(1) cmd.path(("line", (from.at(0), y), (to.at(0), y)), fill: style.fill, stroke: style.stroke) } } } ),) }
https://github.com/SwampertX/cv
https://raw.githubusercontent.com/SwampertX/cv/main/pnc2024/letter.typ
typst
#set text(size: 13pt) #set par(first-line-indent: 1em, justify: true) #show link : body => text(blue, body) Dear Dr. <NAME>, I am <NAME>, an incoming second-year Master's student at #link("https://wikimpri.dptinfo.ens-cachan.fr/doku.php")[MPRI] (Parisian Masters of Research in Computer Science), in France. I am writing to express my enthusiastic interest in attending the "Proof and Computation" Autumn School 2024 at Aurachhof. My research interests lie in Type Theory, Proof Assistants, and Logic, particularly in the metatheory of proof assistants. The courses offered by this autumn school align perfectly with my research focus on proofs and computation, thus it would be a great honor to join the school in Fischbachau this September. Since May 2024, I have been undertaking my Master's Year 1 internship with <NAME> at the Cambium team in INRIA Paris, working on the project "Towards Formalizing the Guard Condition of Coq." This project aims to produce a specification of the guard checker of the Coq proof assistant, which enforces a sufficient condition for termination on fixpoints. A sound guard condition will ensure the termination of fixpoint reduction and facilitate strong normalization proofs, ultimately proving the consistency of the type theory behind the Coq proof assistant. I was pleased to have presented my work at the #link("https://www.irif.fr/reciprog/workshop-guarded-june24")[Workshop on the Guard Condition of Coq], held on 3 June by the #link("https://www.irif.fr/reciprog/index")[RECIPROG project] in Nantes, France, where it was well received. In 2022, I worked on the formalization of the Modules system of Coq in MetaCoq during my undergraduate internship under the guidance of Nicolas Tabareau. Alongside Martin Henz and <NAME>, I co-authored my #link("https://github.com/SwampertX/undergraduate-thesis")[bachelor's thesis] on this topic, which received an A grade from the National University of Singapore, where I completed a dual bachelor's degree in Mathematics and Computer Science. During the first two semesters of my Master's Year 1 (M1) in 2023-24, I studied the formalization of type theory in type theory via Category with Families under the supervision of Ambrus Kaposi. This project culminated in a small formalization of (a less-dependent version of) Category with Families in Agda. Among the courses I studied in M1, #link("http://www.lix.polytechnique.fr/Labo/Samuel.Mimram/teaching/INF551/")[INF551 Computational Logic], taught by <NAME>, was the most relevant to my research interests. I was awarded full marks (20/20) in this course, where I implemented, for the final project, a dependent type-checker / proof-assistant supporting Dependent Function, Equality, and Natural Number types. As an international student studying in Paris, I am seeking funding to attend the autumn school, which I am eager to join but cannot afford without financial assistance. I believe this is an excellent opportunity to further my research and connect with like-minded researchers and peers, as I enter my final year in my master's programme. Thank you very much for considering my application, and I look forward to your favorable response. #v(1fr) #set par(first-line-indent: 0pt, justify: true) Warmest regards,\ <NAME>
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/closure-15.typ
typst
Other
// Error: 14-15 duplicate parameter: a // Error: 23-24 duplicate parameter: b // Error: 35-36 duplicate parameter: b #let f(a, b, a: none, b: none, c, b) = none
https://github.com/VoigtSebastian/typst-CV
https://raw.githubusercontent.com/VoigtSebastian/typst-CV/main/README.md
markdown
MIT License
# CV I tried to recreate my CV in typst and it was surprisingly easy. Change it, use it, do whatever you want with it.
https://github.com/ntjess/typst-tada
https://raw.githubusercontent.com/ntjess/typst-tada/main/docs/_doc-style.typ
typst
The Unlicense
#import "@preview/tidy:0.1.0" #import tidy.styles.default: * #let show-parameter-block( name, types, content, style-args, show-default: false, default: none, ) = block( inset: 10pt, fill: rgb("ddd3"), width: 100%, breakable: style-args.break-param-descriptions, [ #text(weight: "bold", size: 1.1em, name) #h(.5cm) #types.map(x => (style-args.style.show-type)(x)).join([ #text("or",size:.6em) ]) #content #if show-default [ #parbreak() Default: #raw(lang: "typc", default) ] ] ) #let type-colors = ( "content": rgb("#a6ebe699"), "color": rgb("#a6ebe699"), "string": rgb("#d1ffe299"), "none": rgb("#ffcbc499"), "auto": rgb("#ffcbc499"), "boolean": rgb("#ffedc199"), "integer": rgb("#e7d9ff99"), "float": rgb("#e7d9ff99"), "ratio": rgb("#e7d9ff99"), "length": rgb("#e7d9ff99"), "angle": rgb("#e7d9ff99"), "relative-length": rgb("#e7d9ff99"), "fraction": rgb("#e7d9ff99"), "symbol": rgb("#eff0f399"), "array": rgb("#eff0f399"), "dictionary": rgb("#eff0f399"), "arguments": rgb("#eff0f399"), "selector": rgb("#eff0f399"), "module": rgb("#eff0f399"), "stroke": rgb("#eff0f399"), "function": rgb("#f9dfff99"), ) #let get-type-color(type) = type-colors.at(type, default: rgb("#eff0f333")) // Create beautiful, colored type box #let show-type(type) = { h(2pt) box(outset: 2pt, fill: get-type-color(type), radius: 2pt, raw(type)) h(2pt) }
https://github.com/EpicEricEE/typst-quick-maths
https://raw.githubusercontent.com/EpicEricEE/typst-quick-maths/master/tests/shorthands/test.typ
typst
MIT License
#import "/src/lib.typ": shorthands #set page(width: 4cm, height: auto, margin: 1em) #show: shorthands.with( ($|<-$, $arrow.l.stop$), ($!<-$, $arrow.l.not$), ($<-|$, $arrow.l.bar$), ($<=|$, $arrow.l.double.bar$), ($!->$, $arrow.not$), ($!=>$, $arrow.double.not$), ($!<=>$, $arrow.double.l.r.not$), ($!<==>$, $cancel(length: #35%, angle: #20deg, <==>)$), ($!|-$, $tack.not$), ($!|=$, $tack.double.not$), ($|-$, $tack$), ($|=$, $tack.double$), ($-|$, $tack.l$), ($=|$, $tack.l.double$), ($!>$, $gt.not$), ($!>=$, $gt.not.eq$), ($!<$, $lt.not$), ($!<=$, $lt.not.eq$), ($-:$, $dash.colon$), ($!!$, $excl.double$), ($??$, $quest.double$), ($?!$, $quest.excl$), ($!?$, $excl.quest$) ) // Arrows $ a |<- b \ a !<- b \ a <-| b \ a <=| b \ a !-> b \ a !=> b \ a !<=> b \ a !<==> b $ // Relations $ a !|- b \ a !|= b \ a |- b \ a |= b \ a -| b \ a =| b \ a !> b \ a !>= b \ a !< b \ a !<= b \ a -: b $ // Punctuation $ c !! \ c ?? \ c ?! \ c !? \ $
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/036.%20hs.html.typ
typst
hs.html What You'll Wish You'd Known January 2005(I wrote this talk for a high school. I never actually gave it, because the school authorities vetoed the plan to invite me.)When I said I was speaking at a high school, my friends were curious. What will you say to high school students? So I asked them, what do you wish someone had told you in high school? Their answers were remarkably similar. So I'm going to tell you what we all wish someone had told us.I'll start by telling you something you don't have to know in high school: what you want to do with your life. People are always asking you this, so you think you're supposed to have an answer. But adults ask this mainly as a conversation starter. They want to know what sort of person you are, and this question is just to get you talking. They ask it the way you might poke a hermit crab in a tide pool, to see what it does.If I were back in high school and someone asked about my plans, I'd say that my first priority was to learn what the options were. You don't need to be in a rush to choose your life's work. What you need to do is discover what you like. You have to work on stuff you like if you want to be good at what you do.It might seem that nothing would be easier than deciding what you like, but it turns out to be hard, partly because it's hard to get an accurate picture of most jobs. Being a doctor is not the way it's portrayed on TV. Fortunately you can also watch real doctors, by volunteering in hospitals. [1]But there are other jobs you can't learn about, because no one is doing them yet. Most of the work I've done in the last ten years didn't exist when I was in high school. The world changes fast, and the rate at which it changes is itself speeding up. In such a world it's not a good idea to have fixed plans.And yet every May, speakers all over the country fire up the Standard Graduation Speech, the theme of which is: don't give up on your dreams. I know what they mean, but this is a bad way to put it, because it implies you're supposed to be bound by some plan you made early on. The computer world has a name for this: premature optimization. And it is synonymous with disaster. These speakers would do better to say simply, don't give up.What they really mean is, don't get demoralized. Don't think that you can't do what other people can. And I agree you shouldn't underestimate your potential. People who've done great things tend to seem as if they were a race apart. And most biographies only exaggerate this illusion, partly due to the worshipful attitude biographers inevitably sink into, and partly because, knowing how the story ends, they can't help streamlining the plot till it seems like the subject's life was a matter of destiny, the mere unfolding of some innate genius. In fact I suspect if you had the sixteen year old Shakespeare or Einstein in school with you, they'd seem impressive, but not totally unlike your other friends.Which is an uncomfortable thought. If they were just like us, then they had to work very hard to do what they did. And that's one reason we like to believe in genius. It gives us an excuse for being lazy. If these guys were able to do what they did only because of some magic Shakespeareness or Einsteinness, then it's not our fault if we can't do something as good.I'm not saying there's no such thing as genius. But if you're trying to choose between two theories and one gives you an excuse for being lazy, the other one is probably right.So far we've cut the Standard Graduation Speech down from "don't give up on your dreams" to "what someone else can do, you can do." But it needs to be cut still further. There is some variation in natural ability. Most people overestimate its role, but it does exist. If I were talking to a guy four feet tall whose ambition was to play in the NBA, I'd feel pretty stupid saying, you can do anything if you really try. [2]We need to cut the Standard Graduation Speech down to, "what someone else with your abilities can do, you can do; and don't underestimate your abilities." But as so often happens, the closer you get to the truth, the messier your sentence gets. We've taken a nice, neat (but wrong) slogan, and churned it up like a mud puddle. It doesn't make a very good speech anymore. But worse still, it doesn't tell you what to do anymore. Someone with your abilities? What are your abilities?UpwindI think the solution is to work in the other direction. Instead of working back from a goal, work forward from promising situations. This is what most successful people actually do anyway.In the graduation-speech approach, you decide where you want to be in twenty years, and then ask: what should I do now to get there? I propose instead that you don't commit to anything in the future, but just look at the options available now, and choose those that will give you the most promising range of options afterward.It's not so important what you work on, so long as you're not wasting your time. Work on things that interest you and increase your options, and worry later about which you'll take.Suppose you're a college freshman deciding whether to major in math or economics. Well, math will give you more options: you can go into almost any field from math. If you major in math it will be easy to get into grad school in economics, but if you major in economics it will be hard to get into grad school in math.Flying a glider is a good metaphor here. Because a glider doesn't have an engine, you can't fly into the wind without losing a lot of altitude. If you let yourself get far downwind of good places to land, your options narrow uncomfortably. As a rule you want to stay upwind. So I propose that as a replacement for "don't give up on your dreams." Stay upwind.How do you do that, though? Even if math is upwind of economics, how are you supposed to know that as a high school student?Well, you don't, and that's what you need to find out. Look for smart people and hard problems. Smart people tend to clump together, and if you can find such a clump, it's probably worthwhile to join it. But it's not straightforward to find these, because there is a lot of faking going on.To a newly arrived undergraduate, all university departments look much the same. The professors all seem forbiddingly intellectual and publish papers unintelligible to outsiders. But while in some fields the papers are unintelligible because they're full of hard ideas, in others they're deliberately written in an obscure way to seem as if they're saying something important. This may seem a scandalous proposition, but it has been experimentally verified, in the famous Social Text affair. Suspecting that the papers published by literary theorists were often just intellectual-sounding nonsense, a physicist deliberately wrote a paper full of intellectual-sounding nonsense, and submitted it to a literary theory journal, which published it.The best protection is always to be working on hard problems. Writing novels is hard. Reading novels isn't. Hard means worry: if you're not worrying that something you're making will come out badly, or that you won't be able to understand something you're studying, then it isn't hard enough. There has to be suspense.Well, this seems a grim view of the world, you may think. What I'm telling you is that you should worry? Yes, but it's not as bad as it sounds. It's exhilarating to overcome worries. You don't see faces much happier than people winning gold medals. And you know why they're so happy? Relief.I'm not saying this is the only way to be happy. Just that some kinds of worry are not as bad as they sound.AmbitionIn practice, "stay upwind" reduces to "work on hard problems." And you can start today. I wish I'd grasped that in high school.Most people like to be good at what they do. In the so-called real world this need is a powerful force. But high school students rarely benefit from it, because they're given a fake thing to do. When I was in high school, I let myself believe that my job was to be a high school student. And so I let my need to be good at what I did be satisfied by merely doing well in school.If you'd asked me in high school what the difference was between high school kids and adults, I'd have said it was that adults had to earn a living. Wrong. It's that adults take responsibility for themselves. Making a living is only a small part of it. Far more important is to take intellectual responsibility for oneself.If I had to go through high school again, I'd treat it like a day job. I don't mean that I'd slack in school. Working at something as a day job doesn't mean doing it badly. It means not being defined by it. I mean I wouldn't think of myself as a high school student, just as a musician with a day job as a waiter doesn't think of himself as a waiter. [3] And when I wasn't working at my day job I'd start trying to do real work.When I ask people what they regret most about high school, they nearly all say the same thing: that they wasted so much time. If you're wondering what you're doing now that you'll regret most later, that's probably it. [4]Some people say this is inevitable — that high school students aren't capable of getting anything done yet. But I don't think this is true. And the proof is that you're bored. You probably weren't bored when you were eight. When you're eight it's called "playing" instead of "hanging out," but it's the same thing. And when I was eight, I was rarely bored. Give me a back yard and a few other kids and I could play all day.The reason this got stale in middle school and high school, I now realize, is that I was ready for something else. Childhood was getting old.I'm not saying you shouldn't hang out with your friends — that you should all become humorless little robots who do nothing but work. Hanging out with friends is like chocolate cake. You enjoy it more if you eat it occasionally than if you eat nothing but chocolate cake for every meal. No matter how much you like chocolate cake, you'll be pretty queasy after the third meal of it. And that's what the malaise one feels in high school is: mental queasiness. [5]You may be thinking, we have to do more than get good grades. We have to have extracurricular activities. But you know perfectly well how bogus most of these are. Collecting donations for a charity is an admirable thing to do, but it's not hard. It's not getting something done. What I mean by getting something done is learning how to write well, or how to program computers, or what life was really like in preindustrial societies, or how to draw the human face from life. This sort of thing rarely translates into a line item on a college application.CorruptionIt's dangerous to design your life around getting into college, because the people you have to impress to get into college are not a very discerning audience. At most colleges, it's not the professors who decide whether you get in, but admissions officers, and they are nowhere near as smart. They're the NCOs of the intellectual world. They can't tell how smart you are. The mere existence of prep schools is proof of that.Few parents would pay so much for their kids to go to a school that didn't improve their admissions prospects. Prep schools openly say this is one of their aims. But what that means, if you stop to think about it, is that they can hack the admissions process: that they can take the very same kid and make him seem a more appealing candidate than he would if he went to the local public school. [6]Right now most of you feel your job in life is to be a promising college applicant. But that means you're designing your life to satisfy a process so mindless that there's a whole industry devoted to subverting it. No wonder you become cynical. The malaise you feel is the same that a producer of reality TV shows or a tobacco industry executive feels. And you don't even get paid a lot.So what do you do? What you should not do is rebel. That's what I did, and it was a mistake. I didn't realize exactly what was happening to us, but I smelled a major rat. And so I just gave up. Obviously the world sucked, so why bother?When I discovered that one of our teachers was herself using Cliff's Notes, it seemed par for the course. Surely it meant nothing to get a good grade in such a class.In retrospect this was stupid. It was like someone getting fouled in a soccer game and saying, hey, you fouled me, that's against the rules, and walking off the field in indignation. Fouls happen. The thing to do when you get fouled is not to lose your cool. Just keep playing. By putting you in this situation, society has fouled you. Yes, as you suspect, a lot of the stuff you learn in your classes is crap. And yes, as you suspect, the college admissions process is largely a charade. But like many fouls, this one was unintentional. [7] So just keep playing.Rebellion is almost as stupid as obedience. In either case you let yourself be defined by what they tell you to do. The best plan, I think, is to step onto an orthogonal vector. Don't just do what they tell you, and don't just refuse to. Instead treat school as a day job. As day jobs go, it's pretty sweet. You're done at 3 o'clock, and you can even work on your own stuff while you're there.CuriosityAnd what's your real job supposed to be? Unless you're Mozart, your first task is to figure that out. What are the great things to work on? Where are the imaginative people? And most importantly, what are you interested in? The word "aptitude" is misleading, because it implies something innate. The most powerful sort of aptitude is a consuming interest in some question, and such interests are often acquired tastes.A distorted version of this idea has filtered into popular culture under the name "passion." I recently saw an ad for waiters saying they wanted people with a "passion for service." The real thing is not something one could have for waiting on tables. And passion is a bad word for it. A better name would be curiosity.Kids are curious, but the curiosity I mean has a different shape from kid curiosity. Kid curiosity is broad and shallow; they ask why at random about everything. In most adults this curiosity dries up entirely. It has to: you can't get anything done if you're always asking why about everything. But in ambitious adults, instead of drying up, curiosity becomes narrow and deep. The mud flat morphs into a well.Curiosity turns work into play. For Einstein, relativity wasn't a book full of hard stuff he had to learn for an exam. It was a mystery he was trying to solve. So it probably felt like less work to him to invent it than it would seem to someone now to learn it in a class.One of the most dangerous illusions you get from school is the idea that doing great things requires a lot of discipline. Most subjects are taught in such a boring way that it's only by discipline that you can flog yourself through them. So I was surprised when, early in college, I read a quote by Wittgenstein saying that he had no self-discipline and had never been able to deny himself anything, not even a cup of coffee.Now I know a number of people who do great work, and it's the same with all of them. They have little discipline. They're all terrible procrastinators and find it almost impossible to make themselves do anything they're not interested in. One still hasn't sent out his half of the thank-you notes from his wedding, four years ago. Another has 26,000 emails in her inbox.I'm not saying you can get away with zero self-discipline. You probably need about the amount you need to go running. I'm often reluctant to go running, but once I do, I enjoy it. And if I don't run for several days, I feel ill. It's the same with people who do great things. They know they'll feel bad if they don't work, and they have enough discipline to get themselves to their desks to start working. But once they get started, interest takes over, and discipline is no longer necessary.Do you think Shakespeare was gritting his teeth and diligently trying to write Great Literature? Of course not. He was having fun. That's why he's so good.If you want to do good work, what you need is a great curiosity about a promising question. The critical moment for Einstein was when he looked at Maxwell's equations and said, what the hell is going on here?It can take years to zero in on a productive question, because it can take years to figure out what a subject is really about. To take an extreme example, consider math. Most people think they hate math, but the boring stuff you do in school under the name "mathematics" is not at all like what mathematicians do.The great mathematician <NAME>. Hardy said he didn't like math in high school either. He only took it up because he was better at it than the other students. Only later did he realize math was interesting — only later did he start to ask questions instead of merely answering them correctly.When a friend of mine used to grumble because he had to write a paper for school, his mother would tell him: find a way to make it interesting. That's what you need to do: find a question that makes the world interesting. People who do great things look at the same world everyone else does, but notice some odd detail that's compellingly mysterious.And not only in intellectual matters. <NAME>'s great question was, why do cars have to be a luxury item? What would happen if you treated them as a commodity? <NAME>'s was, in effect, why does everyone have to stay in his position? Why can't defenders score goals too?NowIf it takes years to articulate great questions, what do you do now, at sixteen? Work toward finding one. Great questions don't appear suddenly. They gradually congeal in your head. And what makes them congeal is experience. So the way to find great questions is not to search for them — not to wander about thinking, what great discovery shall I make? You can't answer that; if you could, you'd have made it.The way to get a big idea to appear in your head is not to hunt for big ideas, but to put in a lot of time on work that interests you, and in the process keep your mind open enough that a big idea can take roost. Einstein, Ford, and Beckenbauer all used this recipe. They all knew their work like a piano player knows the keys. So when something seemed amiss to them, they had the confidence to notice it.Put in time how and on what? Just pick a project that seems interesting: to master some chunk of material, or to make something, or to answer some question. Choose a project that will take less than a month, and make it something you have the means to finish. Do something hard enough to stretch you, but only just, especially at first. If you're deciding between two projects, choose whichever seems most fun. If one blows up in your face, start another. Repeat till, like an internal combustion engine, the process becomes self-sustaining, and each project generates the next one. (This could take years.)It may be just as well not to do a project "for school," if that will restrict you or make it seem like work. Involve your friends if you want, but not too many, and only if they're not flakes. Friends offer moral support (few startups are started by one person), but secrecy also has its advantages. There's something pleasing about a secret project. And you can take more risks, because no one will know if you fail.Don't worry if a project doesn't seem to be on the path to some goal you're supposed to have. Paths can bend a lot more than you think. So let the path grow out the project. The most important thing is to be excited about it, because it's by doing that you learn.Don't disregard unseemly motivations. One of the most powerful is the desire to be better than other people at something. Hardy said that's what got him started, and I think the only unusual thing about him is that he admitted it. Another powerful motivator is the desire to do, or know, things you're not supposed to. Closely related is the desire to do something audacious. Sixteen year olds aren't supposed to write novels. So if you try, anything you achieve is on the plus side of the ledger; if you fail utterly, you're doing no worse than expectations. [8]Beware of bad models. Especially when they excuse laziness. When I was in high school I used to write "existentialist" short stories like ones I'd seen by famous writers. My stories didn't have a lot of plot, but they were very deep. And they were less work to write than entertaining ones would have been. I should have known that was a danger sign. And in fact I found my stories pretty boring; what excited me was the idea of writing serious, intellectual stuff like the famous writers.Now I have enough experience to realize that those famous writers actually sucked. Plenty of famous people do; in the short term, the quality of one's work is only a small component of fame. I should have been less worried about doing something that seemed cool, and just done something I liked. That's the actual road to coolness anyway.A key ingredient in many projects, almost a project on its own, is to find good books. Most books are bad. Nearly all textbooks are bad. [9] So don't assume a subject is to be learned from whatever book on it happens to be closest. You have to search actively for the tiny number of good books.The important thing is to get out there and do stuff. Instead of waiting to be taught, go out and learn.Your life doesn't have to be shaped by admissions officers. It could be shaped by your own curiosity. It is for all ambitious adults. And you don't have to wait to start. In fact, you don't have to wait to be an adult. There's no switch inside you that magically flips when you turn a certain age or graduate from some institution. You start being an adult when you decide to take responsibility for your life. You can do that at any age. [10]This may sound like bullshit. I'm just a minor, you may think, I have no money, I have to live at home, I have to do what adults tell me all day long. Well, most adults labor under restrictions just as cumbersome, and they manage to get things done. If you think it's restrictive being a kid, imagine having kids.The only real difference between adults and high school kids is that adults realize they need to get things done, and high school kids don't. That realization hits most people around 23. But I'm letting you in on the secret early. So get to work. Maybe you can be the first generation whose greatest regret from high school isn't how much time you wasted. Notes[1] A doctor friend warns that even this can give an inaccurate picture. "Who knew how much time it would take up, how little autonomy one would have for endless years of training, and how unbelievably annoying it is to carry a beeper?"[2] His best bet would probably be to become dictator and intimidate the NBA into letting him play. So far the closest anyone has come is Secretary of Labor.[3] A day job is one you take to pay the bills so you can do what you really want, like play in a band, or invent relativity.Treating high school as a day job might actually make it easier for some students to get good grades. If you treat your classes as a game, you won't be demoralized if they seem pointless.However bad your classes, you need to get good grades in them to get into a decent college. And that is worth doing, because universities are where a lot of the clumps of smart people are these days.[4] The second biggest regret was caring so much about unimportant things. And especially about what other people thought of them.I think what they really mean, in the latter case, is caring what random people thought of them. Adults care just as much what other people think, but they get to be more selective about the other people.I have about thirty friends whose opinions I care about, and the opinion of the rest of the world barely affects me. The problem in high school is that your peers are chosen for you by accidents of age and geography, rather than by you based on respect for their judgement.[5] The key to wasting time is distraction. Without distractions it's too obvious to your brain that you're not doing anything with it, and you start to feel uncomfortable. If you want to measure how dependent you've become on distractions, try this experiment: set aside a chunk of time on a weekend and sit alone and think. You can have a notebook to write your thoughts down in, but nothing else: no friends, TV, music, phone, IM, email, Web, games, books, newspapers, or magazines. Within an hour most people will feel a strong craving for distraction.[6] I don't mean to imply that the only function of prep schools is to trick admissions officers. They also generally provide a better education. But try this thought experiment: suppose prep schools supplied the same superior education but had a tiny (.001) negative effect on college admissions. How many parents would still send their kids to them?It might also be argued that kids who went to prep schools, because they've learned more, are better college candidates. But this seems empirically false. What you learn in even the best high school is rounding error compared to what you learn in college. Public school kids arrive at college with a slight disadvantage, but they start to pull ahead in the sophomore year.(I'm not saying public school kids are smarter than preppies, just that they are within any given college. That follows necessarily if you agree prep schools improve kids' admissions prospects.)[7] Why does society foul you? Indifference, mainly. There are simply no outside forces pushing high school to be good. The air traffic control system works because planes would crash otherwise. Businesses have to deliver because otherwise competitors would take their customers. But no planes crash if your school sucks, and it has no competitors. High school isn't evil; it's random; but random is pretty bad.[8] And then of course there is money. It's not a big factor in high school, because you can't do much that anyone wants. But a lot of great things were created mainly to make money. <NAME> said "no man but a blockhead ever wrote except for money." (Many hope he was exaggerating.)[9] Even college textbooks are bad. When you get to college, you'll find that (with a few stellar exceptions) the textbooks are not written by the leading scholars in the field they describe. Writing college textbooks is unpleasant work, done mostly by people who need the money. It's unpleasant because the publishers exert so much control, and there are few things worse than close supervision by someone who doesn't understand what you're doing. This phenomenon is apparently even worse in the production of high school textbooks.[10] Your teachers are always telling you to behave like adults. I wonder if they'd like it if you did. You may be loud and disorganized, but you're very docile compared to adults. If you actually started acting like adults, it would be just as if a bunch of adults had been transposed into your bodies. Imagine the reaction of an FBI agent or taxi driver or reporter to being told they had to ask permission to go the bathroom, and only one person could go at a time. To say nothing of the things you're taught. If a bunch of actual adults suddenly found themselves trapped in high school, the first thing they'd do is form a union and renegotiate all the rules with the administration.Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Lisa Randall, and <NAME> for reading drafts of this, and to many others for talking to me about high school.Why Nerds are UnpopularJapanese TranslationRussian TranslationGeorgian Translation
https://github.com/jamesrswift/springer-spaniel
https://raw.githubusercontent.com/jamesrswift/springer-spaniel/main/src/models/asterism.typ
typst
The Unlicense
#let make(symbol) = block({h(1fr);symbol;h(1fr)}) #let paragraph = make(sym.ast.triple)
https://github.com/EGmux/TheoryOfComputation
https://raw.githubusercontent.com/EGmux/TheoryOfComputation/master/unit3/complexity.typ
typst
#set heading(numbering: "1.") === 7.1 Answer each part TRUE or FALSE ==== a. $2n = O(n)$ by the definition of $O(n)$ we have *$L in O(n) <=> c L lt.eq n $* set c to 2 , then we have *$2n$*, so it must be the case that $2n in O(n)$ ==== b. $n^2 = O(n)$ by the definition, again $L in O(n) <=> c L lt.eq n$ but note that c must be n, thus $n L lt.eq n^2$ thus it must be that this case is false ==== c. $n^2 = O(n log^2 n)$ by the definition of $O(n log^2 n)$ remember that we can multiply the outside factor for the inside one, thus $L in O(log^2 n^2) <=> L lt.eq c log^2 n^2$ but, then, $2^L lt.eq 2^c n^2$, but it's not the same language anymore, thus it must be the case that $n^2$ does not belong to $O(log^2 n^2)$, false ==== d. $n log n = O(n^2)$ by the definition, $n log n in O(n^2) <=> n log n lt.eq c n^2$ , simplifying $log n^2 lt.eq c n^2$ $n^2 lt.eq 2^c 2^n^2$ again not a constant, as such is false. ==== e . $3^n = 2^O(n)$ $3 ^n in 2^O(n) <=> 3^n lt.eq 2^(c n)$ ==== f . $2^2^n = O(2^2^n)$ again, by definition $2^2^n in O(2^2^n) <=> 2^2^n lt.eq c 2^2^n$ keep applying $log$ $2^n lt.eq log c + 2^n$ repeat, one more time $2^n - 2^n lt.eq log c$ $0 lt.eq log c$ so there's a constant $>= 1$ so TRUE. === 7.2 Answer each part TRUE or FALSE ==== a. $n = o(2n)$ based on the definition of $o(n)$ $L in o(n) <=> n < c n$ if $c = 1$ then it must be the case that $n in O(n)$, but then we can always find a constant that would make this false, they have the same growth rate, thus it must be false. ==== b . $2 n = o(n^2)$ it must be the case that $n in o(n^2) <=> n lt c n^2$ thus it must also be the case that $ 2n < n^2$ for any c, thus $2 n in o(n^2)$ ==== c. $2^n = o(3^n)$ again, based on the definition $2^n in o(3^n) <=> 2^n < c 3^n$ it must be the case as well, thus TRUE. ==== d. $1 = o(n)$ by the definition $1 in O(n)$,that is a linear function always grow faster than a constant, TRUE. ==== e n = o(log n) by the definition *$n in o(log n) <=> n < c log n$* but *$log n <= n$*, thus it must be false. ==== f. *$1 = o(1/n)$* this one must be false, due to *$0 < n < 1$* being the only case for this to be true. ==== 7.4 Fill out the table described in the polynomial time algorithm for context free language recognition from Theorem 7.16 for string w = baba and CFG G: $S -> R T$\ $R -> T R | a$\ $T -> T R | b$ #table( columns: (30pt, auto, auto, auto, auto, auto), inset: 10pt, align: horizon, [], [*1*], [*2*], [*3*], [*4*], [*4*], [*1*], "T", "", "", "", "", [*2*], "", "R", "", "", "", [*3*], "", "", "T", "", "", [*4*], "", "", "", "R", "", ) // Cancelled 7.6 Show that P is closed under union, concatenation, and complement Consider the following TM #math.equation( block: true, $ M &= "\"On input" angle.l M_1,M_2,a angle.r "where" M_1"is a TM" "and" M_2" is a TM and a is a string" && \ & 1. "Run " M_1 "on input a" \ & 2. "Run " M_2 "on input b" && \ & 3. "If any of them accept, accept, else reject" && \ $, ) Due to each machine taking at most polynomial time due to $L in P$ it must be the case that step 1 takes $O(t^(k_i))$ and step 2 $O(t^(k_j))$ for some $(k_j,k_i) in N times N$ and the sum of two polynomials is a polynomial, thus it must be the case that the union of two $P$ languages is also in P. #math.equation( block: true, $ M &= "\"On input" angle.l M_1,M_2,a angle.r "where" M_1 "is a TM and " M_2 "and is a TM, a is a string" && \ & 1. "For " k=0 "to" |a| && \ & " "2. "Partition a as" (l,r) "where" l "start at position 0 of a and end at" k-1 "and r start at" k "and end at |a| position" && \ & " " " "3. "Run " M_1 "in" l "and" M_2 "in" r && \ & " " " " " "4. "If" M_1,M_2 "accepts then accept" && \ & 5. "Reject" && \ $, ) Note that we can partition a in $a^2$ splits, each partition can have at most size $|a|$ and two exists, each partition takes $O(t^(k_j))$ for $M_1$ and $O(t^(k_i))$ for $M_2$ for $(t_k,t_i) in N times N$, so as seen before the sum of polynomials is a polynomial, and the multiplication of a constant by a polynomial is a polynomail,$a^2$, in this case. As such it must be the case that concatenation of languages is in $P$ #math.equation( block: true, $ M &= "\"On input" angle.l M_1,a angle.r "where" M_1 "is a TM and a a string" && \ & 1. "Run " M_1 "on a" \ & 2. "Reject if accepts and accept if rejects" && \ $, ) Note that it must be the case that the time it takes is $O(t^k)$ where $k in N$, as such it take polynomial time, consequently the extra step is constant time, inverting the answer, thus negation of a language in P belongs to P as well === 7.7 Show that NP is closed under union and concatenation #math.equation( block: true, $ M &= "\"On input" angle.l M_1,M_2,a angle.r "where" M_1 "is a TM, " M_2 "is a TM" "and a is a string" && \ & 1. "Run" M_1 "with a as input" \ & 2. "Run" M_2 "with a as input" \ & 3. "Accept if one of them accept, otherwise reject\" " && \ \ $, ) Note that takes polynomial time for each machine, and the sum of polynomials is a poylnomial consequently it must be the case that the union of two languages in NP is in NP #math.equation( block: true, $ M &= "\"On input" angle.l M_1,M_2,a angle.r "where" M_1,M_2,a "is a TM, TM and string respectively" && \ & 1. "Partition a in a non deterministic manner" \ & " "2. "For each partition run " M_1 "on the left substring" "and " M_2 "on the right substring" && \ & " "3. "Accept if both accept" && \ & 4. "Reject" && \ \ $, ) === 7.8 Let CONNECTED = *${<G> | "G is a connected undirected graph"}$*. Analyze the algorithm given on page 185 to show that this language is in P. #math.equation( block: true, $ M &= "\"On input" angle.l G angle.r "where G is the encoding of a Graph" && \ & 1. "Select the first node of G and mark it" \ & 2. "Repeat the following stage until no new nodes are marked:" && \ & 3. " " "For each node in G, mark it if its attached by an edge to a node that is already marked" && \ & 4. "Scan all the nodes of G to determine" && \ & " " " " " " "whether they all are marked. If they are, accept; otherwise, reject\"" $, ) - the first step takes $O(1)$ so constant time - the second step takes $O(G^3)$ so linear time - the last step takes $O(G)$ so linear time so $O(G^2)$ is the final time the second step has the following time because in the worst case a node might compare with $n-1$ nodes and n nodes exist, so $O(n^3)$ === 7.9 A triangle in an undirected graph is a 3-clique. Show that TRIANGLE $in$ P, where TRIANGLE = *${angle.l G angle.r | G "contains a triangle"}$* #math.equation( block: true, $ M &= "\"On input" angle.l G angle.r "where" G "is a graph" && \ & 1. "For i = 1 to " ( G / 3 ) "where the latter is the size of all combinations of size 3 in G of nodes, do:" && \ & 2. "Test whether a combination that has not being seen is a 3-clique" && \ & " "2.1. "If it is, then accept" && \ & 4. "reject\"" && \ $, ) Note that step 1 takes *$G!/((G-3)!3!)$* and that number is *$(G(G-1)(G-2))/6$* that give us *$O(n^3)$* time complexity for this operation, the step two takes *$O(1)$* time complexity, cause a check can be done in constant time, step 4 is *$O(1)$* as well, thus it takes polynomial time to find a 3-clique. ⬚ === 7.10 Show that *$"ALL"_"DFA"$* is in P. #math.equation( block: true, $ M &= "\"On input" angle.l A angle.r "where A is a DFA" && \ & 1. "Mark the starting state" \ & 2. "Repeat until no achievable state can be marked, meaning available by starting at the start state" && \ & " " 2.1. "For each marked state, mark every state that has not been marked" && \ & " " "and is accesible by the application of a single transition function that has the current state as state argument " && \ & " " 2.2 "If a non accepting state has been marked, reject" && \ && \ & 3. "Accept\"" \ $, ) Step 1 takes *$O(1)$* time, step 2 takes, in the worst case, *$O(|"states"| + |δ_"achievable"|)$* thus a polynomial ,the other steps are *$O(1)$*, thus the total runtime is #math.equation( block: true, $ O(|"states"|+|δ_"achiveable"|) dot (O(1) + O(1)) + O(1) $, ) thus a polynomial time complexity algorithm === 7.11 In both parts, provide an anylisis of the time complexity of your algorithm. ==== a. Show that *$"EQ"_"DFA" in P$* #math.equation( block: true, $ M &= "On input" angle.l D_1,D_2 angle.r "where both are dfa's" && \ & 1. "Execute these for each dfa" D_1, D_2 && \ & " " 1.1. "Invert every state of" D_i "and create a new DFA encoded with the modifications, call it" D_3 && \ & " "1.2. "Create a new dfa " D_4 "that is the union of " D_3 , D_j && \ & " "1.3. "Run " "ALL"_"DFA" "with " D_4 "as input, " && \ & 4. "If in both runs the TM " "ALL"_"DFA" "accepts then accept, otherwise reject\"" && \ \ $, ) Note that DFA's are closed for complement and union, as seen in previous chapters. If indeed $D_2$ is equal to $D_1$ it must be the case that the complement of $D_2 union D_1$ is $Sigma^*$, but it could also be that $D_1 or D_2$ are $Sigma^*$ , thus we must deal with that case, and indeed if one of them is $Sigma^*$ the complement will be the empty language, thus not satisfying $Sigma^*$ after their union if $L_2$ is not $Sigma^*$, but in the case that both are them the construction would always return true from $"ALL"_"DFA"$. Now the time complexity analysis, step 0 takes $O(1)$, setp 1 takes $O(|"States of" "dfa"_i|)$, step 2 takes $O(|"states of " "dfa"_3| times "|state of " "dfa"_j |)$ and step 3 takes same time as previous step state 4 takes $O(1)$ time. Then the total runtime is #math.equation( block: true, $ O(1) dot (O("States of " "dfa"_i) + 2 O(|"states of " "dfa"_3| times "|state of " "dfa"_j |)) + O(1) $, ) thus a polynomial and as such it take polynomial time to decide the language. ==== b. Say that a language A is *star closed* if *$A = A^*$*. Give a polynomial time algorithm to test whether a DFA recognizes a star-closed language (Note that *$"EQ"_"NFA"$* is not known to be in P) #math.equation( block: true, $ M &= "\"On input" angle.l D,a angle.r "where D is a DFA and a is a string" && \ & 1. "For k equal to the increasing sequence of numbers that" mod a = 0 \ & " "1.1. "Split a in" a / k "sequences, each of size k" && \ & " "1.2 "For j = 0 to" j = a/k && \ & " " " "1.2.1 "Concatenate the first j sequences and run in D" && \ & " " " "1.2.2 "If it rejects, then go back to step 1 and try the next possible value of k" && \ & " " 1.3 "Accept" && \ & 2. "Reject\"" && \ $, ) Step 1 takes *$O(1) $* time , step 1.1 takes *$O(a/k)$* and step 1.2.1 takes *$j O(k)$* time and step 1.2.2 takes *$O(1)$* time and last steps take *$O(1)$* time as well. it can be seem that we have multiplication of polynomials by constant factor, thus it must be the case that is decidable in polynomial time. ⬚ === 7.12 Call graphs G and H isomorphic if the nodes of G may be reordered so that it is identical to H. Let *$"ISO" = {angle.l G,H angle.r | G "and" H "are isomorphic graphs"}$*. Show that *$"ISO" in "NP"$* #math.equation(block:true, $ M &= "\"On input" angle.l G,H angle.r "where G,H are graphs" && \ & 1. "Non deterministically select a permutation of G, call it p" \ & 2. "Exchange H nodes with the permutation nodes" && \ & 3. "Check if edges are the same in both" && \ & 4. "Accept if they are, reject otherwise" && \ $ ) step 1 takes $O(1)$ time, for each branch, step 2 takes $O(|G_"nodes"|)$ , step 3 takes *$O(|G_"nodes"| dot |H_"nodes"|)$* and last step takes *$O(1)$* thus final time complexity is polynomial and decided by a NDTM, thus ISO is an NP problem. === 7.13 Let *$"MODEXP" = {angle.l a,b,c,p angle.r | a,b,c, "and" p "are positive binary integers such that " a^b equiv c (mod p)} $*. \ *Show that MODEXP *$in P$*. (Note that the most obvious algorithm doesn't run in poly time. Hint: try it first where b is power of 2.)* #math.equation(block:true, $ M &= "On input" angle.l a,b,c,p angle.r "where a,b,c,p each is a positive binary number" && \ & 1. "Compute " a mod p, "store it as x" \ & 2. "For i=0 to " |b| "in binary" && \ & " "2.1. "If " b_i "is 1" && \ & " " " "2.1.2. "update value of y as " y x mod p && \ & " "2.2. "update x" "as" x equiv x^2 mod p && \ & 3. "if " x = c "accept, otherwise reject\"" && \ $ ) Step 1 takes *$O(1)$*, step 2 takes *$O(|b|)$* , step 2.1 takes *$O(1)$*, step 2.1.2 takes *$O(1)$* and last step takes *$O(1)$* thus is a polynomial time algorithm. === 7.14 Show that if $P = "NP"$, then every language $A in P$, except $A = "empty"$ and $A = Sigma^*$, is NP-complete. 1. Suppose that $P = "NP"$. \ 2. We now prove that *$"SAT" lt.eq_p "empty"$* is a false statement and due to that *$"empty"$* can't be NP-complete 3. Note that *$"empty"$* has 0 cardinality there's no mapping possible that allows us to partition the accepting strings and rejected strings, as such this reduction is impossible 4. We now prove that *$"SAT"^* lt.eq_p Sigma^*$* is a false statement