repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/hekzam/test
https://raw.githubusercontent.com/hekzam/test/main/write.typ
typst
#import "basics.typ": * #let wb = state("writebuffer", (:)) // Opens a file to the write buffer #let open(file) = { return wb.update(x => { x.insert(file, (:)) x }) } #let append(file, key, value) = { wb.update(x => { x.insert(file, dict_insert(x.at(file), key, value)) x }) } #let checked_new_append(file, key, value) = { wb.update(x => { x.insert(file, dict_insert(x.at(file), key, value, new: true, check: true)) x }) } #let dump(file) = { locate(loc => { wb.final(loc).at(file) }) } #let jsondump(file) = { locate(loc => { let x = wb.final(loc).at(file) write(file + ".json", jsonify_pretty(x)) }) }
https://github.com/maxgraw/bachelor
https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/2-theory/ar.typ
typst
Das "Reality-Virtuality Continuum", ursprünglich von <NAME> und <NAME> konzipiert, bietet einen Rahmen zur Unterscheidung zwischen realen und virtuellen Umgebungen. An einem Ende des Kontinuums liegt die vollständig reale Umgebung, die unverändert und unbeeinflusst von digitalen Einflüssen bleibt. Am gegenüberliegenden Ende des Spektrums befindet sich die vollständig virtuelle Realität. Innerhalb dieses Kontinuums befindet sich die Mixed Reality, die laut Milgram weiter in Augmented Reality und Augmented Virtuality unterteilt wird. Die Zuordnung entlang dieses Kontinuums basiert auf dem Anteil der realen Welt sowie virtuellen Elementen. Augmented Reality zeichnet sich durch einen überwiegenden Anteil realer Elemente aus, während bei Augmented Virtuality die virtuellen Komponenten dominieren @ar-milgram. In der wissenschaftlichen Literatur finden sich verschiedene Definitionen von Augmented Reality, wobei Ronald Azumas Definition häufig als Referenzpunkt dient. Azuma charakterisiert Augmented Reality durch drei wesentliche Merkmale. Die Kombination von realen und virtuellen Elementen, die Interaktion in Echtzeit sowie den 3D-Bezug zwischen realen und virtuellen Objekten @azuma-survey. === Interaktion Im Bereich der Augmented Reality gibt es eine Vielzahl von Interaktionsmethoden, von denen viele miteinander kombiniert werden können. Im Kontext dieser Arbeit liegt der Fokus auf Methoden, die für die Entwicklung von Anwendungen auf Basis von WebXR relevant und nutzbar sind. ==== Hand-Gesten Gesten sind natürliche Bewegungen, die eng mit der menschlichen Kommunikation verbunden sind. Die Entwicklung gestenbasierter Interaktionssysteme zielt darauf ab, eine Benutzererfahrung zu ermöglichen, die ohne physische Eingabegeräte auskommt und dadurch intuitiv nutzbar sein soll @handbook-ar @gesture-ar. Im Zuge dieser Arbeit wird zwischen Touch-Gesten und Hand-Gesten unterschieden. Im Folgenden werden zunächst Hand-Gesten betrachtet. Die Erkennung von Gesten kann durch verschiedene Technologien oder durch die Kombination mehrerer Technologien erfolgen. Song et al. @in-air-gesture beschrieben in ihrer Arbeit die Verwendung von Kamerasystemen in Kombination mit Machine-Learning-Algorithmen zur Erkennung von Handgesten. Weitere Lösungen basieren auf der Verwendung von Tiefenkameras @depth-gesture oder Handschuhen, die mit Sensoren ausgestattet sind @glove-gesture. Die Nutzung dieser Interaktionsmethode findet hierbei in einem breiten Spektrum von Anwendungen und Branchen statt. So wird die Gestensteuerung beispielsweise in der Medizin, der Industrie oder im Bereich der Unterhaltungselektronik eingesetzt @gesture-ar. Trotz der vielfältigen Anwendungsmöglichkeiten und der intuitiven Bedienung lassen sich gestenbasierte Interaktionen nicht in allen Anwendungsfällen sinnvoll einsetzen @gesture-ar. Einfache Interaktionen lassen sich hierbei leicht merken, allerdings kann die Komplexität der Interaktionen schnell ansteigen, was zu immer komplexeren Gesten führen kann. In Kombination mit einer geringen Fehlertoleranz @user-defined-gesture kann dies die Interaktionsqualität negativ beeinflussen @gesture-ar. ==== Touch-Gesten Touch-Gesten stellen eine natürliche und intuitiv nutzbare Interaktionsmethode dar. Sie basieren auf den gleichen Prinzipien wie die zuvor genannte Interaktion mittels Handgesten @handbook-ar. Die Interaktion erfolgt über das Display eines Geräts, wobei Nutzer durch Berührung oder Bewegung des Fingers auf dem Bildschirm mit der Anwendung interagieren können. Touch-Gesten sind weit verbreitet und finden in vielen Anwendungen Verwendung, wie beispielsweise in Smartphones, Tablets oder interaktiven Tischen @handheld-ar-design. Touch-Gesten bieten zahlreiche Anwendungsmöglichkeiten und sind aufgrund ihrer hohen Verfügbarkeit und Vertrautheit eine beliebte Interaktionsmethode. Jedoch stellt die Interaktion mit Augmented-Reality-Szenen eine Herausforderung dar, da die 2D-Eingabe auf ein 6DOF-System (six degrees of freedom) übertragen werden muss @handheld-ar-design. ==== Multimodal Die Interaktion über einen einzelnen Eingabekanal wird als unimodales System bezeichnet. Die Art des Eingabekanals kann hierbei variieren, beispielsweise durch die Verwendung von Handgesten, Sprachsteuerung oder Touch-Gesten @overview-multimodal. Multimodale Interaktionssysteme ermöglichen es, mehrere dieser Eingabekanäle zu kombinieren, um eine effizientere und vielseitigere Interaktion zu ermöglichen @handbook-ar. Nizam et al. stellen eine Übersicht über multimodale Interaktionen bereit. Es werden verschiedene Kombinationen von Eingabekanälen vorgestellt, die in ihrer Anzahl variieren. Beispielsweise wird die Kombination von Handgesten und Sprachsteuerung sowie die Kombination von Touch-Gesten und Sprachsteuerung beschrieben @overview-multimodal. Die Interaktion über verschiedene Eingabekanäle kann hierbei zeitgleich oder sequenziell erfolgen. In einer weiteren Studie wird die Kombination von Touch-Gesten und Handgesten beschrieben. Hierbei wird zunächst über eine Touch-Geste eine Auswahl getroffen, die anschließend durch eine Handgeste in der Augmented Reality Szene manipuliert wird @touch-and-gesture-interaction. Multimodale Interaktionen bieten eine effizientere Möglichkeit der Interaktion mit Augmented Reality-Anwendungen, setzen jedoch gleichzeitig eine höhere Lernkurve für den Nutzer voraus. Des Weiteren kann die Kombination von Eingabekanälen zu einer höheren Komplexität der Interaktion führen @overview-multimodal. === Ausgabe Für die Darstellung von Augmented Reality sind spezielle Hardwarekomponenten und Sensoren erforderlich. Diese Komponenten erfassen und analysieren die physische Umgebung, wodurch digitale Informationen nahtlos in die reale Welt eingebettet werden können. Zu den Hauptkomponenten gehören Sensoren für das Tracking sowie Eingabegeräte, die die Interaktionen der Nutzer mit der virtuellen Umgebung erfassen. ==== Handheld Handheld bezeichnet eine breite Gerätegruppe, die sich in der Anzahl und Qualität der jeweiligen Hardware und Sensoren erheblich unterscheiden kann. Diese Variation beeinflusst die Verfügbarkeit und Qualität von Funktionen wie Tracking-Technologien oder Eingabemethoden. Die gängigsten Geräte in dieser Kategorie sind Smartphones und Tablets, die über das Display eine Video-See-Through-Ansicht für Augmented Reality-Inhalte bereitstellen @vr-ar-doener. Mit zunehmender Leistungsstärke von Smartphones und Tablets eröffnen sich immer mehr Anwendungsmöglichkeiten für auf Handhelds basierte Augmented Reality-Anwendungen. Hierbei ist einer der entscheidenden Vorteile im Vergleich zu spezialisierter Hardware die weite Verbreitung und die Vertrautheit der Nutzer mit der Technologie @handheld-ar-design. Die Nutzung von Handheld-Geräten bringt spezifische Herausforderungen mit sich. Die Interaktion mit Augmented Reality Systemen erfolgt hauptsächlich über Touch-Eingaben auf dem Display. Diese Form der Interaktion erfordert die Übertragung einer 2D-Eingabe auf ein 6DOF-System (Six Degrees of Freedom), was die Interaktionsqualität einschränken kann @handheld-ar-design. Darüber hinaus basiert die Augmentierung auf der Position und Rotation der am Handheld-Gerät angebrachten Kamera, was den sogenannten Magic-Lens-Effekt einschränken kann. Dieser Effekt beschreibt den Idealfall, in dem die Perspektiven des aufgenommenen und des augmentierten Bildes übereinstimmen @vr-ar-doener. Ein weiteres Problem ist die Begrenzung des Sichtfeldes. Interaktionsmöglichkeiten sowie wichtige Informationen können sich außerhalb des Sichtfeldes des Geräts befinden, was dazu führen kann, dass diese Interaktionen oder Informationen möglicherweise nicht genutzt oder wahrgenommen werden @handheld-ar-design. ==== AR-Brillen Neben Handheld-Geräten kann auch spezialisierte Hardware wie AR-Brillen für die Darstellung von Augmented Reality-Inhalten genutzt werden. Das optische See-Through-Display ermöglicht die Überlagerung von realen und virtuellen Inhalten durch optische Durchsicht. Im Gegensatz dazu ermöglicht das Video-See-Through-Display die Darstellung von virtuellen Inhalten auf einem Bildschirm, der die reale Umgebung durch eine Kamera aufnimmt @vr-ar-doener. AR-Brillen bieten durch die Überlagerung des gesamten Sichtfeldes eine immersive Erfahrung. Im Gegensatz zu Handheld-Geräten ermöglichen sie eine freihändige Interaktion, da sie die Hände des Nutzers nicht blockieren. Allerdings sind AR-Brillen aufgrund ihrer spezialisierten Hardware und Sensoren in der Regel teurer und weniger verbreitet als Handheld-Geräte @vr-ar-doener. === Tracking Tracking umfasst den Einsatz von Technologien und Verfahren zur Bestimmung von Position und Orientierung sowohl physischer als auch virtueller Objekte. Hierbei muss das System in der Lage sein, die Bewegungen des Benutzers und der Umgebung präzise zu erfassen, um eine erfolgreiche Transformation von virtuellen Objekten durchzuführen. ==== Sensorbasiertes Tracking Sensorbasiertes Tracking nutzt verschiedene Sensoren, um die Position und Orientierung eines Geräts oder Objekts zu bestimmen. Inertialtracking ist ein schnelles und robustes Verfahren, das die Bewegung eines Geräts messen kann. Dieses Verfahren kommt ohne externe Referenzen aus, was einen klaren Vorteil gegenüber visuellen Sensoren darstellt, deren Effizienz stark von externen Faktoren beeinflusst wird @interial-tracking-system. Das System setzt sich typischerweise aus einer Kombination von Beschleunigungsmessern und Gyroskopen zusammen. Die einzelnen Sensoren werden hierbei in einer Inertialmess-Einheit (IMU) integriert @interial-tracking-system. Der Beschleunigungsmesser erfasst die lineare Beschleunigung des Geräts, wodurch die Orientierung und deren Veränderung in Bezug zur Erde bestimmt werden können. Das Gyroskop misst die Rotations- oder Winkelgeschwindigkeit des Geräts und ermöglicht so die Bestimmung der Drehbewegung. ==== Optisches Tracking Optisches Tracking beschreibt ein Verfahren, in welchem Kamerabilder benutzt werden, um die Position der Kamera sowie die Position von Objekten in der Umgebung zu bestimmen. Hierbei kann grundlegend zwischen markerbasiertem und markerlosen Verfahren unterschieden werden @vr-ar-doener. Für diese Arbeit wird auf Grundlage der Relevanz für WebXR-Anwendungen der Fokus auf markerlose Verfahren gelegt. Im Bereich der markerlosen Verfahren wird Simultaneous Localization and Mapping (SLAM) als eine der wichtigsten Technologien angesehen. SLAM ermöglicht es, die Position und Orientierung eines Geräts in Echtzeit zu bestimmen, während parallel eine Karte der Umgebung erstellt wird. Die Architektur solcher SLAM-Systeme besteht typischerweise aus mehreren Modulen, wobei drei Grundmodule in jedem System vorhanden sind @handbook-ar. Das Initialisierungsmodul nutzt Kameradaten, um eine erste Karte der Umgebung zu generieren. Hierbei wird häufig die Structure-from-Motion-Technik eingesetzt, die es ermöglicht, die Positionen visueller Merkmale in der Umgebung zu erfassen. Das Tracking-Modul übernimmt die Aufgabe, die aktuelle Position und Orientierung des Geräts zu schätzen. Es verfolgt die Bewegungen des Geräts durch die Umgebung und bestimmt die relative Position zu dieser. Das Mapping-Modul ist für die Erstellung und fortlaufende Aktualisierung der Umgebungskarte zuständig. Es speichert die Positionen der visuellen Merkmale und passt die Karte entsprechend an. Dieses Modul arbeitet langsamer als das Tracking-Modul, da es eine umfangreichere Datenverarbeitung erfordert @handbook-ar. Darüber hinaus können zusätzliche Module integriert werden, die die Zuverlässigkeit und Robustheit des Systems verbessern. Ein Beispiel hierfür ist das Relokalisierungsmodul, das bei einem Verlust der Kameraposition hilft, die damit verbundenen Tracking- und Positionsabweichungen zu korrigieren. Diese Erweiterungen tragen wesentlich zur Leistungsfähigkeit und Flexibilität von SLAM-Systemen bei @handbook-ar. Der Vorteil dieser optischen Verfahren besteht darin, dass kein Vorwissen über die Umgebungen vorhanden sein muss, was zu einer höheren Flexibilität als bei markerbasierten Verfahren führt @handbook-ar. Allerdings sind optische Verfahren stark anfällig für externe Faktoren wie Beleuchtung oder Reflektionen, die die Genauigkeit und Zuverlässigkeit der Tracking-Ergebnisse beeinträchtigen können @handbook-ar. ==== Hybrides Tracking Viele Anwendungen im Bereich der Augmented Reality benötigen eine hohe Präzision und Robustheit des Tracking-Systems. Hybride Ansätze können zur Verbesserung der Systemstabilität beitragen. Döner betont die situative Qualität verschiedener Sensoren @vr-ar-doener. Optische Verfahren können beispielsweise durch externe Einflüsse wie Beleuchtung oder Reflexionen stark beeinträchtigt werden @handbook-ar. In solchen Fällen können andere Sensortypen dazu beitragen, diese situativen Schwächen auszugleichen @vr-ar-doener @handbook-ar.
https://github.com/memset0/ZJU-Project-Report-Template
https://raw.githubusercontent.com/memset0/ZJU-Project-Report-Template/master/README.md
markdown
MIT License
# ZJU-Project-Report-Template ![License](https://img.shields.io/badge/license-MIT-blue) Typst is a new text markup language, considered the successor of LaTeX. This is yet another Zhejiang University project report template written in Typst, mainly designed for the course "Fundamentals of Data Structures (211C0020)" and "Digital Logic Design (211C0060)". **Requirement**: Typst version >= 0.11. (VS Code with the latest version of [Typst Preview](https://marketplace.visualstudio.com/items?itemName=mgt19937.typst-preview) extension installed is recommanded.) **Reminder**: Due to requirements of some specific courses, disclosing personal information is prohibited and will be punished. So use this project at your own risk. ## Configuration ### Theme Currently, I have provided two themes, corresponding to common lab reports and project reports in ZJU's Computer Science courses. | `theme: project` | `theme: lab` | | :---------------------------------------------: | :-------------------------------------------: | | ![fds_report_1](./screenshots/fds_report_1.png) | ![dd_report_1](./screenshots/dd_report_1.png) | | ![fds_report_2](./screenshots/fds_report_2.png) | ![dd_report_2](./screenshots/dd_report_2.png) | | ![fds_report_3](./screenshots/fds_report_3.png) | ![dd_report_3](./screenshots/dd_report_3.png) | ### Fonts I have configured default fallback options for serif, sans-serif, and monospace fonts, which you can set by modifying `font_serif`, `font_sans_serif`, and `font_mono` parameters. However, for better rendering experiences, Chineses font families that support arbitrary levels of font weight, such as [Source Han Serif SC](https://github.com/adobe-fonts/source-han-serif/releases/tag/2.002R), is recommanded. ## Features ### Blocks We provided a series of block functions to offer an experience that is similar to the callout feature in Obsidian. You can set the theme by modifying the `block_theme` parameter. ```typst #note(name: [Lagrange Inversion Theorem])[ Given a power serie $F(x)$ and another power series $G(x)$ related by $F(G(x))=G(F(x))=x$, then the nth coefficient of $F(x)$ is $ [x^n] F(x) = 1/n [x^(-1)] 1/(G^n (x)). $ ] ``` Some alias we have provided is as follows: `example`, `proof`, `abstract`, `summary`, `info`, `note`, `tip`, `hint`, `success`, `important`, `help`, `warning`, `attention`, `caution`, `failure`, `danger`, `error`, `bug`, `quote`, `cite`, `experiment`, `question`, `analysis`. ![themed blocks](./screenshots/themed_blocks.png) ## Contributing If you want to submit code to this project, the formatter [typstyle](https://github.com/Enter-tainer/typstyle) is recommended. Please do not contribute unformatted code.
https://github.com/storopoli/Bayesian-Statistics
https://raw.githubusercontent.com/storopoli/Bayesian-Statistics/main/slides/05-linear_regression.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "@preview/polylux:0.3.1": * #import themes.clean: * #import "utils.typ": * #import "@preview/plotst:0.2.0": plot as pplot, axis, scatter_plot, graph_plot, overlay #new-section-slide("Linear Regression") #slide(title: "Recommended References")[ - #cite(<gelman2013bayesian>, form: "prose"): - Chapter 14: Introduction to regression models - Chapter 16: Generalized linear models - #cite(<mcelreath2020statistical>, form: "prose") - Chapter 4: Geocentric Models - #cite(<gelman2020regression>, form: "prose"): - Chapter 7: Linear regression with a single predictor - Chapter 8: Fitting regression models - Chapter 10: Linear regression with multiple predictors ] #focus-slide(background: julia-purple)[ #align(center)[#image("images/memes/linear_regression.jpg")] ] #slide(title: "What is Linear Regression?")[ #let data_scatter = ( (0.5, 0.7), (1, 0.7), (2, 2.4), (3, 2.6), (4, 4.6), (5, 4.2), ) #let data_graph = ((0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)) #let x_axis = axis(min: 0, max: 5, location: "bottom") #let y_axis = axis(min: 0, max: 5, location: "left") #let pl_scatter = pplot(data: data_scatter, axes: ((x_axis, y_axis))) #let scatter_display = scatter_plot( pl_scatter, 70pt, stroke: 3pt, caption: none, ) #let pl_graph = pplot(data: data_graph, axes: (x_axis, y_axis)) #let graph_display = graph_plot( pl_graph, 70pt, stroke: 2pt + julia-blue, markings: none, caption: none, ) #overlay((scatter_display, graph_display), (360pt, 280pt)) ] #slide(title: "What is Linear Regression?")[ The ideia here is to model a dependent variable as a linear combination of independent variables. $ bold(y) = α + bold(X) bold(β) + ε $ where: - $bold(y)$ -- dependent variable - $α$ -- intercept (also called as constant) - $bold(β)$ -- coefficient vector - $bold(X)$ -- data matrix - $ε$ -- model error ] #focus-slide(background: julia-purple)[ #align(center)[#image("images/memes/assumptions.jpg")] ] #slide(title: "Linear Regression Assumptions")[ #v(3em) - model error $ε$ is independent of $bold(X)$ and $bold(y)$. - Dependent variable $bold(y)$ is continuous, unbounded, and, more importantly, "metric"-scaled, i.e. *equidistant*. - e.g. the increase from $1$ to $2$ is the same from $3$ to $4$. Generally violated when $bold(y)$ is interval-scaled. - Observations are I.I.D #footnote[independent and identically distributed.]. ] #slide(title: "Linear Regression Specification")[ To estimate the intercept $α$ and coefficients $bold(β)$ we use a Gaussian/normal likelihood function. Mathematically speaking, Bayesian linear regression is: #v(2em) $ bold(y) &tilde "Normal"(α + bold(X) bold(β), σ) \ α &tilde "Normal"(μ_α, σ_α) \ bold(β) &tilde "Normal"(μ_bold(β), σ_bold(β)) \ σ &tilde "Exponential"(λ_σ) $ ] #slide(title: "Linear Regression Specification")[ What we are missing is the prior probabilities for the model's parameters: #v(2em) - Prior Distribution for $α$ -- Knowledge that we have about the model's intercept. - Prior Distribution for $bold(β)$ -- Knowledge that we have about the model's independent variable coefficients. - Prior Distribution for $σ$ -- Knowledge that we have about the model's error. ] #slide(title: "Good Candidates for Prior Distributions")[ First, center ($μ = 0$) and standardize ($σ = 1$) the independent variables. #v(2em) - $α$ -- either a normal or student-$t$ ($ν = 3$), with mean as $μ_bold(y)$ and standard deviation as $2.5 dot σ_bold(y)$ (also you can use the median and median absolute deviation). - $bold(β)$ -- either a normal or student-$t$ ($ν = 3$), with mean $0$ and standard deviation $2.5$. - $σ$ -- anything that is long-tailed (mass towards lower values) and restrained to positive values only. Exponential is a good candidate. ] #slide(title: "Posterior Computation")[ Our aim to is to *find the posterior distribution of the model's parameters of interest* ($α$ and $bold(β)$) by computing the full posterior distribution of: #v(3em) $ P(bold(θ) | bold(y)) = P(α, bold(β), σ | bold(y)) $ ]
https://github.com/kdog3682/mathematical
https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/examples/state-and-counter-a1.typ
typst
#context { let c = counter("a") c.step() let x = c.get() c.step() c.step() panic(str(c.final().at(0))) } // #context { // let s = state("x", 1) // s.update((x) => x + 2) // panic(s.final()) // }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/009%20-%20Born%20of%20the%20Gods/004_Kiora's%20Followers.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Kiora's Followers", set_name: "Born of the Gods", story_date: datetime(day: 12, month: 02, year: 2014), author: "<NAME>", doc ) #emph[Every sea is different, but all of them are connected.] Oh, there were the usual variations. Temperature. Salinity. Pressure. She knew them, as any merfolk did, by instinct. A landbound oceanographer might spend a lifetime learning to measure what a merfolk knew in infancy. #emph[Just another way they're inferior, really.] But there were other things, things the landbound didn't even have words to describe, other sensations that painted her vision of the world. #emph[Taste] was the closest word, although in truth it wasn't very close. This water, here, on this world, flowing over her gills... #emph[tasted] different than anywhere else, on any world. #emph[And nowhere tastes like home.] This plane was pleasant enough. The seas were warm, the mana was rich, and the wildlife was plentiful, even if it was a bit... small. One of the locals had shown her how the drakes here plunged straight from sky to sea and back again, and waxed eloquent about their mastery in moving between realms. #figure(image("004_Kiora's Followers/01.gif", width: 100%), caption: [Drake Token | Art by Svetlin Velinov], supplement: none, numbering: none) She'd said nothing. It seemed polite. In any case, he clearly couldn't help her. #emph[Zendikar.] Home. She longed to return to her own world, with its wild and cantankerous temperament. Most worlds were whales—elegant, peaceful, toothless. Zendikar was a shark, and it had been too long since she'd swum in the presence of its power. But she couldn't return to Zendikar. Not yet. Not without a weapon to fight the monstrosities called the Eldrazi. And so her search continued. #emph[Planeswalking, they call it. Ha.] Kiora swam. She moved deeper, into darkness and cold and pressure. It helped her focus, to leave one world behind, to find another. She gathered the languid mana of the deeps and pushed against the walls of the world. It was risky, to venture out into the Blind Eternities with no destination in mind. But the sea helped. The sea guided. She burst into the void and swam, out of one ocean and into another. The universe fractured around her, and she tumbled through a thick and endless nothing. It was like being far beneath the sea, in the deepest places. The pressure was immense, all her senses blinded. All that remained was the vague sense of motion, and of things, #emph[worlds] , immense and unthinking, drifting silently through this sea that was no sea. And then—somewhere. Light, and sound, and motion. Water. Another ocean. Kiora swam, and tasted a new world. Warm, clean salt water flowed through her gills, with not a hint of artificial contamination. There was a tang of sulfur—volcanism, whether on land or down in the deeps. An active world. The sun shone down through a hundred feet of crystal clarity, and swift strong currents pulled her along. From behind and above came the clumsy slap of oars and the creaking of dead wood. Here, as elsewhere, the landbound clung to their little rafts and crawled across the skin of her world—needing the ocean's bounty, fearing its mysteries. She glanced up at the little eggshell of a boat, a distant speck making its ungainly way across the sea. A glance. That was all it deserved. In a boat like that, they wouldn't be too far from shore—and, indeed, hazy with distance, she could make out towering cliffs rising toward the surface. Kiora swam in the opposite direction, tasting this new place, feeling out its mana. In the distance, some of the local wildlife frolicked at the surface—some kind of fish-horses, with two front hooves and long, scaled tails. She'd heard of such things, even heard of merfolk riding them, but she'd never seen them. Well, now she could say she had. Beyond that, they did not interest her. #figure(image("004_Kiora's Followers/02.jpg", width: 100%), caption: [Breaching Hippocamp | Art by <NAME>], supplement: none, numbering: none) She moved deeper into dimmer waters, reaching out with all her senses, straining for some trace of the great ones that dwelt in the deepest places on nearly every world. There was nothing—only a vast, deep darkness. She sent out a pulse of mana, calling them, but heard no answer. #emph[I don't have time for this.] Kiora stopped, hanging in the water column, and began gathering mana. She was trying to catch the attention of some very big animals, and sometimes that took a very big spell. She floated, eyes closed, every spine and fin extended with the effort. Far beneath her, in depths where the sun could not reach, water began to move. Immense and sluggish currents flowed together directly below her, momentum building as more water rushed in. Inexorably, a massive pillar of water surged inward and upward, toward her. After what seemed like hours, Kiora swam back toward the surface, dragging an enormous upwelling of water behind her. She was throwing a lot of weight around, and if experience was any guide, the titans of the deep would emerge from their hiding places to investigate. The rush of water passed her, enveloped her, gaining speed as it thundered toward the surface. It was cold, brutally cold, and tasted of strangeness and age. She tumbled freely for a moment, savoring the sensation of the ocean as it truly was—not the chopping waves the surface-dwellers imagined when they thought of "the sea," but vast volumes of water and darkness where so much life and mana lurked unnoticed. The tower of water swept her up, splayed out as it neared the surface, and moved outward as a massive wave. Kiora surfaced, blinking as she adjusted to the sunlight and the air, and watched. In the distance, the boat she'd spotted earlier bucked and rolled beneath the wave, the sailors clinging to its masts and guardrails. She ducked under the water and listened. She couldn't see the wave hit the shore she'd glimpsed earlier, but she heard it. The ocean rang like a bell. #figure(image("004_Kiora's Followers/03.jpg", width: 100%), caption: [Whelming Wave | Art by <NAME>], supplement: none, numbering: none) Kiora waited, and listened, and watched. Waves slapped. Dolphins chattered. The surface of the water soon looked and felt exactly as it had when she arrived. #emph[The sea is ancient, but it has a short memory.] She heard no further stirrings in the depths, sensed no roiling tide of flesh and hunger rising up to meet her. She #emph[knew] they were down there. Where were they? She needed more information, and she wasn't going to get it here. More focus. More mana. A vast dark body took shape beneath her, a leviathan from another world. Planeswalking, wave-making, now summoning—she was pushing herself to the limit. But she wasn't in the mood to wait. #figure(image("004_Kiora's Followers/04.gif", width: 100%), caption: [Trench Gorger | Art by <NAME>], supplement: none, numbering: none) The leviathan rose beneath her and she clung to its spines. It breached, and she laughed wildly before it, and she, slammed back into the water. She willed it toward that far-off shore, and it surged forward, tail pumping back and forth. Water and wind rushed past her in turns as the creature's enormous bulk broke the surface, heaved forward, and sunk back down to rise again. She'd been riding only a few minutes when a group of heads popped up out of the water in her path. Locals. Good. Now she might get some answers. She willed the leviathan to a halt and stood as it settled patiently in the water, looming over the native merfolk. Each merfolk's head bore a tall crest that trailed out behind it. She would look as alien to them as they did to her, but that could be an advantage. A dozen pairs of eyes peered up at her, filled with fear and awe. That was a good start. "Where am I?" she asked. The natives exchanged glances, and one of them swam forward to speak. "Near the human polis of Meletis," he said. Useless. She glared down at him and waited. "In the Siren Sea," he said. She frowned and gestured all around—to the sea, the land, the sky. "Where am I?" she asked again. The speaker's eyes widened, and his fellows murmured to each other. She picked out #emph[Nyx] and #emph[Thassa] and something about #emph[the Silence.] "You are on #emph[Theros] ," he said. "You are in the mortal world." #figure(image("004_Kiora's Followers/05.jpg", width: 100%), caption: [Kiora's Follower | Art by <NAME>], supplement: none, numbering: none) She smiled but said nothing, letting them talk among themselves. There was something strange about this world, and she wasn't about to let on that she didn't understand it. "...Thassa herself, returned to us!" "...doesn't bear the mark of Nyx. How could she be..." "Fool! A god can appear however she..." God. Now #emph[that] was interesting. "Enough," said Kiora. "You have questions." The speaker considered his words. He wasn't an idiot, then. Good. "Who are you?" he asked. "Do you truly doubt me?" "Of course not," he said, eyes roving over the closed maw of the leviathan. "We tritons are ever in your service. Only..." "That sounds like doubt," she said. "How is it that you defy the Silence, my lady?" "The Silence?" "When Kruphix spoke, and the gods retreated into Nyx," he said, "we called their absence—your absence—the Silence. Our prayers go unanswered. The night sky is filled with darkness and unmoving stars. We are frightened." It seemed there was much about this world she didn't understand. Maybe later she could find a human and play the simple merfolk. For now... "I move with the currents," she said. "The Silence does not bind me." "We were led to believe it bound all gods," said the speaker. "It was a human's crime that brought the Silence," said one of the other tritons. "The Sun's Champion slew Nylea's pet hydra. Why should that matter to Thassa, or to us? Why should we suffer for the misdeeds of the drywalkers?" Kiora smiled. "Why indeed?" She silently commanded the leviathan to lower its head, so the water lapped at her feet. #figure(image("004_Kiora's Followers/06.jpg", width: 100%), caption: [Kiora, the Crashing Wave | Art by <NAME>], supplement: none, numbering: none) "You," she said, pointing to the speaker. "Join me." She held out a hand. The triton took it, and stepped up onto the leviathan's broad snout. He was taller than her, and handsome, in a strange way. The leviathan raised its head above the waves again, so the two could speak privately. "What's your name?" "Kalemnos, my lady." "And do you believe I am Thassa?" "...No," he said. "I do not think Thassa would so brazenly defy the eldest of the gods." "Good," she said. "Then who do you think I am?" "I believe you may be her emissary, sent to guide us while she is absent." "And when she returns?" "Then I suppose we will find out who you really are," he said. She grinned. "I like you," she said. "I also have a sea monster. Want to help me out?" He glanced down at the assembled tritons. The leviathan's jaws could easily close around all of them at once. "I would like nothing better," he said. "Good!" she said. "Now then. I'm looking for Thassa's mightiest children—leviathans, serpents, that sort of thing. I called, but none came. Where are they?" "The sea is vast, and even the tritons do not know its boundaries," said Kalemnos. "The krakens come when they will, or when Thassa does." "Then consider this a quest from Thassa," said Kiora. "If she is not here to plumb the depths for you, you must explore them yourselves. Hang on to something, will you?" Kalemnos gripped one of the leviathan's fins as it turned and swam, keeping its massive head above water. "Follow me!" she yelled to the tritons. They vanished into the water and swam behind her, riding the leviathan's wake. She turned to Kalemnos, who was clinging desperately but bravely to the titan's pebbled back. "Now then," she said. "Tell me more about these krakens." Kalemnos began to speak, about creatures that could lay waste to land and sea alike, fearsome monsters that seemingly only the gods could command. #emph[We'll see about that.] Kiora lounged on the leviathan's head, exhausted from her spellcasting but far too proud to show it. The sun warmed her skin, and the spraying sea moistened it. She rode in silence, enjoying the cadence of Kalemnos's voice and the power promised by his tales. The leviathan swam with steady strokes, away from the shore, toward the open water and all the secrets it held. They were hers for the taking. All she had to do was ask.
https://github.com/vEnhance/1802
https://raw.githubusercontent.com/vEnhance/1802/main/lamv.typ
typst
MIT License
#import "@local/evan:1.0.0":* #let poonen = link("https://math.mit.edu/~poonen/notes02.pdf")[Poonen's notes] #show: evan.with( title: [Linear Algebra and Multivariable Calculus], subtitle: [Notes from 18.02 Fall 2024], author: "<NAME>", date: datetime.today(), ) #toc #pagebreak() #include "src/preface.typ" #pagebreak() #include "src/type-safety.typ" #pagebreak() #part[Part Alfa: Linear Algebra of Vectors] For comparison, Part Alfa corresponds approximately to §1, §2, §3.9 of #poonen. #include "src/vectors.typ" #pagebreak() #include "src/dotprod.typ" #pagebreak() #include "src/crossprod.typ" #pagebreak() #part[Part Bravo: Linear Algebra of Matrices] For comparison, Part Bravo corresponds approximately to §3, §4, §6 of #poonen. #include "src/matrix.typ" #pagebreak() #include "src/basis.typ" #pagebreak() #include "src/eigen.typ" #pagebreak() #part[Part Charlie: Review of complex numbers] For comparison, Part Charlie (not including the review) corresponds approximately to §11 of #poonen. #include "src/complex.typ" #pagebreak() #include "src/mt1.typ" #pagebreak() #part[Part Delta: Parametric side-quest] For comparison, Part Delta corresponds approximately to §5 and §7 of #poonen. #include "src/parametric.typ" #pagebreak() #part[Part Echo: Multivariable differentiation] For comparison, Part Echo corresponds approximately to §8 and §12.1-§12.3 of #poonen. #include "src/level.typ" #pagebreak() #include "src/partial.typ" #pagebreak() #include "src/grad.typ" #pagebreak() #part[Part Foxtrot: Optimization] For comparison, Part Foxtrot corresponds approximately to §9 and §12.4-§12.6 of #poonen. #include "src/minmax.typ" #pagebreak() #include "src/opt.typ" #pagebreak() #include "src/mt2.typ" #pagebreak() #part[Part Golf: Multivariate integrals] For comparison, Part Golf corresponds to §13 and §17 of #poonen. #include "src/ipep.typ" #pagebreak() #include "src/ints.typ" #pagebreak() #include "src/chvar.typ" #pagebreak() #include "src/polar.typ" #pagebreak() #include "src/triple.typ" #pagebreak() #include "src/paraint.typ" #pagebreak() #part[Part Hotel: Grad, Curl, and Div] For comparison, Part Hotel corresponds to §14, §15, §18, §19, §20, §21 of #poonen. #include "src/vecfield.typ" #pagebreak() #include "src/gcd.typ" #pagebreak() #include "src/stokes.typ" #pagebreak() #part[Solutions to mock midterm problems] #include "src/sol-mt1.typ" #pagebreak() #include "src/sol-mt2.typ" #pagebreak() #part[Solutions to normal exercises] #include "src/sol-bravo.typ" #pagebreak() #include "src/sol-charlie.typ" #pagebreak() #include "src/sol-foxtrot.typ" #pagebreak() #part[Appendix] #include "src/appendix.typ"
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/可视化/椭圆/tuoyuan.typ
typst
= ellipse 具有可选内容的椭圆。 #image("1.png") #image("2.png") #image("3.png")
https://github.com/justinvulz/typst_packages
https://raw.githubusercontent.com/justinvulz/typst_packages/main/symbol.typ
typst
#let negspace = [#h(-0.005em)] #let implies = [$==>$] #let st = $space s.t. space $ #let cir = $circle.stroked.tiny$ #let coinv(a,b) = $[#a,#b)$ #let leq = $<=$ #let iso = $tilde.equiv$
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/stonewall/0.1.0/stonewall.typ
typst
Apache License 2.0
#let trans = ( rgb("#F7A8D8"), rgb("#55CDFC"), rgb("#ffffff"), rgb("#55CDFC"), rgb("#F7A8D8"), ); #let graysexual = ( rgb("#740194"), rgb("#aeb1aa"), rgb("#ffffff"), rgb("#aeb1aa"), rgb("#740194") ); #let nonbinary = ( rgb("#fcf434"), rgb("#ffffff"), rgb("#9c59d1"), rgb("#2c2c2c") ) #let blacktrans = ( rgb("#F7A8D8"), rgb("#55CDFC"), rgb("#000000"), rgb("#55CDFC"), rgb("#F7A8D8"), ) #let gay = ( rgb("#078d70"), rgb("#26ceaa"), rgb("#98e8c1"), rgb("#ffffff"), rgb("#7bade2"), rgb("#5049cc"), rgb("#3d1a78") ) #let trigender = ( rgb("#ff95c5"), rgb("#9581ff"), rgb("#67d966"), rgb("#9581ff"), rgb("#ff95c5"), ) #let genderfaun = ( rgb("#fcd689"), rgb("#fff09b"), rgb("#faf9cd"), rgb("#ffffff"), rgb("#8eded9"), rgb("#8cacde"), rgb("#9782ec"), ) #let polygender = ( rgb("#000000"), rgb("#939393"), rgb("#ed94c5"), rgb("#f5ed81"), rgb("#64bbe6"), ) #let multisexual = ( rgb("#7e55c7"), rgb("#ffffff"), rgb("#9bdbe8"), rgb("#f14e98"), ) #let biromantic = ( rgb("#d70170"), rgb("#e55aa2"), rgb("#734f95"), rgb("#a48cba"), rgb("#0038a7"), rgb("#597dc6"), ) #let demisexual = ( rgb("#ffffff"), rgb("#000000"), rgb("#6e0070"), rgb("#d2d2d2") ) #let demigirl = ( rgb("#7f7f7f"), rgb("#c4c4c4"), rgb("#fdadc8"), rgb("#ffffff") ) #let demiboy = ( rgb("#7f7f7f"), rgb("#c4c4c4"), rgb("#9dd7ea"), rgb("#ffffff"), ) #let genderfae = ( rgb("#97c3a5"), rgb("#c3deae"), rgb("#f9facd"), rgb("#ffffff"), rgb("#fca2c4"), rgb("#db8ae4"), rgb("#a97edd"), ) #let genderflux = ( rgb("#f57694"), rgb("#f2a3b9"), rgb("#cfcfcf"), rgb("#7be1f5"), rgb("#3ecdfa"), rgb("#fff48c"), ) #let pangender = ( rgb("#fff798"), rgb("#ffddcd"), rgb("#ffebfb"), rgb("#ffffff"), ) #let genderfloren = ( rgb("#54c2bd"), rgb("#aedeb2"), rgb("#f9face"), rgb("#ffffff"), rgb("#f9face"), rgb("#f3d09f"), rgb("#fba78a"), ) #let neptunic = ( rgb("#039bba"), rgb("#3ad5c8"), rgb("#74e9d4"), rgb("#a1e6ef"), rgb("#99b0ea"), rgb("#9799ef"), ) #let multigender = ( rgb("#3f47cd"), rgb("#00a3e8"), rgb("#fa7f27"), rgb("#00a3e8"), rgb("#3f47cd"), ) #let bigender = ( rgb("#c479a2"), rgb("#eda5cd"), rgb("#d6c7e8"), rgb("#ffffff"), rgb("#d6c7e8"), rgb("#9ac7e8"), rgb("#6d82d1"), ) #let boyflux = ( rgb("#d8e9f8"), rgb("#6eacf5"), rgb("#033570"), rgb("#9fedac"), rgb("#033570"), rgb("#6eacf5"), rgb("#d8e9f8"), ) #let demiromantic = ( rgb("#ffffff"), rgb("#000000"), rgb("#339933"), rgb("#d2d2d2"), ) #let queerplatonic = ( rgb("#f89fc9"), rgb("#2e2826"), rgb("#7e7e7e"), rgb("#ffffff"), rgb("#7e7e7e"), rgb("#2e2826"), rgb("#f89fc9"), ) #let queer = ( rgb("#ff0000"), rgb("#ff8e00"), rgb("#ffff00"), rgb("#008e00"), rgb("#00c0c0"), rgb("#400098"), rgb("#8e008e"), ) #let agender = ( rgb("#000000"), rgb("#bcc4c7"), rgb("#ffffff"), rgb("#b7f684"), rgb("#ffffff"), rgb("#bcc4c7"), rgb("#000000"), ) #let genderqueer = ( rgb("#b57edc"), rgb("#ffffff"), rgb("#4a8123"), ) #let intersex = ( rgb("#ffd800"), rgb("#7902aa"), ) #let omnisexual = ( rgb("#fe9ace"), rgb("#ff53bf"), rgb("#200044"), rgb("#6760fe"), rgb("#8ea6ff"), ) #let polysexual = ( rgb("#f714ba"), rgb("#01d66a"), rgb("#1594f6"), ) #let genderfluid = ( rgb("#ff76a4"), rgb("#ffffff"), rgb("#c011d7"), rgb("#000000"), rgb("#2f3cbe"), ) #let aromantic = ( rgb("#3da542"), rgb("#a7d379"), rgb("#ffffff"), rgb("#a9a9a9"), rgb("#000000"), ) #let pansexual = ( rgb("#ff218c"), rgb("#ffd800"), rgb("#21b1ff"), ) #let asexual = ( rgb("#000000"), rgb("#a3a3a3"), rgb("#ffffff"), rgb("#800080"), ) #let bisexual = ( rgb("#d60270"), rgb("#9b4f96"), rgb("#0038a8") ) #let lesbian = ( rgb("#d52d00"), rgb("#ef7627"), rgb("#ff9a56"), rgb("#ffffff"), rgb("#d162a4"), rgb("#b55690"), rgb("#a30262") ) #let flags = ( ("trans",trans), ("graysexual",graysexual), ("nonbinary",nonbinary), ("blacktrans",blacktrans), ("gay",gay), ("trigender",trigender), ("genderfaun",genderfaun), ("polygender",polygender), ("multisexual",multisexual), ("biromantic",biromantic), ("demisexual",demisexual), ("demigirl",demigirl), ("demiboy",demiboy), ("genderfae",genderfae), ("genderflux",genderflux), ("pangender",pangender), ("genderfloren",genderfloren), ("neptunic",neptunic), ("multigender",multigender), ("bigender",bigender), ("boyflux",boyflux), ("demiromantic",demiromantic), ("queerplatonic",queerplatonic), ("queer",queer), ("agender",agender), ("genderqueer",genderqueer), ("intersex",intersex), ("omnisexual",omnisexual), ("polysexual",polysexual), ("genderfluid",genderfluid), ("aromantic",aromantic), ("pansexual",pansexual), ("asexual",asexual), ("bisexual",bisexual), ("lesbian",lesbian), )
https://github.com/levinion/typst-dlut-templates
https://raw.githubusercontent.com/levinion/typst-dlut-templates/main/templates/translate/main.typ
typst
MIT License
#import "../util/style.typ":font_family,font_size #import "./cover.typ":cover #import "../util/functions.typ":empty_box #let three_line_table(values, caption: none, columns: auto)={ let _three_line_table(values) = { let tlt_header(content) = { set align(center) rect(width: 100%, stroke: (bottom: 0.3pt), [#content]) } let tlt_cell(content) = { set align(center) rect(width: 100%, stroke: none, [#content]) } let tlt_row(r) = { (..r.map(tlt_cell).flatten()) } rect( stroke: (bottom: 0.3pt, top: 0.3pt), inset: 0pt, outset: 0pt, grid( columns: auto, rows: auto, // table title grid(columns: columns, ..values.at(0).map(tlt_header).flatten()), grid(columns: columns, ..values.slice(1).map(tlt_row).flatten()), ), ) } figure(_three_line_table(values), caption: caption, kind: table) } #let equa(content, caption: "")={ figure(content, caption: caption, kind: "equation", supplement: "equation") } #let pic(content, caption: "")={ figure(content, caption: caption, kind: image) } #let bold(content)={ text(font: font_family.songti_bold, weight: "bold", content) } #let translate( content, chinese_title: "外文的中文题目", english_title: "The title of foreign language", author: "", workplace: "", faculty: "", major: "", name: "", id: "", sup: "", date: "", abstract: none, keywords: (), )={ // set text(lang: "zho") set heading(numbering: "1.1.1 ") show heading:it=>{ set align(left) set text(weight: "regular") set par(leading: 1.5em, first-line-indent: 0em) if it.level == 1 { set text(font: font_family.heiti, size: font_size.xiao_san) set block(below: 25pt) it + empty_box } else if it.level == 2 { set text(font: font_family.heiti, size: font_size.si) set block(above: 1.5em, below: 18pt) it + empty_box } else { set text(font: font_family.heiti, size: font_size.xiao_si) set block(above: 1.5em, below: 15pt) it } empty_box } show figure:it=>{ set align(center) set text(font: font_family.songti, size: font_size.wu) v(1em) let num(kind) = locate( loc=>{ let chap = counter(heading.where(level: 1)).at(loc).first() let chap_loc = query(heading.where(level: 1), loc).at(chap - 1).location() let num_before = counter(figure.where(kind: kind)).at(chap_loc).first() let count = counter(figure.where(kind: kind)).at(loc).first() str(chap) + "." + str(count - num_before) }, ) if it.kind == image and it.caption != none { it.body "图" + num(image) + " " + it.caption.body v(1em) } else if it.kind == table and it.caption != none { text(size: font_size.wu)[ #{ "表" + num(table) + " " + it.caption.body it.body v(1em) } ] + empty_box } else if it.kind == "equation" { grid( columns: (20fr, 1fr), it.body, align(center + horizon)[(#num("equation"))], ) } else { it } } show ref:it=>{ let el = it.element if el != none { let num(kind) = locate( loc=>{ let el_loc = el.location() let chap = counter(heading.where(level: 1)).at(el_loc).first() let chap_loc = query(heading.where(level: 1), el_loc).at(chap - 1).location() let num_before = counter(figure.where(kind: kind)).at(chap_loc).first() let count = counter(figure.where(kind: kind)).at(el_loc).first() str(chap) + "." + str(count - num_before) }, ) if el.kind == image { "图" + num(image) } else if el.kind == table { "表" + num(table) } else if el.kind == "equation" { "公式" + num("equation") } } else { it } } cover(chinese_title, english_title, faculty, major, name, id, sup, date) set page( margin: (top: 4.3cm, bottom: 3.3cm, left: 2.5cm, right: 2.5cm), footer: { set align(center) set text(font: font_family.songti, size: font_size.xiao_wu) counter(page).display("-1-") }, numbering: "1", header: { set align(center) set text(font: font_family.songti, size: font_size.wu, weight: "regular") rect(width: 100%, stroke: (bottom: 0.5pt + black))[#chinese_title] }, ) counter(page).update(1) align( center, )[ #par( leading: 1em, )[ #text( font: font_family.songti_bold, size: font_size.san, weight: "medium", )[#chinese_title]\ #text( font: font_family.songti_bold, size: font_size.xiao_san, weight: "medium", )[#author]\ #text( font: font_family.songti_bold, size: font_size.si, weight: "regular", )[#workplace] ] ] set text(font: font_family.songti, size: font_size.xiao_si) set par(justify: false, leading: 1em, first-line-indent: 2em) show par:set block(spacing: 1em) set enum(numbering: "(1)", indent: 2em) show enum:it=>{ set block(spacing: 1.25em) it } [#h(-2em)摘要:] parbreak() abstract parbreak() text(font: font_family.heiti, size: font_size.xiao_si, weight: "medium")[ #h(-2em)关键词: #keywords.join(";") ] v(1em) content pagebreak(weak: true) }
https://github.com/ymgyt/techbook
https://raw.githubusercontent.com/ymgyt/techbook/master/math/number/number.typ
typst
== ルート $sqrt(a)$ は2乗してaになる数のうち正のものを表す(定義) \ $ sqrt(a^2) = |a| $ 2乗して$a^2$になる数はaと-aがある。$a < 0$のとき(a = -2)、2乗して4になる正の数は$-a$(-(-2))とする必要があり、この操作を絶対値で表現している == 絶対値 以下が成り立つ $ abs(a) &= n <=> a = n or a = -n \ abs(a) &< n <=> -n < a < n \ abs(a) &> n <=> a < -n or n < a $
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/bracket.typ
typst
Apache License 2.0
$((,(#[)],)))$ #for i in range(0) [)] #if true [)] else if false [}] else [}] #while false [)]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/pinit/0.1.0/README.md
markdown
Apache License 2.0
# Pinit Pin things as you like, especially useful for creating slides. ## Example ### Pin things as you like Have a look at the source [here](./examples/example.typ). ![Example](./examples/example.png) ### Dynamic Slides Have a look at the pdf file [here](./examples/example.pdf). ![Example Pages](./examples/example-pages.png) ## Usage The idea of pinit is pinning pins on the normal flow of the text, and then placing the content on the page by `absolute-place` function. For example, we can highlight text and add a tip by pins simply: ```typ #import "@preview/pinit:0.1.0": * #set text(size: 24pt) A simple #pin(1)highlighted text#pin(2). #pinit-highlight(1, 2) #pinit-point-from(2)[It is simple.] ``` ![simple-demo](./examples/simple-demo.png) ## Outline - [Pinit](#pinit) - [Example](#example) - [Pin things as you like](#pin-things-as-you-like) - [Dynamic Slides](#dynamic-slides) - [Usage](#usage) - [Outline](#outline) - [Reference](#reference) - [`pin`](#pin) - [`pinit`](#pinit-1) - [`absolute-place`](#absolute-place) - [`pinit-place`](#pinit-place) - [`pinit-rect`](#pinit-rect) - [`pinit-highlight`](#pinit-highlight) - [`pinit-line`](#pinit-line) - [`pinit-arrow`](#pinit-arrow) - [`pinit-point-to`](#pinit-point-to) - [`pinit-point-from`](#pinit-point-from) - [`simple-arrow`](#simple-arrow) - [Acknowledgements](#acknowledgements) - [License](#license) ## Reference ### `pin` Pinning a pin in text, the pin is supposed to be unique in one page. ```typ #let pin(name) = { .. } ``` **Arguments:** - `name`: [`integer` or `string` or `any`] &mdash; Name of pin, which can be any types with unique `repr()` return value, such as integer and string. ### `pinit` Query positions of pins in the same page, then call the callback function `func`. ```typ #let pinit(pins, func) = { .. } ``` **Arguments:** - `pins`: [`pin` or `array`] &mdash; Names of pins you want to query. It is supposed to be a pin, or an array of pins. - `func`: [`(positions) => { .. }`] &mdash; A callback function accepting an array of positions (or a single position) as a parameter. Each position is a dictionary like `(page: 1, x: 319.97pt, y: 86.66pt)`. You can use the `absolute-place` function in this callback function to display something around the pins. ### `absolute-place` Place content at a specific location on the page relative to the top left corner of the page, regardless of margins, current containers, etc. > This function comes from [typst-drafting](https://github.com/ntjess/typst-drafting). ```typ #let absolute-place( dx: 0em, dy: 0em, content, ) = { .. } ``` **Arguments:** - `dx`: [`length`] &mdash; Length in the x-axis relative to the left edge of the page. - `dy`: [`length`] &mdash; Length in the y-axis relative to the top edge of the page. - `content`: [`content`] &mdash; The content you want to place. ### `pinit-place` Place content at a specific location on the page relative to the pin. ```typ #let pinit-place( dx: 0pt, dy: 0pt, pin-name, body, ) = { .. } ``` **Arguments:** - `dx`: [`length`] &mdash; Offset X relative to the pin. - `dy`: [`length`] &mdash; Offset Y relative to the pin. - `pin-name`: [`pin`] &mdash; Name of the pin to which you want to locate. - `body`: [`content`] &mdash; The content you want to place. ### `pinit-rect` Draw a rectangular shape on the page **containing all pins** with optional extended width and height. ```typ #let pinit-rect( dx: 0em, dy: -1em, extended-width: 0em, extended-height: 1.4em, pin1, pin2, pin3, // Optional ..pinX, ..args, ) = { .. } ``` **Arguments:** - `dx`: [`length`] &mdash; Offset X relative to the min-left of pins. - `dy`: [`length`] &mdash; Offset Y relative to the min-top of pins. - `extended-width`: [`length`] &mdash; Optional extended width of the rectangular shape. - `extended-height`: [`length`] &mdash; Optional extended height of the rectangular shape. - `pin1`: [`pin`] &mdash; One of these pins. - `pin2`: [`pin`] &mdash; One of these pins. - `pin3`: [`pin`] &mdash; One of these pins, optionally. - `...args`: Additional named arguments or settings for [`rect`](https://typst.app/docs/reference/visualize/rect/), like `fill`, `stroke` and `radius`. ### `pinit-highlight` Highlight a specific area on the page with a filled color and optional radius and stroke. It is just a simply styled `pinit-rect`. ```typ #let pinit-highlight( fill: rgb(255, 0, 0, 20), radius: 5pt, stroke: 0pt, dx: 0em, dy: -1em, extended-width: 0em, extended-height: 1.4em, pin1, pin2, pin3, // Optional ..pinX, ...args, ) = { .. } ``` **Arguments:** - `fill`: [`color`] &mdash; The fill color for the highlighted area. - `radius`: [`length`] &mdash; Optional radius for the highlight. - `stroke`: [`stroke`] &mdash; Optional stroke width for the highlight. - `dx`: [`length`] &mdash; Offset X relative to the min-left of pins. - `dy`: [`length`] &mdash; Offset Y relative to the min-top of pins. - `extended-width`: [`length`] &mdash; Optional extended width of the rectangular shape. - `extended-height`: [`length`] &mdash; Optional extended height of the rectangular shape. - `pin1`: [`pin`] &mdash; One of these pins. - `pin2`: [`pin`] &mdash; One of these pins. - `pin3`: [`pin`] &mdash; One of these pins, optionally. - `...args`: Additional arguments or settings for [`pinit-rect`](#pinit-rect). ### `pinit-line` Draw a line on the page between two specified pins with an optional stroke. ```typ #let pinit-line( stroke: 1pt, start-dx: 0pt, start-dy: 0pt, end-dx: 0pt, end-dy: 0pt, start, end, ) = { ... } ``` **Arguments:** - `stroke`: [`stroke`] &mdash; The stroke for the line. - `start-dx`: [`length`] &mdash; Offset X relative to the start pin. - `start-dy`: [`length`] &mdash; Offset Y relative to the start pin. - `end-dx`: [`length`] &mdash; Offset X relative to the end pin. - `end-dy`: [`length`] &mdash; Offset Y relative to the end pin. - `start`: [`pin`] &mdash; The start pin. - `end`: [`pin`] &mdash; The end pin. ### `pinit-arrow` Draw an arrow between two specified pins with optional settings. ```typ #let pinit-arrow( start-dx: 0pt, start-dy: 0pt, end-dx: 0pt, end-dy: 0pt, start, end, ..args, ) = { ... } ``` **Arguments:** - `start-dx`: [`length`] &mdash; Offset X relative to the start pin. - `start-dy`: [`length`] &mdash; Offset Y relative to the start pin. - `end-dx`: [`length`] &mdash; Offset X relative to the end pin. - `end-dy`: [`length`] &mdash; Offset Y relative to the end pin. - `start`: [`pin`] &mdash; The start pin. - `end`: [`pin`] &mdash; The end pin. - `...args`: Additional arguments or settings for [`simple-arrow`](#simple-arrow), like `fill`, `stroke` and `thickness`. ### `pinit-point-to` Draw an arrow from a specified pin to a point on the page with optional settings. ```typ #let pinit-point-to( pin-dx: 5pt, pin-dy: 5pt, body-dx: 5pt, body-dy: 5pt, offset-dx: 35pt, offset-dy: 35pt, pin-name, body, ..args, ) = { ... } ``` **Arguments:** - `pin-dx`: [`length`] &mdash; Offset X of arrow start relative to the pin. - `pin-dy`: [`length`] &mdash; Offset Y of arrow start relative to the pin. - `body-dx`: [`length`] &mdash; Offset X of arrow end relative to the body. - `body-dy`: [`length`] &mdash; Offset Y of arrow end relative to the body. - `offset-dx`: [`length`] &mdash; Offset X relative to the pin. - `offset-dy`: [`length`] &mdash; Offset Y relative to the pin. - `pin-name`: [`pin`] &mdash; The name of the pin to start from. - `body`: [`content`] &mdash; The content to draw the arrow to. - `...args`: Additional arguments or settings for [`simple-arrow`](#simple-arrow), like `fill`, `stroke` and `thickness`. ### `pinit-point-from` Draw an arrow from a point on the page to a specified pin with optional settings. ```typ #let pinit-point-from( pin-dx: 5pt, pin-dy: 5pt, body-dx: 5pt, body-dy: 5pt, offset-dx: 35pt, offset-dy: 35pt, pin-name, body, ..args, ) = { ... } ``` **Arguments:** - `pin-dx`: [`length`] &mdash; Offset X relative to the pin. - `pin-dy`: [`length`] &mdash; Offset Y relative to the pin. - `body-dx`: [`length`] &mdash; Offset X relative to the body. - `body-dy`: [`length`] &mdash; Offset Y relative to the body. - `offset-dx`: [`length`] &mdash; Offset X relative to the left edge of the page. - `offset-dy`: [`length`] &mdash; Offset Y relative to the top edge of the page. - `pin-name`: [`pin`] &mdash; The name of the pin that the arrow to. - `body`: [`content`] &mdash; The content to draw the arrow from. - `...args`: Additional arguments or settings for [`simple-arrow`](#simple-arrow), like `fill`, `stroke` and `thickness`. ### `simple-arrow` Draw a simple arrow on the page with optional settings, implemented by [`polygon`](https://typst.app/docs/reference/visualize/polygon/). ```typ #let simple-arrow( fill: black, stroke: 0pt, start: (0pt, 0pt), end: (30pt, 0pt), thickness: 2pt, arrow-width: 4, arrow-height: 4, inset: 0.5, tail: (), ) = { ... } ``` **Arguments:** - `fill`: [`color`] &mdash; The fill color for the arrow. - `stroke`: [`stroke`] &mdash; The stroke for the arrow. - `start`: [`point`] &mdash; The starting point of the arrow. - `end`: [`point`] &mdash; The ending point of the arrow. - `thickness`: [`length`] &mdash; The thickness of the arrow. - `arrow-width`: [`integer` or `float`] &mdash; The width of the arrowhead relative to thickness. - `arrow-height`: [`integer` or `float`] &mdash; The height of the arrowhead relative to thickness. - `inset`: [`integer` or `float`] &mdash; The inset value for the arrowhead relative to thickness. - `tail`: [`array`] &mdash; The tail settings for the arrow. ## Acknowledgements - Some of the inspirations and codes comes from [typst-drafting](https://github.com/ntjess/typst-drafting). - Thanks to [polylux](https://github.com/andreasKroepelin/polylux), you can create beautiful and dynamic slides by [polylux](https://github.com/andreasKroepelin/polylux) simply. - The concise and aesthetic example slide style come from course *Data Structures and Algorithms* of [Chaodong ZHENG](https://chaodong.me/). ## License This project is licensed under the MIT License.
https://github.com/weeebdev/cv
https://raw.githubusercontent.com/weeebdev/cv/main/modules_ru/skills.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Навыки") #cvSkill( type: [Языки], info: [Английский #hBar() Казахский #hBar() Русский #hBar() Японский] ) #cvSkill( type: [Tech stack], info: [JS/TS/Python/Java/C/C++/Golang #hBar() React/Angular #hBar() SQL/MSSQL/MongoDB #hBar() Git/Docker] ) #cvSkill( type: [Soft skills], info: [Командная работа #hBar() Коммуникация #hBar() Решение проблем #hBar() Лидерство] )
https://github.com/cs-24-sw-3-01/typst-documents
https://raw.githubusercontent.com/cs-24-sw-3-01/typst-documents/main/report/chapters/problem_analysis.typ
typst
#import "../custom.typ": * = Problem Analysis #include "foundation.typ" #pagebreak(weak: true) #include "problem_domain_analysis.typ" #pagebreak(weak: true) #include "application_domain_analysis.typ" #pagebreak(weak: true)
https://github.com/qlaush/template_thesis_stuttgart_imvt
https://raw.githubusercontent.com/qlaush/template_thesis_stuttgart_imvt/main/metadata.typ
typst
MIT License
// Enter your thesis data here: #let titleEnglish = "Understanding ink formulations for high temperature polymer electrolyte membrane fuel cells having ion pair ionomers" #let titleGerman = "Untersuchungen zu Tintenformulierungen für Hochtemperatur-Polymerelektrolytmembran-Brennstoffzellen mit Ionenpaar-Ionomeren" #let degree = "Master" #let program = "Chemical‐ and Bio‐Engineering" #let supervisor = "Prof. <NAME>" #let advisors = ("Prof. <NAME>", "<NAME>, B.Sc.",) #let author = "<NAME>" #let startDate = datetime(day: 1, month: 1, year: 2024) #let submissionDate = datetime(day: 1, month: 1, year: 2024)
https://github.com/hugoledoux/msc_geomatics_thesis_typst
https://raw.githubusercontent.com/hugoledoux/msc_geomatics_thesis_typst/main/chapters/introduction.typ
typst
MIT License
#import "../template.typ": * = Introduction <chap:intro> This is a complete template for the MSc Geomatics thesis. It contains all the parts that are required and is structured in such a way that most/all supervisors expect. Observe that the MSc Geomatics at TU Delft has no formal requirements, how the document looks like (fonts, margins, headers, etc) is entirely up to you. We basically took the template LaTeX at #link("https://github.com/tudelft3d/msc_geomatics_thesis_template") and tried to convert it to Typst. #info[It is not an official template and it is not mandatory to use it.] But we hope it will encourage everyone to use Typst for writing their thesis, and we also hope that it will _discourage_ some from using Word. If you run into mistakes/problems/issues, please report them on the GitHub page, and if you fix an error, then please submit a pull request. == Cross-references <sec:cross-ref> @chap:intro[Chapter] is to refer to the Chapter, but all other sections you can just use @sec:figures or @sec:cross-ref. // The next chapter (\nameref{chap:rw}), is on page~\pageref{chap:rw}. For a figure, you can also just use @fig:cat, but I guess you can qualify it with whatever you fancy, eg @fig:cat[Hugo]. == Figures <sec:figures> #info[Typst---very annoyingly!---does not support figures in PDF, only PNG and SVG. You need to convert your PDF to SVG, you can use that: #link("https://cloudconvert.com/pdf-to-svg")] @fig:sometriangles is a simple figure in PNG format, notice the use of `placement: auto` to put the figure at the best place possible (top or bottom, Typst decides for you). #figure( image("../figs/sometriangles.png", width:60%), // rect(), placement: auto, //-- otherwise figures gets placed where it's called caption: flex-caption( [1 nice figure.], [2 nice figure.]), // caption: [1 nice figure.], ) <fig:sometriangles> #figure( rect(), // placement: auto, caption: flex-caption( [This is short], [This is my long caption text in the document.], ), ) <un> #info[All figures in your thesis should be referenced to in the main text. The same applies to tables and algorithms.] As shown in @fig:cat, it is possible to have two figures (or more) side by side. You can also refer to a subfigure: see @fig:cat:b. #subpar.grid( figure( image("../figs/tricat-1.svg"), caption: [], ), <fig:cat:a>, figure( image("../figs/tricat-2.svg"), caption: [], ), <fig:cat:b>, figure( image("../figs/tricat-3.svg"), caption: [], ), <fig:cat:c>, columns: (1fr, 1fr, 1fr), caption: [Three figures side-by-side. *(a)* A cat formed of 2 polygons. *(b)* its triangulation. *(c)* with some colours.], // caption: // flex-caption( // [Triangulation of a cat.], // [Three figures side-by-side. *(a)* A cat formed of 2 polygons. *(b)* its triangulation. *(c)* with some colours.], // ), placement: auto, label: <fig:cat>, ) == References We know from #citet(<Descartes37>) that this can be done, and others have done that too @Descartes37. And #citet(<Delaunay34>) did VoroCrust. // We know from #cite(<Hawker22>, form: "prose") that this can done, and others have done that too #cite(<Esch22>, form: "year"). // All the same + @Voronoi08 \ + #cite(<Voronoi08>) \ + #citep(<Voronoi08>) \ + #cite(label("Voronoi08")) == Footnotes Footnotes are a good way to write text that is not essential for the understanding of the text #footnote[but please do not overuse them]. == Equations Equations and variables can be put inline in the text, but also numbered. Let $S$ be a set of points in $RR^d$. The Voronoi cell of a point $p in S$, defined $cal(V)_p$, is the set of points $x in RR^d$ that are closer to $p$ than to any other point in $S$; that is: $ cal(V)_p = \{x in RR^d | \|x-p\| lt.eq \|x-q\|, forall q in S \}. $ The union of the Voronoi cells of all generating points $p in S$ form the Voronoi diagram of $S$, defined VD($S$). == Tables <sec:table> Tables builtin in Typst are pretty powerful, see #link("https://typst.app/docs/guides/table-guide/"). If you need some of the features of LaTeX `booktabs`, it seems that tablex is your friend: #link("https://typst.app/universe/package/tablex"). An example of a simple table is in @tab:example1. #figure( placement: auto, caption: [Details concerning the datasets used for the experiments.], table( stroke: none, columns: 5, align: (left, right, right, right, right), // columns: (auto, auto, auto, auto, auto), table.hline(), table.header[][solids][faces][vertices][constraints], table.hline(), [*campus*], [370], [4~298], [5~970], [3~976], [*kvz*], [637], [6~549], [8~951], [13~571], [*engelen*], [1~629], [15~870], [23~732], [15~868], table.hline(), ) )<tab:example1> == Plots The best way is to use #link("http://matplotlib.org")[matplotlib], or its more beautiful version #link("http://stanford.edu/~mwaskom/software/seaborn/index.html")[seaborn]. With these, you can use Python to generate nice plots, such as that in @fig:myplot. #figure( image("../plots/myplot.svg", width:70%), placement: auto, caption: [A super plot.], ) <fig:myplot> In the folder `./plots/`, there is an example of a CSV file of the temperature of Delft, taken somewhere. From this CSV, the plot is generated with the script `createplot.py`. == Pseudo-code <sec:pseudo-code> Please avoid putting code (Python, C++, Fortran) in your thesis. Small excerpt are probably fine (for some cases), but do not put all the code in an appendix. Instead, put your code somewhere online (eg GitHub) and put _pseudo-code_ in your thesis. The package `lovelace` is pretty handy, see for instance @algo:walk. All your algorithms will be automatically added to the list of algorithms at the begining of the thesis. #figure( kind: "algorithm", supplement: [Algorithm], caption: [W#smallcaps([alk]) ($cal(T)$, $tau$, $p$)], pseudocode-list[ + *Input:* A Delaunay tetrahedralization $cal(T)$, a starting tetrahedron $tau$, and a query point $p$ + *Output:* $tau_r$: the tetrahedron in $cal(T)$ containing $p$ + *while* $tau_r$ not found + *for* $i #sym.arrow.l$ 0 *to* 3 *do* + $sigma_i #sym.arrow.l$ get opposite vertex $i$ in $tau$ + *if* O#smallcaps([rient]) ($sigma_i, p$) $<0$ *then* + $tau #sym.arrow.l$ get neighbouring tetrahedron of $tau$ incident to $sigma_i$ + break + *if* $i==3$ *then* - \//-- all the faces of $tau$ have been tested + *return* $tau_r = tau$ ] ) <algo:walk> == Source/raw code You can use exactly the same principle as in Markdown, and you can wrap the raw code in a `#figure` to have a caption and place it where you want (see @fig:gml). #figure( ```xml <gml:Solid> <gml:exterior> <gml:CompositeSurface> <gml:surfaceMember> <gml:Polygon> <gml:exterior> <gml:LinearRing> <gml:pos>0.000000 0.000000 1.000000</gml:pos> <gml:pos>1.000000 0.000000 1.000000</gml:pos> <gml:pos>1.000000 1.000000 1.000000</gml:pos> <gml:pos>0.000000 1.000000 1.000000</gml:pos> <gml:pos>0.000000 0.000000 1.000000</gml:pos> </gml:LinearRing> </gml:exterior> <gml:interior> ... </gml:surfaceMember> </gml:CompositeSurface> </gml:interior> </gml:Solid> ```, placement: auto, caption: [Some GML for a `gml:Solid`.], ) <fig:gml> == And finally what matters the most: emojis! #emoji.face.smile #emoji.rocket #emoji.spaghetti == TODOs At P4 or for earlier drafts, it might be good to let the readers know that some part need more work. Or that a figure will be added. The package #link("https://typst.app/universe/package/dashy-todo/") is perfect for this. #todo[make sure that the URL is correct :J] #todo[adding holders for figures is also possible] A summary of all TODOs in the thesis can even be generated: #outline(title: "TODOs", target: figure.where(kind: "todo"))
https://github.com/leesum1/brilliant-cv
https://raw.githubusercontent.com/leesum1/brilliant-cv/master/modules_en/pullrequst.typ
typst
// Import #import "@preview/brilliant-cv:2.0.2": cvEntry, cvSection #import "@preview/fontawesome:0.4.0": * #let metadata = toml("../metadata.toml") #let cvSection = cvSection.with(metadata: metadata) #let cvEntry = cvEntry.with(metadata: metadata) #cvSection("Open Source Contributions") #cvEntry( society: [RT-Thread], title: link("https://github.com/RT-Thread/rt-thread/pull/7040")[ #fa-icon("code-merge") rt-thread/pull/7040], date: [May 13, 2023], location: [RT-Thread is an open-source IoT real-time operating system (RTOS)], description: list( [Resolved an issue that prevented startup in S-mode under the qemu-riscv-virt64 BSP, enhancing system stability.], ), ) #cvEntry( society: [Ibex], title: link("https://github.com/lowRISC/ibex/pull/2044")[ #fa-icon("code-merge") ibex/pull/2044], date: [May 31, 2023], location: [Ibex is a small 32-bit RISC-V CPU core, previously known as zero-riscy], description: list( [Added support for MTVEC Direct Mode in Ibex, enhancing processor functionality.], ), ) #cvEntry( society: [xmake], title: link("https://github.com/xmake-io/xmake/pull/3944")[ #fa-icon("code-merge") xmake/pull/3944], date: [July 9, 2023], location: [A cross-platform build utility based on Lua], description: list( [Added the support for Verilator project builds in xmake and the necessary documentation.], ), ) #cvEntry( society: [riscv-tests], title: link("https://github.com/riscv-software-src/riscv-tests/pull/549")[ #fa-icon("code-merge") riscv-tests/pull/549], date: [April 17, 2024], location: [This repository hosts unit tests for RISC-V processors.], description: list( [Fixed an initialization issue in the GDB TEST of the Debug test suite in riscv-tests, improving test suite compatibility.], ), )
https://github.com/arakur/typst-sharp
https://raw.githubusercontent.com/arakur/typst-sharp/master/README.md
markdown
# [WIP] Composing Typst document from .NET ## Example ```fsharp open TypstSyntax open TypstSyntax.Script let markup = Markup [ setRule?text <&& [ "font" *=* str "Garamond"; "fill" *=* ii "purple" ] setRule?heading <& "numbering" *=* str "1." heading 1 [ tt "Our First Section" ] tt "A " emph [ tt "monad" ] tt " is just a monoid " block [ paren [ tt "M"; tt ","; mi?mu; tt ","; mi?eta ] ] tt " in the monoidal category " inline_ [ paren [ str "End"; math?cal <& tt "C"; tt ","; mi?compose; tt ","; tt "I" -% tt "C" ] ] tt " of endofunctors, what" escape '\'' tt "s the problem?" unicode 0x1F914 ] System.IO.File.WriteAllText("./sample.typ", markup |> compose Context.Markup) ``` ```typst #set text(font: "Garamond", fill: purple) #set heading(numbering: "1.") = Our First Section A _monad_ is just a monoid $ (M , mu , eta) $ in the monoidal category $("End" cal(C) , compose , I_C)$ of endofunctors, what\'s the problem?\u{1f914} ``` [Output](/sample.pdf)
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/03-lebesgue-integral/02-summable-functions.typ
typst
#import "../../utils/core.typ": * == Суммируемые функции #def(label: "def-sfn")[ Измеримая $f: E --> overline(RR)$ называется _суммируемой на $E$_, если оба следующих интеграла#rf("def-integral") конечны: $ integral_E f_plus.minus dif mu < +oo. $ ] #props(label: "sfn-props")[ 1. #sublabel("abs-finite") $f$ --- суммируема#rf("def-sfn") на измеримом $E$ тогда и только тогда, когда $integral_E abs(f) dif mu < +oo$. 2. #sublabel("ae-finite") Если $f$ суммируема на $E$, то $f$ почти везде конечна#rf("def-ae") на $E$. 3. #sublabel("restriction-sfn") Если измеримое $A subset B$ и $f$ суммируема на $B$, то $f$ суммируема на $A$. 4. #sublabel("bounded-sfn") Ограниченная функция суммируема на множестве конечной меры. 5. #sublabel("inequality") Если $f$ и $g$ суммируемы и $f <= g$, то $ integral_E f dif mu <= integral_E g dif mu. $ 6. #sublabel("add") _Аддитивность интеграла_. Если $f$ и $g$ суммируемы, то $f + g$ суммируема и $ integral_E (f + g) dif mu = integral_E f dif mu + integral_E g dif mu.$ 7. #sublabel("uniform") _Однородность интеграла_. Если $f$ --- суммируема, то $c f$ суммируема и $ integral_E (c f) dif mu = c integral_E f dif mu. $ 8. #sublabel("linear") _Линейность интеграла_. Пусть $alpha_1, ... alpha_n in RR$, $f_1, ..., f_n$ --- суммируемые. Тогда $alpha_1 f_1 + alpha_2 f_2 + ... + alpha_n f_n$ суммируемая и $ integral_E (alpha_1 f_1 + alpha_2 f_2 + ... + alpha_n f_n) dif mu = alpha_1 integral_E f_1 dif mu + alpha_2 integral_E f_2 dif mu + ... + alpha_n integral_E f_n dif mu. $ 9. #sublabel("set-additive") _Аддитивность по множеству_. Если $E = Union_(k = 1)^n E_k$, $f$ суммируема на $E_k$ при $k = 1, ... n$, то $f$ суммируема на $E$. В случае, когда объединение дизъюнктно, $ integral_E dif mu = integral_(E_1) f dif mu + ... + integral_(E_n) f dif mu. $ 10. #sublabel("measure-sum") _Интеграл по сумме мер_. Пусть $mu_1$ и $mu_2$ меры на $sigma$-алгебре $Aa$. Пусть $mu = mu_1 + mu_2$ в смысле $forall A space mu A = mu_1 A + mu_2 A$. Тогда $f$ суммируемо относительно $mu$ тогда и только тогда, когда $f$ суммируема относительно и $mu_1$, и $mu_2$ и $ integral_E f dif mu = integral_E f dif mu_1 + integral_E f dif mu_2 $ если $f >= 0$ или $f$ суммируема по $mu$ (хотя бы одно). ] #let IE = $integral_E$ #proof[ 1. - "$==>$": $abs(f) = f_+ + f_-$#rf("def-sfn") - "$<==$": $0 <= f_plus.minus <= abs(f)$#rf("def-sfn") 2. Предыдущее свойство#rf("ae-props", "abs-finite") + см. предыдущий параграф#rf("ae-props", "finite-integral-finite") 3. $ bb(1)_A abs(f) <= abs(f) ==> integral_A abs(f) dif mu =^rf("mfn-props", "indicator-extension") integral_B bb(1)_A abs(f) dif mu <=^rf("mfn-props", "inequality") integral_B abs(f) dif mu ==>^rf("sfn-props", "abs-finite") f space #[--- суммируема на] A. $ 4. Модуль#rf("sfn-props", "abs-finite") интеграла не превосходит#rf("mfn-props", "inequality") константу на меру множества#rf("simple-fn-props", "const"). 5. $ f_+ - f_- = f <= g = g_+ - g_- ==> f_+ + g_- <= g_+ + f_- newline(==>^(rf("mfn-props", "inequality") rf("mfn-props", "add"))) integral_E f_+ dif mu + integral_E g_- dif mu <= integral_E g_+ dif mu + integral_E f_- dif mu ==> \ ==> integral_E f_+ dif mu - integral_E f_- dif mu <= integral_E g_+ dif mu - integral_E g_- dif mu ==>^rf("def-integral") integral_E f dif mu <= integral_E g dif mu. $ 6. $abs(f + g) <= abs(f) + abs(g)$, поэтому#rf("mfn-props", "abs-finite") $f + g$ --- суммируемая. Пусть $h = f + g$. Тогда $h_+ + f_- + g_- = f_+ + g_+ + h_-$. $ integral_E h_+ dif mu + integral_E f_- dif mu + integral_E g_- dif mu =^rf("mfn-props", "add") integral_E f_+ dif mu + integral_E g_+ dif mu + integral_E h_- dif mu. $ 7. Если $c = 0$ --- очев. Пусть $c > 0$. Тогда $(c f)_+ = c f_+$, $(c f)_- = c f_-$. $ integral_E (c f)_plus.minus dif mu =^rf("mfn-props", "uniform") c integral_E f_plus.minus dif mu. $ Дальше по определению#rf("def-integral"). Если $c < 0$, рассмотрим $c = -1 dot abs(c)$. Для минус единицы все очевидно. 8. Просто 6)#rf("sfn-props", "add") + 7)#rf("sfn-props", "uniform") + индукция. 9. $integral_(E_k) f dif mu =^rf("mfn-props", "indicator-extension") integral_X bb(1)_(E_k) f dif mu$. $bb(1)_E abs(f) <= bb(1)_(E_1) abs(f) + ... + bb(1)_(E_n) abs(f)$#rf("mfn-props", "inequality")#rf("mfn-props", "add")#rf("sfn-props", "abs-finite"). Если есть дизъюнктность, $bb(1)_E abs(f) = bb(1)_(E_1) abs(f) + ... + bb(1)_(E_n) abs(f)$. Ну и интегрируем#rf("mfn-props", "set-additive")#rf("def-integral"). 10. Пусть $f >= 0$. Докажем формулу по шагам. - Шаг 1. $f = bb(1)_A$: $ integral_E bb(1)_A dif mu =^rf("def-integral-simple") mu(E sect A) = mu_1(E sect A) + mu_2(E sect A) =^rf("def-integral-simple") integral_E bb(1)_A dif mu_1 + integral_E bb(1)_A dif mu_2. $ - Шаг 2. $f >= 0$ --- простая. Очевидно верно по линейности#rf("simple-fn-props", "add")#rf("simple-fn-props", "uniform"). - Шаг 3. $f >= 0$ измеримая. Берем#rf("simple-approx") последовательность $0 <= phi_1 <= phi_2 <= ...$ простых функций, таких, что $phi_n --> f$ поточечно. Тогда $ integral_E phi_n dif mu = integral_E phi_n dif mu_1 + integral_E phi_n dif mu_2 ==>_"<NAME>"^rf("levy") integral_E f dif mu = integral_E f dif mu_1 + integral_E f dif mu_2. $ - Шаг 4. $f$ --- суммируемые#rf("def-sfn"): $integral_E f_plus.minus dif mu, integral_E f_plus.minus dif mu_1, integral_E f_plus.minus dif mu_2 < +oo$. Тогда $ IE f_plus.minus dif mu = IE f_plus.minus dif mu_1 + IE f_plus.minus dif mu_2 $ и вычтя из одного другое, получим что хотим. ] #def(label: "def-cmfn")[ $f: E --> CC$ _измеримая_ если $Re f$ и $Im f$ измеримы. ] #def(label: "def-csfn")[ $f: E --> CC$ _суммируемая_ если $Re f$ и $Im f$ суммируемые. ] #def(label: "def-integral-c")[ Пусть $f: E --> CC$ --- суммируемая#rf("def-csfn"). Тогда комплексно-значным _интегралом_ назовем $ IE f dif mu = IE Re f dif mu + i IE Im f dif mu. $ ] #props(label: "csfn-props")[ 1. #sublabel("abs-finite") $f$ --- суммируема тогда и только тогда, когда $IE abs(f) dif mu < +oo$. 2. Все свойства#rf("sfn-props") интеграла сохраняются. ] #proof[ 1. $abs(f) <= abs(Re f) + abs(Im f)$ и $0 <= Re f_(plus.minus), Im f_(plus.minus) <= abs(f)$#rf("def-csfn")#rf("sfn-props", "abs-finite"). 2. По сути все очевидно, кроме комплексной линейности#rf("sfn-props", "linear"), где мы можем вынести не только положительное или отрицательное вещественное число, но и комплексное. Докажем его для $c = i$. $ IE (i f) dif mu =^rf("def-integral-c") -IE Im f dif mu + i IE Re f dif mu =^rf("def-integral-c") i IE f dif mu. $ ] #let INT(f, E: $E$, mu: $mu$) = $ integral_#E #f dif #mu $ #props(label: "csfn-props'")[ 3. #sublabel("abs-bound") $f: E --> CC$. $ abs(INT(f)) <= INT(abs(f)) $ ] #proof[ Возьмем $alpha in RR$ такое, что $ e^(i alpha) INT(f) = abs(INT(f)). $ Тогда $c e^(i alpha) = abs(c)$ и $e^(-i alpha) = c / abs(c)$. $ abs(INT(f)) = e^(i alpha) INT(f) =^rf("sfn-props", "uniform") INT(e^(i alpha) f) =^rf("def-integral-c") INT(Re (e^(i alpha) f)) + i underbrace(INT(Im(e^(i alpha) f)), = 0 #[т.к. $|INT(f)| in RR$]) newline(=) INT(Re(e^(i alpha) f)) <=^rf("sfn-props", "inequality") INT(abs(Re(e^(i alpha) f))) <=^rf("sfn-props", "inequality") INT(underbrace(abs(e^(i alpha) f), = abs(e^(i alpha)) dot abs(f) = 1 dot abs(f))) = INT(abs(f)). $ ] #th(name: "счетная аддитивность интеграла", label: "integral-additive")[ Пусть $f >= 0$ измеримая, $E = usb_(n = 1)^oo E_n$. Тогда $ INT(f) = sum_(n = 1)^oo INT(f, E: E_n). $ ] #proof[ $bb(1)_E = sum_(n = 1)^oo bb(1)_(E_n)$, $S_n := sum_(k = 1)^n bb(1)_(E_k) f arrow.tr bb(1)_E f$. Тогда по теореме Леви#rf("levy") $ INT(E: X, sum_(k = 1)^n bb(1)_(E_k) f)= INT(S_n, E: X) --> INT(bb(1)_E f, E: X) = INT(f). $ Более того, $ INT(E: X, sum_(k = 1)^n bb(1)_(E_k) f) =^rf("mfn-props", "add") sum_(k = 1)^n INT(E: X, bb(1)_(E_k) f) =^rf("mfn-props", "indicator-extension") sum_(k = 1)^n INT(E: E_k, f) --> sum_(k = 1)^oo INT(E: E_k, f). $ ] #let INTX = INT.with(E: $X$) #let pm = $plus.minus$ #follow(plural: true, label: "integral-additive-follows")[ 1. #sublabel("measure") Если $f >= 0$, то $nu A := INT(E: A, f)$ --- мера. 2. #sublabel("sfn") Если $E = usb_(n = 1)^oo E_n$ и $f$ суммируема на $E$, то $ INT(f) = sum_(n = 1)^oo INT(f, E: E_n). $ 3. #sublabel("tower-domain") Пусть $f$ суммируема на $X$. Если $E_1 supset E_2 supset E_3 supset ...$, то $ INT(E: E_n, f) --> INT(E: sect.big_(n = 1)^oo E_n, f), $ а если $E_1 subset E_2 subset E_3 subset ...$, то $ INT(E: E_n, f) --> INT(E: union.big_(n = 1)^oo E_n, f). $ 4. #sublabel("finite-restriction-eps-bound") Если $INT(abs(f)) < +oo$, то $exists A space mu A < +oo$ и $ abs(INT(E: E without A, f)) < eps. $ ] #proof[ 1. Очевидно по определению#rf("def-measure"). 2. $ INT(f_plus.minus) =^rf("integral-additive") sum_(n = 1)^oo INT(E: E_n, f_plus.minus) $ Все конечно, поэтому можно вычесть. 3. Пусть $nu_plus.minus A = INT(E: A, f_plus.minus)$ --- конечные меры#rf("integral-additive-follows", "measure"). В первом случае $ nu_plus.minus -->_"непр. сверху"^rf("top-down-continious") nu_plus.minus (sect.big_(n = 1)^oo E_n) ==> INT(E: E_n, f_pm) --> INT(E: sect.big_(n = 1)^oo E_n, f_pm). $ Второй случай аналогичен#rf("bottom-up-continious"). 4. Рассмотрим $E_n := E{abs(f) <= 1/n}$. Тогда $E_1 supset E_2 supset E_3 supset ...$. Заметим, что $sect.big_(n = 1)^oo E_n = E{f = 0}$. По предыдущему свойству#rf("integral-additive-follows", "tower-domain"), $ INT(E: E_n, abs(f)) --> INT(E: E{f = 0}, abs(f)) = 0. $ Найдется $E_n$ такое, что $INT(E: E_n, abs(f)) < eps$. Рассмотрим $A := E without E_n$, тогда $ abs(INT(E: E without A, f)) <=^rf("csfn-props", "abs-bound") INT(E: E without A, abs(f)) < eps. $ Проверим меру $A = E{abs(f) > 1/n}$. По неравенству Чебышева#rf("chebyshev-inequality"), $ mu A <= (INT(abs(f))) / (1/n) < +oo. $ ] #th(name: "Абсолютная непрерывность интеграла", label: "abs-continious")[ Пусть $f$ суммируема. Тогда $ forall eps > 0 space exists delta > 0 space forall e subset E space mu e < delta ==> INT(E: e, abs(f)) < eps. $ ] #proof[ $ INT(abs(f)) =^rf("def-integral-mfn") sup{INT(phi): 0 <= phi <= abs(f), phi - "простая"} $ Рассмотрим такую простую $phi$, что $0 <= phi <= abs(f)$ и $INT(phi) > INT(abs(f)) - eps$. Здесь мы пользуемся суммируемостью $f$. $phi$ простая, значит ограниченная. Пусть $phi <= C$. Возьмем $delta = eps / C$. Пусть $e subset E$ такое, что $mu e < eps / C$. Тогда $ INT(E: e, abs(f)) =^rf("sfn-props", "add") INT(E: e, phi) + INT(E: e, underbrace((abs(f) - phi), >= 0)) <=^rf("mfn-props''", "set-additive") INT(E: e, phi) + underbrace(INT(abs(f) - phi), < eps) newline(<) eps + INT(E: e, phi) <=^(rf("mfn-props", "inequality") rf("integral-simple-props", "const")) eps + INT(E: e, C) < eps + eps = 2eps. $ ] #follow(label: "sfn-small-domain-zero")[ Если $f$ суммируемая, а $e_n$ такова, что $mu e_n --> 0$, то $ INT(E: e_n, f) --> 0. $ ] #proof[ Берем#rf("abs-continious") $eps > 0$, по нему $delta > 0$, по $delta$ номер $N$ такой, что при $n >= N$ получается $mu e_n < delta$. Тогда $INT(E: e_n, abs(f)) < eps$. ] #def(label: "def-density")[ $mu$ и $nu$ --- меры, заданные на $sigma$-алгебре $Aa$. $w >= 0$ измеримая. $w$ --- _плотность меры $nu$ относительно меры $mu$_, если $nu A = INT(E: A, w)$ для любого $A in Aa$. ] #notice(label: "density-zero-measure-zero")[ Если $nu$ имеет плотность относительно $mu$, то $mu e = 0 ==> nu e = 0$. ] #let absolutely-continious-sign = text(size: 0.5em, box( path( stroke: 0.6pt, ((1em, 1em), (1em, 1.5em)), ((1em, 0em), (-1em, 1.5em)) ) )) #def(label: "abs-continious-measure")[ Пусть $mu$ и $nu$ --- меры, заданные на одной $sigma$-алгебре $Aa$. $nu$ _абсолютно непрерывна_ относительно $mu$, если $mu e = 0 ==> nu e = 0$. Обозначается $nu << mu$ или $nu #absolutely-continious-sign mu$. ] #th(label: "integrals-eq-ae-sfn-eq")[ Пусть $f$, $g$ --- суммируемы. Если для любого $A$ измеримого, $INT(E: A, f) = INT(E: A, g)$, то $f = g$ почти везде. ] #proof[ Пусть $h = f - g$. Тогда#rf("sfn-props", "linear") $INT(h, E: A) = 0$ для всех измеримых $A$. Если $A := {h >= 0}$ и $tilde(A) := {h < 0}$, $ INT(E: X, abs(h)) =^(rf("sfn-props", "linear") rf("mfn-props", "indicator-extension")) underbrace(INT(E: A, h), = 0) + underbrace(INT(E: tilde(A), (-h)), = 0) = 0 ==>^rf("ae-props", "zero-integral-zero") h = f - g = 0 "почти везде". $ ] #follow(label: "density-unique")[ Если $nu$ имеет плотность#rf("def-density") относительно $mu$ и $sigma$-конечна#rf("def-sfinite"), то плотность единственна с точностью до равенства почти везде#rf("def-ae") (различается только на множестве меры 0). ] #proof[ Если $nu X < +oo$, то $w$ --- суммируемая функция, так как: $ INT(E: A, w_1) = nu A = INT(E: A, w_2) ==> INT(E: X, w_1) = nu X < +oo. $ и она определена однозначно почти везде по теореме#rf("integrals-eq-ae-sfn-eq"). Если $nu X = +oo$, нарежем $X$ на счетное количество кусочков конечной меры#rf("def-sfinite") и применим предыдущее. Если $w_1$ и $w_2$ две плотности, то $mu X_n {w_1 != w_2} = 0$, и их счетное объединение тоже имеет нулевую меру. ] #th(name: "об интегрировании по мере, имееющей плотность", label: "density-integration")[ Пусть $w$ --- плотность меры $nu$ относительно меры $mu$#rf("def-density"). Тогда если $f >= 0$ или $f w$ суммируемо по мере $mu$ (что равносильно $f$ суммируемо по мере $nu$), то $ INT(f, mu: nu) = INT(f w). $ ] #proof[ - Шаг 1. $f = bb(1)_A$. Тогда $ INT(bb(1)_A, mu: nu) =^rf("def-integral-simple") nu(E sect A) =^rf("def-integral-simple") INT(E: E sect A, w) =^rf("mfn-props", "indicator-extension") INT(bb(1)_A w). $ - Шаг 2. По линейности#rf("mfn-props", "add"), верно для простых. - Шаг 3. $f >= 0$ измеримые. Рассматриваем#rf("simple-approx") $0 <= phi_1 <= phi_2 <= ...$ простые, $phi_n --> f$ поточечно. Тогда $0 <= phi_1 w <= phi_2 w <= ...$ и $phi w --> f w$. $ INT(f, mu: nu) <--_"<NAME>"^rf("levy") INT(phi_n, mu: nu) = INT(phi_n w) -->_"<NAME>"^rf("levy") INT(f w). $ - Шаг 4. $f w$ суммируема по $mu$ равносильно $f$ суммируема по $nu$: $ INT(abs(f), mu: nu) = INT(abs(f) w) $ Более того, $ INT(f_pm, mu: nu) = INT(f_pm w) = INT((f w)_pm), $ и по определению#rf("def-integral") интегралы равны. ] #th(name: "Радона-Никодима", label: "radon-nikodym")[ Пусть $mu$ --- $sigma$-конечная#rf("def-sfinite") на какой-то $sigma$-алгебре $Aa$. $nu$ --- мера на $Aa$. Тогда $nu$ имеет плотность относительно $mu$ равносильно $nu$ абсолютно непрерывна относительно $mu$. ] #proof[ - "$==>$": очевидно#rf("abs-continious-measure")#rf("def-density"). - "$<==$": доказательство займет пару или две. Давайте не будем... ] #th(name: "<NAME>", label: "holder-inequality")[ Пусть $p, q > 1$, $1/p + 1/q = 1$. Тогда $ INT(abs(f g)) <= (INT(abs(f)^p))^(1/p) (INT(abs(g)^q))^(1/q). $ ] #show "ПВ": "почти везде" #proof[ Считаем $f, g >= 0$ (неотрицательность, модуль --- одно и тоже). Пусть $A^p := INT(f^p)$, $B^q := INT(g^q)$. Если $mu E = 0$, то все интегралы нули#rf("mfn-props", "zero-domain-zero"). Иначе, если $A = 0$, то $f = 0$ почти везде#rf("mfn-props''", "nonzero"), значит $f g = 0$ почти везде, значит $INT(f g) = 0$. Аналогично, если $B = 0$. Считаем $A, B > 0$. Если $A = +oo$, то правая часть это $+oo$ и неравенство очевидно. Аналогично если $B = +oo$. Остался случай $0 < A, B < +oo$. Можно записать неравенство Юнга: $ u v <= u^p / p + v^q / q, "где" u, v in RR_(>= 0). $ Доказывается такое неравенство через дифференцирование. Пусть $f(u) = u^p/p + v^q/q - u v$. Производная $f'(u) = u^(p - 1) - v$. Эта функция в начале убывает, потом возрастает. Можно подставить минимум и все получится. Имея это неравенство, все очевидно. Его можно записать в каждой точке и проинтегрировать: $ f / A dot g / B <= 1/p (f/A)^p + 1/q (g/B)^q newline(==>^(rf("mfn-props", "inequality") rf("mfn-props'", "add"))) 1/(A B) INT(f g) <= 1/p dot underbrace(1/A^p INT(f^p), = 1) + 1/q dot underbrace(1/B^q INT(g^q), =1) = 1/p + 1/q = 1 ==> \ ==> INT(f g) <= A dot B. $ ] #th(name: "неравенство Минковского", label: "minkowski-inequality")[ Пусть $p >= 1$. Тогда $ (INT(abs(f + g)^p))^(1/p) <= (INT(abs(f)^p))^(1/p) + (INT(abs(g) ^p))^(1/p). $ ] #proof[ Пусть $ A := (INT(abs(f)^p))^(1/p), quad B := (INT(abs(g) ^p))^(1/p), quad C := (INT(abs(f + g)^p))^(1/p). $ Докажем, что $C <= A + B$, считаем $f, g >= 0$. Если $A = +oo$, $B = +oo$, $C = 0$ или $p = 1$, то очевидно. $ f + g <= 2 max{f, g} ==> (f + g)^p <= 2^p max{f^p, g^p} <= 2^p (f^p + g^p). $ Проинтегрировав, $ C^p <= 2^p (A^p + B^p) < +oo. $ Значит $C != +oo$. Тогда $C in (0, +oo)$. $ C^p = INT((f + g)^p) = INT((f + g) dot (f + g)^(p - 1)) =^rf("mfn-props'", "add") INT(f dot (f + g)^(p - 1)) + INT(g dot (f + g)^(p - 1)). $ По неравенству Гельдера, если $q = p/(p - 1)$, $ INT(f dot (f + g)^(p - 1)) <= underbrace((INT(f^p))^(1/p), A) dot underbrace((INT((f + g)^((p - 1)dot q)))^(1/q), C^(p/q)). $ Тогда $ C^p <= A C^(p/q) + B C^(p / q) ==> C^p <= (A + B) C^(p / q) ==> underbrace(C^(p - p/q), C^1) <= (A + B) ==> C <= A + B. $ ]
https://github.com/Dherse/boxaroo
https://raw.githubusercontent.com/Dherse/boxaroo/main/example/simple.typ
typst
MIT License
#import "../boxaroo.typ": boxaroo, binfo #set page(width: 250pt, height: auto, margin: 2pt) #show: boxaroo #binfo(footer: "It even has a footer")[ This is an info box for all of your important information. ]
https://github.com/chengluyu/typst-template
https://raw.githubusercontent.com/chengluyu/typst-template/main/README.md
markdown
# Typst Template This is a Typst slide template for my PQE. ## Features - Scala 3 syntax highlight. - MLscript syntax highlight. ## Usage - Install typst-lsp in VSCode. - Instlal typst-preview for live preview in VSCode. - Enable this settings in your VSCode's settings.json. ```json { "typst-lsp.exportPdf": "onPinnedMainSave" } ``` So, typst-lsp will only compile PDF files when pinned tab is saved. Note that the Typst comes with typst-lsp already includes [Polylux][polylux]). You may need to install the following fonts. [polylux]: https://github.com/andreasKroepelin/polylux - [STIX Two Math](https://github.com/stipub/stixfonts) for equations - [Fira Code](https://github.com/tonsky/FiraCode) for inline code and code block
https://github.com/Fabioni/Typst-TUM-Thesis-Template
https://raw.githubusercontent.com/Fabioni/Typst-TUM-Thesis-Template/main/titlepage.typ
typst
MIT No Attribution
#import "cover.typ": covertitel #let titlepage( title: "", titleGerman: "", degree: "", program: "", supervisor: "", advisors: (), author: "", startDate: none, submissionDate: none, ) = { covertitel(degree: degree, program: program) align(center, text(2em, weight: 700, title)) align(center, text(2em, weight: 500, titleGerman)) v(1fr) align( center, table( align: left, columns: 2, stroke: none, strong("Author: "), author, strong("Supervisor: "), supervisor, strong("Advisors: "), advisors.join(", \n"), //strong("Start Date: "), startDate, strong("Submission Date: "), submissionDate, ) ) pagebreak() }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/recursion-05.typ
typst
Other
#let f(x) = "hello" #let f(x) = if x != none { f(none) } else { "world" } #test(f(1), "world")
https://github.com/Quaternijkon/Typst_ADSL
https://raw.githubusercontent.com/Quaternijkon/Typst_ADSL/main/content.typ
typst
#import "config.typ": * #outline-slide() = NNS - Brute Force Approach - Tree-Based Approach - KD-tree - Ball-tree - R-tree - M-tree == KD-tree #slide(composer:(2fr,1fr))[ KD树是每个叶子节点都为k维点的二叉树。所有非叶子节点可以视作用一个超平面把空间分割成两个半空间。节点左边的子树代表在超平面左边的点,节点右边的子树代表在超平面右边的点。 #set text(size: 0.8em) #pseudocode-list(hooks: .5em, title:[KD-tree最邻近搜索])[ + *start* 从根节点开始向下递归: + *if* 点在超平面的左边:移动到_左子节点_ + *else*: 移动到_右子节点_ + *once* 到达_叶节点_, 将当前叶节点设置为"_当前最好节点_" + *for all*: + *if* 目前所在点比目前最佳点更靠近输入点 + 将其变为目前最佳点。 ] ][ #figure( image("./img/3dtree.png", width: 100%), caption: "一个三维k-d树。第一次划分(红色)把根节点(黄色)划分成两个节点,然后它们分别再次被划分(绿色)为两个子节点。最后这四个子节点的每一个都被划分(蓝色)为两个子节点。因为没有更进一步的划分,最后得到的八个节点称为叶子节点。" ) ] == Ball-tree #slide(composer:(2fr,1fr))[ Ball-tree每个节点代表一个超球(ball),由一个中心点和一个半径定义,包含空间中一部分数据点。非叶节点包含其子节点的超球范围信息,用于剪枝和加速查询。叶节点包含少量的实际数据点,由于直接计算。 #set text(size: 0.8em) #pseudocode-list(hooks: .5em, title:[Ball-tree最邻近搜索])[ 测试点为T, 从root开始采用DFS检查节点。维护一个最大优先优先级队列,用 Q 表示目前遇到的 k 个最近点。在每个节点 B 上: + if distance(T,B)> max distance in Q,ignore B。 + if B is leaf node,for all node in B:update queue。 + B is internal node,searching the child whose center is closer to T. ] ][ #figure( image("./img/ball-tree.png", width: 100%), caption: "计算当前节点所有数据的质心(centroid),找到离质心最远的两个数据点,标记为child1和child2。确定child1和child2后,将当前节点的所有数据根据距离划分:距离child1较近的数据归入child1对应的子节点,距离child2较近的数据归入child2对应的子节点。" ) ] == R-tree #slide(composer:(2fr,1fr))[ R-tree 的每个节点代表一个最小边界矩形(Minimum Bounding Rectangle,MBR),包含若干个子节点或数据对象。非叶节点包含子节点的 MBR,用于构建树的层次结构。叶节点包含实际的空间数据对象。R-tree 是一棵平衡树,所有的叶节点在同一层。 #set text(size: 0.8em) #pseudocode-list(hooks: .5em, title:[R-tree最邻近搜索])[ + 初始化:设置_最小优先队列_,将根节点加入优先队列。 + DFS: + 从队列中取出最小距离的节点。 + *if* 叶节点,计算其中对象与查询点的实际距离,更新最近邻信息。 + *if* 内部节点,将其子节点根据最小距离加入优先队列。 ] ][ #figure( image("./img/R-tree.png", width: 100%), caption: "根据待插入对象的 MBR,与树中节点的 MBR 计算重叠和扩展量,选择需要最小化 MBR 扩展的路径。将对象的 MBR 插入选定的叶节点。如果叶节点超过了最大容量,则需要分裂成两个节点,并调整父节点的 MBR。" ) ] == M-tree = ANSS
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/changelog.typ
typst
Other
#import "template.typ": * = Änderungsverlauf Da der KÜK noch in Arbeit ist, werden hier die Änderungen jeder Version transparent aufgelistet. *Die nächsten Ziele:* - Text, fachlich: - Lösungsvorschläge der Aufgaben == Version 2024-10 // naja, mal schauen wann's wirklich rauskommt... *Hinzugefügt:* - Text, fachlich: - Definition "ephemere Medien" wieder in geänderter und belegter Form - Belege für Sachnorm, individuelle und soziale Bezugsnorm anhand Literatur der pädagogischen Psychologie - Sokrates' elenktisches Verfahren in "Historische Standpunkte zur Philosophiedidaktik" - SPÜ-Teil - neue #taskref("kritikMartens") und #taskref("bub-normen") - Lösung für #taskref("langer-diskursiv-präsentativ"), #taskref("kritikMartens"), #taskref("kompetenzbegriff-weinert"), #taskref("drei-aufgabenstellungen"), #taskref("methoden-martens"), #taskref("martens-vs-rohbeck"), #taskref("pest-vs-inquiry"), #taskref("bub-normen"), #taskref("intersubjektivität"), #taskref("philosophie-ersatzfach") - Hinweise für die Klausur - gestalterisch, strukturell: - Literaturverzeichnis - technisch: - (automatisch generiertes) Literaturverzeichnis - Anpassungen am Template - automatisch halbe Leerzeichen zwischen Abkürzungen wie "z.B.", "o.ä.", etc. *Geändert:* - Text, fachlich: - Reihenfolge der Methodenschlange nur noch als sinnvoll, nicht mehr obligatorisch, mit Belegen ergänzt - Sozialformen einzelner Methoden angepasst - Martens sokratisch-aristotelische Methoden: Zitation angepasst - Martens Kulturtechnik: Technik-Aspekt differenziert - Text, sonstiges: - Einleitungstext, der KÜK ist nun nicht mehr nur für das Seminar "Einführung in die Philosophiedidaktik" gedacht, sondern auch für die SPÜ und folgende Veranstaltungen - Rechtschreibung hier und da angepasst - alphabetische Nummerierung (A, B, ...) von Aufgaben in arabische Nummerierung (1, 2, ...) - gestalterisch, strukturell: - Änderungsverlauf nun genauer und ganz am Ende des Dokuments - technisch: - Austauschen aller händisch angelegten Literaturverweise durch automatisch erzeugte - technische Überarbeitung der fehlerhaften und nur eingeschränkt funktionierenden Umsetzung und Verlinkung von Endnoten, Aufgaben und Indexeinträgen - aufgr. technischer Probleme wurden die Kategorisierung in Seitenzahlen in den Anhängen entfernt, und werden evtl. in späteren Versionen wieder hinzugefügt - falsche Nummerierung von Aufgaben, die Beispiel-Lernerfolgskontrollen haben den Aufgabenzähler der KÜK-Aufgaben beeinflusst (das tun sie nun nicht mehr sondern sind nun unabhängige Zähler) // Gelöscht: // Sonstiges: *Bekannte Fehler:* - falsche Seitennummerierung ab Index, Lösung hat hohe Priorität, jedoch bisher grundlegend keine Idee für eine Lösung vorhanden == Version 2024-04 *Hinzugefügt:* - Text, fachlich: - Belege im Abschnitt "Historische Standpunkte zur Philosophiedidaktik" - Text, sonstiges: - Änderungsverlauf - Hinweis zur Zitierfähigkeit des KÜKs - gestalterisch, strukturell: - Teile, Vorbereitungen für den SPÜ-Teil des KÜKs (in Aufbau) *Geändert:* - Text, fachlich: - "Transformationsphase" → "Transferphase" *Gelöscht:* - Text, fachlich: - Definition "ephemere Medien", da Belege fehlten und die Definition unsicher war // Sonstiges:
https://github.com/ChristophVanDeest/FH-Kiel-Typst-Template
https://raw.githubusercontent.com/ChristophVanDeest/FH-Kiel-Typst-Template/main/examples/bachelor-thesis/main.typ
typst
MIT License
// Import dependencies such as glossaries etc. #import "dependencies.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #import "../../src/lib.typ": bachelor-thesis #show: bachelor-thesis.with( language: "en", title-de: "Antwort auf die endgültige Frage nach dem Leben, dem Universum und dem ganzen Rest", keywords-de: ("Leben", "Universum", "Alles"), abstract-de: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis. Curabitur dictum gravida mauris. Nam arcu lib ero, nonummy eget, consectetuer id, vulputate a, magna.", title-en: "Answer to the Ultimate Question of Life, the Universe, and Everything", keywords-en: ("Live", "Universe", "Everything"), abstract-en: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis. Curabitur dictum gravida mauris. Nam arcu lib ero, nonummy eget, consectetuer id, vulputate a, magna.", author: "<NAME>", faculty: "Engineering and Computer Science", department: "Computer Science", study-course: "Bachelor of Science Informatik Technischer Systeme", supervisors: ("Prof. Dr. Example", "Prof. Dr. Example"), submission-date: datetime(year: 1948, month: 12, day: 10), include-declaration-of-independent-processing: true, ) // Enable glossary // Use: #gls("key") or #glspl("key") to reference and #print-glossary to print it // More documentation: https://typst.app/universe/package/glossarium/ #show: make-glossary // Print abbreviations #pagebreak(weak: true) #include "abbreviations.typ" // Include chapters of thesis #pagebreak(weak: true) #include "chapters/01_preamble.typ" #include "chapters/02_articles.typ" // Print glossary #pagebreak(weak: true) #include "glossary.typ" // Print bibliography #pagebreak(weak: true) #bibliography("bibliography.bib", style: "../../src/assets/ieeetran.csl")
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion/let-context.typ
typst
Apache License 2.0
// contains: a #let a = 1; #let b = /* range after 1..2 */ #(); #let add(x, y) = { x + y }
https://github.com/ooliver1/a-level-project
https://raw.githubusercontent.com/ooliver1/a-level-project/master/writeup/writeup.typ
typst
#import "./palettes/xcolor.typ": xcolor #import "@preview/fletcher:0.4.2" as fletcher: node, edge, shapes #show heading.where(level: 1): set text(24pt) #show heading.where(level: 2): set text(20pt) #show heading.where(level: 3): set text(18pt) #show heading.where(level: 4): set text(16pt) #set page(numbering: "1") #set text(14pt) #set raw(syntaxes: "./GDScript.sublime-syntax.yaml", tab-size: 4) // #show raw.where(block: true): block.with(breakable: false) #show raw.where(lang: "gdscript"): set text(8pt) #let link-heading(label) = locate(loc => { let target = query(label, loc).first() link(label)[#underline(target.body)] }) #page[ #set align(center) <NAME> Nottingham College #linebreak() #text(18pt)[ Computer Science Programming Project ] #heading(outlined: false, level: 1)[Crazy Golf] #linebreak() #text(16pt, fill: xcolor.royal-purple)[ 2023/24 ] ] #page[ // Strong 2nd level. #show outline.entry.where(level: 2): it => { strong(it) } #outline(indent: 1em, title: text(16pt)[Contents]) ] == Analysis === Problem Identification In exam time, students can get stressed from revising for exams. Many students use video games as a way to escape from revision from time to time, but many games require too much of a time investment to be able to play for short periods of time. Multiplayer games can help during exam time as it can be a time to socialise during breaks while revising. Many recent games also require powerful computers to run the graphics requirements they meet, so I propose a game which has simpler graphics, shorter round times, and is multiplayer. ==== Clients My users are a group of 16-19 year old students which sometimes play video games. Many of them prefer smaller games where you do not have to worry if you have time to finish the game/round. Many of them also have low powered laptops, so a game that is easier on the graphics is more enjoyable due to less lag. ==== Computational Methods ===== Problem Recognition The first part of the problem is taking user input and translating it into in-game movement. This movement needs to be calculated on the course, and the ball has to interact with any obstacles in the way. Once this is done as single player, multiplayer would need to be implemented. This involves connecting other players to the game, and synchronising the game state between all players, while using minimal bandwidth. Players can also interact with each other via items, which involves player to player interactions. ===== Problem Decomposition The different components the game involves are: + Connecting to the network to play multiplayer + Take user input and and serialise it to send to the server + Process multiple players' movements on the server + Synchronise state to the client, which shows the ball(s) moving ===== Divide and Conquer These steps can be solved on their own for the most part, as each component can be designed separately, and implemented modularly. ===== Abstraction Many different abstractions can be done between these components. When movements are sent to the server, the server is not concerned with what buttons the user pressed, but what direction the ball will move in. This abstraction allows the server to process movement without having to worry about the input method. Similarly, the client should not have to process collisions with obstacles, but just show the ball moving via instructions from the server. This abstraction allows all players to have synchronised states easily, reduces processing on the client, and makes cheating harder. === Interview ==== First Interview ===== Questions The clients I have chosen to interview have played arcade-style games before. The aim of my first interview is to gather a general idea of mechanics and play styles that my clients enjoy. I will ask them questions about similar games they have played, and what they liked and disliked about them. 1. Have you played a multiplayer arcade-style game before? 2. If so, how many different games in this genre have you played? 3. What were your favourite parts of these games? 4. What were your least favourite parts of these games? 5. What would you like to see in a game like this? ===== Responses #[ #set heading(outlined: false) ====== Milan ======= 1. Have you played a multiplayer arcade-style game before? Yes, I have. ======= 2. If so, how many different games in this genre have you played? Probably something around 20. The new Discord activities, Golf With Your Friends, Ultimate Chicken Horse, etc. ======= 3. What were your favourite parts of these games? I particularly enjoy how these games facilitate a competitive environment while not being particularly frustrating to lose. Compared to real competitive games, it's easy to jump into a game like this with a group of friends and just have a good time trying to win, even if you end up doing poorly. ======= 4. What were your least favourite parts of these games? Generally, there's a very simple premise behind this type of game. After a couple hours of play it can feel like I've seen everything the game has to offer, which leads to me growing tired of such a game particularly quickly. ======= 5. What would you like to see in a game like this? 5. This mostly relates to my answer to (4.), where I think some extra thought into replayability can go a long way. Something like impactful power-ups can drastically change the flow of a game, which can go a long way towards keeping it interesting. ======= Extra Comments Another pretty cool example of this is Ultimate Chicken Horse, where the whole premise of the game is to have the players "create" the levels on the fly in a match. Each player gets to pick one of a few random items at the beginning of each round which they then place. Levels generally start off impossible to clear so players need to cooperate to make it winnable, and from there they start placing stuff to make it hard to clear. The goal of the game is to clear the stage while making others unable to clear it. ====== Alex ======= 1. Have you played a multiplayer arcade-style game before? Yes ======= 2. If so, how many different games in this genre have you played? At least 10 ======= 3. What were your favourite parts of these games? Playing against/with friends --> competition / teamwork ======= 4. What were your least favourite parts of these games? When someone is a lot better than the rest of the group (skill gap) ======= 5. What would you like to see in a game like this? Skill levelling (chess.com has this when playing with friends, making it harder for one of the players) ====== Gwen ======= 1. Have you played a multiplayer arcade-style game before? Yes ======= 2. If so, how many different games in this genre have you played? About 5 ======= 3. What were your favourite parts of these games? I like it when the rules are pretty simple but the game can be played in different ways based on the player ======= 4. What were your least favourite parts of these games? I don't like it when seemingly benign aspects of a game (i.e. character selection or locations on a map) give a player an unfair advantage over their competitors ======= 5. What would you like to see in a game like this? More collaboration between teammates ======= Extra Comments I like Pico Park where several players (2+) have to learn and use the physics system of the game to their advantage, reach certain checkpoints, and use teamwork in order to complete a level. I want more of that in arcade-style games. ====== Enoki ======= 1. Have you played a multiplayer arcade-style game before? Yes ======= 2. If so, how many different games in this genre have you played? 10-15 ======= 3. What were your favourite parts of these games? The multiplayer aspect of it with different player interacting with each other in meaningful ways ======= 4. What were your least favourite parts of these games? The meta progression that some games have that give players unfair advantages over others ======= 5. What would you like to see in a game like this? Players being able to hijack other players' controls ] ===== Analysis From those questions, I have gathered a general idea of what my clients would like to see in a game like this. They would like to see a game that is simple to understand, but has a lot of replayability. They would also like to see a game that has a competitive aspect, but is not frustrating to lose. They would also like to see a game that has a multiplayer aspect, but is not unfair to players that are new to the game. Every game should act almost ephemeral in a way, where the previous game does not affect the next game. This keeps it to the arcade style as standard arcade games do not have progression between games. A co-operative aspect is something that Milan, Alex and Gwen mentioned in their responses. This could be something implemented as an extra game-mode in the game, but it would not be the main focus of the game. It would be something that could be played if the players wanted to, but it would not be forced upon them. ==== Second Interview In this second interview, I asked my clients more specific questions about the mechanics of the game. I asked about the controls, the camera, the items and the co-op aspect of the game. This allows me to curate success criteria for my game, and a set of requirements that I can use to make my game. ===== Questions + How would you like to control your ball and camera? + Should there be items/power-ups, and if so, what should they do? + How should the co-op part of the game work? + What kind of music would you like in the background? + How should you be able to join a multiplayer game (invite code, add via in-game friend, etc.)? ===== Responses #[ #set heading(outlined: false) ====== Milan ======= 1. How would you like to control your ball and camera? I think the most intuitive camera setup would be - The camera is centred onto the ball. - You can zoom in and out using the scroll wheel, - You can click and drag with middle mouse/right click to rotate the camera around the ball, - You can click and drag with left click to shoot the ball at different levels of power. (Essentially the same as Golf With Your Friends/Putt Party) It could be interesting to experiment with some control fine-tuning like gear effect (think Wii Sports where you can shoot the ball along different trajectories by introducing effect), though that probably only makes any real amount of sense in sufficiently large courses. Lastly, it may be nice to have a way to detach the camera from the ball to scout ahead and discover the course. ======= 2. Should there be items/power-ups, and if so, what should they do? Given the focus of a "multiplayer arcade-style" game, I do believe there should be power-ups. I feel like the main focus for these power-ups should be affecting every player in the game. Essentially, anything that isn't downright frustrating but is still sufficient to put a wrench in the works for the "victims" should be good. An example of this could be a wind effect that can influence every player's next shot(s). ======= 3. How should the co-op part of the game work? As far as co-op is concerned, I feel like it's important that players get to play on the same hole simultaneously, especially so when taking power-ups into account. You could then make a decision between whether you want there to be distinct turns (i.e. each player gets to do one swing, then waits for all other players to have finished their swing, until the hole is cleared). Introducing turns in this fashion could make power-ups more impactful as you could have them stay active for a number of turns, making players unable to just wait it out. ======= 4. What kind of music would you like in the background? You could lean into the arcade side of things and make peppy music you would hear in actual arcade games. Something chiptune-like could also work depending on the graphical style of the game. Overall, as long as the music matches the creative direction of the game, I think a lot of different styles could work. An interesting example here is Golf With Your Friends. This game heavily leans into creative map design with an exploration element, and this is reflected well in the music. The bgm for that game could actually fit pretty well into an RPG-style game. ======= 5. How should you be able to join a multiplayer game (invite code, add via in-game friend, etc.)? I think at a base level, using invite codes is fine, as long as groups aren't disbanded after each game. Entering an invite code once for a session of play with friends is more than acceptable. If the game were to be launched on a platform such as Steam, integrating with the platform's built-in friends system would be a nice addition. For a standalone game, however, I don't think a friends system is really a hard requirement. ====== Alex ======= 1. How would you like to control your ball and camera? I would like to control the ball with the mouse, and the camera with the keyboard. ======= 2. Should there be items/power-ups, and if so, what should they do? Yes, not sure. ======= 3. How should the co-op part of the game work? A few ideas: 1. One person can edit the course, other one shoots the ball. 2. One player moves the camera, one controls the ball 3. One player has a camera locked onto the ball but can't see where it's going to hit, other player only has a top down view but can see where the ball hits ======= 4. What kind of music would you like in the background? Tetr.io battle music ======= 5. How should you be able to join a multiplayer game (invite code, add via in-game friend, etc.)? Invite code / link and friends seem reasonable (so you can play with "strangers" and friends) ====== Gwen ======= 1. How would you like to control your ball and camera? The camera should loosely follow the ball, if 3d the ball should have a ‘forward’ direction that the camera should follow behind ======= 2. Should there be items/power-ups, and if so, what should they do? Items/power ups should be available but not necessary to complete a level, they should essentially give the player ability modify the game difficultly ======= 3. How should the co-op part of the game work? There should be sections of the game that require multiple players to be in different places to achieve a goal ======= 4. What kind of music would you like in the background? There should be a quiet ambient music at all/most times and louder music based on events that happen in-game ======= 5. How should you be able to join a multiplayer game (invite code, add via in-game friend, etc.)? Players should be able to send invitations from in a game to other players they want to play with, for the receiver to accept or deny ====== Enoki ======= 1. How would you like to control your ball and camera? Similar to putt party ======= 2. Should there be items/power-ups, and if so, what should they do? Yes, ideally more focused on affecting others rather than yourself, more extreme stuff is always more fun ======= 3. How should the co-op part of the game work? Potentially either have them take turns controlling the ball or have one ball that's not controlled by anyone but everyone has to hit it (like in pool) until it gets in the hole ======= 4. What kind of music would you like in the background? Anything works ======= 5. How should you be able to join a multiplayer game (invite code, add via in-game friend, etc.)? In game friend is more steps, a code / url is easier, more transient and more accessible ] ===== Analysis From these questions, I now have a more specific set of requirements for my game. I will use these requirements to create a set of success criteria below. Question 1 has shown that putt party provides an ideal control scheme, but a possible keyboard control as suggested by Alex could be more accessible too. Question 2's results explain how items provide a different experience for every run of the game, and Enoki suggested that power ups that affect others more than yourself are more fun. Question 3 is still a bit undecided, but Milan suggested that players should be able to play on the same hole simultaneously, and Gwen suggested that there should be sections of the game that require multiple players to be in different places to achieve a goal. Question 4's results can be combined into one idea. Arcade-like ambient music, with more intense music for events such as when time is running out. Question 5 demonstrates a simple URL/code is good enough to join a multiplayer game, and Enoki suggested that an in-game friend system is not necessary but a nice to have. ==== Existing Solutions #[ #set heading(outlined: false) ===== Putt Party #image("./images/analysis/putt-party.png", height: 250pt) Putt party is a Discord "activity" built in to voice channels. This is an example of what my game will be like, as it is arcade-style and multiplayer. It can be played many times with different results as there are items in the many courses, and it is not frustrating to lose at. It implements multiplayer very well as you just join the same voice channel as your friends. It is simple to understand as the controls are just drag and point with the mouse, and it is not too graphically intensive. It is also not too long, as each hole has a time limit. One of the downsides though is that you all have to have Discord to be able to play together. The window is quite small as it is a small section of the voice channel overview, so is difficult to see sometimes, especially on smaller screens like laptops. ====== Parts of Putt Party I Can Apply Multiple of my interviewees have mentioned the controls of putt party, or similar controls. I will take inspiration from this as a way to control the ball. ===== Bomb Party #image("./images/analysis/bomb-party.png", height: 250pt) Bomb Party is a small party game where you have to type words based on a prompt. It is fast-paced, multiplayer, and has a competitive aspect. It is simple to understand as the controls are just typing, and it is not too graphically intensive. It is also usually not too long as you can configure turn limits and difficulty. The multiplayer aspect is implemented with a 4 letter code that can be entered or used via a link (`domain.tld/CODE`). ====== Parts of Bomb Party I Can Apply The multiplayer aspect of Bomb Party is something I can apply to my game. It is simple to understand and easy to use, so I will use a similar system in my game. This system was supported by Enoki, Alex and Milan in their responses. ===== Pico Park #image("./images/analysis/pico-park.png", height: 250pt) Pico Park is a co-operative multiplayer game where you have to work together to complete levels. It also has simple graphics and has short levels, which can get quite difficult as it requires co-ordination of multiple people. It is simple to understand as the controls are just arrow keys and space. ====== Parts of Pico Park I Can Apply I will consider the ways they make players work together and see how they can fit in a golf-style game. Gwen suggested to look at this game as it has a co-operative aspect. ===== Golf With Your Friends #image("./images/analysis/golf-with-your-friends.png", height: 250pt) Golf With Your Friends is a 3D multiplayer golf game. It has a bit more complex graphics compared to the other games, but still simple to understand. It has a lot of different courses, and a lot of different game modes. It has a lot of replayability as there are many different ways to play the game. It is also not too long as each hole has a time limit. It has both online and local multiplayer support. There are no items but it has the concept of choosing where to hit your ball, and the power of the shot which makes the controls more complex. ====== Parts of Golf With Your Friends I Can Apply As this is a 3D game, I can take into consideration how the camera follows the ball on this, which was mentioned by Milan and Gwen in their responses. I can also look at how local multiplayer works too to consider adding. ] ==== Features of the Proposed Solution My solution will be a game with a main menu to select whether to host a room, join a room or change settings. When entering a round, there will be a heads-up display with information about the game such as the time left, scoreboard, and the current hole. The controls will be drag and point, the camera will follow the ball but still be possible to rotate with the mouse or keyboard, and the power of the shot will be controlled by how far you drag the mouse. There will be items that affect other players, and there will be a co-operative aspect to the game as a separate game mode. There will be a simple URL/code to join a multiplayer game, and there will be arcade-style ambient music. ==== Limitations of the Proposed Solution My game would require a Wi-Fi connection. It could use a LAN for local play, but not bluetooth. This is a limitation as school/college Wi-Fi can be unreliable or not accessible at times, and some students may not have access to Wi-Fi at home. Some visual impairments may be a limitation too. As the game will be 3D, it may be difficult to interpret with a visual impairment. I will try to make the game as accessible as possible with changes such as a high contrast interface, but it may not be possible to make it accessible for all visual impairments. The game will be controlled with a keyboard and mouse. This is a limitation as some students may not have access to a mouse, or may not be able to use a mouse due to a physical impairment. This would not be something I can solve completely initially, but a low amount of keyboard inputs would mean they can be remapped to a controller or an accessible input device. The game could also act as a distraction from revision or school work. This is a limitation as it is not the intended purpose of the game. This could be solved by having a setting to lock the game at certain times of the day, but this could be bypassed by changing the system time. === Requirements ==== Stakeholder Requirements ===== Design #table( columns: (1fr, 1fr), align: top, [*Requirement*], [*Explanation*], [Main menu], [The game should have a main menu so the player can choose what to do.], [Full screen and windowed], [The option of full screen is useful for smaller screens like laptops, but windowed is useful for large screens like desktops.], [Simple to understand], [The game should be simple to understand so it is easy to pick up and play.], [Simple graphics], [The game should have simple graphics so it is not too graphically intensive.], [Simple controls], [The game should have minimal controls so it can be learned straight away.], [Following camera], [The camera should follow the ball so the player can see where they are going.], ) ===== Functionality #table( columns: (1fr, 1fr), align: top, [*Requirement*], [*Explanation*], [High Contrast Colour Palette], [The game should have a high contrast colour palette so it is accessible to people with visual impairments, whilst also looking playful too.], [Drag and point controls], [The controls should be drag and point so it is simple to understand.], [Power of shot controlled by drag], [The power of the shot should be controlled by how far the player drags the mouse.], [Items that affect other players], [There should be items that affect other players so the game is more interesting.], [Co-operative aspect], [There should be a co-operative aspect to the game so players can work together if they wish.], [Simple URL/code to join a multiplayer game], [There should be a simple URL/code to join a multiplayer game so it is easy to join.], [Arcade-style ambient music], [There should be arcade-style ambient music so it is not too distracting.], ) ===== Hardware and Software #table( columns: (1fr, 1fr), align: top, [*Requirement*], [*Explanation*], [Keyboard and mouse], [The game should be playable with a keyboard and mouse.], [Windows >=10, macOS >=13.1, Linux x86_64], [These are the operating system versions that the game should be at minimum playable on.] ) ==== Measurable Success Criteria for the Proposed Solution // What I will actually do to solve the stakeholder requirements ("buttons with clear text") #let success-criteria = table( columns: (1fr, 1fr), align: top, [*Criteria*], [*How to get evidence*], [Clear main menu], [Screenshot of the main menu and user feedback.], [Full-screen and windowed options], [Screenshot of the application being full-screen and windowed + code to switch between modes.], [Simple to understand controls], [Screenshot of the controls menu and user feedback of the controls.], [In-game camera follows the ball], [Video which shows the ball is followed by the camera + code to support.], [High contrast colour palette], [Screenshot of the game interface.], [Drag and point controls], [Screenshot of the ball being controlled + code to support.], [Power of shot controlled via dragging the ball], [Screenshot of the ball being controlled + code to support.], [Items that affect other players], [Video of the items in effect during gameplay + code to support.], [Multiplayer functionality], [Screenshot of game with multiple players + code to support.], [Co-operative aspect], [Screenshot and explanation of the co-operative aspect.], [Simple URL/code to join a multiplayer game], [Screenshot of the URL/code being used + code of code being handled.], [Arcade-style ambient music], [The code for the music, and where it came from.], [Keyboard and mouse controls], [Screenshot of the controls menu + code showing custom keyboard controls.], [Support for controllers], [Screenshot of the controls menu supporting controller inputs along with code that support controller inputs.], [Includes a settings menu], [Screenshot of the settings menu.], [Simple graphics], [Screenshot of the game and video usage statistics.], [Scoreboard], [Screenshot of the scoreboard + code to support.], [Time limit], [Screenshot of the time limit + code to support.], [Configurable controls], [Screenshot of the controls menu + code to support.], [Quit button in the main menu], [Screenshot of the main menu with the quit button + code to support.], [Pause menu], [Screenshot of the pause menu + code to support.], [Start game button], [Screenshot of the menus with the start game button.], [Adjustable volume], [Screenshot of the settings menu with the volume sliders + code to support.], [Ball rolls naturally], [Video of the ball rolling.], [Ball collides with obstacles], [Video of the ball colliding with obstacles + code to support.], ) #success-criteria == Design === User Interface ==== Main Menu #image("./images/design/menu.png", height: 250pt) This is the main menu the user sees when starting the game. There are only two main clear options on if the user is ready to play or if they want to change any settings. The background is a placeholder and may be replaced with a preview of one of the levels, to show the player what the game is like before they play. The options button will give the player a list of settings they can change for their own experience, such as graphics settings and controls. The buttons are in the center of the screen, with clear and large labels to let the player know what these buttons do. Links to success criteria: - Clear main menu - Simple graphics ==== Options Menu #image("./images/design/options.png", height: 250pt) This is the menu which is shown after selecting the options button on the main menu or pause menu. This is where the player can change settings such as graphics settings, controls, and audio settings. There are tabs at the top for each category of setting, with clear and concise labels. Links to success criteria: - Full-screen and windowed options - Simple to understand controls - Keyboard and mouse controls - Includes a settings menu ==== Main HUD #image("./images/design/hud.png", height: 250pt) This is the heads up display that will display in the main game. It shows the scoreboard of all the players (which can be collapsed as it could get big with many players). It also shows the time left on the hole, and the player's inventory of items. Links to success criteria: - Scoreboard - Time limit === Stakeholder Input I sent the following message to my stakeholders for feedback on the user interface designs. "Hi, Attached are some screenshots of the designed layout of the menus for the game. These demonstrate the layout and roughly what they will look like in the game. They are the main menu, the options menu, and the main HUD in the game. The buttons are large to easily understand and read, with clear labels. The options menu has tabs at the top to easily navigate between different settings. The HUD is simple with everything at the top, with a collapsible scoreboard for if it gets in the way. I would love to hear your feedback on these or any other comments you have. Thanks, Oliver" ==== Responses #[ #set heading(outlined: false) ===== Enoki IMO the buttons look a bit weird on the corners due to the rounding of the inner sprite, and the font doesn't differentiate between H and K. I personally prefer the slider to be a bit higher, but that is not necessary. Besides that there isn't much I'd comment on. ===== Gwen The scoreboard could have the label "toggle scoreboard" to demonstrate it is toggleable, but that is the only thing I could find after some deliberation. It looks really good and you don't have to implement that change but that's my bit of feedback. ===== Alex - The individual slider markers are a bit hard to see for me, they need a bit more contrast / need to be more bright - Scoreboard content text seems a bit small to parse at a glance, especially because it is collapsible I would make the text bigger - Nitpick: Why is it "MUSIC VOLUME" but not "MASTER VOLUME" I like the big buttons and large text and the very central timer ===== Milan The overall placement of HUD elements looks fine to me, though it would be nice to have some clear indication of how to access settings while in-game, perhaps through a "pause" menu. I feel like a button to quit the game is missing from the main menu. While it isn't strictly necessary, it can be convenient for certain users, for example those playing with a gamepad. ( #link("https://www.youtube.com/shorts/kgxAeQyJz-s")[controller support is cool!!!] [video referring to accessibility advantages of controller support] ) For the options menu, I like the layout with navigable menus at the top and the actual options laid out underneath. I think the sliders specifically would be improved a little if the actual slider bar was visible too, instead of only the ticks. The overall styling seems fine, if a bit plain, which is to be expected for a draft version. As long as this is updated when the overall style of the game is decided upon, I think the UI should work well. Lastly, I think the font could do with some modification, as the V looks a lot like a U. In context this isn't an issue (e.g. it's obviously "Video" and not "Uideo"), but I do personally find it a bit awkward to read. ] ==== Analysis The feedback I received was generally positive, with some minor changes suggested. The following changes will be made to the designs based on the feedback: - The inner corner of the buttons will be made more square to make the buttons look less weird. - The font will be modified to differentiate between H and K, U and V. - The slider markers will be made more bright to be easier to see. - The scoreboard content text will be made bigger. - The settings will be accessible through a pause menu with a physical button in the corner (as well as the escape button). - A button to quit the game will be added to the main menu. ==== Improvements #image("./images/design/menu-improved.png", height: 240pt) There is now a button to quit the game in the main menu. #image("./images/design/options-improved.png", height: 240pt) The sliders are now more visible, and the font has been changed to differentiate between H and K, U and V. #image("./images/design/hud-improved.png", height: 240pt) The scoreboard content text is now bigger, and there is a physical button to access the pause menu. === Assets ==== UI Theme #image("./images/design/ui-pack.png") This Godot UI theme is based off of #link("https://www.kenney.nl/assets/ui-pack", [Kenney's UI Pack]). It is a simple and clean UI with large buttons and high contrast colours. This is useful for the game as it is simple to understand and looks playful. It is also free to use and modify, which I will be doing to update it from Godot 3 to Godot 4.2. https://azagaya.itch.io/kenneys-ui-theme ==== 3D Models #image("./images/design/3d-models.png") These 3D models for the golf course are from the same creator as the UI theme base. There are many separate modular sections to choose from, and they are simple and clean. They also are CC0 licensed like the UI pack, so I can use and modify them for free. https://www.kenney.nl/assets/minigolf-kit ==== Control Inputs #image("./images/design/control-inputs.png") I will be using these images as the content of the controls menu. They follow the same theme as the UI pack. There are many different supported setups such as Xbox, PlayStation, and keyboard and mouse. https://www.kenney.nl/assets/input-prompts === Algorithms ==== User Interface ===== Options The options menu does not take much complex scripting to implement. The most complex element is saving the settings to a file, and loading them when the game starts. Set properties refers to using Godot singletons to set the settings in game, which can also be retrieved later to save to a file. #fletcher.diagram( node-stroke: 1pt, spacing: (10mm, 10mm), { import fletcher.shapes: * node((0, 0), "Start", shape: shapes.pill) edge("-|>") node((0, 1), "Load settings", shape: shapes.rect) edge("-|>") node((0, 2), "Set slider and dropdown values", shape: shapes.rect) edge("-|>") node((0, 3), "Setting modified?", shape: shapes.diamond) edge((0, 3), "r", "-|>", "Yes") edge((0, 3), "d", "-|>", "No") node((1, 3), "Set properties in game", shape: shapes.rect) edge((1, 3), (1, 3.5), (0, 3.5), (0, 4), "-|>") node((0, 4), "Exited?", shape: shapes.diamond) edge("r", "-|>", "Yes") edge("l,u,r", "-|>", "No") node((1, 4), "Save settings", shape: shapes.rect) edge("-|>") node((1, 5), "End", shape: shapes.pill) }) ==== Physics ===== Collisions Ball collisions should bounce off the walls. Godot `move_and_collide` moves the ball at the existing velocity and returns collisions if any. The collision object provides a vector referring to the "normal" of the collision, represented in the following diagram: #fletcher.diagram( spacing: (40mm, 35mm), node-defocus: 0, node-stroke: 1pt, axes: (ltr, btt), { node((0, 0), "Ball", shape: shapes.circle, fill: xcolor.royal-blue) edge((1, 0), (1, 2), "|-|", "Wall") edge((0, 0), (1, 1), "->") edge((1, 1), (0, 1), "--", "Normal") edge((1, 1), (0, 2), "->") }) The colliding vector can be reflected along the normal vector to get the resulting vector. Godot provides `Vector3.bounce(Vector3)` to do this for me. ==== World Node Structure The world will contain multiple holes, and multiple players. Players are instanced in scripts as there are a dynamic amount of them and they contain different data depending on the player. There are multiple holes but they can be instanced in the editor as they are static. #fletcher.diagram( spacing: (10mm, 15mm), node-stroke: 1pt, { node((0, 0), "World") node((0, 1), "Player") edge((0, 0), "d", "->", "Instanced in script\nMultiple") node((4, 1), "Course") edge((0, 0), "rrrr,d", "->") node((4, 2), "Hole") edge((4, 1), "d", "->", "Multiple") node((0, 2), "Ball") edge((0, 1), "d", "->") node((1, 2), "Camera") edge((0, 1), "r,d", "->") node((2, 2), "RayCast") edge((0, 1), "rr,d", "->") node((3, 2), "Arrow") edge((0, 1), "rrr,d", "->") } ) ==== Controls The controls consist of the ability to pivot and zoom the camera, and shoot the ball. The camera can pivot around the ball using Godot's `SpringArm` node. The camera can zoom in and out using the scroll wheel by adjusting the length of this arm, and the camera can rotate around the ball by rotating the arm. Drag and point controls require figuring out the position of the mouse in 3D space relative to the ball. This can be done using a `RayCast` node, which casts a ray from the camera to the mouse position. The point where the ray intersects the ground is where the ball should go (where the arrow should point). `get_control_position` would perform the ray cast, returning the position in 3D space relative to the ball. `point_towards` would rotate the arrow to point using provided vector, and scale to its size. `CANCEL_DISTANCE` is the distance from the ball which a dragging action is cancelled. `action` would be a global variable to determine the current action of the player, likely an enum. `DRAG_THRESHOLD` is the maximum distance from the ball in which a dragging action can be started. `MOUSE_SENSITIVITY` is the sensitivity of the mouse movement, to be configurable by the player. The mouse button press should be detected first and noted down, and the movement of the mouse should be detected. What action the movement does depends on what button is held down. If the right mouse button is held down, the camera should pivot around the ball. If the left mouse button is held down, the arrow should be rotated and scaled to show the power of the shot. The left mouse button should only drag the ball if the distance from the ball is less than `DRAG_THRESHOLD`, if not then it should pivot the camera just like right click does. #import "@preview/lovelace:0.2.0": * #show: setup-lovelace ===== Right Click Press #pseudocode( [*if* event.button $==$ MOUSE_RIGHT *then*], ind, [*if* event.pressed *then*], ind, [*if* get_mouse_mode() $==$ MOUSE_VISIBLE *then*], ind, [action = PIVOTING], ded, [*else*], ind, [*if* get_mouse_mode() $==$ MOUSE_CAPTURED *then*], ind, [action = NONE], ded, [*endif*], ded, [*endif*], ded, [*endif*], ded, [*endif*] ) ===== Left Click Press #pseudocode( [*if* event.button $==$ MOUSE_LEFT *then*], ind, [*if* event.pressed *then*], ind, [#comment[get position of mouse in the viewport, then cast it in 3D space]], [mouse_position = get_mouse_position()], [control_position = get_control_position(mouse_position)], [ball_distance = control_position.length()], [point_towards(control_position)], [*if* ball_distance $<$ DRAG_THRESHOLD *then*], ind, [action = DRAGGING], ded, [*else*], ind, [action = PIVOTING], ded, [*endif* #comment[end of if distance less than DRAG_THRESHOLD]], ded, [*else*], ind, [*if* action $==$ DRAGGING *then*], ind, [control_position = get_control_position(mouse_position)], [ball_distance = control_position.length()], [*if* ball_distance $>$ CANCEL_DISTANCE *then*], ind, [rotation = arrow.rotation_y], [power = arrow.get_power()], [direction = vector_from_angle(rotation) #comment[create unit vector from angle]], [result = direction $*$ power], [ball.apply_impulse(result)], ded, [*endif* #comment[end of if greater than CANCEL_DISTANCE]], ded, [*endif* #comment[end of if action is DRAGGING]], [*if* action $!=$ NONE *then*], ind, [set_mouse_mode(MOUSE_MODE_VISIBLE)], [action = NONE], ded, [*endif* #comment[end of if action is NONE]], ded, [*endif* #comment[end of if button pressed]], ded, [*endif* #comment[end of if left click]] ) ===== Mouse Wheel #pseudocode( [*if* event.button $==$ MOUSE_WHEEL_DOWN *then*], ind, [camera_spring.spring_length += 0.05 #comment[zoom out]], ded, [*endif*], [*if* event.button $==$ MOUSE_WHEEL_UP *then*], ind, [camera_spring.spring_length -= 0.05 #comment[zoom in]], ded, [*endif*] ) ===== Mouse Movement #pseudocode( [*if* event $==$ MOUSE_MOVEMENT *then*], ind, [*if* action $==$ PIVOTING *then*], ind, [camera_spring.rotation_x += event.x $*$ MOUSE_SENSITIVITY], [camera_spring.rotation_y += event.y $*$ MOUSE_SENSITIVITY], ded, [*endif* #comment[end of if action is PIVOTING]], [*if* action $==$ DRAGGING *then*], ind, [control_position = get_control_position(mouse_position)], [point_towards(control_position)], ded, [*endif* #comment[end of if action is DRAGGING]], ded, [*endif* #comment[end of if event is MOUSE_MOVEMENT]] ) === Inputs and Outputs These are the inputs and outputs my game will need to handle. #table( align: top, columns: (1fr, 1fr, 1fr), [*Input*], [*Process*], [*Output*], [Mouse movement], [Move the camera or rotate the arrow depending on if the left or right button is held], [Camera movement or arrow rotation], [Mouse wheel], [Zoom the camera in or out depending on direction of scroll], [Camera zoom], [Left mouse click], [Start dragging the arrow or pivot the camera depending on distance from ball], [Arrow drag or camera pivot], [Right mouse click], [Pivot the camera around the ball], [Camera pivot], [Keyboard input], [Pause the game, change settings or use item], [Pause menu, settings menu, item use], [Right joystick], [Pivot the camera around the ball], [Camera pivot], [Left joystick], [Move the ball, pull stick back for direction and power, release to move], [Ball movement], [Controller button press], [Pause the game, change settings, use items], [Pause menu, settings menu, item use], ) === Key Variables These are the key variables that will be used in the game. #table( align: top, columns: (1fr, 1fr, 2fr), [*Variable*], [*Type*], [*Description*], [action], [enum], [The current action of the player, such as dragging the ball or pivoting the camera.], [scores], [array], [An array of the scores of all the players in the game.], [time_left], [int], [The time left on the current hole.], [ball], [RigidBody3D], [The ball that the player is controlling.], [items], [array], [An array of the items the player has in their inventory.], [control_position], [Vector3], [The position of the mouse in 3D space relative to the ball.], [ball_distance], [float], [The distance from the ball to the mouse position.], [hole], [int], [The current hole the player is on.], [arrow], [Node3D], [The arrow that shows the direction and power of the shot.], [camera_spring], [SpringArm], [The spring arm that controls the camera.], [mouse_position], [Vector2], [The position of the mouse in the viewport.], [linear_velocity], [Vector3], [The velocity of the ball.], ) === Testing Approach Developing a game requires a lot of testing to ensure it works as expected for as many users as possible. Test logs need to show the aspect tested, inputs, the expected result, actual result, and any extra notes from the result of the test such as fixes. The main method of testing will be black box testing, where the game is tested without knowledge of the internal workings. This is to ensure the game works as expected from a user's perspective. If something does not work as expected then debugging can be enabled and the internal workings can be checked. As the development process I am using is iterative, I will be testing the game as it is developed. When adding a new piece of code I will check to make sure it works as I expect, then more thoroughly at the end of each stage for edge cases. This ensures each small part of the game is tested properly before moving on to the next part. == Development The first stage of development is about creating the user interfaces. This includes linking the buttons to the different interfaces, and adding the relevant settings to the options menu. === Stage 1: Setup & Menus ==== Main Menu In the main menu, the buttons are added via Godot's 2D editor, and each button is linked to a central script via signals. These signals are responded to below. Clicking the quit button sends a request to the `SceneTree` to quit. The `play_scene` and `options_scene` are exported properties, so they can be set in the editor. This reduces coupling of the scenes and means the path of those scenes can change without issue. These `PackedScene`s are used to change the current scene to the play or options scene. ```gdscript # main_menu.gd extends MarginContainer # Take in scenes as an exported property, to reduce coupling. @export var play_scene: PackedScene @export var options_scene: PackedScene func _on_quit_button_pressed() -> void: # `get_tree()` gets the `SceneTree` which manages the game loop. get_tree().quit() func _on_options_button_pressed() -> void: get_tree().change_scene_to_packed(options_scene) func _on_play_button_pressed() -> void: get_tree().change_scene_to_packed(play_scene) ``` The `play_scene` looks like this: #image("./images/development/play.png", height: 240pt) ==== Options Menu The options menu is also designed with the Godot 2D editor. The tabs are nodes underneath a `TabContainer` which handles switching the tabs. I added an exit button on the top right to go back to the previous scene - which can be either the main menu or pause menu. As the scene to switch back to depends on the previous scene, this is handled via a global script. The tabs have also been extended downwards when selected so it is clearer as to if they are selected. #image("./images/development/options/music.png", height: 240pt) The following script is a global autoload 'singleton' script which holds the previous scene. This is used to determine which scene to switch back to when the exit button is pressed. ```gdscript # global.gd extends Node ## The scene before switching, used for back/close menu buttons. var previous_scene: String ``` This is used in `main_menu.gd` (and soon to be used in `pause_menu.gd` too) to set the previous scene before switching to the options scene. This is so the options scene knows which scene to switch back to when the exit button is pressed. ```gdscript # main_menu.gd func _on_options_button_pressed() -> void: var tree := get_tree() Global.previous_scene = tree.current_scene.scene_file_path tree.change_scene_to_packed(options_scene) ``` In the options menu, the close button retrieves the previous scene from the global script and switches back to it. ```gdscript extends Control func _on_close_button_pressed() -> void: # Global.previous_scene could be either options or pause, this is set # before switching to options. get_tree().change_scene_to_file(Global.previous_scene) ``` ===== Audio Settings Each volume slider is a child of a parent volume slider scene, which contains the slider, the label which contains the volume, and the script to handle the volume. `audio_bus_name` is different per slider, so it is set per slider in the editor via an exported property. `audio_bus_index` is a unique number relating to this audio bus, used in the `AudioServer` API. `_ready` is ran whenever the script is loaded. It retrieves the current bus volume from the `AudioServer` and sets the slider and label to that value. The `value_changed` signal is emitted whenever the slider is moved, and the `set_bus_volume_db` function is called to set the volume of the bus. Both of these require converting to/from decibels, as the `AudioServer` API uses decibels for volume and that is a logarithmic scale. ```gdscript extends VBoxContainer @export var audio_bus_name: StringName # The index of the audio bus in all buses. @onready var audio_bus_index := AudioServer.get_bus_index(audio_bus_name) @onready var value_node: Label = %Value @onready var slider: HSlider = %Slider func _ready() -> void: # Retrieve existing volume and set that on the slider and label. var db := AudioServer.get_bus_volume_db(audio_bus_index) var percentage := db_to_linear(db) var value := roundi(percentage * 100) value_node.text = str(value) + "%" slider.value = value func _on_slider_value_changed(value: float) -> void: # Godot uses decibels, which is logarithmic. This function converts a number # from 0-1 into decibels (-80 to 24dB) var db := linear_to_db(value / 100) AudioServer.set_bus_volume_db(audio_bus_index, db) value_node.text = str(value) + "%" ``` ===== Video Settings The video settings I have decided to implement, to keep it simple, are: - Window mode (windowed/fullscreen) - Anti-aliasing (MSAA) - Vertical-sync (VSync) ====== Window Mode The first setting to implement is the window mode - whether the window is windowed or fullscreen. For this I asked one of my stakeholders which I know uses multiple (virtual) monitors on Windows 10 *and* Linux. I asked if they would like a borderless windowed fullscreen option, and they said they would like it. This is because it is more consistent across multiple monitors and is generally better for alt+tabbing especially in Windows. ```gdscript # video.gd extends MarginContainer @onready var display_mode: OptionButton = %DisplayMode func _on_display_mode_item_selected(index: int) -> void: # 0: Windowed # 1: Fullscreen # 2: Fullscreen Borderless if index == 0: # Windowed windows have a border and this sets it to maximised for a # consistent size when switching away from fullscreen. DisplayServer.window_set_flag(DisplayServer.WINDOW_FLAG_BORDERLESS, false) DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_MAXIMIZED) elif index == 1: DisplayServer.window_set_position(Vector2i(0, 0)) # Exclusive fullscreen has a lower overhead as it usually avoids # the display compositor. DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_EXCLUSIVE_FULLSCREEN) elif index == 2: # Fullscreen borderless is a full screen sized window without a border. # It usually works better with multiple monitor setups when alt+tab/esc # in windows. DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_MAXIMIZED) DisplayServer.window_set_size(DisplayServer.screen_get_size()) DisplayServer.window_set_flag(DisplayServer.WINDOW_FLAG_BORDERLESS, true) DisplayServer.window_set_position(Vector2i(0, 0)) ``` #image("./images/development/options/video-1.png", height: 240pt) This only shows the dropdown, where selecting each option will change the window mode. The next thing to do is setting the initial value of this dropdown so it shows the currently selected mode. This defaults to assuming the window mode is windowed. If it finds that it is fullscreen, then sets it to fullscreen. If it finds that the window is borderless and windowed (maximised), then it sets it to fullscreen borderless. ```gdscript # video.gd func _ready() -> void: # 0: Windowed # 1: Fullscreen # 2: Fullscreen Borderless var mode := DisplayServer.window_get_mode() var borderless := DisplayServer.window_get_flag(DisplayServer.WINDOW_FLAG_BORDERLESS) var id := 0 if mode == DisplayServer.WINDOW_MODE_EXCLUSIVE_FULLSCREEN: id = 1 elif mode == DisplayServer.WINDOW_MODE_MAXIMIZED and borderless: id = 2 display_mode.select(id) ``` #image("./images/development/options/video-2.png", height: 240pt) ====== Anti-Aliasing The next setting to implement is anti-aliasing. This keeps the 2D MSAA and 3D MSAA settings equal, as users are only going to enable anti-aliasing if their graphics card can handle it. The script is fairly simple, it sets the anti-aliasing quality in the project settings to the selected value. ```gdscript # video.gd # settings paths for anti-aliasing. const ANTIALIASING_2D = &"rendering/anti_aliasing/quality/msaa_2d" const ANTIALIASING_3D = &"rendering/anti_aliasing/quality/msaa_3d" @onready var anti_aliasing: OptionButton = %AntiAliasing # ... func _on_anti_aliasing_item_selected(index: int) -> void: # 0: Disabled # 1: MSAA 2x # 2: MSAA 4x # 3: MSAA 8x if index == 0: ProjectSettings.set_setting(ANTIALIASING_2D, Viewport.MSAA_DISABLED) ProjectSettings.set_setting(ANTIALIASING_3D, Viewport.MSAA_DISABLED) elif index == 1: ProjectSettings.set_setting(ANTIALIASING_2D, Viewport.MSAA_2X) ProjectSettings.set_setting(ANTIALIASING_3D, Viewport.MSAA_2X) elif index == 2: ProjectSettings.set_setting(ANTIALIASING_2D, Viewport.MSAA_4X) ProjectSettings.set_setting(ANTIALIASING_3D, Viewport.MSAA_4X) elif index == 3: ProjectSettings.set_setting(ANTIALIASING_2D, Viewport.MSAA_8X) ProjectSettings.set_setting(ANTIALIASING_3D, Viewport.MSAA_8X) ``` #image("./images/development/options/video-3.png", height: 240pt) The dropdown also needs to set the initial value of the dropdown to the currently selected anti-aliasing setting. This is done by checking the project settings and setting the dropdown to the correct value. ```gdscript # video.gd func _ready() -> void: # ... # msaa_2d and msaa_3d are the same here var antialiasing := get_viewport().msaa_2d id = 0 if antialiasing == Viewport.MSAA_2X: id = 1 elif antialiasing == Viewport.MSAA_4X: id = 2 elif antialiasing == Viewport.MSAA_8X: id = 3 anti_aliasing.select(id) ``` #image("./images/development/options/video-4.png", height: 240pt) ====== Vertical Sync The final setting to implement is vertical sync. This is a simple setting, as it only has two options - on or off. This is set in the project settings, and the dropdown sets the initial value to the currently selected setting. ```gdscript # video.gd @onready var v_sync: CheckBox = %VSync func _ready() -> void: # ... var vsync := DisplayServer.window_get_vsync_mode() if vsync == DisplayServer.VSYNC_ENABLED: v_sync.set_pressed_no_signal(true) else: v_sync.set_pressed_no_signal(false) func _on_vsync_toggled(toggled_on: bool) -> void: if toggled_on: DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_ENABLED) else: DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED) ``` #image("./images/development/options/video-5.png", height: 240pt) ==== Control Settings ===== Control Inputs ====== Textures #image("./images/development/options/controls.png", height: 240pt) The controls menu contains separate controls for both keyboard and controller. This is so the user can set custom settings for both so they can play how they want to. The textures for these buttons need to be stored in a resource to be used later. The following script provides properties that can be set in the editor with each texture for all the supported keys. It also implements a `get_texture` method to retrieve the corresponding texture for an `InputEvent`. #block(breakable: true)[ ```gdscript # keys.gd @tool class_name KeyboardTextures extends Resource # All keys that can reasonably be used as custom controls. # This means no modifier keys, no mouse buttons, no keys which do not usually # pass through to programs such as numlock, const _KEYS: Array[Key] = [ KEY_0, KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_6, KEY_7, KEY_8, KEY_9, KEY_A, KEY_B, KEY_C, KEY_D, KEY_E, KEY_F, KEY_G, KEY_H, KEY_I, KEY_J, KEY_K, KEY_L, KEY_M, KEY_N, KEY_O, KEY_P, KEY_Q, KEY_R, KEY_S, KEY_T, KEY_U, KEY_V, KEY_W, KEY_X, KEY_Y, KEY_Z, KEY_APOSTROPHE, KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, KEY_ASTERISK, KEY_BACKSPACE, KEY_BRACKETLEFT, KEY_BRACKETRIGHT, KEY_GREATER, KEY_LESS, KEY_CAPSLOCK, KEY_ASCIICIRCUM, KEY_COLON, KEY_COMMA, KEY_DELETE, KEY_END, KEY_ENTER, KEY_ESCAPE, KEY_EXCLAM, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, KEY_HOME, KEY_INSERT, KEY_MINUS, KEY_PAGEDOWN, KEY_PAGEUP, KEY_PERIOD, KEY_PLUS, KEY_PRINT, KEY_QUESTION, KEY_QUOTEDBL, KEY_SEMICOLON, KEY_SLASH, KEY_BACKSLASH, KEY_SPACE, KEY_ASCIITILDE, KEY_TAB, ] var textures: Dictionary = {} func _init() -> void: for k in _KEYS: textures[OS.get_keycode_string(k)] = null # Make this Resource act like all of its properties are contained in `textures`. func _get(property: StringName) -> Variant: if property in textures.keys(): return textures[property] return null func _set(property: StringName, value: Variant) -> bool: if property in textures.keys(): textures[property] = value return true return false # Fake the properties we have as all the supported keys. func _get_property_list() -> Array[Dictionary]: var properties: Array[Dictionary] = [] for k in _KEYS: properties.append( { name = OS.get_keycode_string(k), type = TYPE_OBJECT, hint = PROPERTY_HINT_RESOURCE_TYPE, hint_string = "Texture2D" } ) return properties func get_texture(event: InputEvent) -> Texture2D: if not event is InputEventKey: return var key_event := event as InputEventKey var scancode := key_event.keycode return textures.get(OS.get_keycode_string(scancode), null) ``` ] #image("./images/development/options/controls-keys-res.png", height: 240pt) This allows me to insert the textures into a new resource file and use them in the controls menu. And similar with the controller textures, but with the controller buttons instead of keyboard keys. There are much less controller buttons so the properties do not need to be created dynamically, and allows me to add docstrings for what each button corresponds to. ```gdscript # controller.gd @tool class_name ControllerTextures extends Resource ## Bottom action (PS X, Xbox/Steam A, Nintendo B) @export var button_0: Texture2D = null ## Right action (PS O, Xbox/Steam B, Nintendo A) @export var button_1: Texture2D = null ## Left action (PS □, Xbox/Steam X, Nintendo Y) @export var button_2: Texture2D = null ## Top action (PS △, Xbox/Steam Y, Nintendo X) @export var button_3: Texture2D = null ## Back (PS 1/2/3 Select, PS 4/5 Share, Xbox Back, Nintendo -) @export var button_4: Texture2D = null ## Guide (PS PS button, Xbox home, Nintendo home) @export var button_5: Texture2D = null ## Start (PS 1/2/3 Start, PS4/5 Options, Xbox menu, Nintendo +) @export var button_6: Texture2D = null ## Left stick (PS L3, Xbox L/LS, Nintendo left stick) @export var button_7: Texture2D = null ## Right stick (PS R3, Xbox R/RS, Nintendo right stick) @export var button_8: Texture2D = null ## Left shoulder (PS L1, Xbox LB, Nintendo L) @export var button_9: Texture2D = null ## Right shoulder (PS R1, Xbox RB, Nintendo R) @export var button_10: Texture2D = null ## D-pad up @export var button_11: Texture2D = null ## D-pad down @export var button_12: Texture2D = null ## D-pad left @export var button_13: Texture2D = null ## D-pad right @export var button_14: Texture2D = null ## PS5 Microphone, Xbox Share, Nintendo capture @export var button_15: Texture2D = null ## Paddle 1 @export var button_16: Texture2D = null ## Paddle 2 @export var button_17: Texture2D = null ## Paddle 3 @export var button_18: Texture2D = null ## Paddle 4 @export var button_19: Texture2D = null ## PS4/5 touchpad @export var button_20: Texture2D = null func get_texture(event: InputEvent) -> Texture2D: if not event is InputEventJoypadButton: return null var joypad_event := event as InputEventJoypadButton var button := joypad_event.button_index return get("button_" + str(button)) ``` #image("./images/development/options/controls-controller-res.png", height: 240pt) And this is similar with controllers, where I have created multiple resource files for different controller platforms. To ensure only one button can be waiting for input, I have added a property to `global.gd` to share the currently listening prompt. ```gdscript # global.gd ## The control input that is currently listening. var listening_control: ControlInput ``` ====== Buttons I then created a generic input prompt script which can be used for both keyboard and controller inputs. `get_texture` is left unimplemented as that is the part which differs depending on keyboard or controller inputs. This uses the `global.gd` script to ensure only one input prompt can be waiting for input at a time. If a new input prompt is selected, the old one is unselected by calling `unlisten()` on it, and then setting the current prompt as the global property. ```gdscript # control_input.gd class_name ControlInput extends Button # Whether to act upon new `gui_input` events. var listening: bool = false # The texture to revert to if this input is unselected. var previous_texture: Texture2D = null @onready var texture_rect: TextureRect = %TextureRect @onready var label: Label = %Label func _on_pressed() -> void: # Don't redo the same process if we are already listening, as that will # call `unlisten` below. if listening: return # Store the previous texture to revert to later if needed. previous_texture = texture_rect.texture texture_rect.texture = null label.text = "Waiting for input..." listening = true if Global.listening_control != null: Global.listening_control.unlisten() Global.listening_control = self func _on_gui_input(event: InputEvent) -> void: if not listening: return var texture := get_texture(event) if texture == null: return label.text = "" texture_rect.texture = texture listening = false Global.listening_control = null func _on_tree_exited() -> void: unlisten() # Called either when this node is not visible (`tree_exited`), or a different # control input is selected (see above). func unlisten() -> void: listening = false label.text = "" texture_rect.texture = previous_texture # keep `get_texture` abstract, for separate key inputs and controller inputs. func get_texture(_event: InputEvent) -> Texture2D: return null ``` And then the individual implementations for keyboard and controller inputs. ```gdscript # key_input.gd class_name KeyInput extends ControlInput const textures: KeyboardTextures = preload("./resources/keys.tres") func get_texture(event: InputEvent) -> Texture2D: var texture := textures.get_texture(event) # If it is not null, this is a valid texture, store this event as action`. if texture != null: store_action(event) return texture ``` ```gdscript # controller_input.gd class_name ControllerInput extends ControlInput const xb_textures: ControllerTextures = preload("./resources/xbox.tres") const ps_textures: ControllerTextures = preload("./resources/playstation.tres") const ni_textures: ControllerTextures = preload("./resources/nintendo.tres") const st_textures: ControllerTextures = preload("./resources/steam.tres") func get_texture(event: InputEvent) -> Texture2D: var device := event.device var joy_name := Input.get_joy_name(device) # The following conditions come from the public SDL controller database # https://github.com/mdqinc/SDL_GameControllerDB/ var texture: Texture2D if joy_name.contains("Xbox"): texture = xb_textures.get_texture(event) elif ( joy_name.contains("PlayStation") or joy_name.contains("PS") or joy_name.contains("DualShock") ): texture = ps_textures.get_texture(event) elif joy_name.contains("Nintendo") or joy_name.contains("Switch"): texture = ni_textures.get_texture(event) elif joy_name.contains("Steam"): texture = st_textures.get_texture(event) else: texture = xb_textures.get_texture(event) return texture ``` #image("./images/development/options/controls-inputs.png", height: 240pt) Only item 1, 2 and 3 are implemented as controls right now, as I am not sure what the other controls will be yet. This will be implemented later when I have a better idea of what the controls will be. These settings do not apply to the game yet. The following code sets them in the global `InputMap` so they can be used in the game. Each control input takes in the `action` which is the name of the action in the `InputMap`. ```gdscript # key_input.gd @export var action: StringName func _ready() -> void: var current_events := InputMap.action_get_events(action) for existing_event in current_events: if existing_event is InputEventKey: texture_rect.texture = get_texture(existing_event) break func store_action(event: InputEvent) -> void: var current_events := InputMap.action_get_events(action) # Clear any existing key events for this current action and replace it with # the new one. for existing_event in current_events: if existing_event is InputEventKey: InputMap.action_erase_event(action, existing_event) InputMap.action_add_event(action, event) ``` #linebreak() ```gdscript # controller_input.gd @export var action: StringName func _ready() -> void: var current_events := InputMap.action_get_events(action) for existing_event in current_events: if existing_event is InputEventJoypadButton: texture_rect.texture = get_texture(existing_event) break func get_texture(event: InputEvent) -> Texture2D: # ... if texture != null: store_action(event) return texture func store_action(event: InputEvent) -> void: var current_events := InputMap.action_get_events(action) # Clear any existing key events for this current action and replace it with # the new one. for existing_event in current_events: if existing_event is InputEventJoypadButton: InputMap.action_erase_event(action, existing_event) InputMap.action_add_event(action, event) ``` ====== Ongoing Testing ======= Controller Input Passthrough During testing of the controller inputs, I found that when assigning a D-pad button, the GUI would also accept that input and move the focus to the next button. This is not what I want, as I want the GUI to ignore the input and only use it for the control input. I found that this can be prevented with a simple `Control.accept_event()` when handling an `InputEvent` in a specific `Control`. ```gdscript # control_input.gd func _on_gui_input(event: InputEvent) -> void: # ... if texture == null: return accept_event() label.text = "" texture_rect.texture = texture # ... ``` ======= Keyboard Input Loading <keyboard-input-loading> During testing of the keyboard inputs, I found that the existing keys from the `InputMap` are not properly loaded. There seems to be an inconsistency with `InputEvent`s from real input, and those stored in `InputMap`, where `InputEventKey.keycode` is `0`. Thankfully the Godot docs provide another property - `InputEventKey.physical_keycode` - which correlates to a US QUERTY keyboard layout. This can be converted back to a `Key` enum for the current keyboard layout. ```gdscript func get_texture(event: InputEvent) -> Texture2D: if not event is InputEventKey: return var key_event := event as InputEventKey var scancode := key_event.keycode # When accessing InputMap, this is 0 if scancode == 0: var physical := key_event.physical_keycode scancode = DisplayServer.keyboard_get_keycode_from_physical(physical) return textures.get(OS.get_keycode_string(scancode), null) ``` ======= Controller Input Initial Focus <controller-focus> I also found that for controller input to work in menus, one `Control` should grab the focus initially so the controller focus knows where to start. ```gdscript # main_menu.gd func _ready() -> void: play_button.grab_focus() ``` ```gdscript # options.gd func _ready() -> void: tab_container.get_tab_bar().grab_focus() ``` ===== Saving Settings The settings need to be saved between sessions, so the user does not have to set them every time they play the game. This is done by saving the settings to a file in the user's home directory. This is done in the `global.gd` script, which is autoloaded so `save_settings` can always be accessed. ====== Restructuring Since the video mode will be retrieved here, I have moved that logic to `global.gd`, which is used in `video.gd` to set the initial value of the dropdown. ```gdscript # global.gd enum {WINDOW_WINDOWED, WINDOW_FULLSCREEN, WINDOW_BORDERLESS} enum {ANTIALIASING_DISABLED, ANTIALIASING_2X, ANTIALIASING_4X, ANTIALIASING_8X} # ... func get_window_mode() -> int: var mode := DisplayServer.window_get_mode() var borderless := DisplayServer.window_get_flag(DisplayServer.WINDOW_FLAG_BORDERLESS) var id := WINDOW_WINDOWED if mode == DisplayServer.WINDOW_MODE_EXCLUSIVE_FULLSCREEN: id = WINDOW_FULLSCREEN elif mode == DisplayServer.WINDOW_MODE_WINDOWED and borderless: id = WINDOW_BORDERLESS return id func get_antialiasing() -> int: # msaa_2d and msaa_3d are the same here var antialiasing := get_viewport().msaa_2d var id = ANTIALIASING_DISABLED if antialiasing == Viewport.MSAA_2X: id = ANTIALIASING_2X elif antialiasing == Viewport.MSAA_4X: id = ANTIALIASING_4X elif antialiasing == Viewport.MSAA_8X: id = ANTIALIASING_8X return id ``` #linebreak() ```gdscript # video.gd func _ready() -> void: var id: int = Global.get_window_mode() display_mode.select(id) var antialiasing: int = Global.get_antialiasing() anti_aliasing.select(id) # ... ``` ====== File Saving ======= Video Settings The settings are saved using a `ConfigFile`. This is a key-value store which maps to an "ini" (non-standard) file format. This is saved in the user's home directory. ```gdscript # global.gd ## Config file for holding modified settings. var settings := ConfigFile.new() func save_settings() -> void: var vsync := DisplayServer.window_get_vsync_mode() var video_mode := get_window_mode() var video_antialiasing := get_antialiasing() var video_vsync_enabled := vsync == DisplayServer.VSYNC_ENABLED settings.set_value("video", "mode", video_mode) settings.set_value("video", "antialiasing", video_antialiasing) settings.set_value("video", "vsync", video_vsync_enabled) settings.save("user://settings.ini") ``` This is then called in `options.gd` when the options are being exited. ```gdscript # options.gd func _on_tree_exiting() -> void: Global.save_settings() ``` #image("./images/development/options/saved-video.png", height: 120pt) ======= Audio Settings The audio settings saving is similar to the video settings. The settings are saved as a mapping of bus index to volume in decibels. ```gdscript # global.gd func save_settings() -> void: var bus_count := AudioServer.bus_count for bus in range(bus_count): var db := AudioServer.get_bus_volume_db(bus) settings.set_value("audio", str(bus), db) # ... ``` #image("./images/development/options/saved-audio.png", height: 120pt) ======= Control Settings The control settings need to store a key event and a joypad button event for each action. `store_event` is a separate function to reduce the size of `save_settings` as there were too many indents for it to be easily readable. ```gdscript # global.gd func save_settings() -> void: # ... var actions := InputMap.get_actions() for action in actions: # ui_* are default UI traversal controls. if not action.begins_with("ui_"): var events := InputMap.action_get_events(action) for event in events: store_event(action, event) # ... func store_event(action: StringName, event: InputEvent) -> void: if event is InputEventKey: # Similar to prompts/resources/keys.gd#get_texture var key_event := event as InputEventKey var keycode := key_event.keycode if keycode == 0: var physical := key_event.physical_keycode keycode = DisplayServer.keyboard_get_keycode_from_physical(physical) settings.set_value("controls", action + "_key", keycode) elif event is InputEventJoypadButton: var joypad_event := event as InputEventJoypadButton var button := joypad_event.button_index settings.set_value("controls", action + "_control", button) ``` #image("./images/development/options/saved-controls.png", height: 180pt) ====== Ongoing Testing ======= Anti-Aliasing Loading <anti-aliasing-loading> During testing of saving video settings, I found that antialiasing was always disabled. I found out that `ProjectSettings` is not needed for this, and it can be set directly as `Viewport.msaa_2d` and `Viewport.msaa_3d` in `video.gd`. ```gdscript # video.gd func _on_anti_aliasing_item_selected(index: int) -> void: var viewport := get_viewport() if index == 0: viewport.msaa_2d = Viewport.MSAA_DISABLED viewport.msaa_3d = Viewport.MSAA_DISABLED elif index == 1: viewport.msaa_2d = Viewport.MSAA_2X viewport.msaa_3d = Viewport.MSAA_2X elif index == 2: viewport.msaa_2d = Viewport.MSAA_4X viewport.msaa_3d = Viewport.MSAA_4X elif index == 3: viewport.msaa_2d = Viewport.MSAA_8X viewport.msaa_3d = Viewport.MSAA_8X ``` ====== File Loading ======= Audio Settings The settings are now saved to `settings.ini`. They need to be loaded when the game is ran. This can be done in `Global._ready` by loading the settings from the file and setting the values in the game in the global singletons `DisplayServer`, `AudioServer` and `InputMap`. `SETTINGS_PATH` is moved to a constant as it is used in both `save_settings` and `load_settings`. ```gdscript # global.gd const SETTINGS_PATH = "user://settings.ini" # ... func _ready() -> void: load_settings() func load_settings() -> void: var err := settings.load(SETTINGS_PATH) if err == ERR_FILE_CANT_OPEN: return # Audio var buses := settings.get_section_keys("audio") for bus in buses: var db: int = settings.get_value("audio", bus) var index := int(bus) AudioServer.set_bus_volume_db(index, db) ``` #image("./images/development/options/loaded-audio.png", height: 240pt) The options shown above in the screenshots are being loaded as decibels and stored in `AudioServer`. ======= Video Settings For video settings, I moved the logic of setting window mode and antialiasing out from `video.gd` and into `global.gd` so they can be used by both. ```gdscript # global.gd func set_window_mode(mode: int) -> void: if mode == 0: # Windowed windows have a border and this sets it to maximised for a # consistent size when switching away from fullscreen. DisplayServer.window_set_flag(DisplayServer.WINDOW_FLAG_BORDERLESS, false) DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_MAXIMIZED) elif mode == 1: DisplayServer.window_set_position(Vector2i(0, 0)) # Exclusive fullscreen has a lower overhead as it usually avoids # the display compositor. DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_EXCLUSIVE_FULLSCREEN) elif mode == 2: # Fullscreen borderless is a full screen sized window without a border. # It usually works better with multiple monitor setups when alt+tab/esc # in windows. DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_MAXIMIZED) DisplayServer.window_set_size(DisplayServer.screen_get_size()) DisplayServer.window_set_flag(DisplayServer.WINDOW_FLAG_BORDERLESS, true) DisplayServer.window_set_position(Vector2i(0, 0)) func set_antialiasing(mode: int) -> void: var viewport := get_viewport() if mode == 0: viewport.msaa_2d = Viewport.MSAA_DISABLED viewport.msaa_3d = Viewport.MSAA_DISABLED elif mode == 1: viewport.msaa_2d = Viewport.MSAA_2X viewport.msaa_3d = Viewport.MSAA_2X elif mode == 2: viewport.msaa_2d = Viewport.MSAA_4X viewport.msaa_3d = Viewport.MSAA_4X elif mode == 3: viewport.msaa_2d = Viewport.MSAA_8X viewport.msaa_3d = Viewport.MSAA_8X func load_settings() -> void: # ... # Video var mode: int = settings.get_value("video", "mode") set_window_mode(mode) var antialiasing: int = settings.get_value("video", "antialiasing") set_antialiasing(antialiasing) var vsync: bool = settings.get_value("video", "vsync") if vsync: DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_ENABLED) else: DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED) ``` ======= Control Settings The control settings are loaded in a similar way to the video settings. The settings are loaded from the file and set in the game in the global singleton `InputMap`. Each setting is either a `*_key` or a `*_control` so they have to be handled differently. ```gdscript func load_settings() -> void: # ... # Controls var controls := settings.get_section_keys("controls") for stored_control in controls: if stored_control.ends_with("_key"): var control := stored_control.trim_suffix("_key") for existing_event in InputMap.action_get_events(control): if existing_event is InputEventKey: InputMap.action_erase_event(control, existing_event) var new_event := InputEventKey.new() new_event.keycode = settings.get_value("controls", stored_control) InputMap.action_add_event(control, new_event) elif stored_control.ends_with("_control"): var control := stored_control.trim_suffix("_control") for existing_event in InputMap.action_get_events(control): if existing_event is InputEventJoypadButton: InputMap.action_erase_event(control, existing_event) var new_event := InputEventJoypadButton.new() new_event.button_index = settings.get_value("controls", stored_control) InputMap.action_add_event(control, new_event) ``` ==== Review: Setup & Menus ===== Progress Made The program runs, and the options menu is fully functional. The settings are saved and loaded from a file in the user's home directory. The settings are also applied to the game when it is loaded. Extra key-binds can be added later when necessary. This means that I now have a program with the main menu and options menu fully functional, providing the base for a game to be built on top of. ===== Testing Done #show table: set text(12pt) #table( columns: (1fr, 1.5fr, 1.5fr, 1.5fr, 2fr), align: top, [*Aspect Tested*], [*Input*], [*Expected Output*], [*Actual Output*], [*Comments/Resolution*], [Quit button], [Run game -> press quit], [Game closes], [Game closes], [], [Options exit], [Open options -> press close], [Options close and return to main menu], [Options close and return to main menu], [], [Video settings], [Change window mode], [Window mode changes], [Window mode changes], [The difference between fullscreen and windowed fullscreen was verified using the X11 `xprops` program (via `xwayland`).], [Video settings], [Change video settings -> close game -> reopen options], [Settings are as they were set], [Antialiasing was always "disabled"], [This was resolved in #link-heading(<anti-aliasing-loading>)], [Audio settings], [Modify audio sliders], [Audio played with different buses changes volume], [Audio played with different buses changes volume], [This was tested by adding a new `AudioStreamPlayer` to the UI and changing what audio bus it uses.], [Audio settings], [Change audio settings -> close game -> reopen options], [Settings are as they were set], [Settings are as they were set], [], [Control settings], [Using a controller -> change control settings], [Controller textures change depending on the device used], [Controller textures change depending on the device used], [This was tested by using a PS5 controller and a Nintendo Switch Pro controller.], [Control settings], [Change control settings -> close game -> reopen options], [Settings are as they were set], [Settings were blank, not even the default setting], [This was solved in #link-heading(<keyboard-input-loading>) before file loading was implemented, this was to do with `InputMap` and not storing settings.], [Controller support], [Using a controller -> navigate menus], [Controller navigates menus], [D-pad and left stick have no effect], [This was solved in #link-heading(<controller-focus>), and then was tested using a PS5 controller and a Nintendo Switch Pro controller once solved.], ) ===== Links to Success Criteria - Clear main menu - Full-screen and windowed options - Simple to understand controls - Keyboard and mouse controls - Support for controllers - Includes a settings menu - Quit button in the main menu - Configurable controls - Adjustable volume === Stage 2: Course Creation & Initial Physics ==== Ball Placement Firstly, I wanted to test to make sure my models of the course and ball work okay with Godot. I created a scene with a `Camera3D`, and programatically added a ball just above a `Start` platform. ```gdscript # world.gd extends Node3D const BALL_BLUE = preload("res://courses/scenes/ball_blue.tscn") func _ready() -> void: var ball: Node3D = BALL_BLUE.instantiate() add_child(ball) ball.position = Vector3(0, 0.09, 0.1) ``` #image("./images/development/course/test.png", height: 240pt) This worked, the ball went down the slope and off the edge (as there is no ground). This is a good start, this means that my `RigidBody3D` ball and `StaticBody3D` platforms have the correct collision meshes/boxes. #image("./images/development/course/test-success.png", height: 240pt) ==== First Course Design ===== Hole 1 The first hole will just be like a practice hole, a simple straight towards an open hole. This also makes it easy for me to test the physics of the ball and the course with only perpendicular surfaces. #image("./images/development/course/hole-1.png") ====== Wall Collisions The ball needed to bounce off the horizontal walls of this hole. I overrode the `_physics_process` method of the ball as the default is to `move_and_slide` along the walls. The correction for `linear_velocity.y` to be `0` is because I would find the ball fall through and collide with the intersections of the floor collision mesh. ```gdscript # ball.gd extends RigidBody3D func _physics_process(delta: float) -> void: var collision := move_and_collide(linear_velocity * delta) if collision: var normal := collision.get_normal() # Keep the ball on the ground, not fall through. if normal.y != 0: linear_velocity.y = 0 # Bounce off walls. if normal.x != 0 or normal.z != 0: var new_velocity := linear_velocity.bounce(normal) linear_velocity.x = new_velocity.x linear_velocity.z = new_velocity.z ``` ====== Stop Rolling The ball would continue moving, slowing down due to angular and linear velocity dampening but not slowing down enough to stop completely. I added an exported variable to the ball to set the minimum velocity, and if the ball's velocity is below this, it is set to `Vector3.ZERO`. ```gdscript @export var MIN_VELOCITY: float = 0.3 func _physics_process(delta: float) -> void: # ... # Stop the ball rolling forever. if linear_velocity.length() < MIN_VELOCITY: linear_velocity = Vector3.ZERO ``` ===== Hole 2 The second hole will be a bit more complex, with a bend and a hill. This will test the ball's ability to go up and down slopes, and around corners. #image("./images/development/course/hole-2.png") ====== Slope Collisions As the ball goes up and down slopes, `move_and_collide` does not work as expected as sometimes it may collide with the slope itself. I found that simply detecting if the collision is not horizontal and ignoring it if so, works well. ```gdscript func _physics_process(delta: float) -> void: # ... if normal.y != 0 and normal.y != 1: return ``` ====== Inelastic Collisions Collisions with a wall should not bounce back with the same velocity, as this is not realistic. I added a `elasticity` property to the ball to control how much it bounces off walls. ```gdscript @export var ELASTICITY: float = 0.9 func _physics_process(delta: float) -> void: # ... # Bounce off walls. if normal.x != 0 or normal.z != 0: var new_velocity := linear_velocity.bounce(normal) * ELASTICITY linear_velocity.x = new_velocity.x linear_velocity.z = new_velocity.z # ... ``` ===== Hole 3 #image("./images/development/course/hole-3.png") This hole has nothing different in terms of physics, as the slope is handled fine just like the previous hole's hill. ===== Hole 4 ====== Slope Climbing <slope-climbing> Hole 3 has nothing extra interesting, but hole 4 has a ramp up to the main part of the hole. #image("./images/development/course/hole-4.png") During testing of the ball rolling up the slope, at a high enough velocity the ball would clip through the ground. I found that this is because when it collides with the ground, `normal.y` is not `0` so `linear_velocity.y` would be set to `0` and disallow the ball to climb the slope. To solve this I only compensate for falling through the floor when `normal.y == 0`, otherwise all components of `linear_velocity` would be bounced on a collision. ```gdscript extends RigidBody3D @export var MIN_VELOCITY: float = 0.03 @export var ELASTICITY: float = 0.9 func _physics_process(delta: float) -> void: var collision := move_and_collide(linear_velocity * delta) if collision: var normal := collision.get_normal() # Don't fall through the floor. if normal.y == 1: linear_velocity.y = 0 return # Bounce off walls. if normal.x != 0 or normal.z != 0: linear_velocity = linear_velocity.bounce(normal) * ELASTICITY # ... ``` ====== Continuous Collision Detection <continuous-cd> #image("./images/development/course/continuous-cd.png", height: 160pt) I found the "Continuous CD" setting in the `RigidBody3D` node, which is used to prevent the ball from clipping through collision boxes. It does this by predicting collisions before they happen, which works well for small, fast moving objects. This allowed me to remove the following code: ```gdscript if normal.y == 1: linear_velocity.y = 0 return ``` ==== Review: Course Creation & Initial Physics ===== Progress Made I now have the course and ball working well together. The ball can roll around the course, bounce off walls and slopes, and stop when it reaches a low enough velocity. The course has a few holes to test the ball's physics, and the ball can climb slopes and go around corners. ===== Testing Done #table( columns: (1fr, 1.5fr, 1.5fr, 1.5fr, 2fr), align: top, [*Aspect Tested*], [*Input*], [*Expected Output*], [*Actual Output*], [*Comments/Resolution*], [Wall collisions], [Ball hits wall], [Ball bounces off wall], [Ball bounces off wall], [], [Roll ball at low velocity], [Ball stops moving], [Ball stops moving], [Ball stops moving], [], [Slope collisions], [Send ball rolling up slope], [Ball goes up slope], [Ball stops and rolls back down when going too fast], [This was solved in #link-heading(<slope-climbing>)], [Ball stays on course], [Send ball rolling around course], [Ball stays on course], [Ball falls through floor or clips through walls], [This was solved in #link-heading(<continuous-cd>)], [Ball loses more velocity when colliding], [Send ball rolling into wall], [Ball loses velocity when colliding], [Ball loses velocity when colliding], [], ) ==== Links to Success Criteria - Simple graphics - Ball rolls naturally - Ball collides with obstacles === Stage 3: Controls & Camera ==== Point Controls First off is drafting out the point and drag controls for the ball. This requires finding where the mouse is "in 3D space" relative to the ball. This can be done via drawing an invisible circle around the ball and finding the point where a ray cast from the camera to the mouse intersects the circle. #image("./images/development/controls/plane.png", height: 240pt) ```gdscript # player.gd extends Node3D @onready var ray_cast: RayCast3D = %RayCast @onready var camera: Camera3D = %Camera func get_control_position(mouse_position: Vector2) -> Vector3: # Draw a ray cast from the camera, to the mouse position far away. # The ray is configured to only collide with the ball control plane, # so the collision is the mouse position in the same plane as the ball. var origin := camera.project_ray_origin(mouse_position) var direction := camera.project_ray_normal(mouse_position) var ray_length := camera.far var end := direction * ray_length ray_cast.global_position = origin ray_cast.target_position = end return ray_cast.get_collision_point() func _input(event: InputEvent) -> void: # Temporary code to test the use of the ray cast. if event is InputEventMouseMotion: var mouse_event := event as InputEventMouseMotion var mouse_position := mouse_event.position var mouse_position_3d = get_control_position(mouse_position) ``` This results in correct detection by the ray, showing as red in this debug mode when colliding, and blue otherwise. The ray can be seen in the debugging sub-viewport in the top left, and by the centre of the box in the main camera. #image("./images/development/controls/ray-cast-success.png", height: 240pt) #image("./images/development/controls/ray-cast-success-2.png", height: 240pt) ==== Pivot Camera To be able to properly use these controls, the camera must be able to pivot around the ball. This is done by attaching the camera to a spring arm that can pivot around the ball. #image("./images/development/controls/pivot.png") The pivoting is operated by click and dragging the right mouse button. Joystick controls can be added later. First, using the `_input` virtual method, the right mouse button can be detected conditionally with `InputEventMouseButton.button_index`. ```gdscript func _input(event: InputEvent) -> void: if event is InputEventMouseButton: var mouse_event := event as InputEventMouseButton # Pivot camera on right click drag. if mouse_event.button_index == MOUSE_BUTTON_RIGHT: pass ``` If the right mouse button is pressed down, the mouse should be captured so it is invisible and in the middle of the screen. This prevents the mouse from going off the screen and allows for continuous pivoting. ```gdscript if mouse_event.button_index == MOUSE_BUTTON_RIGHT: if mouse_event.pressed: if Input.get_mouse_mode() == Input.MOUSE_MODE_VISIBLE: Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) ``` Otherwise if it is released, the mouse should be given back to the user. ```gdscript else: if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED: Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE) ``` Since the mouse is captured when the right mouse button is held, this can be detected when the mouse is moved. ```gdscript elif event is InputEventMouseMotion: var mouse_event := event as InputEventMouseMotion # Rotate camera spring arm when pivot button is down. if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED: pass ``` This event can then be used to change the camera spring rotation, which is a child of the player node. ```gdscript ## Sensitivity of the mouse movement when pivoting. @export var mouse_sensitivity: int = 1 # ... if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED: # Invert mouse movements as the coordinate origin is different. var rotation_y := deg_to_rad(-mouse_event.relative.x * mouse_sensitivity) var rotation_x := deg_to_rad(-mouse_event.relative.y * mouse_sensitivity) camera_spring.rotation.x += rotation_x camera_spring.rotation.y += rotation_y ``` `mouse_sensitivity` should be added to the options menu later. The camera has no reason to go lower than 45° below horizontal, so that is restricted by clamping the rotation values after they are changed. ```gdscript # ... camera_spring.rotation.x += rotation_x # Restrict camera from rotating more than 45° from horizontal downwards. camera_spring.rotation.x = clampf(camera_spring.rotation.x, -PI/2, PI/4) camera_spring.rotation.y += rotation_y ``` #image("./images/development/controls/pivot-success.png", height: 240pt) ===== Ongoing Testing ====== Ball Idle Bouncing I found when the ball is idle, it would bounce up and down slightly. This is because the ball is a `RigidBody3D` and has gravity applied to it, which would try to pull the ball through the ground. I found the easiest way to solve this at least for now is to just set the ball's `linear_velocity.y` to `0` when it is idle. ```gdscript # ball.gd func _physics_process(delta: float) -> void: # ... if collision: var normal := collision.get_normal() # Prevent ball from bouncing off the ground when stationary. if normal == Vector3(0, 1, 0): if linear_velocity.x == 0 and linear_velocity.z == 0: linear_velocity = Vector3.ZERO # ... ``` ====== Camera Rotation When testing if the camera follows the ball correctly, I found that the camera also rotated with the ball as it was a child of the ball node. I solved this by restructuring the player scene so that the ball and everything else were siblings. #image("./images/development/controls/camera-rotation.png") This also meant that the whole of the `Controls` node needed to be repositioned as the `Ball` moved. This was a simple fix by updating the position every tick like so: ```gdscript # player.gd func _process(_delta: float) -> void: # Keep controls centred on the ball. controls.position = ball.position ``` ==== Drag Controls ===== Left Click Handling To continue with the point and drag controls, there needs to be a way to differentiate between when a mouse drag is for pivoting the camera or dragging the arrow. This can be done with an enum like so: ```gdscript enum Action { PIVOTING, DRAGGING, NONE } var action: Action = Action.NONE # ... func _input(event: InputEvent) -> void: if event is InputEventMouseButton: var mouse_event := event as InputEventMouseButton # Pivot camera on right click drag. if mouse_event.button_index == MOUSE_BUTTON_RIGHT: if mouse_event.pressed: if action == Action.NONE: Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) action = Action.PIVOTING else: if action == Action.PIVOTING: Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE) action = Action.NONE elif event is InputEventMouseMotion: var mouse_event := event as InputEventMouseMotion # Rotate camera spring arm when pivot button is down. if action == Action.PIVOTING: # ... ``` I only want left click to work when the mouse cursor is close enough to the ball, otherwise it should pivot the camera instead. This means I need to make sure `get_control_position` is relative to the ball's position to be able to get the distance away. This can be done simply by subtracting the ball's global position vector from the ray cast. ```gdscript func get_control_position(mouse_position: Vector2) -> Vector3: # ... return ray_cast.get_collision_point() - ball.position ``` This correctly results in values close to 0.5 (radius of the plane) on the cardinal directions. #image("./images/development/controls/plane-relative.png") Now left click can be handled just like right click, starting with the if condition: ```gdscript # player.gd func _input(event: InputEvent) -> void: if event is InputEventMouseButton: var mouse_event := event as InputEventMouseButton # Pivot camera on right click drag. if mouse_event.button_index == MOUSE_BUTTON_RIGHT: # ... # Drag ball controls with left click, but only if close enough, else # pivot camera. elif mouse_event.button_index == MOUSE_BUTTON_LEFT: ``` When the left mouse button is pressed down, there needs to be a condition deciding whether this is a drag of the controls or a pivot of the camera. This requires the mouse position, to get the distance from the ball. ```gdscript if mouse_event.pressed: var mouse_position := get_viewport().get_mouse_position() var control_position := get_control_position(mouse_position) ``` There should be a maximum distance away from the ball that the mouse can be to drag the controls. This means that the distance between the mouse and the ball needs to be calculated. This can be done by getting the length of the vector like so: ```gdscript var ball_distance := control_position.length() ``` The maximum distance can be set as a constant in the `player,gd` file. ```gdscript ## Distance from ball to consider a gesture a drag. @export var DRAG_THRESHOLD: float = 0.2 ``` Which can then be used to decide what action is happening, and capture the mouse only when pivoting: ```gdscript if ball_distance < DRAG_THRESHOLD: action = Action.DRAGGING else: Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) action = Action.PIVOTING ``` If the left mouse button is released, this is when the ball should be "fired" in the direction and power of the drag, which comes later, so for now I will just cancel the current action. ```gdscript if action != Action.NONE: Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE) action = Action.NONE ``` This all results in the following code: ```gdscript ## Distance from ball to consider a gesture a drag. @export var DRAG_THRESHOLD: float = 0.2 # ... func _input(event: InputEvent) -> void: if event is InputEventMouseButton: var mouse_event := event as InputEventMouseButton # ... # Drag ball controls with left click, but only if close enough, else # pivot camera. elif mouse_event.button_index == MOUSE_BUTTON_LEFT: if mouse_event.pressed: var mouse_position := get_viewport().get_mouse_position() var control_position := get_control_position(mouse_position) var ball_distance := control_position.length() if ball_distance < DRAG_THRESHOLD: action = Action.DRAGGING else: Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) action = Action.PIVOTING else: if action != Action.NONE: Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE) action = Action.NONE ``` ===== Drag Motion Handling When the mouse is moved while the left mouse button is down, the control arrow should rotate and scale in the opposite direction and magnitude of the mouse movement to show the direction and power of the ball. At the current scale, the arrow is at around 0.15 away from the ball, which seems like a good minimum power as the arrow is still easily visible. The maximum scale to get to 0.5 away from the ball is 4.5, so the scale can be clamped between these values. Not only should the z direction be scaled for length, but the x direction should balance out the shape slightly so the arrow isn't so thin long and thick when short. The following values I found were best for this: #table( columns: (auto, auto), align: top, [*z scale*], [*x scale*], [1], [0.5], [2], [0.75], [3], [1], [4], [1.25], [5], [1.5], ) This gives the following mathematical function for the scale: $S_x = 1 + (S_z - 3) * 0.25$ When $S_z$ is 1, $S_x$ results in $1 + (-2 * 0.25)$ which is correctly $0.5$. $S_z$ needs to also be calculated from the distance from the ball, ranging from $0.15 -> 1$ to $0.55 -> 4.5$. This ends up with the following linear function: $S_z = 10 * d - 0.5$ Both of these equations can be easily implemented: ```gdscript ## Convert a distance to an approximately appropriate scale. func _distance_to_z_scale(distance: float) -> float: distance = clampf(distance, 0.15, 5) return 10 * distance - 0.5 ## Map a z scale to an appropriate x scale. func _z_scale_to_x(z_scale: float) -> float: return 1 + (z_scale - 3) * 0.25 ``` We can then create a function to resize and rotate the arrow based off a 3D position. First here is the structure of the arrow scene: #image("./images/development/controls/arrow-scene.png") `$Inner` contains the arrow shapes and is offset. This is the part which should be scaled to retain the same offset from the ball. This means we need to get the `Inner` node in our script ```gdscript # arrow.gd class_name Arrow extends Node3D @onready var inner: Node3D = $Inner ``` The previous functions can then be used to get the x and z scale for the inner node. ```gdscript ## Rotate and scale the arrow opposite to the given `position`. func move_to(mouse_position: Vector3) -> void: var z_scale := _distance_to_z_scale(mouse_position.length()) var x_scale := _z_scale_to_x(z_scale) ``` The angle is needed for the rotation, this can be done by getting the angle between the mouse vector and the vector at angle 0. `Vector3.signed_angle_to` uses the current vector it is called on, and the first parameter to calculate an angle, through the reference of the axis provided in the second parameter. So I use mouse vector, the opposite of the forward vector, and the down axis to get the angle - between -$pi$ and $pi$. ```gdscript var angle := mouse_position.signed_angle_to(-Vector3.FORWARD, Vector3.DOWN) ``` ====== Arrow Rotation When the cursor is dragged out of the circle, the arrow should rotate to point in the direction of the cursor. This means that the `$Plane` needs to be large, with code to detect distance for if the cursor is out of bounds. This is because it feels unnatural for rotation to stop when the cursor is too far away but rotating around the ball. The code currently already handles this by using `clampf` on the scale. ====== Ongoing Testing ======= Arrow Scaling <arrow-scaling> When testing the arrow scaling, I found that the arrow would scale even when the cursor is "0.5m away" from the ball. This is because `clampf` was passed min $0.15$ and max $5$ instead of a maximum of $0.5$. ```diff -distance = clampf(distance, 0.15, 5) +distance = clampf(distance, 0.15, 0.5) ``` #image("./images/development/controls/arrow-scaling.png", height: 240pt) The arrow now correctly scales to a maximum size (power). ==== Moving The Ball Now the arrow can be used to control the ball. When the left mouse button is released, the ball should be moved in the direction and power of the arrow. This means that there should be a way to get the power from the arrow's scale, and the direction from the arrow's rotation. As the scale is stored in the `Inner` node, there needs to be a public function to get this out, to reduce coupling of external code on the arrow's structure: ```gdscript # arrow.gd ## Get the power, between 1 and 4.5. func get_power() -> float: return inner.scale.z ``` The dragging of the ball should be cancellable by moving the cursor back close to the ball. This can be done by checking the distance from the ball when the left mouse button is released. ```gdscript # player.gd ## Distance from ball when letting go to cancel the action. @export var CANCEL_DISTANCE: float = 0.05 # ... if action == Action.DRAGGING: # ... if ball_distance > CANCEL_DISTANCE: pass ``` The power can be obtained via `arrow.get_power()` and the direction can be obtained via `arrow.rotation.y`. This can then be used to move the ball in the direction and power. ```gdscript if ball_distance > CANCEL_DISTANCE: var rotation := arrow.rotation.y var power := arrow.get_power() ``` `rotation` is in radians, based off the forward vector, so the direction can be calculated by rotating the forward vector by the rotation angle. This can be done by using the `rotated` method on the unit vector. ```gdscript var ahead := Vector3.FORWARD var direction := ahead.rotated(Vector3.UP, rotation) ``` Finally, the `direction` vector can be scaled, and `RigidBody3D.apply_impulse` can be used to move the ball in the direction and power. ```gdscript var result := direction * power ball.apply_impulse(result) ``` ===== Ongoing Testing ====== Pivoting and Dragging Multiple Times When testing the controls, I found that the camera would pivot every first time you interact with the ball using left click. This is because the `RayCast` would not be updated immediately and always be one update behind. This was fine for when dragging, but in the check on if the cursor is close enough to the ball this was not acceptable. This was a simple fix by using `RayCast.force_raycast_update()` to update the ray cast immediately. ```gdscript # arrow.gd func get_control_position(mouse_position: Vector2) -> Vector3: # ... ray_cast.global_position = origin ray_cast.target_position = end ray_cast.force_raycast_update() return ray_cast.get_collision_point() - ball.position ``` ====== Camera Clipping Through Walls <camera-clipping-through-walls> When the ball would move so that the camera was behind a wall, the camera spring would adjust length to be in front of the wall. This is intended but would be annoying when it would happen briefly as the ball moved. One solution would be to disable camera spring collisions so the camera can be behind walls. This can be done by setting the `collision_mask` of the camera spring to ignore `0`. This would make the camera go above an underpass, but the camera can be rotated by the player anyway. #image("./images/development/controls/camera-collision.png") Another thing that can be changed is restricting the angle the camera can pivot to, as there is no reason to go below the ground. This can be done by clamping the rotation values in the `player.gd` script. ```gdscript # player.gd if action == Action.PIVOTING: # ... camera_spring.rotation.x += rotation_x # Restrict camera from rotating too far down. camera_spring.rotation.x = clampf(camera_spring.rotation.x, -PI/2, -PI/6) ``` ==== Adjusting Power The current power range of 1-4.5 is not very useful. A power of 1 still moves the ball far, and 4.5 is not enough to get up some hills. I have adjusted the power with a scale, and an offset for lower values: ```gdscript func get_power() -> float: return (inner.scale.z * 2) - 1.75 ``` ==== Zooming The camera should be able to zoom in and out. This can be done by changing the length of the camera spring. The camera spring has a property for this called `spring_length`. The mouse scroll wheel is a button action, with a `factor` as the amount/delta of each scroll - usually `1.0` but can vary depending on the mouse. ```gdscript # player.gd elif mouse_event.button_index == MOUSE_BUTTON_WHEEL_DOWN: camera_spring.spring_length += mouse_event.factor / 20 camera_spring.spring_length = clampf(camera_spring.spring_length, 0.25, 5) elif mouse_event.button_index == MOUSE_BUTTON_WHEEL_UP: camera_spring.spring_length -= mouse_event.factor / 20 camera_spring.spring_length = clampf(camera_spring.spring_length, 0.25, 5) ``` `InputEventMouseMotion.factor` is scaled to get the distance in metres to change by. This is clamped to a minimum of 0.25 and 5 so the camera is not too close or far. #image("./images/development/controls/camera-close.png", height: 240pt) #image("./images/development/controls/camera-far.png", height: 240pt) ==== Review: Controls & Camera ===== Progress Made The controls for the ball are now fully functional. The ball can be dragged around the course, and the camera can be pivoted around the ball. The camera can also be zoomed in and out, and the ball can be moved in the direction and power of the arrow. ===== Testing Done #table( columns: (1fr, 1.5fr, 1.5fr, 1.5fr, 2fr), align: top, [*Aspect Tested*], [*Input*], [*Expected Output*], [*Actual Output*], [*Comments/Resolution*], [Camera pivoting], [Right click drag], [Camera pivots around ball], [Camera pivots around ball], [], [Camera pivoting], [Left click drag], [Arrow rotates and scales to a limit], [Arrow rotates and scales too much], [Solved the scaling issue in #link-heading(<arrow-scaling>)], [Camera pivoting], [Left click drag -> right click drag], [Camera pivots around ball], [Camera pivots around ball], [], [Camera pivoting], [Pivot camera down], [Camera stops rotating below ground], [Camera stops rotating below ground], [This was adjusted in #link-heading(<camera-clipping-through-walls>)], [Ball dragging], [Left click drag then move back towards ball], [Dragging motion is cancelled], [Dragging motion is cancelled], [], [Ball dragging], [Left click drag -> release], [Ball moves in direction and power of arrow], [Ball moves in direction and power of arrow], [], [Camera position], [Move ball behind wall], [Camera does not glitch past walls], [Camera goes in front of wall momentarily when moving], [This was solved by disabling camera spring collisions in #link-heading(<camera-clipping-through-walls>)], [Camera zooming], [Scroll wheel down], [Camera zooms out to a limit], [Camera zooms out to a limit], [], [Camera zooming], [Scroll wheel up], [Camera zooms in to a limit], [Camera zooms in to a limit], [], ) ==== Links to Success Criteria - Simple to understand controls - Drag and point controls - Power of shot controlled via dragging the ball - Keyboard and mouse controls == Final Testing === User Interface #table( columns: (1fr, 0.5fr, 2fr), align: top, [*Aspect Tested*], [*Did This Work?*], [*Evidence*], [Main menu with options, play and quit buttons], [Y], [#image("./images/testing/ui/main-menu.png")], [Options menu with video, audio and controls settings], [Y], [#image("./images/testing/ui/options-menu.png")], [Video settings affects graphics], [Y], [#image("./images/testing/ui/video-settings.png")], [Controls settings modify InputMap, for keyboard and controller], [Y], [#image("./images/testing/ui/controls-settings.png")], [Audio settings affect volume], [Y], [#image("./images/testing/ui/audio-settings.png")], [Options menu saves to persistent file], [Y], [#image("./images/testing/ui/options-file.png")], ) === Course Physics #table( columns: (1fr, 0.5fr, 2fr), align: top, [*Aspect Tested*], [*Did This Work?*], [*Evidence*], [Ball collides with walls], [Y], [https://youtu.be/xqQuCVQF5mY], [Ball stops moving when idle], [Y], [https://youtu.be/xqQuCVQF5mY], [Ball bounces off slopes], [Y], [https://youtu.be/ZUcf8NkPb-w], [Ball can climb slopes], [Y], [https://youtu.be/ZUcf8NkPb-w], [Ball loses velocity when colliding], [Y], [https://youtu.be/xqQuCVQF5mY], [Ball stops moving when velocity is low], [Y], [https://youtu.be/xqQuCVQF5mY], ) === Controls & Camera #table( columns: (1fr, 0.5fr, 2fr), align: top, [*Aspect Tested*], [*Did This Work?*], [*Evidence*], [Camera pivots around ball], [Y], [https://youtu.be/MyRiPBwlchY], [Arrow rotates and scales to a limit], [Y], [https://youtu.be/MyRiPBwlchY], [Dragging motion is cancelled], [Y], [https://youtu.be/MyRiPBwlchY], [Ball moves in direction and power of arrow], [Y], [https://youtu.be/MyRiPBwlchY], [Camera stops rotating below ground], [Y], [https://youtu.be/MyRiPBwlchY], [Camera does not glitch past walls], [Y], [https://youtu.be/MyRiPBwlchY], [Camera zooms out to a limit], [Y], [https://youtu.be/MyRiPBwlchY], [Camera zooms in to a limit], [Y], [https://youtu.be/MyRiPBwlchY], ) == Evaluation === Success Criteria Here is the success criteria table from the analysis section, along with evidence to justify the ones met. #success-criteria ==== Clear main menu, high contrast colour palette, quit button in the main menu The main menu is clear, with a high contrast colour palette, and a quit button in the main menu. #image("./images/evaluation/main-menu.png") ==== Full-screen and windowed options, include a settings menu, adjustable volume, configurable controls The settings menu includes full-screen and windowed options, adjustable volume, and configurable controls. This saves to a file to persist settings between sessions. #image("./images/evaluation/options-audio.png") #image("./images/evaluation/options-video.png") #image("./images/evaluation/options-controls.png") ==== Simple to understand controls, drag and point controls, power of shot controlled via dragging the ball, keyboard and mouse controls The controls are simple to understand, with drag and point controls, the power of the shot is controlled via dragging the ball, and there are keyboard and mouse controls. This is shown in the following videos from final testing: - https://youtu.be/MyRiPBwlchY - https://youtu.be/xqQuCVQF5mY === Limitations The game is quite simple in its current state, with only one set of 6 holes and no background to the course. A 'skybox' could be added around the whole course, and the ability to create a new course easily would be a good addition. The game could also be expanded with more complex holes, such as ones with moving platforms or obstacles. Multiplayer functionality is missing, which would greatly improve the game. A server would need to be implemented that can facilitate a "lobby" where you can be invited via a code, and then play the course together. This was detailed in the original proposal but was not implemented due to time and complexity constraints. The server would have to synchronise ball positions and player actions, and the game would have to be able to handle multiple players at once. Godot provides many multiplayer nodes to add to the scene tree to implement a higher level version of multiplayer, which reduces the complexity of development. As this game was originally designed for multiplayer, adding features such as a time limit and score counter before multiplayer would be counterproductive as the system would be quite different for multiplayer. This is a scope of development problem as this takes a lot of time to design, implement and thoroughly test. Audio is also missing, which includes adding background music and sound effects for the ball rolling and colliding with walls. This would greatly improve the game's immersion and make it more enjoyable to play. This would be relatively simple to add, using the `AudioStreamPlayer` node in Godot. It would also provide feedback to the player when selecting buttons in the UI. Controller support is also lacking. Adding controller support would improve accessibility to the game for more platforms and players. This would not be too difficult to add, as Godot provides controller input events just like keyboard and mouse, it was simply missed in the development process to save time and get further in development. === Maintenance The game in its current state does not seem to have many bugs, the only issues I have found is some visual glitches in the seams between the course tiles. Stakeholder input would also be required throughout development of multiplayer, which can include integrated testing between stakeholders. This would be to ensure that the game is fun and engaging for all players, and that the game is accessible to all players. This would also include feedback on the course design and the physics of the ball, to ensure that the game is challenging but not frustrating. == Final Code & Scenes ===== menu/options/sliders/volume_slider.gd ```gdscript extends VBoxContainer @export var audio_bus_name: StringName # The index of the audio bus in all buses. @onready var audio_bus_index := AudioServer.get_bus_index(audio_bus_name) @onready var value_node: Label = %Value @onready var slider: HSlider = %Slider func _ready() -> void: # Retrieve existing volume and set that on the slider and label. var db := AudioServer.get_bus_volume_db(audio_bus_index) var percentage := db_to_linear(db) var value := roundi(percentage * 100) value_node.text = str(value) + "%" slider.value = value func _on_slider_value_changed(value: float) -> void: # Godot uses decibels, which is logorithmic. This function converts a number # from 0-1 into decibels (-80 to 24dB) var db := linear_to_db(value / 100) AudioServer.set_bus_volume_db(audio_bus_index, db) value_node.text = str(value) + "%" ``` ===== menu/options/sliders/volume_slider.tscn #image("./images/final/volume_slider.png") #image("./images/final/volume_slider-exported.png") ===== menu/options/options.tscn #image("./images/final/options.png") ===== menu/options/options.gd ```gdscript extends Control @onready var tab_container: TabContainer = $TabContainer func _ready() -> void: tab_container.get_tab_bar().grab_focus() func _on_close_button_pressed() -> void: # global.previous_scene could be either options or pause, this is set # before switching to options. get_tree().change_scene_to_file(Global.previous_scene) func _on_tree_exiting() -> void: Global.save_settings() ``` ===== menu/options/option_button_transparent.gd ```gdscript extends OptionButton func _ready() -> void: get_popup().transparent_bg = true ``` ===== menu/gui.tscn #image("./images/final/gui.png") ===== menu/main_menu.tscn #image("./images/final/main_menu.png") #image("./images/final/main_menu-props.png") ===== menu/main_menu.gd ```gdscript extends MarginContainer # Take in scenes as an exported property, to reduce coupling. @export var play_scene: PackedScene @export var options_scene: PackedScene @onready var play_button: Button = %PlayButton func _ready() -> void: play_button.grab_focus() func _on_quit_button_pressed() -> void: # `get_tree()` gets the `SceneTree` which manages the game loop. get_tree().quit() func _on_options_button_pressed() -> void: var tree := get_tree() Global.previous_scene = tree.current_scene.scene_file_path tree.change_scene_to_packed(options_scene) func _on_play_button_pressed() -> void: get_tree().change_scene_to_packed(play_scene) ``` ===== menu/play.tscn #image("./images/final/play.png") ===== player/arrow.tscn #image("./images/final/arrow.png") ===== player/arrow.gd ```gdscript class_name Arrow extends Node3D @onready var inner: Node3D = $Inner ## Get the power. func get_power() -> float: return (inner.scale.z * 2) - 1.75 ## Rotate and scale the arrow opposite to the given `position`. func move_to(mouse_position: Vector3) -> void: var z_scale := _distance_to_z_scale(mouse_position.length()) var x_scale := _z_scale_to_x(z_scale) var angle := mouse_position.signed_angle_to(-Vector3.FORWARD, Vector3.DOWN) inner.scale.x = x_scale inner.scale.z = z_scale rotation.y = angle ## Convert a distance to an approximately appropriate scale. func _distance_to_z_scale(distance: float) -> float: distance = clampf(distance, 0.15, 0.5) return 10 * distance - 0.5 ## Map a z scale to an appropriate x scale. func _z_scale_to_x(z_scale: float) -> float: return 1 + (z_scale - 3) * 0.25 ``` ===== player/plane.tscn #image("./images/final/plane.png") #image("./images/final/plane-props.png") ===== player/player.tscn #image("./images/final/player.png") #image("./images/final/player-props.png") #image("./images/final/player-cameraspring.png") #image("./images/final/player-ball.png") #image("./images/final/player-raycast.png") ===== player/player.gd ```gdscript extends Node enum Action { PIVOTING, DRAGGING, NONE } ## Distance from ball to consider a gesture a drag. @export var DRAG_THRESHOLD: float = 0.2 ## Distance from ball when letting go to cancel the action. @export var CANCEL_DISTANCE: float = 0.05 ## Sensitivity of the mouse movement when pivoting. @export var MOUSE_SENSITIVITY: int = 1 var action: Action = Action.NONE @onready var ray_cast: RayCast3D = %RayCast @onready var camera: Camera3D = %Camera @onready var arrow: Arrow = %Arrow @onready var camera_spring: SpringArm3D = %CameraSpring @onready var ball: RigidBody3D = %Ball @onready var controls: Node3D = $Controls func _ready() -> void: ball.position = Vector3(9.25, 2, 7.25) #await get_tree().create_timer(1).timeout #ball.apply_impulse(Vector3(5, 0, 3)) func _input(event: InputEvent) -> void: if event is InputEventMouseButton: var mouse_event := event as InputEventMouseButton # Pivot camera on right click drag. if mouse_event.button_index == MOUSE_BUTTON_RIGHT: if mouse_event.pressed: if Input.get_mouse_mode() == Input.MOUSE_MODE_VISIBLE: Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) action = Action.PIVOTING else: if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED: Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE) action = Action.NONE # Drag ball controls with left click, but only if close enough, else # pivot camera. elif mouse_event.button_index == MOUSE_BUTTON_LEFT: if mouse_event.pressed: var mouse_position := get_viewport().get_mouse_position() var control_position := get_control_position(mouse_position) var ball_distance := control_position.length() arrow.move_to(control_position) if ball_distance < DRAG_THRESHOLD: action = Action.DRAGGING else: Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) action = Action.PIVOTING else: if action == Action.DRAGGING: var mouse_position := get_viewport().get_mouse_position() var control_position := get_control_position(mouse_position) var ball_distance := control_position.length() if ball_distance > CANCEL_DISTANCE: var rotation := arrow.rotation.y var power := arrow.get_power() var ahead := Vector3.FORWARD var direction := ahead.rotated(Vector3.UP, rotation) var result := direction * power ball.apply_impulse(result) if action != Action.NONE: Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE) action = Action.NONE elif mouse_event.button_index == MOUSE_BUTTON_WHEEL_DOWN: camera_spring.spring_length += mouse_event.factor / 20 camera_spring.spring_length = clampf(camera_spring.spring_length, 0.25, 5) elif mouse_event.button_index == MOUSE_BUTTON_WHEEL_UP: camera_spring.spring_length -= mouse_event.factor / 20 camera_spring.spring_length = clampf(camera_spring.spring_length, 0.25, 5) elif event is InputEventMouseMotion: var mouse_event := event as InputEventMouseMotion # Rotate camera spring arm when pivot button is down. if action == Action.PIVOTING: # Invert mouse movements as the coordinate origin is different. var rotation_y := deg_to_rad(-mouse_event.relative.x * MOUSE_SENSITIVITY) var rotation_x := deg_to_rad(-mouse_event.relative.y * MOUSE_SENSITIVITY) camera_spring.rotation.x += rotation_x # Restrict camera from rotating more than 45° from horizontal downwards. camera_spring.rotation.x = clampf(camera_spring.rotation.x, -PI/2, -PI/6) camera_spring.rotation.y += rotation_y elif action == Action.DRAGGING: var mouse_position := mouse_event.global_position var control_position := get_control_position(mouse_position) arrow.move_to(control_position) func _process(_delta: float) -> void: # Keep controls centred on the ball. controls.position = ball.position func get_control_position(mouse_position: Vector2) -> Vector3: # Draw a ray cast from the camera, to the mouse position far away. # The ray is configured to only collide with the ball control plane, # so the collision is the mouse position in the same plane as the ball. var origin := camera.project_ray_origin(mouse_position) var direction := camera.project_ray_normal(mouse_position) var ray_length := camera.far var end := direction * ray_length ray_cast.global_position = origin ray_cast.target_position = end ray_cast.force_raycast_update() return ray_cast.get_collision_point() - ball.position ``` ===== player/ball.gd ```gdscript extends RigidBody3D @export var MIN_VELOCITY: float = 0.03 @export var ELASTICITY: float = 0.9 func _physics_process(delta: float) -> void: var collision := move_and_collide(linear_velocity * delta) if collision: var normal := collision.get_normal() # Prevent ball from bouncing off the ground when stationary. if normal == Vector3(0, 1, 0): if linear_velocity.x == 0 and linear_velocity.z == 0: linear_velocity = Vector3.ZERO # Bounce off walls. if normal.x != 0 or normal.z != 0: linear_velocity = linear_velocity.bounce(normal) * ELASTICITY # Stop the ball rolling forever. if linear_velocity.length() < MIN_VELOCITY: linear_velocity = Vector3.ZERO ``` ===== UI/prompts/resources/controller.gd ```gdscript @tool class_name ControllerTextures extends Resource ## Bottom action (PS X, Xbox/Steam A, Nintendo B) @export var button_0: Texture2D = null ## Right action (PS O, Xbox/Steam B, Nintendo A) @export var button_1: Texture2D = null ## Left action (PS □, Xbox/Steam X, Nintendo Y) @export var button_2: Texture2D = null ## Top action (PS △, Xbox/Steam Y, Nintendo X) @export var button_3: Texture2D = null ## Back (PS 1/2/3 Select, PS 4/5 Share, Xbox Back, Nintendo -) @export var button_4: Texture2D = null ## Guide (PS PS button, Xbox home, Nintendo home) @export var button_5: Texture2D = null ## Start (PS 1/2/3 Start, PS4/5 Options, Xbox menu, Nintendo +) @export var button_6: Texture2D = null ## Left stick (PS L3, Xbox L/LS, Nintendo left stick) @export var button_7: Texture2D = null ## Right stick (PS R3, Xbox R/RS, Nintendo right stick) @export var button_8: Texture2D = null ## Left shoulder (PS L1, Xbox LB, Nintendo L) @export var button_9: Texture2D = null ## Right shoulder (PS R1, Xbox RB, Nintendo R) @export var button_10: Texture2D = null ## D-pad up @export var button_11: Texture2D = null ## D-pad down @export var button_12: Texture2D = null ## D-pad left @export var button_13: Texture2D = null ## D-pad right @export var button_14: Texture2D = null ## PS5 Microphone, Xbox Share, Nintendo capture @export var button_15: Texture2D = null ## Paddle 1 @export var button_16: Texture2D = null ## Paddle 2 @export var button_17: Texture2D = null ## Paddle 3 @export var button_18: Texture2D = null ## Paddle 4 @export var button_19: Texture2D = null ## PS4/5 touchpad @export var button_20: Texture2D = null func get_texture(event: InputEvent) -> Texture2D: if not event is InputEventJoypadButton: return null var joypad_event := event as InputEventJoypadButton var button := joypad_event.button_index return get("button_" + str(button)) ``` ===== UI/prompts/resources/keys.gd ```gdscript @tool class_name KeyboardTextures extends Resource # All keys that can reasonably be used as custom controls. # This means no modifier keys, no mouse buttons, no keys which do not usually # pass through to programs such as numlock, const _KEYS: Array[Key] = [ KEY_0, KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_6, KEY_7, KEY_8, KEY_9, KEY_A, KEY_B, KEY_C, KEY_D, KEY_E, KEY_F, KEY_G, KEY_H, KEY_I, KEY_J, KEY_K, KEY_L, KEY_M, KEY_N, KEY_O, KEY_P, KEY_Q, KEY_R, KEY_S, KEY_T, KEY_U, KEY_V, KEY_W, KEY_X, KEY_Y, KEY_Z, KEY_APOSTROPHE, KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, KEY_ASTERISK, KEY_BACKSPACE, KEY_BRACKETLEFT, KEY_BRACKETRIGHT, KEY_GREATER, KEY_LESS, KEY_CAPSLOCK, KEY_ASCIICIRCUM, KEY_COLON, KEY_COMMA, KEY_DELETE, KEY_END, KEY_ENTER, KEY_ESCAPE, KEY_EXCLAM, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, KEY_HOME, KEY_INSERT, KEY_MINUS, KEY_PAGEDOWN, KEY_PAGEUP, KEY_PERIOD, KEY_PLUS, KEY_PRINT, KEY_QUESTION, KEY_QUOTEDBL, KEY_SEMICOLON, KEY_SLASH, KEY_BACKSLASH, KEY_SPACE, KEY_ASCIITILDE, KEY_TAB, ] var textures: Dictionary = {} func _init() -> void: for k in _KEYS: textures[OS.get_keycode_string(k)] = null # Make this Resource act like all of its properties are contained in `textures`. func _get(property: StringName) -> Variant: if property in textures.keys(): return textures[property] return null func _set(property: StringName, value: Variant) -> bool: if property in textures.keys(): textures[property] = value return true return false # Fake the properties we have as all the supported keys. func _get_property_list() -> Array[Dictionary]: var properties: Array[Dictionary] = [] for k in _KEYS: properties.append( { name = OS.get_keycode_string(k), type = TYPE_OBJECT, hint = PROPERTY_HINT_RESOURCE_TYPE, hint_string = "Texture2D" } ) return properties func get_texture(event: InputEvent) -> Texture2D: if not event is InputEventKey: return var key_event := event as InputEventKey var scancode := key_event.keycode # When accessing InputMap, this is 0 if scancode == 0: var physical := key_event.physical_keycode scancode = DisplayServer.keyboard_get_keycode_from_physical(physical) return textures.get(OS.get_keycode_string(scancode), null) ``` ===== UI/prompts/resources/keys.tres #image("./images/final/keys.png") ===== UI/prompts/resources/nintendo.tres #image("./images/final/nintendo.png") ===== UI/prompts/resources/playstation.tres #image("./images/final/playstation.png") ===== UI/prompts/resources/steam.tres #image("./images/final/steam.png") ===== UI/prompts/resources/xbox.tres #image("./images/final/xbox.png") ===== UI/prompts/controller_input.gd ```gdscript class_name ControllerInput extends ControlInput const xb_textures: ControllerTextures = preload("./resources/xbox.tres") const ps_textures: ControllerTextures = preload("./resources/playstation.tres") const ni_textures: ControllerTextures = preload("./resources/nintendo.tres") const st_textures: ControllerTextures = preload("./resources/steam.tres") @export var action: StringName func _ready() -> void: var current_events := InputMap.action_get_events(action) for existing_event in current_events: if existing_event is InputEventJoypadButton: texture_rect.texture = get_texture(existing_event) break func get_texture(event: InputEvent) -> Texture2D: var device := event.device var joy_name := Input.get_joy_name(device) # The following conditions come from the public SDL controller database # https://github.com/mdqinc/SDL_GameControllerDB/ var texture: Texture2D if joy_name.contains("Xbox"): texture = xb_textures.get_texture(event) elif ( joy_name.contains("PlayStation") or joy_name.contains("PS") or joy_name.contains("DualShock") ): texture = ps_textures.get_texture(event) elif joy_name.contains("Nintendo") or joy_name.contains("Switch"): texture = ni_textures.get_texture(event) elif joy_name.contains("Steam"): texture = st_textures.get_texture(event) else: texture = xb_textures.get_texture(event) if texture != null: store_action(event) return texture func store_action(event: InputEvent) -> void: var current_events := InputMap.action_get_events(action) # Clear any existing key events for this current action and replace it with # the new one. for existing_event in current_events: if existing_event is InputEventJoypadButton: InputMap.action_erase_event(action, existing_event) InputMap.action_add_event(action, event) ``` ===== UI/prompts/controller_input.tscn #image("./images/final/controller_input.png") #image("./images/final/controller_input-signals.png") ===== UI/prompts/control_input.gd ```gdscript class_name ControlInput extends Button # Whether to act upon new `gui_input` events. var listening: bool = false # The texture to revert to if this input is unselected. var previous_texture: Texture2D = null @onready var texture_rect: TextureRect = %TextureRect @onready var label: Label = %Label func _on_pressed() -> void: # Don't redo the same process if we are already listening, as that will # call `unlisten` below. if listening: return # Store the previous texture to revert to later if needed. previous_texture = texture_rect.texture texture_rect.texture = null label.text = "Waiting for input..." listening = true if Global.listening_control != null: Global.listening_control.unlisten() Global.listening_control = self func _on_gui_input(event: InputEvent) -> void: if not listening: return var texture := get_texture(event) if texture == null: return accept_event() label.text = "" texture_rect.texture = texture listening = false Global.listening_control = null func _on_tree_exited() -> void: unlisten() # Called either when this node is not visible (`tree_exited`), or a different # control input is selected (see above). func unlisten() -> void: listening = false label.text = "" texture_rect.texture = previous_texture # keep `get_texture` abstract, for separate key inputs and controller inputs. func get_texture(_event: InputEvent) -> Texture2D: return null ``` ===== UI/prompts/control_input.tscn #image("./images/final/control_input.png") ===== UI/prompts/key_input.gd ```gdscript class_name KeyInput extends ControlInput @export var action: StringName const textures: KeyboardTextures = preload("./resources/keys.tres") func _ready() -> void: var current_events := InputMap.action_get_events(action) for existing_event in current_events: if existing_event is InputEventKey: texture_rect.texture = get_texture(existing_event) break func get_texture(event: InputEvent) -> Texture2D: var texture := textures.get_texture(event) # If it is not null, this is a valid texture, store this event as action`. if texture != null: store_action(event) return texture func store_action(event: InputEvent) -> void: var current_events := InputMap.action_get_events(action) # Clear any existing key events for this current action and replace it with # the new one. for existing_event in current_events: if existing_event is InputEventKey: InputMap.action_erase_event(action, existing_event) InputMap.action_add_event(action, event) ``` ===== UI/prompts/key_input.tscn #image("./images/final/key_input.png") #image("./images/final/key_input-signals.png") ===== UI/themes/margin_stylebox.gd ```gdscript @tool class_name MarginStyleBox extends StyleBox @export var style_box: StyleBox: set(value): style_box = value emit_changed() @export var padding_left: int = 0: set(value): padding_left = value emit_changed() @export var padding_top: int = 0: set(value): padding_top = value emit_changed() @export var padding_right: int = 0: set(value): padding_right = value emit_changed() @export var padding_bottom: int = 0: set(value): padding_bottom = value emit_changed() func _draw(to_canvas_item: RID, rect: Rect2) -> void: var new_rect: Rect2 = rect.grow_individual( -padding_left, -padding_top, -padding_right, -padding_bottom ) if style_box: style_box.draw(to_canvas_item, new_rect) ``` ===== global.gd ```gdscript extends Node const SETTINGS_PATH = "user://settings.ini" enum {WINDOW_WINDOWED, WINDOW_FULLSCREEN, WINDOW_BORDERLESS} enum {ANTIALIASING_DISABLED, ANTIALIASING_2X, ANTIALIASING_4X, ANTIALIASING_8X} ## The scene before switching, used for back/close menu buttons. var previous_scene: String ## The control input that is currently listening. var listening_control: ControlInput ## Config file for holding modified settings. var settings := ConfigFile.new() func _ready() -> void: load_settings() func get_window_mode() -> int: var mode := DisplayServer.window_get_mode() var borderless := DisplayServer.window_get_flag(DisplayServer.WINDOW_FLAG_BORDERLESS) var id := WINDOW_WINDOWED if mode == DisplayServer.WINDOW_MODE_EXCLUSIVE_FULLSCREEN: id = WINDOW_FULLSCREEN elif mode == DisplayServer.WINDOW_MODE_WINDOWED and borderless: id = WINDOW_BORDERLESS return id func get_antialiasing() -> int: # msaa_2d and msaa_3d are the same here var antialiasing := get_viewport().msaa_2d var id := ANTIALIASING_DISABLED if antialiasing == Viewport.MSAA_2X: id = ANTIALIASING_2X elif antialiasing == Viewport.MSAA_4X: id = ANTIALIASING_4X elif antialiasing == Viewport.MSAA_8X: id = ANTIALIASING_8X return id func store_event(action: StringName, event: InputEvent) -> void: if event is InputEventKey: # Similar to prompts/resources/keys.gd#get_texture var key_event := event as InputEventKey var keycode := key_event.keycode if keycode == 0: var physical := key_event.physical_keycode keycode = DisplayServer.keyboard_get_keycode_from_physical(physical) settings.set_value("controls", action + "_key", keycode) elif event is InputEventJoypadButton: var joypad_event := event as InputEventJoypadButton var button := joypad_event.button_index settings.set_value("controls", action + "_control", button) func set_window_mode(mode: int) -> void: if mode == 0: # Windowed windows have a border and this sets it to maximised for a # consistent size when switching away from fullscreen. DisplayServer.window_set_flag(DisplayServer.WINDOW_FLAG_BORDERLESS, false) DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_MAXIMIZED) elif mode == 1: DisplayServer.window_set_position(Vector2i(0, 0)) # Exclusive fullscreen has a lower overhead as it usually avoids # the display compositor. DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_EXCLUSIVE_FULLSCREEN) elif mode == 2: # Fullscreen borderless is a full screen sized window without a border. # It usually works better with multiple monitor setups when alt+tab/esc # in windows. DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_MAXIMIZED) DisplayServer.window_set_size(DisplayServer.screen_get_size()) DisplayServer.window_set_flag(DisplayServer.WINDOW_FLAG_BORDERLESS, true) DisplayServer.window_set_position(Vector2i(0, 0)) func set_antialiasing(mode: int) -> void: var viewport := get_viewport() if mode == 0: viewport.msaa_2d = Viewport.MSAA_DISABLED viewport.msaa_3d = Viewport.MSAA_DISABLED elif mode == 1: viewport.msaa_2d = Viewport.MSAA_2X viewport.msaa_3d = Viewport.MSAA_2X elif mode == 2: viewport.msaa_2d = Viewport.MSAA_4X viewport.msaa_3d = Viewport.MSAA_4X elif mode == 3: viewport.msaa_2d = Viewport.MSAA_8X viewport.msaa_3d = Viewport.MSAA_8X func save_settings() -> void: var bus_count := AudioServer.bus_count for bus in range(bus_count): var db := AudioServer.get_bus_volume_db(bus) settings.set_value("audio", str(bus), db) var vsync := DisplayServer.window_get_vsync_mode() var video_mode := get_window_mode() var video_antialiasing := get_antialiasing() var video_vsync_enabled := vsync == DisplayServer.VSYNC_ENABLED settings.set_value("video", "mode", video_mode) settings.set_value("video", "antialiasing", video_antialiasing) settings.set_value("video", "vsync", video_vsync_enabled) var actions := InputMap.get_actions() for action in actions: # ui_* are default UI traversal controls. if not action.begins_with("ui_"): var events := InputMap.action_get_events(action) for event in events: store_event(action, event) settings.save(SETTINGS_PATH) func load_settings() -> void: var err := settings.load(SETTINGS_PATH) if err == ERR_FILE_CANT_OPEN: return # Audio var buses := settings.get_section_keys("audio") for bus in buses: var db: int = settings.get_value("audio", bus) var index := int(bus) AudioServer.set_bus_volume_db(index, db) # Video var mode: int = settings.get_value("video", "mode") set_window_mode(mode) var antialiasing: int = settings.get_value("video", "antialiasing") set_antialiasing(antialiasing) var vsync: bool = settings.get_value("video", "vsync") if vsync: DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_ENABLED) else: DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED) # Controls var controls := settings.get_section_keys("controls") for stored_control in controls: if stored_control.ends_with("_key"): var control := stored_control.trim_suffix("_key") for existing_event in InputMap.action_get_events(control): if existing_event is InputEventKey: InputMap.action_erase_event(control, existing_event) var new_event := InputEventKey.new() new_event.keycode = settings.get_value("controls", stored_control) InputMap.action_add_event(control, new_event) elif stored_control.ends_with("_control"): var control := stored_control.trim_suffix("_control") for existing_event in InputMap.action_get_events(control): if existing_event is InputEventJoypadButton: InputMap.action_erase_event(control, existing_event) var new_event := InputEventJoypadButton.new() new_event.button_index = settings.get_value("controls", stored_control) InputMap.action_add_event(control, new_event) ```
https://github.com/Its-Alex/resume
https://raw.githubusercontent.com/Its-Alex/resume/master/lib/interests.typ
typst
MIT License
#import "components/title.typ": customTitle #let interests(title, interests) = [ #customTitle(title) #grid( columns: (50%, 50%), gutter: 0pt, row-gutter: 1.5em, ..interests.map((interest) => [ #text(weight: 600)[#interest] ]) ) ]
https://github.com/mkpoli/ipsj-typst-template
https://raw.githubusercontent.com/mkpoli/ipsj-typst-template/master/lib/mixed-font.typ
typst
/// 和文・欧文で異なるフォントを指定する /// /// - jfont (string, array): 和文フォントの種類 /// - jweight (string, integer): 和文フォントの太さ /// - efont (string, array): 欧文フォントの種類 /// - eweight (string, integer): 欧文フォントの太さ /// - body (content): 本文 /// -> content #let mixed(jfont, jweight: "regular", jsize: 1em, efont, eweight: "bold", esize: 1.05em, body) = { show regex("[\p{Latin}0-9]"): set text(font: efont, weight: eweight, size: esize) show regex("[\p{scx:Han}\p{scx:Hira}\p{scx:Kana}]"): set text(font: jfont, weight: jweight, size: jsize) body }
https://github.com/erictapen/typst-invoice
https://raw.githubusercontent.com/erictapen/typst-invoice/main/README.md
markdown
MIT No Attribution
# German invoice template A template for writing invoices, inspired by the [beautiful LaTeX template by @mrzool.](https://github.com/mrzool/invoice-boilerplate/) ```typ #import "@preview/classy-german-invoice:0.3.0": invoice #show: invoice( // Invoice number "2023-001", // Invoice date datetime(year: 2024, month: 09, day: 03), // Items ( ( description: "The first service provided. The first service provided. The first service provided", price: 200, ), ( description: "The second service provided", price: 150.2 ), ), // Author ( name: "<NAME>", street: "Straße der Privatsphäre und Stille 1", zip: "54321", city: "Potsdam", tax_nr: "12345/67890", // optional signature, can be omitted signature: image("example_signature.png", width: 5em) ), // Recipient ( name: "<NAME>", street: "Musterallee", zip: "12345", city: "Musterstadt", ), // Bank account ( name: "<NAME>", bank: "Deutsche Postbank AG", iban: "DE89370400440532013000", bic: "PBNKDEFF", // There is currently only one gendered term in this template. // You can overwrite it, or omit it and just choose the default. gender: (account_holder: "Kontoinhaberin") ), // Umsatzsteuersatz (VAT) vat: 0.19, kleinunternehmer: true, ) ``` ![](thumbnail.png) ## Scope This template should work well for freelancers and small companies in the german market, that don't have an existing system in place for order tracking. Or to put it the other way round; This template is for people that mostly have to fulfill outside requirements with their invoices and don't so much benefit from extensive tracking themselfes. ## Features - [X] multiple invoice items - [X] configurable VAT - [X] configurable § 19 UStG (Kleinunternehmerregelung) note - [X] configurable signature from PNG file - [X] employs both lining and old-style number types, depending on the application - [X] [EPC QR Code](https://en.wikipedia.org/wiki/EPC_QR_code) for easier banking transactions - [ ] recipient address is guaranteed to fit in a windowed envolope (DIN 5008) ## Disclaimer This template doesn't constitute legal advice. Please check for yourself wether it fulfills your legal requirements!
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas8/2_Utorok.typ
typst
#let V = ( "HV": ( ("","O preslávnaho čudesé!","Ni umilénija sťažách, nižé sléz istóčnika, ni téplaho ispovídanija, nižé pláča omyvájuščaho, ni serdéčnaho smirénija: ni mytarjú revníteľ bých, nižé bludníci, nižé blúdnomu ótroku. Káko úbo obrjášču mojích mnóhich hrichóv ostavlénije? No ímiže Christé vísi suďbámi, spasí mja."), ("","","Stránen vsjákija sotvoríchsja božéstvennyja zápovidi: o dobroďíteli že lúčšej vsjáko nebrehóch, i bezúmno požích v ľínosti vsé žitijé mojé, v bluďí vsjá ďilá mojá soďíjach, nepodóbnaja i bezzakónnaja. Ťíímže Christé, uščédri jáko blahoutróben, i túne mjá spasí."), ("","","Ne járostiju tvojéju obličí mené, ďílo rúk tvojejá bláhosti, ottórhšasja umóm nerazúmnym, íže mené rádi po mňí blahoizvólivyj býti, neizrečénnyja rádi blahoutróbija pučíny čelovikoľúbče: no molítvami prisnoďívy, tvojejá Slóve Mátere, božéstvennaho spodóbi mjá obraščénija, jáko Bóh."), ("","O preslávnaho čudesé!","Blažénne Jo<NAME>éče, smirénnuju mojú dúšu, jáže ko Hóspodu ľubóviju vozvraščáj vsehdá, svjaščénnymi chodátajstvy tvojími slastéj mojích óhň uhasí, privoďá mja ko ispolnéniju božéstvennych poveľínij, i sérdca mojehó očiščája voístinnu čúvstvija, da slávľu ťá."), ("","","Neplódnyja prozjabénije, i čistotý sád Vladýčnij, čelovíkov udobrénije, predtéče Joánne vsechváľne, chraníteľu božéstvennyj smirénnyja mojejá duší, tvojími molítvami i pómoščiju blahouvítije dážď, izbavľája ot zmíjeva kovárstva, i lukávych tohó lájanij i prilóh."), ("","","Vés jesí sladčájšij, i sládosti božéstvennyja ispólnen prisnoslávne, i veselíši vsjá vírno prichoďáščyja k tebí, uslaždája čúvstva dušévnaja že i ťilésnaja, nedúh i skorbéj, i nachoždénij zlých, i slastéj dušetľínnych, vsehdá razrišája nás."), ("Bohoródičen","","Víroju pritekáju k pokróvu tvojemú, Bohorodíteľnice čístaja, ot napástej i bíd i strástnaho slijánija, i ot bisóvskaho ozloblénija spasí mja: jáko mílosti imúšči pučínu, i spasénija jávľšisja chodátaica Vladýčice, jáže Bóha róždši mílostivaho, jedínaho vseščédraho, i mnohoblahoutróbnaho."), ), "S": ( ("","","Tebé carjá i Vladýku, ánheli neprestánno vospivájut, áz že tí pripádaju jáko mytár zovýj: Bóže očísti mjá, i pomíluj mjá."), ("","","Bezsmértna súšči dušé mojá, volnámi žitéjskimi ne pokryvájsja, no vozníkni vopijúšči k tvojemú blahodáteľu: Bóže očísti mjá, i pomíluj mjá."), ("Múčeničen","","Múčency Hospódni, molíte Bóha nášeho, i isprosíte dušám nášym mnóžestvo ščedrót, i očiščénije mnóhich prehrišénij, mólim vý."), ("Bohoródičen","","Rádujsja vselénnyja pochvaló. Rádujsja chráme Hospódeň. Rádujsja horó priosinénnaja. Rádujsja vsích pribížišče. Rádujsja svíščniče zlatýj. Rádujsja slávo pravoslávnych čéstnája. Rádujsja Maríje Máti Christá Bóha. Rádujsja rajú. Rádujsja božéstvennaja trapézo. Rádujsja síne. Rádujsja rúčko vsezlatája. Rádujsja vsích upovánije."), ), ) #let P = ( "1": ( ("","","Vódu prošéd jáko súšu, i jehípetskaho zlá izbižáv, Izráiľťanin vopijáše: izbáviteľu i Bóhu nášemu pojím."), ("","","Vód istóčnik molítvennyj, ťá Bohorodíteľnicu vídušče vsí, istočájušč vírnym strují dušám i ťílom: ťímže ťá neprestánno slávim."), ("","","Páče jestestvá Bohonačáľnoje Slóvo rodilá jesí Ďívo, i jestestvó ot tlí izbávila jesí: ťímže bezslovésnych mjá, i črezjestéstvennych strastéj svobodí."), ("","","Pážiti strastéj plotskích nýňi okružájut mjá, i oskorbľájut ľúťi: posití skóro rabá tvojehó Ďívo, i ot ozlobľájuščich mjá spasí."), ("","","Íže vsjú tvár soderžáj i nosjáj i spasájaj, na rukú tvojéju čístaja opísan javísja, i čelovíčeskij ród obnoví."), ), "3": ( ("","","Tý jesí utverždénije pritekájuščich k tebí Hóspodi: tý jesí svít omračénnych, i pojét ťá dúch mój."), ("","","Uspí smuščénije ľútaho nedúha obderžáščaho mjá nýňi, prečístaja Vladýčice, i prehrišénij i strastéj svobodí."), ("","","Neizrečénna pučína ščedrót tvojích prečístaja, ímiže i mené izbávi prehrišénij, i nedúhov."), ("","","Ukorí i posití prečístaja, nedúhujuščaho mjá, i ťážkija boľízni izbávi, i vsjákija skórbi."), ("","","Vozvelíči mílosť i zastuplénije prečístaja, tvojích molítv na mňí: i izbávi mjá ot napástej i skorbéj."), ), "4": ( ("","","Uslýšach Hóspodi, smotrénija tvojehó tájinstvo: razumích ďilá tvojá, i proslávich tvojé Božestvó."), ("","","Očistílišče vsehdá mojemú sérdcu pokaží prečístaja, svjatých vospominánije, i prehrišénij očiščénije."), ("","","Spasénije podážď mí dušévnoje i ťilésnoje preneporóčnaja: i boľáščemu dážď ciľbú, i ľútych izbavlénije."), ("","","Kovárstvija uprazdní lukávych bisóv, prečístaja, i strastéj vostánija, i nemoščným nám sílu podážď."), ("","","Ot ložésn tvojích prečístaja, právdy sólnce vozsijá, i mír prosvití: jehóže božéstvennymi zarjámi i mené prosvití."), ), "5": ( ("","","Vskúju mjá otrínul jesí ot licá tvojehó svíte nezachodímyj, i pokrýla mjá jésť čuždája ťmá okajánnaho? No obratí mja, i k svítu zápovidej tvojích putí mojá naprávi, moľúsja."), ("","","Razrišíšasja tvojím roždestvóm úzy smértnyja, i svjazásja tlí deržáva, presvjatája Ďívo vsepítaja. Ťímže razriší vskóri i mojích prehrišénij plenícy, i ťážkija pečáli."), ("","","Lukávstvija bisóv, i zlóby čelovíčeskija izbávi Vladýčice: i dušévnyj nedúh i ťilésnyj skóro uvračúj, róždšaja jedína vsjákija plóti i duchóv vračá, Spása i Hóspoda."), ("","","Jáko kleščá božéstvennaho úhľa, prečístaja, moľú ťa, popalí vsjákuju strástnuju póchoť rabá tvojehó, i nemožénija ľútaja neudób sterpímaja, i izsuší potóki pečálej."), ("","","Spasénije ťá vsím podál jésť Sýn tvój vsečístaja Vladýčice, vírovavšym v nehó, i Bóha propovídajuščym voploščénna ot tebé jávi: ťímže mjá spasí ot razlíčnych bíd i skorbéj."), ), "6": ( ("","","Očísti mjá Spáse, mnóha bo bezzakónija mojá, i iz hlubiný zól vozvedí, moľúsja: k tebí bo vozopích, i uslýši mjá, Bóže spasénija mojehó."), ("","","Prízri na mjá mílostivnym tvojím ókom Vladýčice, i ot nedúhov ľútych izbávi vskóri, i vsjákaho ozloblénija čájemaho nýňi, i sítej, i padénija."), ("","","Bezúmnaho nráva strástnaho, i závisti nepodóbnych, i vsjákija zlóby, i ozloblénija žitéjskaho izbávi mjá, prečístaja Vladýčice, tvojími moľbámi."), ("","","Sozdávyj nás, v tebí Ďívo sozdásja, jestestvó čelovíčeskoje ot tlí izbavľája, i mené úbo izbávi čístaja, ot oderžáščich mjá iskušénij tvojími molítvami."), ("","","Chrám pokazálasja jesí Bóha nevmistímaho prečíst, tý prečístaja Vladýčice: chrám i mené pokaží tohó blahodáti, tvojími molítvami, i sobľudí nevredíma."), ), "S": ( ("","","Jáko Ďívu i jedínu v ženách, ťá bez símene róždšuju Bóha plótiju, vsí blážím ródi čelovíčestiji: óhň bo vselísja v ťá Božestvá, i jáko mladénca dojíši ziždíteľa i Hóspoda. Ťímže ánheľskij i čelovíčeskij ród dostójno slávim presvjatóje roždestvó tvojé, i sohlásno vopijém tí: molí Christá Bóha sohrišénij ostavlénije darováti vospivájuščym dostójno slávu tvojú."), ), "7": ( ("","","Ot Judéji došédše ótrocy v Vavilóňi inohdá, víroju Tróičeskoju plámeň péščnyj popráša, pojúšče: otcév Bóže blahoslovén jesí."), ("","","Ťážkija boľízni vozdajánija obritóch, i mnóhim nedúhom oderžím boľú: no moľú ťa Bohoródice, pomozí mi, i podážď zdrávije vskóri tvojími molítvami."), ("","","Blažénnaja Ďívo, pribížišče skorbjáščich vsích vírnych, ot vsjákaho iskušénija i pečáli i zlóby zavíďaščich mňí izmí, i ot hrích i razlíčnych nedúh izbávi."), ("","","Zlatokovánnaja stámno, iz nejáže istečé míro životvórnoje vírnym, otimí duší mojejá i ťíla nedúh, i prehrišénij skvérnu, zastupléňmi tvojími čístaja Bohorodíteľnice."), ("","","Roždénnaho neizrečénno iz tebé Bohomáti, sobeznačáľnaho Slóva Otcú i Dúchu slávjašče neprestánno, vo chvaléniji pojém: otéc nášich Bóže blahoslovén jesí."), ), "8": ( ("","","Sedmeríceju péšč chaldéjskij mučíteľ Bohočestívym neístovno razžžé, síloju že lúčšeju spasény sijá víďiv, tvorcú i izbáviteľu vopijáše: ótrocy blahoslovíte , svjaščénnicy vospójte, ľúdije prevoznosíte vo vsjá víki."), ("","","Velíčestvija razlíčnych čudés tvojích Vladýčice vsí propovídujem, vírno pritekájuščiji k tvojemú zastupléniju: no nýňi mjá ot nedúha ľúta i boľíznej dušévnych že i ťilésnych preminí, i pokaží zdráva obojúdu, sláviti Sýna tvojehó Christá vo víki."), ("","","Naprásno vozvíjaša zavíďaščich vítri, i zloľútych ríki pripróšasja ziló chrámiňi mojéj úmňij, Ďívo čístaja: no jákože bezúmno volnújuščahosja mórja, razorí stremlénije pečáľnych vsích: dážď i mňí tvojími molítvami tišinú vo vsjá víki."), ("","","Sozdávyj brénnoje ťílo čelovíka, táže dúšu jemú vložívyj bezsmértnu, v tebí zíždetsja Ďívo, sýj, i obnovľájet páki tohó: jehóže mňí blahouvítliva, i blahopremínna pokaží tvojími molítvami, i sílu podážď vsém skorbjáščym, i izbavlénije vskóri."), ("","","Svítom ozarjáješi vsehdá prečístaja slávjaščich ťá: iz tvojejá bo utróby vozsijá svít nevečérnij, i ot strácha noščnáho i témnaho i bisóvskaho lájanija izbavľáješi tvojá rabý: ot níchže izmí i mené, i spasí ot oderžáščich zól tvojími molítvami."), ), "9": ( ("","","Voístinnu Bohoródicu ťá ispovídujem, spasénniji tobóju Ďívo čístaja, s bezplótnymi líki ťá veličájušče."), ("","","Voznesí róh cérkve, prečístaja, vírnym podážď kríposť i utverdí."), ("","","Nizloží voznesénnyja, i pobidí polkí inopleménnych choťáščyja bránej, Ďívo čístaja: i tvojá rabý nevrédny ot sích svobodí, otrokovíce."), ("","","Jedína pobórnice christijánom pravoslávnym, tebé slávjaščym, molítvami tvojími ahárjany oruženósnyja vskóri posramí."), ("","","Vrazumí Ďívo, vírnych líki, na vrahí nevídimyja i vídimyja ukrípľši, i spasí ot vsjákija skórbi."), ), ) #let U = ( "S1": ( ("","","Okom blahoutróbnym Hóspodi, vížď mojé smirénije, jáko pomáľi žízň mojá skončavájetsja, i ot ďíl ňísť mňí spasénija. Sehó rádi moľúsja: ókom blahoutróbnym vížď mojé smirénije, i spasí mja."), ("","","Jáko sudijí prišédšu popecýsja o dušé! I strášnaho dné čás pomyšľáj: súd bo bez mílosti jésť ne soďílavšym mílosti. Ťímže préžde koncá vopíj: poščadí mja Spáse, jedín bo jesí bezhríšen."), ("Bohoródičen","","Nedvížimoje utverždénije víry, i čéstnýj dár dúš nášich, Bohoródicu písňmi veličájem vírniji: rádujsja, kámeň žízni vo črévi tvojém vmistívšaja. Rádujsja koncév nadéždo, skorbjáščich zastuplénije. rádujsja nevísto nenevístnaja."), ), "S2": ( ("","","Jáko bludníca pripádaju tí, da prijimú ostavlénije, i vmísto míra slézy ot sérdca prinošú ti: da jáko ónuju uščédriši mjá Spáse, i podási mí očiščénije hrichóv. Jáko ónaja bo zovú ti: izbávi mjá ot timínija ďíl mojích."), ("","","Vík mój skončavájetsja, žitijé mimochódit, i strášnyj tvój prestól hotóvitsja Spáse: súd mené ždét, preťá mňí óhnennoju múkoju, plámenem nehasímym: sléz túču dážď mí, i uhasí jehó sílu, choťáj spastísja vsím čelovíkom."), ("Múčeničen","","Svitíla úmnaja javístesja svjatíji múčenicy: mhlú bo prélesti uprazdníste víroju, dušévnyja váša sviščý prosvitíste, i s ženichóm so slávoju vnidóste v nebésnyj čertóh: i nýňi molítesja spastísja, mólimsja, dušám nášym."), ("Bohoródičen","","Prečístaja Ďívo, Máti Christóva, duší mojejá strásti ľútyja iscilí, moľúsja, i proščénije dáruj mojích prehrišénij, jáže bezúmňi soďíjach, dúšu mojú oskvernív, i ťílo okaľách okajánnyj. Uvý mňí, čtó sotvorjú v čás ón, vnehdá ánheli dúšu mojú razlučát ot ubóhaho mojehó ťilesé? Tohdá pomóščnica mí búdi i predstáteľnica: tebé bo ímam upovánije ráb tvój."), ), "S3": ( ("","Poveľínnoje tájno","Strášnaho i užásnaho i neumýtnaho sudíšča tvojehó Vladýko Christé, vo umí prijémľu déň i čás, trepéšču jáko zloďíj: stúdnaja ďilá ímam, i ďijánija ľútaja, jáže jedín soďíjach priľížno. Ťímže so stráchom pripádaju tí, i vopijú boľíznenno: molítvami predtéči tvojehó, mnohomílostive, spasí mja."), ("","","Dušé mojá, neradívo žízň iznurjájušči, vostáni ňíkohda, k pokajániju vozzrí: vospláčisja hórci iz hlubiný serdéčnyja, da ne káko vozrydáješi támo bez uspícha: sodrohnísja, pomyšľájušči Vladýčneje vtoróje prišéstvije, i préžde sudá samá sebé osudí: i ubíhneši ónaho sudá právednaho."), ("Bohoródičen","","Bezplótnych tvojích, Christé, i predtéči tvojehó, i učeník, i prorók, i múčenik, i svjatých vsích, i Bohoródicy neiskusomúžnyja i blahíja Mátere tvojejá molítvami umolén býv, dážď nám vo svíťi tvojém chodíti: i spodóbi nás ulučíti cárstvije tvojé, za milosérdije mílosti tvojejá."), ), "K": ( "P1": ( "1": ( ("","","Sokrušívšemu bráni mýšceju svojéju, i provédšemu Izráiľa skvozí čermnóe móre, pojím jemú, jáko izbáviteľu nášemu Bóhu: jáko proslávisja."), ("","","Ispólni mojé sérdce umilénija Christé, jáko da vnídu pokajánijem v selénija tvojá: i ispovídanijem pomoľúsja tebí, ot dolhóv mjá razrišájušču."), ("","","Razriší mja Slóve, ot soúz bezčíslennych mojích zól, da šéstvuju v pokajániji právednyja stezí tvojá, v božéstvennoje nastavľájuščyja pokójišče víčnych krasót."), ("Múčeničen","","Vzjátsja k vysoťí velíkoje múčenik tvojích Christé velikoľípije, vseslávno bo postradávše, i prevelíkimi tvojími blahodáťmi vozvelíčišasja."), ("Múčeničen","","Kroplénijem božéstvennych krovéj svjatých stradálec, króv trébiščnaja prinosímaja vrahú prestá, i osvjatíšasja zemnája Dúcha blahodátiju ."), ("Bohoródičen","","Pokajánija mí Ďívo pokaží putí, i ot voďáščyja mjá ko hrichú vozvratí stezí: da ťá pojú mnohopítuju Bóžiju rodíteľnicu."), ), "2": ( ("","","Istrjásšemu v móri mučíteľstvo faraóne, i Izráiľa súšeju nastávľšemu pojím Christú jáko proslávisja vo víki."), ("","","Predtéče propovídateľu pokajánija, pokájatisja mí ot duší vsejá, molí Spása i Hóspoda, úm mój prosviščája i sérdce, ľubóviju čtúščaho ťá."), ("","","Jáko pustýnnoje krasňíjšeje ovčá predtéče, múčeniče Christóv, nýňi v pustýni mjá strastéj vodvorjájuščasja, nastávi k žízni pokajánija, božéstvennoju tvojéju molítvoju."), ("","","Múčaščaho mjá hrichá skóro svobodí, chodátajstvom tvojím múdre predtéče, moľúsja, i razruší na mjá dvížimuju bisóvskuju búrju."), ("Bohoródičen","","Spasí mja Máti ístiny, oburevájemaho ľúťi ot strastéj, i částo pohružájema, i isprávi mjá čístaja k spasénija blahoutíšnomu pristánišču."), ), ), "P3": ( "1": ( ("","","Utverdísja sérdce mojé vo Hóspoďi, voznesésja róh mój v Bózi mojém, razširíšasja na vrahí mojá ustá mojá, vozveselíchsja o spaséniji tvojém."), ("","","Skvérny zlóbnyja otmýv mojehó sérdca, i javítisja mí neporóčnu pred tobóju v déň strášnyj spodóbi Christé mój, jáko preblahíj."), ("","","Vozmóže lukávstvom umertvíti mjá otstúpnik, žálom Slóve hrichóvnym: no sám mjá Christé, živonósnym iscilí býlijem pokajánija."), ("Múčeničen","","Stánem múžeski, vozhlašáchu strastotérpcy drúh drúhu, da ne któ vóinstva otvéržetsja: Vladýka pomóščnik nám predstojít, strážduščym dóblestvennym umóm."), ("Múčeničen","","Prečestnóje kámenije cérkve, božéstvennyja stolpý blahočéstija, prélesti pobidíteli, vsí v písnech počtím vírniji múčeniki Hospódni."), ("Bohoródičen","","Nizpádšym ispravlénije Bohoródice, pádšaho mjá vozdvíhni iz róva zól mojích: i utverdí Vladýčice, na kámeni zápovidej Bóžijich."), ), "2": ( ("","","Utverdí náš úm i serdcá, nebesá slóvom utverždéj, vo jéže píti i sláviti ťá, vo spasénije dúš nášich."), ("","","Odoždí i mňí kápli pokajánija, íže v ricí bézdnu krestívyj blahoutróbija, Hóspoda vsích predtéče, múčeniče dostoslávne."), ("","","Napástnymi volnámi žitijá vsehdá umóm koléblem, pribiháju pod króv tvój predtéče Spásov, potščísja pomoščí mi rabú tvojemú."), ("","","V noščných molítvach prizyváju dnevnáho svitíľnika tebé míru, bohoblažénne predtéče, prosvití mojá serdéčnaja čúvstva."), ("Bohoródičen","","Rádujsja ot nás svjatája Bohoródice: rádujsja, jáže rádosť róždšaja míru: rádujsja rúčko, iz nejáže mánna nebésnaja vsém vírnym dadésja."), ), ), "P4": ( "1": ( ("","","Uslýšach Hóspodi, slúch tvój, i ubojáchsja: jáko neizrečénnym sovítom, Bóh sýj prisnosúščnyj, ot Ďívy prošél jesí voplóščsja: sláva snizchoždéniju tvojemú Christé, sláva síľi tvojéj."), ("","","Preľstí mjá vkušénijem hrichóvnym vráh ľstéc, i ot tebé bláže, daléče udalí, i zubóm svojím sňíď soďíla mjá: jedíne Spáse, potščísja izjáti mjá."), ("","","Nejavlénaja Hóspodi, i sokrovénaja mojá sám vísi, sohrišívšaho tí mnóho: mnóhimi tvojími ščedrótami uščédri Slóve Bóžij, jáko mílostiv, i pokajánija mí vrémja podážď očistíteľno."), ("Múčeničen","","Jáko volnámi mučéňmi potopľájemi múčenicy, okormlénijem Christóvym ko pristániščem privedóstesja nebésnaho cárstvija, ot nehó pobidonósnymi vincý voístinnu udobrjájemi."), ("Múčeničen","","Obnovívše múčenicy, blahočéstijem zémľu serdéčnuju, ispovídanija na néj símja vložíste: i mučénija požáste jávi storíčestvujuščij krásnyj klás blahodátiju ."), ("Bohoródičen","","Vsepítaja Vladýčice, velehlásno vospivájuščaho tí, ispólni vsjákija rádosti mojú mýsľ, podajúšči mí pláč bláh, i pokajánija viný, i rázum spasénija."), ), "2": ( ("","","Uslýšach Hóspodi, smotrénija tvojehó táinstvo: razumích ďilá tvojá, i proslávich tvojé Božestvó."), ("","","Sebé samohó pláču, žitijé neisprávleno imíja vsehdá: spasí i uščédri mjá predtéče, hrichí pohibájuščaho."), ("","","V molítvach i molénijich da obrjášču ťá pomóščnika blažénne, dúšu mojú ukripľájušča, i pomyšlénije mojé ozarjájušča."), ("","","Potopľájema búreju sohrišénij, i bídstvujušča mjá, krestíteľu Christóv, okormí k pristánišču božéstvennaho rázuma."), ("Bohoródičen","","Smirívši mjá vysokomúdrenno živúščaho, spasí prečístaja, róždšaja voznésšaho smirívšejesja jestestvó."), ), ), "P5": ( "1": ( ("","","Mrák duší mojejá razžení svitodávče Christé Bóže, načaloródnuju ťmú izhnáv bézdny: i dáruj mí svít poveľínij tvojích Slóve, da útreňuja slávľu ťá."), ("","","Íže bludnícu očístivyj, i prokažénnyja, tvojím poveľínijem soďíteľu vsjáčeskich, skvérnaho hrichá smirénnuju dúšu mojú očísti, i odéždami blistájuščimi krasnú soďílaj Vladýko, moľúsja."), ("","","Ot úz razrišív mjá mnóhich mojích prehrišénij Christé Bóže, nevozbránno chodíti naprávi v putí tvojá: jáko da otrišívsja ot plóti, v pokóišča svjatája vselívsja, slávľu ťá."), ("Múčeničen","","Istkávše ot boľíznej sebí rízu slávy múčenicy, i oďíjavšesja krasnó, v výšnem živút cárstviji v rádosti, pobídy vincý krásnymi udobrjájemi."), ("Múčeničen","","Tekúščimi stojáščaja izminíša blahomúdrenno múčenicy: ťisnotámi bo mučénij razlíčnych objáti bývše, k prostránstvu ístinnomu nebésnaho cárstvija múdriji dostihóste rádujuščesja."), ("Bohoródičen","","Svjatája Bohoródice, jáže svjatóje Slóvo róždšaja plótiju, jedínaho počivájuščaho na vsích svjatých, osvjatí mój úm v lukávych ďíľich prísno prebyvájuščij."), ), "2": ( ("","","Ot nóšči nevíďinija, Bohovíďinija déň vo svíťi licá tvojehó Christé, da vozsijájet, ko útru chvalénije tvojé v serdcách nášich."), ("","","V noščí žitijá zablúždšaho mjá prosvití, slávnyj predtéče, svitíľnik sýj sólnca právednaho."), ("","","V búduščem suďí, jehdá ímam Hóspodevi predstáti, da obrjášču ťá predstáteľa predtéče, osuždénija mjá strášnaho izimájušča."), ("","","Napástvujemaho mjá, i iskušéňmi bisóvskimi koléblemaho, utverdí na kámeni božéstvennych choťínij prisnopivájemyj."), ("Bohoródičen","","Jáko prevýššaja vsích tvárej, Máti Bóžija prisnoďívo, výšša pokaží mja vrážijich sítej."), ), ), "P6": ( "1": ( ("","","Jákože proróka izbávil jesí iz hlubiný preispódnija Christé Bóže, i mené ot hrichóv mojích izbávi jáko čelovikoľúbec, i uprávi živót mój, moľúsja."), ("","","Kájuščasja prijimí mja, jákože inohdá Ninevíťany, vírovavšyja božéstvenňij própovidi, Christé, proróka tvojehó: i okormí živót mój, moľúsja tí."), ("","","Jáko mytár vozdycháju, jákože bludníca slezjú, jáko Pétr vopijú, mnóhimi pohružájem prehrišéniji Christé: pómošči mí rúku dážď, i spasí mja."), ("Múčeničen","","Jáko Bohosvítlaja svitíla múčenicy, lučámi stradánija ozarjájete vsehdá zemnýj mír, i othoňájete prélesti ťmú hlubókuju."), ("Múčeničen","","Blážénňijšij konéc obrítše vsesvjatíji múčenicy, počitájete vsehdá Bóha blažénnaho, naslaždájemi tohó svítlostiju."), ("Bohoródičen","","Mannoprijémnaja rúčka, ťá Bohoródice inohdá proobrazí: Christá bo nosíla jesí, mánnu rázuma odoždívšaho vsím čtúščym ťá."), ), "2": ( ("","","Rízu mňí podážď svítlu, oďijájsja svítom jáko rízoju, mnohomílostive Christé Bóže náš."), ("","","Sekíroju pokajánija ístinnaho vsé očísti sérdce mojé Joánne premúdre, plodonósno dobroďíteľmi soďílovaja jé."), ("","","Kítom soderžím napástej, iz hlubiný sérdca mojehó vzyváju tí predtéče: boľíznej mjá ľútych svobodí."), ("","","Dušé mojá, pokájsja tépľi, sé sudíšče priíde, vozníkni zovúšči: Iisúse Bóže mój, predtéči rádi tvojehó tý mja uščédri."), ("Bohoródičen","","Jedína slóvom, plótiju Slóvo róždšaja čístaja, mólimsja, izbávi sítej vrážijich dúšy náša."), ), ), "P7": ( "1": ( ("","","Ánhelom ótroki iz ohňá spasýj, i hremjáščuju péšč preložívyj na rósu, blahoslovén jesí Bóže otéc nášich."), ("","","Jáko v bezzakónijich začát i rodíchsja, ščédre, sohriších páče vsích čelovík: obraščénija mí podážď vrémja opravdájuščeje mjá."), ("","","Prevoznéslsja bezúmno, jákože préžde fariséj, i padénijem ľútym padóchsja, i víďa mjá rádujetsja vraždébnyj: Slóve Bóžij, ne prézri mené."), ("Múčeničen","","Sobór čéstných múčenik, vójinstvo nepoborímoje, pólk že svjatýj, hrádu napisásja na nebesích, na zemlí múžestvovavšeje."), ("Múčeničen","","Vóleju strásť prošédše múčenicy, chodátaicu bezsmértija, strujú iscilénij istočájete, čelovíkov strásti othoňájušču."), ("Bohoródičen","","Páče viný raždáješi vsích vinú, premnóžestvom bláhosti čelovíka bývšaho: ťímže sohlásno ťá čístaja, ublažájem."), ), "2": ( ("","","V načáľi zémľu osnovávyj, i nebesá slóvom utverdívyj, blahoslovén jesí vo víki, Hóspodi Bóže otéc nášich."), ("","","Íže putí Hospódni uhotóvavyj predtéče, k tomúže isprávi i mojá stezí, da zovú: blahoslovén jesí Bóže otéc nášich."), ("","","Propovídniče svíta, prosvití dúšu mojú, i ľútyja ťmý, i hejénny paľáščija izbávi mjá, pribihájuščaho k tebí nesumňínnoju dušéju."), ("","","Neplódnyja izraščénije plodovítoje sýj, mojehó sérdca neplódije vo blahoplódije pretvorí tvojími molítvami múdre krestíteľu Christóv."), ("Bohoródičen","","Izbránnaja áhnice Bóžija Slóva, molí iz tebé voplóščšahosja Bóha, ko izbránnym ovcám mjá pričtáti v čás strášnyj."), ), ), "P8": ( "1": ( ("","","Pokryvájaj vodámi prevýsprenňaja svojá, polahájaj mórju preďíl pesók, i soderžáj vsjá, ťá pojét sólnce, ťá slávit luná, tebí prinósit písň vsjá tvár, jáko soďíteľu vsích vo víki."), ("","","Rúci vsjákimi oskverníla jesí zloďijáňmi dušé mojá: i káko ťích vozďiváješi na vysotú besídujušči Bóhu? Nózi nepotrébny sotvoríla jesí, na ďilá choďášči stúdnaja: potščísja chodíti pokajánijem v putí spasíteľnyja."), ("","","Ne prebých Hóspodi, v zápovidech tvojích nikohdáže, ne sotvorích ni jedín déň tvojehó choťínija bláže: kotóryma úbo očíma vozzrjú na ťá tohdá, tvorjášča súd právednyj, i povínnyja otsylájušča vo óhň hejénskij?"), ("Múčeničen","","Razžžénnyja uhasíste péšči mnohobóžija, múdriji stradáľcy, jákože vódu izlivájušče mnóhu váša króvi, neprávedno prolijávšyjasja, za ľubóv tvorcá: ťímže potók sládostnyj nasľídujete."), ("Múčeničen","","Prevzydóste svjatíji, smirénija zemnóje ťílo, i múki jákože stráždušču inómu preterpíste, otsičénije rukám že i nohám: otňúduže prevýššija nýňi spodóbistesja žízni vo víki."), ("Bohoródičen","","Volnújema mjá búreju hrichóvnoju, vopijú ti Vladýčice čístaja, tvojím chodátajstvom naprávi mjá ko spasíteľnomu pokajániju, i ko vseutíšnomu pristánišču: jáko da uvížu svít spasénija, omračájemyj prísno ľínostiju."), ), "2": ( ("","","Beznačáľnaho carjá slávy, jehóže trepéščut nebésnyja síly, pójte svjaščénnicy, ľúdije prevoznosíte vo vsjá víki."), ("","","Vzémľuščaho hrichí míra áhnca Bóžija, jehóže pokazál jesí vsím, molí krestíteľu, strásti mojá umertvíti, i spastí dúšu mojú."), ("","","Oblehčí brémja duší mojejá, poborí borjúščyja mjá, Hospódeň krestíteľu: i ne ujázvlena mjá pokaží ot ťích zloďíjstvija."), ("","","Udalílsja jesí bíhajaj proróče, vodvorílsja že jesí v pustýňu neprochódnuju: ťímže ťá moľú, strásti duší mojejá pústy sotvorí vskóri."), ("Bohoródičen","","Lozá jesí Ďívo, jáže hrózd zríl róždšaja, umilénija pitijém napojájušči mjá nýňi, otimí pijánstvo zól mojích."), ), ), "P9": ( "1": ( ("","","Blahoslovén Hospóď Bóh Izráilev, vozdvíhnuvyj róh spasénija nám, v domú Davídovi ótroka svojehó. V níchže posití nás vostók s vysotý, i naprávil ný jésť na púť míra."), ("","","Da i áz spasájem blahodárstvenno tebí, Christé, veličáju, prízri na mjá mnóhi rány na pleščú prijémšaho, i iscilí, vinó na ních i jeléj vozlivája, tvojehó Spáse blahoutróbija poznánije."), ("","","Jákože razbójnika blahonrávnaho ispustívšaho hlás, izbávil jesí ubíjstva i ťím zlých, jákože uščédril jesí bludnícu proslezívšujusja, jáko Petrá velíkaho učeniká, i Davída proróka: i mené Spáse, pomíluj otčájannaho."), ("Múčeničen","","Soobrázni bývše strastém, stradávšaho nás rádi strastotérpcy, s ním nýňi kúpno proslavľájetesja, obožájemi božéstvennymi pričástiji, i sijájušče páče zaréj čúvstvennaho sólnca, i prosviščájušče vírnych serdcá."), ("Múčeničen","","Dobroďíteľ vozsijá svjatých stradálec, vsják hrád sími sokróvišči voístinnu nekrádomymi obohaščájetsja víroju, oblistájuščich blahodáť obíľno čudés preslávnych: jáže pisnoslóvim jáko téplyja predstáteli."), ("Bohoródičen","","Prosvitíteľnymi mólnijami, vseneporóčnaja, iz tvojejá prošédšaho utróby, Sýna Bóžija, víroju pojúščyja ťá prosvití: i ťmý nás nesvitímyja, i víčnyja múki izmí tvojím predstáteľstvom."), ), "2": ( ("","","Projavlénnoje na horí zakonopolóžniku vo ohní i kupiňí, roždestvó prisnoďívy, v náše vírnych spasénije, písňmi nemólčnymi veličájem."), ("","","Choťášču strášnomu tvojemú predstáti prestólu Slóve, i ďijánij mojích isťazájemij býti viňí, kotóryj obrjášču otvít, okajánnyj? Tvojehó rádi krestíteľa, Hóspodi Bóže mój, tohdá poščadí mja."), ("","","Jáko hlás Slóva, isprávi hlásy mojá k Bóhu, premúdre krestíteľu, i izbávi mjá zlóby bisóvskija i iskušénija čelovík: da po dólhu ublážáju ťá."), ("","","Napitáj mjá píščeju bezsmértnoju Christóvych zápovidej, napój mjá pitijém živótnym krestíteľu i proróče: i predstávi Bóhu spaséna, pod króv tvój pritekájuščaho."), ("Bohoródičen","","Vladýčice Ďívo čístaja, i preproslávlennaja, s predtéčeju Sýna tvojehó i carjá molí, ot vsjákija núždy spastí víroju ťá blažáščyja."), ), ), ), "CH": ( ("","","Jehdá prijimú vo umí mnóžestvo soďíjannych mnóju zól, i v pomyšlénije prijidú strášnaho ónaho ispytánija? Trépetom soderžím k tebí pribiháju čelovikoľúbcu Bóhu. Ťímže ne prézri mené, moľú ťa, jedíne bezhríšne: dáruj umilénije smirénňij mojéj duší préžde koncá, i spasí mja."), ("","","Slézy mí dážď Bóže, jákože inohdá žeňí hréšnici, i spodóbi mjá omočíti nózi tvojí, jáže mjá ot putí prélesti svobodívšyja, i míro blahouchánija tebí prinosíti žitijé čísto, pokajánijem mí sozdánoje, da uslýšu i áz želájemyj tvój hlás: víra tvojá spasé ťa, idí v míri."), ("Múčeničen","","Velmí podvizástesja svjatíji, múki ot bezzakónnik preterpívše dóblestvenňi, i Christá ispovídavše pred carí: i prestávľšesja ot žitijá páki síly ďíjstvujete v míri, i nedúhujuščyja isciľájete strásťmí svojími svjatíji. molíte spastísja dušám nášym."), ("Bohoródičen","","Króv tvój Bohoródice Ďívo, vračevstvó jésť duchóvnoje: vóň bo pribihájušče, ot dušévnych nedúh izbavľájemsja."), ), ) #let L = ( "B": ( ("","","Pomjaní nás Christé Spáse míra, jákože razbójnika pomjanúl jesí na drévi: i spodóbi vsích, jedíne ščédre, nebésnomu cárstviju tvojemú."), ("","","Pučínu jáko imíja Christé milosérdija, izsuší mojích prehrišénij pučínu: i umilénija slezámi dúšu mojú okamenénnuju pretvorí."), ("","","Drévle Christá v voďí krestív, božéstvennyj krestíteľu, ot strastéj mjá trevolnénija oburevájema, ko pristánišču pokajánija tvojími moľbámi ustremí."), ("Múčeničen","","Krovmí vášimi, svjatíji strastotérpcy, uhasívše óhň idolobísija, strují istočájete, vsehdá iscilénij, strásti razlíčnyja isciľájušče."), ("","","Beznačáľne Ótče, i Sýne, i božéstvennyj Dúše, krestíteľa molítvami, mnohoľítnyja strásti duší mojejá utolí, moľúsja: i spasí mja rabá tvojehó."), ("","","Izbávi nás ot strastéj bezčéstija, i ľútaho vo áďi mučénija. Moľbámi tvojími prečístaja Bohoródice, blahočéstno ťá ublažájuščich."), ), )
https://github.com/fredguth/tufte-typst
https://raw.githubusercontent.com/fredguth/tufte-typst/main/example/main.typ
typst
#import "../tufte_handout_template.typ": template, sidenote #import "@preview/tablex:0.0.5": tablex, rowspanx, colspanx, hlinex #let tbl_1 = text(size: 9pt, weight: "thin", tablex( columns: (1fr, 2fr, 2fr), rows: auto, inset: .3em, auto-lines: false, hlinex(stroke:.75pt), [$n$],[$C_n=V_n (1)$], [#align(right, $V_n (r)$)], hlinex(stroke:.5pt), align: left, [$0$], [$1$], [$1$], [$1$], [$2$], [$2r$], [$2$], [$pi$], [$pi r^2$], [$3$], [$4/3 pi$], [$4/3 pi r^3$], [$4$], [$1/2 pi^2$], [$1/2 pi^2 r^4$], [$5$], [$8/15 pi^2$], [$8/15 pi^2 r^5$], [],[],[], hlinex(stroke:.5pt) )) #show: doc => template( title: [Well-rounded facts about spheres for typsts], authors: ("<NAME>",), abstract: [This document showcases a layout for handouts inspired by the work of <NAME> (@edward_tufte), and typeset of the tufte-LaTex class. The contents of the handouts were copied from (cite Weissman) ],//be aware of the comma after name doc,) = Computing the Volume #sidenote([#v(-4em)#figure( image("./files/et_midjourney_transparent.png", width: 75%), caption: [Edward Tufte.], ) <edward_tufte>]) The closed n-dimensional ball of radius $r$, centered at the origin, is defined by: #align(center, $B^n = {accent(x, arrow) in bb(R)^n | x_1^2 + x_2^2 + ... + x_n^2 <= r^2}.$) #sidenote(align(right, block(width: 12em)[#v(5em)#tbl_1])) As a bounded closed subset of $bb(R)^n$, the $n$-ball has a well-defined volume, which we call $V_n (r)$. A table of volumes is given in the margin. Of course, the word “volume” might be a bit misleading in this degree of generality. In dimension $0$, the “volume” $V_0 (r)$ is the cardinality of the one-point set $bb(R)^0$. In dimension 1, the “volume”, $V_1 (r) = 2r$, is simply the length of the line segment $[−r, r]$. In dimension $2$, the “volume” of a circle is its area, and $V_2 (r) = pi r^2$. #sidenote(text(size:8pt, [#v(5em)Don’t confuse a definition with a computation. Of course, one could “compute” the area of a circle with an integral, but such an argument would necessarily be circular, pun intended. Perhaps the only fact that needs to be proven is that the circumference is the derivative of the area, as functions of the radius, which follows from Stokes theorem. Scaling is a particularly simple instance of the technique of change of variables. Scaling a measurable subset of $bb(R)^n$ by $r$ changes its volume by a factor of $r^n$. ])) This, in essence, is the definition of $pi$. In dimension Don’t confuse a definition with a computation. Of course, one could “compute” the area of a circle with an integral, but such an argument would necessarily be circular, pun intended. Perhaps the only fact that needs to be proven is that the circumference is the derivative of the area, as functions of the radius, which follows from Stokes theorem. 3, the “volume” of a sphere is its volume as the word is used by the English-speaking community at large. There is one fact about volumes of balls – the functions $V_n(r)$ – that can be deduced from the simplest change of variables: a ball of radius $r$ can be obtained by scaling a unit ball by $r$. It follows that $V_n (r) = V_n (1)r^n$. // For this reason, it is convenient to define Scaling is a particularly simple instance of the technique of change of variables. Scaling a measurable subset of Rn by r changes its volume by a factor of rn Cn = Vn(1), so that Vn(r) = Cnrn // In high dimensions, volume is more difficult to imagine, but // no easier and no more difficult to define mathematically. The // basic techniques of calculus suffice to compute the volumes Vn(r) // in any dimension. It is a useful exercise to identify precisely the // techniques required to compute these volumes. == Basic slicing Slicing the n-dimensional ball like an egg is helpful for computing the volume $V_n (r)$: // #sidenote([#v(-4em)#figure( // image("./files/slicer.png", width: 80%), // caption: [#text(size: 8pt)[Egg slicers, good for slicing eggs and teaching calculus.]], // ) <slicer>]) = Layout inconsistencies - leading between author and date - margin note font size should be set automatically - figure caption should be left aligned - table fractions should be slanted = Roadmap - add image - add references in the margin - integrate python/R rendering via Quarto #lorem(90) #lorem(90) = Conclusion #lorem(90)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/CHANGELOG/CHANGELOG-0.5.md
markdown
Apache License 2.0
# v0.5.0 (Unreleased) ## Changelog since v0.5.0 **Full Changelog**: https://github.com/Myriad-Dreamin/typst.ts/compare/v0.4.1...v0.5.0 ## New Contributors - @sinchang made their first contribution in https://github.com/Myriad-Dreamin/typst.ts/pull/438 - @winstonewert made their first contribution in https://github.com/Myriad-Dreamin/typst.ts/pull/482 - @quank123wip made their first contribution in https://github.com/Myriad-Dreamin/typst.ts/pull/555 - @Loosetooth made their first contribution in https://github.com/Myriad-Dreamin/typst.ts/pull/560 - @oluceps made their first contribution in https://github.com/Myriad-Dreamin/typst.ts/pull/584 ### Security Notes No new security note. ### Package: @myriaddreamin/typst.node (New) - feat: add typst.node in https://github.com/Myriad-Dreamin/typst.ts/pull/460 - dev(pkg::node): add more api and comments in https://github.com/Myriad-Dreamin/typst.ts/pull/463 - fix(pkg::node): remove additional fields added by napi prepublish in https://github.com/Myriad-Dreamin/typst.ts/pull/464 - fix: entry state mutation in node compiler by @seven-mile in https://github.com/Myriad-Dreamin/typst.ts/pull/550 - feat: add pdf options to typst.node in https://github.com/Myriad-Dreamin/typst.ts/pull/552 - dev: simplify node api in https://github.com/Myriad-Dreamin/typst.ts/pull/558 ### Package: rehype-typst (New) - feat: add rehype-typst by @Enter-tainer in https://github.com/Myriad-Dreamin/typst.ts/pull/435, https://github.com/Myriad-Dreamin/typst.ts/pull/436, and https://github.com/Myriad-Dreamin/typst.ts/pull/437 - feat: use typst.node in rehype-typst in https://github.com/Myriad-Dreamin/typst.ts/pull/549 - docs: add links to rehype-typst readme by @Loosetooth in https://github.com/Myriad-Dreamin/typst.ts/pull/560 ### Package: @myriaddreamin/typst.react (New) - feat(pkg::react): support react 18 by @sinchang in https://github.com/Myriad-Dreamin/typst.ts/pull/438 - chore(pkg::react): update to React 18 client rendering APIs by @sinchang in https://github.com/Myriad-Dreamin/typst.ts/pull/442 ### Package: @myriaddreamin/typst.vue3 (New) - feat: create typst-vue3 (simplified component) by @quank123wip in https://github.com/Myriad-Dreamin/typst.ts/pull/555 ### Package: @myriaddreamin/typst.solid (New) - dev(pkg::solid): init by @oluceps in https://github.com/Myriad-Dreamin/typst.ts/pull/584 ### Package: hexo-renderer-typst - feat: hexo-renderer-typst use typst.node in https://github.com/Myriad-Dreamin/typst.ts/pull/471 - fix(hexo): delete unused variables in processor in https://github.com/Myriad-Dreamin/typst.ts/pull/592 ### CLI - feat(cli): support reading input from stdin in https://github.com/Myriad-Dreamin/typst.ts/pull/495 ### Compiler API - feat: use random main file path for svg by mainContent in https://github.com/Myriad-Dreamin/typst.ts/pull/491 - feat(pkg::compiler): expose incremental api in https://github.com/Myriad-Dreamin/typst.ts/pull/445 ### Renderer API - fix(pkg::core): unify inconsistent pixel per pt in https://github.com/Myriad-Dreamin/typst.ts/pull/450 - dev: break change: use sys.args to control layout in https://github.com/Myriad-Dreamin/typst.ts/pull/540 - dev: replace inline svg with html command in https://github.com/Myriad-Dreamin/typst.ts/pull/541 - feat: add query interface and export customize points for scripts in https://github.com/Myriad-Dreamin/typst.ts/pull/576 - feat(pkg::compiler): expose incremental api in https://github.com/Myriad-Dreamin/typst.ts/pull/445 ### Compiler, Rust Part - dev(svg): use span based text selection in https://github.com/Myriad-Dreamin/typst.ts/pull/447 - fix(upstream): ensure thread-safe when using comemo macros in https://github.com/Myriad-Dreamin/typst.ts/pull/451 - dev: add debug loc definitions in https://github.com/Myriad-Dreamin/typst.ts/pull/456 - feat(core): rework vector IR and create passes in https://github.com/Myriad-Dreamin/typst.ts/pull/459 - fix(core): consider text elements which doesn't have source location in https://github.com/Myriad-Dreamin/typst.ts/pull/461 - fix(compiler): correctly detect not found packages in https://github.com/Myriad-Dreamin/typst.ts/pull/465 - revert: "fix(compiler): correctly detect not found packages" in https://github.com/Myriad-Dreamin/typst.ts/pull/467 - feat(compiler): resolve spans in granularity of char in https://github.com/Myriad-Dreamin/typst.ts/pull/468 - feat(compiler): api for mapping src to element positions in https://github.com/Myriad-Dreamin/typst.ts/pull/469 - dev: remove last use of unsafe spans in https://github.com/Myriad-Dreamin/typst.ts/pull/476 - feat(compiler): run in wasm32 unknown in https://github.com/Myriad-Dreamin/typst.ts/pull/484 - feat: export diagnostics objects in https://github.com/Myriad-Dreamin/typst.ts/pull/492 - feat(compiler): allow specifying input arguments in https://github.com/Myriad-Dreamin/typst.ts/pull/494 - feat: pull list of packages for world in https://github.com/Myriad-Dreamin/typst.ts/pull/499 - fix: blocking receiving http requests on another thread in https://github.com/Myriad-Dreamin/typst.ts/pull/500 - dev: generialze font resolver in https://github.com/Myriad-Dreamin/typst.ts/pull/506 - dev: shrink options for font resolver in https://github.com/Myriad-Dreamin/typst.ts/pull/508 - feat: let world take entry into consideration in https://github.com/Myriad-Dreamin/typst.ts/pull/509 - dev(compiler): add debug information on fonts in https://github.com/Myriad-Dreamin/typst.ts/pull/510 - dev: update benchmark and use naive reparsing in https://github.com/Myriad-Dreamin/typst.ts/pull/520 - dev: make file watching friendly in https://github.com/Myriad-Dreamin/typst.ts/pull/522 - fix: restore from "file not found" error after restoring deleted file in https://github.com/Myriad-Dreamin/typst.ts/pull/523 - feat: calculate color transforms at compile time in https://github.com/Myriad-Dreamin/typst.ts/pull/528 - feat: full support to world snapshot in https://github.com/Myriad-Dreamin/typst.ts/pull/545 - dev: improve impl of `EntryState` in https://github.com/Myriad-Dreamin/typst.ts/pull/557 - dev: update compiler docs in https://github.com/Myriad-Dreamin/typst.ts/pull/559 - docs: update get-started and revise compilers in https://github.com/Myriad-Dreamin/typst.ts/pull/564 - feat: allow setting targets or layout widths in https://github.com/Myriad-Dreamin/typst.ts/pull/562 - fix(core): reset diff group state in https://github.com/Myriad-Dreamin/typst.ts/pull/454 - fix(core): convert colors from different color spaces to rgb in https://github.com/Myriad-Dreamin/typst.ts/pull/501 - fix: edge cases for strokes in https://github.com/Myriad-Dreamin/typst.ts/pull/578 ### Dom Renderer (new) - feat(exporter::dom): init in https://github.com/Myriad-Dreamin/typst.ts/pull/470 - dev(dom): make higher render priority on visible pages in https://github.com/Myriad-Dreamin/typst.ts/pull/474 - dev: update dom export and all css for `&nbsp;` escaping in https://github.com/Myriad-Dreamin/typst.ts/pull/489 - fix: dom viewport width calculation by @seven-mile in https://github.com/Myriad-Dreamin/typst.ts/pull/504 - feat: better fallback emit by @seven-mile in https://github.com/Myriad-Dreamin/typst.ts/pull/480 - dev: replace legacy pdf js usages by sema export in https://github.com/Myriad-Dreamin/typst.ts/pull/531 - feat: improve the rerendering performance on multiple-page documents in https://github.com/Myriad-Dreamin/typst.ts/pull/536 - dev: sync compile actor implementation in https://github.com/Myriad-Dreamin/typst.ts/pull/546 ### Renderer Common - dev: improve performance on text selection in https://github.com/Myriad-Dreamin/typst.ts/pull/439 - dev(svg): use span based text selection in https://github.com/Myriad-Dreamin/typst.ts/pull/447 - Removed `&nbsp;` escapes in svg export by @winstonewert in https://github.com/Myriad-Dreamin/typst.ts/pull/482 - fix: render zero-sized text elements correctly in https://github.com/Myriad-Dreamin/typst.ts/pull/556 - feat: add span rules to avoid user overriden by simply `span` selector. in https://github.com/Myriad-Dreamin/typst.ts/pull/575 - docs: add guide to use rendering techniques in https://github.com/Myriad-Dreamin/typst.ts/pull/579 ### Incremental Rendering - fix(pkg::core): reset render state on `reset` call in https://github.com/Myriad-Dreamin/typst.ts/pull/452 ### Svg Renderer - fix(export::svg): reuse reference in a transformed item in https://github.com/Myriad-Dreamin/typst.ts/pull/443 - dev(export::svg): localize clip path definitions in https://github.com/Myriad-Dreamin/typst.ts/pull/444 - fix(exporter::svg): set width to zero if data is not available in https://github.com/Myriad-Dreamin/typst.ts/pull/449 - dev(exporter::svg): memorize glyph hash builder in https://github.com/Myriad-Dreamin/typst.ts/pull/457 ### Canvas Renderer - fix: incorrect value reference in canvas rendering in https://github.com/Myriad-Dreamin/typst.ts/pull/441 - feat: compute bbox of canvas elements in https://github.com/Myriad-Dreamin/typst.ts/pull/532 - feat: compute tight bbox of canvas path elements in https://github.com/Myriad-Dreamin/typst.ts/pull/533 - feat: render canvas with damage tracking in https://github.com/Myriad-Dreamin/typst.ts/pull/534 - feat: clip-based canvas rerendering in https://github.com/Myriad-Dreamin/typst.ts/pull/535 ### Misc - dev(exporter::svg): aggressive browser rasterization in https://github.com/Myriad-Dreamin/typst.ts/pull/448 - dev: add watch renderer script in https://github.com/Myriad-Dreamin/typst.ts/pull/472 - dev: reimplement safe QueryRef in https://github.com/Myriad-Dreamin/typst.ts/pull/507 - dev: remove excessive newline in logging in https://github.com/Myriad-Dreamin/typst.ts/pull/521 - refactor: refactor crates in https://github.com/Myriad-Dreamin/typst.ts/pull/566, https://github.com/Myriad-Dreamin/typst.ts/pull/569, https://github.com/Myriad-Dreamin/typst.ts/pull/570, https://github.com/Myriad-Dreamin/typst.ts/pull/571, https://github.com/Myriad-Dreamin/typst.ts/pull/572, and https://github.com/Myriad-Dreamin/typst.ts/pull/573 - dev: switch default release profile to best performance in https://github.com/Myriad-Dreamin/typst.ts/pull/581 - feat: use vite instead of esbuild and webpack in https://github.com/Myriad-Dreamin/typst.ts/pull/587
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/test/1.typ
typst
#import "@preview/touying:0.2.1": * #import "notes.typ": note, notes #let (init, slide, slides) = utils.methods(s) #show: init #set text(font:("Times New Roman","STSong")) // #set heading(numbering: "none") #let bianxi(word1,word2)=[ #word1, #word2 ] #show: slides // 用于辨析 = 雅思笔记 == 3-4日 / Alternatively: instead or else 或者 - The *_agency_* will make travel _*arrangements*_ for you. Alternatively, you can organize your own _*transport*_.旅行社将为你安排旅行,或者你也可以自己安排交通工具。 / scope: the range of a subject covered by a book, programme, discussion, class, etc. 范围 - The book covers a wide _*scope*_ of topics. 这本书涵盖了很广泛的话题。 / Coordinate: 坐标 - The _*coordinates*_ of the ship were reported to the _*coastguard*_. 船的坐标已经报告给了海岸警卫队。 // / Anchors: 锚 == 公式推导 #align(center,image("img/1.png",width:10em)) 以车体坐标系为原点, 在世界坐标系下,假设装甲板中心坐标是$(x,y,z)$,装甲板宽度长度分别为$(2a,2b)$,假设旋转角度$theta=0$,四个点的坐标分别为 #import "@preview/cetz:0.2.1" 假设上述转动角度为$theta$,其有一个旋转矩阵已经确定为$R_1$(前哨站,车两种情况,一种$+25^o$,一种$-25^o$),另外一个旋转矩阵为$R_2(theta)$ 四个点以左上角开始1编号,顺时针,有四个点$P_1,P_2,P_3,P_4$
https://github.com/mariunaise/HDA-Thesis
https://raw.githubusercontent.com/mariunaise/HDA-Thesis/master/content/introduction.typ
typst
#import "@preview/glossarium:0.4.1": * #import "@preview/bob-draw:0.1.0": * = Introduction In the field of cryptography, @puf devices are a popular tool for key generation and storage @PUFIntro @PUFIntro2. In general, a @puf refers to a type of circuit that exhibits slightly different behaviors during operation due to minor variations in the manufacturing process. Since the behaviour of one @puf device is now only reproducible on itself and not on a device of the same type with the same manufacturing process, it can be used for secure key generation and/or storage.\ To improve the reliability of the keys generated and stored using the @puf, various #glspl("hda") have been introduced. The general operation of a @puf with a @hda can be divided into two separate stages: _enrollment_ and _reconstruction_ as shown in @fig:puf_operation @PUFChartRef. #figure( include("../charts/PUF.typ"), caption: [@puf model description using enrollment and reconstruction @PUFChartRef] )<fig:puf_operation> The enrollment stage will usually be performed in near ideal, lab-like conditions i.e. at room temperature ($25°C$). During this phase, a first @puf readout $nu$ with corresponding helper data $h$ is generated. Going on, reconstruction can now be performed under varying conditions, for example at a higher temperature. Here, slightly different @puf readout $nu^*$ is generated. Using the helper data $h$ the new @puf readout $nu^*$ can be improved to be less deviated from $v$ as before. One possible implementation of this principle is called _Fuzzy Commitment_ @fuzzycommitmentpaper @ruchti2021decoder. Previous works already introduced different #glspl("hda") with various strategies @delvaux2014helper @maes2009soft. The simplest form of helper-data one could generate is reliability information for every @puf bit. Here, the @hda marks unreliable @puf bits that are then either discarded during reconstruction or rather corrected using an error correction code after the quantization process. Going on, publications @tmhd1 and @tmhd2 introduced a metric-based @hda as @tmhdt. The main goal of such a @hda is to improve the reliability of the @puf during the quantization step of the enrollment phase. To achieve that, helper data is generated to define multiple quantizers for the reconstruction phase to minimize the risk of bit errors. A generalization outline to extend @tmhdt for higher order bit quantization has already been proposed by Fischer in @smhd. In the course of this work, we will first take a closer look at @smhdt as proposed by Fischer @smhd and provide a concrete realization for this method. We will also propose the idea of a method to shape the input values of a @puf to better fit within the bounds of a multi-bit quantizer which we call @bach and discuss how such a @hda can be successfully implemented in the future. == Notation To ensure a consistent notation of functions and ideas, we will now introduce some conventions and definitions. Random distributed variables will be notated with a capital letter, i.e. $X$. Realizations will be the corresponding lower case letter, $x$. Values of $x$ subject to some kind of error are marked with a $*$ in the exponent e.g., $x^*$. Vectors will be written in bold text: e.g., $bold(k)$ represents a vector of quantized symbols. Matrices are denoted with a bold capital letter: $bold(M)$. We will call a quantized symbol $k$. $k$ consists of all possible binary symbols, i.e. $0, 01, 110$. A quantizer will be defined as a function $cal(Q)(x, bold(a))$ that returns a quantized symbol $k$. We also define the following special quantizers for metric based #glspl("hda"): A quantizer used during the enrollment phase is defined by a calligraphic $cal(E)$. For the reconstruction phase, a quantizer will be defined by a calligraphic $cal(R)$ @example-quantizer shows the curve of a 2-bit quantizer that receives $tilde(x)$ as input. In the case, that the value of $tilde(x)$ equals one of the four bounds, the quantized value is chosen randomly from the relevant bins. #figure( include("../graphics/quantizers/two-bit-enroll.typ"), caption: [Example quantizer function]) <example-quantizer> For the S-Metric Helper Data Method, we introduce a function $ cal(Q)(S,M) , $<eq-1> where $S$ determines the number of metrics and $M$ the bit width of the symbols. The corresponding metric is defined through the lower case $s$, the bit symbol through the lower case $m$. To compare both @smhdt and @bach, we will use a ratio $cal(r) = frac("Extracted bits", "Helper data bits")$. This ratio gives us an idea how many helper data bits were used to obtain a quantized symbol. $cal(r)$ is smaller than $1$ if the amount of helper data bits per quantized symbol is bigger than the symbol bit width itself and bigger than $1$ otherwise. === Tilde Domain<tilde-domain> The tilde domain describes the range of numbers between $0$ and $1$, which is defined by the image of a @cdf. As also described in @smhd, we will use a @cdf to transform the real PUF values into the tilde domain. This transformation can be performed using the function $xi = tilde(x)$. The key property of this transformation is the resulting uniform distribution of $x$. Considering a normal distribution, the CDF is defined as $ xi(frac(x - mu, sigma)) = frac(1, 2)[1 + op("erf")(frac(x - mu, sigma sqrt(2)))]. $ ==== #gls("ecdf", display: "Empirical cumulative distribution function (eCDF)") We will not always be able to find an analytical description of a probability distribution and its corresponding @cdf. Alternatively, an @ecdf can be constructed through sorting the empirical measurements of a distribution @dekking2005modern. Although less accurate, this method allows a more simple and less computationally complex way to transform real valued measurements into the tilde domain. We will mainly use the @ecdf in @chap:smhd because of the difficulty of finding an analytical description for the @cdf of a weighted linear combination of random variables. The function for an @ecdf can be defined as $ xi_#gls("ecdf") (x) = frac("number of elements in " bold(z)", s.t" <= x, n) in [0, 1], $<eq:ecdf_def> where $n$ defines the number of elements in the vector $bold(z)$. If the vector $bold(z)$ were to contain the elements $[1, 3, 4, 5, 7, 9, 10]$ and $x = 5$, @eq:ecdf_def would result to $xi_#gls("ecdf") (5) = frac(4, 7)$.\ The application of @eq:ecdf_def on $X$ will transform its values into the empirical tilde domain. We can also define an inverse @ecdf: $ xi_#gls("ecdf")^(-1) (tilde(x)) = tilde(x) dot n $<eq:ecdf_inverse> The result of @eq:ecdf_inverse is the index $i$ of the element $z_i$ from the vector of realizations $bold(z)$. To apply the @ecdf to our numerical results later, we will sort the vector of realizations $bold(z)$ of a random distributed variable $Z$ in ascending order.
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/design/design_iteration_2_proposal.typ
typst
#import "../../../style.typ": * #let load-drawio-svg(path, ..args) = image.decode(read(path).replace("Text is not SVG - cannot display", ""), ..args) = Final Design Proposal <design-proposal-2> #grid( columns: (2fr, 1.4fr), column-gutter: 5pt, [The basic structure consists of nested blocks, each representing a different expression. In that regard, it is similar to the scratch-inspired design as described in @scratch-inspired-design, with the difference that the blocks are completely enclosing their children, as can be seen in @mehta-proposal-basic-structure.], align(center + horizon)[ #figure( load-drawio-svg("../../static/mehta-proposal-basic-structure.svg"), caption: [Proposal 2 - basic structure],)<mehta-proposal-basic-structure> ] ) #grid( columns: (2fr, 1.3fr), column-gutter: 5pt, [Another similarity to the scratch-inspired design is the use of type holes for parameters that are not yet supplied. In such a case, a placeholder with nothing but the type of the parameter is shown, as can be seen in @mehta-proposal-type-hole.], align(center + horizon)[ #figure( load-drawio-svg("../../static/mehta-proposal-type-hole.svg", width: 50%), caption: [Proposal 2 - type hole],)<mehta-proposal-type-hole> ] ) #grid( columns: (2fr, 1.3fr), column-gutter: 5pt, [The main difference to the previous proposals is how scoping is solved: Instead of providing specialized expressions for constructs such as pattern matching, list comprehension, etc., the idea is to do scoping using only basic structures of functional programming such as lambda expressions. An example of that can be seen in @mehta-proposal-lambda.], align(center + horizon)[ #figure( load-drawio-svg("../../static/mehta-proposal-lambda.svg", width: 70%), caption: [Proposal 2 - lambda],)<mehta-proposal-lambda> ] ) Regarding the re-use of expressions, the idea is to define multiple small functions and then stick them together rather than providing a `let ... in ...`-like expression to declare re-usable values. #include_section("design_concept/content/design/design_iteration_2_decisions_application.typ", heading_increase: 2) #include_section("design_concept/content/design/design_iteration_2_decisions_sum_type_destruction.typ", heading_increase: 2)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/numty/0.0.2/README.md
markdown
Apache License 2.0
# Numty Numeric Typst Mathematical functions to operate vectors / arrays and numbers in typst, with simple broadcasting and Nan handling. ```typ #import "numty.typ" as nt #let a = (1,2,3) #let b = 2 #nt.mult(a,b) => (2,4,6) #nt.add(a,a) => (2,4,6) #nt.add(2,a) => (3,4,5) #nt.dot(a,a) => 11 #calc.sin((3,4)) -> fails #nt.sin((3.4)) -> (0.14411, 0.90929) #let x = nt.linspace(0,10,3) => (0,5,10) #let y = nt.sin(x) => (0, -0.95, -0.54) ``` Supported Features: Basic logic: ```typ #import "numty.typ" as nt #let a = (1,2,3) #let b = 2 #nt.eq(a,b) => (false, true, false) #nt.all(nt.eq(a,b)) => false #nt.any(nt.eq(a,b)) => true ``` Operators: ```typ #nt.add((0,1,3), 1) => (1,2,4) #nt.mult((1,3),(2,2)) => (2,6) #nt.div((1,3), (2,0)) => (0.5,float.nan) ``` Algebra with Nan handling: ```typ #nt.log((0,1,3)) = (float.nan, 0 , 0.47...) #nt.sin((1,3)) = (0.84.. , 0.14...) ``` Array operations: ```typ #nt.dot((1,2),(2,4)) => 9 #nt.normalize((1,4), l:1) => (1/5,4/5) ``` Others: ```typ #nt.lisnspace(0,10,3) => (0,5,10) nt.logspace(1,3,3) nt.geomspace(1,3,3) ```
https://github.com/storopoli/Bayesian-Statistics
https://raw.githubusercontent.com/storopoli/Bayesian-Statistics/main/slides/12-mcmc.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "@preview/polylux:0.3.1": * #import themes.clean: * #import "utils.typ": * #import "@preview/cetz:0.1.2": * #import "@preview/algo:0.3.3": algo, i, d, comment, code #new-section-slide("Markov Chain Monte Carlo (MCMC) and Model Metrics") #slide(title: "Recommended References")[ #text(size: 18pt)[ - #cite(<gelman2013bayesian>, form: "prose"): - Chapter 10: Introduction to Bayesian computation - Chapter 11: Basics of Markov chain simulation - Chapter 12: Computationally efficient Markov chain simulation - #cite(<mcelreath2020statistical>, form: "prose") - Chapter 9: Markov Chain Monte Carlo - #cite(<neal2011mcmc>, form: "prose") - #cite(<betancourtConceptualIntroductionHamiltonian2017>, form: "prose") - #cite(<gelman2020regression>, form: "prose") - Chapter 22, Section 22.8: Computational efficiency - #cite(<chibUnderstandingMetropolisHastingsAlgorithm1995>, form: "prose") - #cite(<casellaExplainingGibbsSampler1992>, form: "prose") ] ] #focus-slide(background: julia-purple)[ #align(center)[#image("images/memes/computation.png")] ] #slide(title: [Monte Carlo Methods])[ #side-by-side(columns: (4fr, 1fr))[ - #link("http://mc-stan.org/")[Stan] is named after the mathematician Stanislaw Ulam, who was involved in the Manhattan project, and while trying to calculate the neutron diffusion process for the hydrogen bomb ended up creating a whole class of methods called *Monte Carlo* @eckhardtStanUlamJohn1987. - Monte Carlo methods employ randomness to solve problems in principle are deterministic in nature. They are frequently used in physics and mathematical problems, and very useful when it is difficult or impossible to use other approaches.][ #image("images/persons/stanislaw.jpg") ] ] #slide(title: [ History Behind the Monte Carlo Methods #footnote[those who are interested, should read #cite(<eckhardtStanUlamJohn1987>, form: "prose").] ])[ #side-by-side(columns: (4fr, 1fr))[ #text(size: 17pt)[ - The idea came when Ulam was playing Solitaire while recovering from surgery. Ulam was trying to calculate the deterministic, i.e. analytical solution, of the probability of being dealt an already-won game. The calculations where almost impossible. So, he thought that he could play hundreds of games to statistically estimate, i.e. numerical solution, the probability of this result. - Ulam described the idea to John von Neumann in 1946. - Due to the secrecy, von Neumann and Ulam's work demanded a code name. Nicholas Metropolis suggested using "Monte Carlo", a homage to the "Casino Monte Carlo" in Monaco, where Ulam's uncle would ask relatives for money to play. ] ][ #image("images/persons/stanislaw.jpg") ] ] #slide(title: [Why Do We Need MCMC?])[ #text(size: 18pt)[ The main computation barrier for Bayesian statistics is the denominator in Bayes' theorem, $P("data")$: $ P(θ | "data") = (P(θ) dot P("data" | θ)) / P("data") $ In discrete cases, we can turn the denominator into a sum over all parameters using the *chain rule* of probability: $ P(A,B | C) = P(A | B,C) dot P(B | C) $ This is also known as *marginalization*: $ P("data") = sum_θ P("data" | θ) dot P(θ) $ ] ] #slide(title: [Why Do We Need MCMC?])[ However, in the case of continuous values, the denominator $P("data")$ turns into a very big and nasty integral: $ P("data") = ∫_θ P("data" | θ) dot P(θ) dif θ $ In many cases the integral is intractable (not possible of being deterministic evaluated) and, thus, we must find other ways to compute the posterior $P(θ | "data")$ without using the denominator $P("data")$. #v(2em) *This is where Monte Carlo methods comes into play!* ] #slide(title: [Why Do We Need the Denominator $P("data")$?])[ To normalize the posterior with the intent of making it a *valid probability*. This means that the probability for all possible parameters' values must be $1$: - in the *discrete* case: $ sum_θ P(θ | "data") = 1 $ - in the *continuous* case: $ ∫_θ P(θ | "data") dif θ = 1 $ ] #slide(title: [What If We Remove the Denominator $P("data")$?])[ By removing the denominator $("data")$, we conclude that the posterior $P(θ | "data")$ is *proportional* to the product of the prior and the likelihood $P(θ) dot P("data" | θ)$: #v(3em) $ P(θ | "data") ∝ P(θ) dot P("data" | θ) $ ] #slide(title: [Markov Chain Monte Carlo (MCMC)])[ Here is where *Markov Chain Monte Carlo* comes in: MCMC is an ample class of computational tools to approximate integrals and generate samples from a posterior probability @brooksHandbookMarkovChain2011. MCMC is used when it is not possible to sample $bold(θ)$ directly from the posterior probability $P(bold(θ) | "data")$. Instead, we collect samples in an iterative manner, where every step of the process we expect that the distribution which we are sampling from $P^*(bold(θ)^((*)) | "data")$ becomes more similar in every iteration to the posterior $P(bold(θ) | "data")$. All of this is to *eliminate the evaluation* (often impossible) of the *denominator* $P("data")$. ] #slide(title: [ Markov Chains ])[ #side-by-side(columns: (4fr, 1fr))[ #v(2em) - We proceed by defining an *ergodic Markov chain* #footnote[ meaning that there is an *unique stationary distribution*. ] in which the set of possible states is the sample size and the stationary distribution is the distribution to be _approximated_ (or _sampled_). - Let $X_0, X_1, dots, X_n$ be a simulation of the chain. The Markov chain *converges to the stationary distribution from any initial state* $X_0$ after a *sufficient large number of iterations* $r$. The distribution of the state $X_r$ will be similar to the stationary distribution, hence we can use it as a sample. ][ #image("images/persons/andrei_markov.jpg") ] ] #slide(title: [ Markov Chains ])[ #side-by-side(columns: (4fr, 1fr))[ - Markov chains have a property that the probability distribution of the next state *depends only on the current state and not in the sequence of events that preceded*: $ P(X_(n + 1) = x | X_0, X_1, X_2, dots, X_n) = P(X_(n + 1)=x | X_n) $ This property is called *Markovian* - Similarly, using this argument with $X_r$ as the initial state, we can use $X_(2r)$ as a sample, and so on. We can use the sequence of states $X_r, X_(2r), X_(3r), dots$ as almost (independent samples) of Markov chain stationary distribution.][ #image("images/persons/andrei_markov.jpg") ] ] #slide(title: [ Example of a Markov Chain ])[ #align(center)[ #canvas( length: 0.9cm, { import draw: * set-style( mark: (end: ">", fill: black), stroke: (thickness: 2pt), radius: 2, ) circle((0, 0)) content((0, 0), [#align(center)[Sun]]) bezier-through((0, 2), (4, 4), (8, 2)) content((4, 5), [#align(center)[$0.6$]]) bezier-through((-2, 0), (-3, -1), (-4, 0), mark: (end: none)) bezier-through((-4, 0), (-3, 1), (-2, 0)) content((-5, 0), [#align(center)[$0.4$]]) circle((8, 0)) content((8, 0), [#align(center)[Rain]]) content((4, -5), [#align(center)[$0.7$]]) bezier-through((8, -2), (4, -4), (0, -2)) bezier-through((10, 0), (11, -1), (12, 0), mark: (end: none)) bezier-through((12, 0), (11, 1), (10, 0)) content((13, 0), [#align(center)[$0.3$]]) }, ) ] ] #slide(title: [Markov Chains])[ #text(size: 18pt)[ The efficacy of this approach depends on: - *how big $r$ must be* to guarantee an *adequate sample*. - *computational power* required for every Markov chain iteration. Besides, it is custom to discard the first iterations of the algorithm because they are usually non-representative of the underlying stationary distribution to be approximate. In the initial iterations of MCMC algorithms, often the Markov chain is in a "warm-up" #footnote[some references call this "burnin".] process, and its state is very far away from an ideal one to begin a trustworthy sampling. Generally, it is recommended to *discard the first half iterations* @gelmanBasicsMarkovChain2013. ] ] #slide(title: [MCMC Algorithms])[ We have *TONS* of MCMC algorithms #footnote[ see the #link( "https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo", )[Wikipedia page for a full list]. ]. Here we are going to cover two classes of MCMC algorithms: #v(2em) - Metropolis-Hastings @metropolisEquationStateCalculations1953 @hastingsMonteCarloSampling1970. #v(2em) - Hamiltonian Monte Carlo #footnote[sometimes called Hybrid Monte Carlo, specially in the physics literature.] @neal2011mcmc @betancourtConceptualIntroductionHamiltonian2017. ] #slide(title: [MCMC Algorithms -- Metropolis-Hastings])[ These are the first MCMC algorithms. They use an *acceptance/rejection rule for the proposals*. They are characterized by proposals originated from a random walk in the parameter space. The *Gibbs algorithm* can be seen as a *special case* of MH because all proposals are automatically accepted @gelmanIterativeNonIterativeSimulation1992 #v(2em) Asymptotically, they have an acceptance rate of 23.4%, and the computational cost of every iteration is $cal(O)(d)$, where $d$ is the number of dimension in the parameter space @beskosOptimalTuningHybrid2013. ] #slide(title: [MCMC Algorithms -- Hamiltonian Monte Carlo])[ The current most efficient MCMC algorithms. They try to *avoid the random walk behavior by introducing an auxiliary vector of momenta using Hamiltonian dynamics*. The proposals are "guided" to higher density regions of the sample space. This makes *HMC more efficient in orders of magnitude when compared to MH and Gibbs*. #v(2em) Asymptotically, they have an acceptance rate of 65.1%, and the computational cost of every iteration is $cal(O)(d^(1 / 4))$, where $d$ is the number of dimension in the parameter space @beskosOptimalTuningHybrid2013. ] #slide(title: [ Metropolis Algorithm ])[ #side-by-side(columns: (4fr, 1fr))[ #text(size: 18pt)[ The first broadly used MCMC algorithm to generate samples from a Markov chain was originated in the physics literature in the 1950s and is called Metropolis @metropolisEquationStateCalculations1953, in honor of the first author #link( "https://en.wikipedia.org/wiki/Nicholas_Metropolis", )[<NAME>]. In sum, the Metropolis algorithm is an adaptation of a random walk coupled with an acceptance/rejection rule to converge to the target distribution. Metropolis algorithm uses a "proposal distribution" $J_t (bold(θ)^*)$ to define the next values of the distribution $P^*(bold(θ)^* | "data")$. This distribution must be symmetric: $ J_t (bold(θ)^* | bold(θ)^(t-1)) = J_t (bold(θ)^(t-1) | bold(θ)^(*)) $ ] ][ #image("images/persons/nicholas_metropolis.png") ] ] #slide(title: [Metropolis Algorithm])[ #text(size: 18pt)[ Metropolis is a random walk through the parameter sample space, where the probability of the Markov chain changing its state is defined as: $ P_"change" = min(P(bold(θ)_"proposed") / (P(bold(θ)_"current")), 1). $ This means that the Markov chain will only change to a new state based in one of two conditions: - when the probability of the random walk proposed parameters $P(bold(θ)_"proposed")$ is #text(fill: julia-blue)[*higher*] than the probability of the current state parameters $P(bold(θ)_"current")$, we change with 100% probability. - when the probability of the random walk proposed parameters $P(bold(θ)_"proposed")$ is #text(fill: julia-red)[lower] than the probability of the current state parameters $P(bold(θ)_"current")$, we change with probability equal to the proportion of this probability difference. ] ] #slide(title: [Metropolis Algorithm])[ #algo(line-numbers: false)[ Define an initial set $bold(θ)^0 ∈ RR^p$ that $P(bold(θ)^0 | bold(y)) > 0$ \ for $t = 1, 2, dots$ #i \ Sample a proposal of $bold(θ)^*$ from a proposal distribution in time $t$, $J_t (bold(θ)^* | bold(θ)^(t - 1))$ \ As an acceptance/rejection rule, compute the proportion of the probabilities: \ $ r = (P(bold(θ)^* | bold(y))) / (P(bold(θ)^(t - 1) | bold(y))) $ Assign: $ bold(θ)^t = cases(bold(θ)^* "with probability" min(r, 1), bold(θ)^(t - 1) "otherwise") $ ] ] #slide(title: [Visual Intuition -- Metropolis])[ #align(center)[ #import draw: * #canvas( length: 0.9cm, { set-style(stroke: (thickness: 2pt)) plot.plot( size: (16, 9), x-label: none, y-label: "PDF", x-tick-step: 1, y-tick-step: 0.1, y-max: 0.55, { plot.add( domain: (-4, 4), samples: 200, style: (stroke: (paint: julia-purple, thickness: 2pt)), x => gaussian(x, 0, 1), ) }, ) // mark: (end: ">", fill: black), content((4, 1.5), text(size: 24pt, fill: julia-blue)[🚶]) content((8, 7), text(size: 24pt, fill: julia-blue)[🚶]) content((12, 1.5), text(size: 24pt, fill: julia-blue)[🚶]) { set-style(mark: (end: ">", fill: black)) bezier-through((4, 2), (6, 8), (7.5, 7)) bezier-through((8.5, 7), (10, 8), (12, 2)) } content((3, 7), [$P = 1$]) content((13, 7), [$P ≈ 1 / 4$]) }, ) ] ] #slide(title: [ Metropolis-Hastings Algorithm ])[ #side-by-side(columns: (4fr, 1fr))[ In the 1970s emerged a generalization of the Metropolis algorithm, which *does not need that the proposal distributions be symmetric*: #v(2em) $ J_t (bold(θ)^* | bold(θ)^(t - 1)) ≠ J_t (bold(θ)^(t - 1) | bold(θ)^*) $ #v(2em) The generalization was proposed by #link("https://en.wikipedia.org/wiki/W._K._Hastings")[<NAME>] @hastingsMonteCarloSampling1970 and is called *Metropolis-Hastings algorithm*. ][ #image("images/persons/hastings.jpg") ] ] #slide(title: [Metropolis-Hastings Algorithm])[ #algo(line-numbers: false)[ Define an initial set $bold(θ)^0 ∈ RR^p$ that $P(bold(θ)^0 | bold(y)) > 0$ \ for $t = 1, 2, dots$ #i \ Sample a proposal of $bold(θ)^*$ from a proposal distribution in time $t$, $J_t (bold(θ)^* | bold(θ)^(t - 1))$ \ As an acceptance/rejection rule, compute the proportion of the probabilities: \ $ r = ((P(bold(θ)^* | bold(y))) / (J_t ( bold(θ)^* | bold(θ)^(t - 1) ))) / ((P(bold(θ)^(t - 1) | bold(y))) / (J_t ( bold(θ)^(t - 1) | bold(θ)^* ))) $ Assign: $ bold(θ)^t = cases(bold(θ)^* "with probability" min(r, 1), bold(θ)^(t - 1) "otherwise") $ ] ] #slide(title: [Metropolis-Hastings Animation])[ #v(4em) #align(center)[ See Metropolis-Hastings in action at #link( "https://chi-feng.github.io/mcmc-demo/app.html?algorithm=RandomWalkMH&target=banana", )[ `chi-feng/mcmc-demo` ]. ] ] #slide(title: [Limitations of the Metropolis Algorithms])[ The limitations of the Metropolis-Hastings algorithms are mainly *computational*: - with the proposals randomly generated, it can take a large number of iterations for the Markov chain to enter higher posterior densities spaces. - even highly-efficient MH algorithms sometimes accept less than 25% of the proposals @robertsWeakConvergenceOptimal1997 @beskosOptimalTuningHybrid2013. - in lower-dimensional contexts, higher computational power can compensate the low efficiency up to a point. But in higher-dimensional (and higher-complexity) modeling situations, higher computational power alone are rarely sufficient to overcome the low efficiency. ] #slide(title: [Gibbs Algorithm])[ #side-by-side(columns: (4fr, 1fr))[ To circumvent Metropolis' low acceptance rate, the Gibbs algorithm was conceived. Gibbs *do not have an acceptance/rejection rule* for the Markov chain state change: *all proposals are accepted!* Gibbs algorithm was originally conceived by the physicist <NAME> while referencing an analogy between a sampling algorithm and statistical physics (a physics field that originates from statistical mechanics). The algorithm was described by the Geman brothers in 1984 @gemanStochasticRelaxationGibbs1984, about 8 decades after Gibbs death. ][ #image("images/persons/josiah_gibbs.jpg") ] ] #slide(title: [Gibbs Algorithm])[ The Gibbs algorithm is very useful in multidimensional sample spaces. It is also known as *alternating conditional sampling*, because we always sample a parameter *conditioned* on the probability of the other model's parameters. The Gibbs algorithm can be seen as a *special case* of the Metropolis-Hastings algorithm, because all proposals are accepted @gelmanIterativeNonIterativeSimulation1992. The essence of the Gibbs algorithm is the sampling of parameters conditioned in other parameters: $ P(θ_1 | θ_2, dots, θ_p) $ ] #slide(title: [Gibbs Algorithm])[ #algo(line-numbers: false)[ Define an initial set $bold(θ)^0 ∈ RR^p$ that $P(bold(θ)^0 | bold(y)) > 0$ \ for $t = 1, 2, dots$ #i \ Assign: $ bold(θ)^t = cases( bold(θ)^t_1 tilde P(θ_1 | θ^0_2, dots, θ^0_p), bold(θ)^t_2 tilde P(θ_2 | θ^(t - 1)_1, dots, θ^(t - 1)_p), dots.v, bold(θ)^t_p tilde P(θ_p | θ^(t - 1)_1, dots, θ^(t - 1)_(p - 1)), ) $ ] ] #slide(title: [Gibbs Animation])[ #v(4em) #align(center)[ See Gibbs in action at #link( "https://chi-feng.github.io/mcmc-demo/app.html?algorithm=GibbsSampling&target=banana", )[ `chi-feng/mcmc-demo` ]. ] ] #slide(title: [Limitations of the Gibbs Algorithm])[ The main limitation of Gibbs algorithm is with relation to *alternating conditional sampling*: - In Metropolis, the parameters' random proposals are sampled *unconditionally*, *jointly*, and *simultaneous*. The Markov chain state changes are executed in a *multidimensional* manner. This makes *multidimensional diagonal movements*. - In the case of the Gibbs algorithm, this movement only happens one parameter at a time, because we sample parameters in a *conditional* and *sequential* manner with respect to other parameters. This makes *unidimensional horizontal/vertical movements*, and never multidimensional diagonal movements. ] #slide(title: [Hamiltonian Monte Carlo (HMC)])[ #side-by-side(columns: (4fr, 1fr))[ Metropolis' low acceptance rate and Gibbs' low performance in multidimensional problems (where the posterior geometry is highly complex) made a new class of MCMC algorithms to emerge. These are called Hamiltonian Monte Carlo (HMC), because they incorporate Hamiltonian dynamics (in honor of Irish physicist #link( "https://en.wikipedia.org/wiki/William_Rowan_Hamilton", )[<NAME>ton]). ][ #image("images/persons/hamilton.png") ] ] #slide(title: [HMC Algorithm])[ #text(size: 18pt)[ HMC algorithm is an adaptation of the MH algorithm, and employs a guidance scheme to the generation of new proposals. It boosts the acceptance rate, and, consequently, has a better efficiency. More specifically, HMC uses the gradient of the posterior's log density to guide the Markov chain to higher density regions of the sample space, where most of the samples are sampled: $ (dif log P(bold(θ) | bold(y))) / (dif θ) $ As a result, a Markov chain that uses a well-adjusted HMC algorithm will accept proposals with a much higher rate than if using the MH algorithm @robertsWeakConvergenceOptimal1997 @beskosOptimalTuningHybrid2013. ] ] #slide(title: [History of HMC Algorithm])[ HMC was originally described in the physics literature #footnote[where is called "Hybrid" Monte Carlo (HMC)] @duaneHybridMonteCarlo1987. #v(2em) Soon after, HMC was applied to statistical problems by #cite(<nealImprovedAcceptanceProcedure1994>, form: "prose") who named it as Hamiltonian Monte Carlo (HMC). #v(2em) For a much more detailed and in-depth discussion (not our focus here) of HMC, I recommend #cite(<neal2011mcmc>, form: "prose") and #cite(<betancourtConceptualIntroductionHamiltonian2017>, form: "prose"). ] #slide(title: [What Changes With HMC?])[ HMC uses Hamiltonian dynamics applied to particles efficiently exploring a posterior probability geometry, while also being robust to complex posterior's geometries. #v(2em) Besides that, HMC is much more efficiently than Metropolis and does _not_ suffer Gibbs' parameters correlation issues ] #slide(title: [Intuition Behind the HMC Algorithm])[ #text(size: 18pt)[ For every parameter $θ_j$, HMC adds a momentum variable $φ_j$. The posterior density $P(bold(θ) | y)$ is incremented by an independent momenta distribution $P(bold(φ))$, hence defining the following joint probability: $ P(bold(θ), bold(φ) | y) = P(bold(φ)) dot P(bold(θ) | y) $ HMC uses a proposal distribution that changes depending on the Markov chain current state. HMC finds the direction where the posterior density increases, the *gradient*, and alters the proposal distribution towards the gradient direction. The probability of the Markov chain to change its state in HMC is defined as: $ P_"change" = min( (P(bold(θ)_"proposed") dot P(bold(φ)_"proposed")) / (P(bold(θ)_"current") dot P(bold(φ)_"current")), 1, ) $ ] ] #slide(title: [Momenta Distribution -- $P(bold(φ))$])[ Generally we give $bold(φ)$ a multivariate normal distribution with mean $0$ and covariance $bold(M)$, a "mass matrix". #v(2em) To keep things computationally simple, we used a *diagonal* mass matrix $bold(M)$. This makes that the diagonal elements (components) $bold(φ)$ are independent, each one having a normal distribution: $ φ_j tilde "Normal"(0, M_(j j)) $ ] #slide(title: [HMC Algorithm])[ #text(size: 13pt)[ #algo(line-numbers: false)[ Define an initial set $bold(θ)^0 ∈ RR^p$ that $P(bold(θ)^0 | bold(y)) > 0$ \ Sample $bold(φ)$ from a $"Multivariate Normal"(bold(0),bold(M))$ \ Simultaneously sample $bold(θ)^*$ and $bold(φ)$ with $L$ steps and step-size $ε$ \ Define the current value of $bold(θ)$ as the proposed value $bold(θ)^*$: $bold(θ)^* <- bold(θ)$ \ for $1, 2, dots, L$ #i \ Use the $log$ of the posterior's gradient $bold(θ)^*$ to produce a half-step of $bold(φ)$: $bold(φ) <- bold(φ) + 1 / 2 ε (dif log P( bold(θ)^* | bold(y) )) / (dif θ)$ \ Use $bold(φ)$ to update $bold(θ)^*$: $bold(θ)^* <- bold(θ)^* + ε bold(M)^(-1) bold(φ)$ \ Use again $bold(θ)^*$ $log$ gradient to produce a half-step of $bold(φ)$: $bold(φ) <- bold(φ) + 1 / 2 ε (dif log P( bold(θ)^* | bold(y) )) / (dif θ)$ #d \ As an acceptance/rejection rule, compute: \ $ r = (P (bold(θ)^* | bold(y)) P (bold(φ)^*)) / (P ( bold(θ)^(t - 1) | bold(y) ) P(bold(φ)^(t - 1))) $ Assign: $ bold(θ)^t = cases(bold(θ)^* "with probability" min(r, 1), bold(θ)^(t - 1) "otherwise") $ ] ] ] #slide(title: [HMC Animation])[ #v(4em) #align(center)[ See HMC in action at #link( "https://chi-feng.github.io/mcmc-demo/app.html?algorithm=HamiltonianHMC&target=banana", )[ `chi-feng/mcmc-demo` ]. ] ] #slide(title: [An Interlude into Numerical Integration])[ In the field of ordinary differential equations (ODE), we have the idea of "discretizing" a system of ODEs by applying a small step-size $ε$ #footnote[sometimes also called $h$]. Such approaches are called "numerical integrators" and are composed by an ample class of tools. #v(2em) The most famous and simple of these numerical integrators is the Euler method, where we use a step-size $ε$ to compute a numerical solution of system in a future time $t$ from specific initial conditions. ] #slide(title: [An Interlude into Numerical Integration])[ #side-by-side(columns: (3fr, 2fr))[ The problem is that Euler method, when applied to Hamiltonian dynamics, *does not preserve volume*. #v(1em) One of the fundamental properties of Hamiltonian dynamics if *volume preservation*. #v(1em) This makes the Euler method a bad choice as a HMC's numerical integrator. ][ #figure( image("images/mcmc/euler_0_3.jpg", height: 55%), caption: [HMC numerically integrated using Euler with $ε = 0.3$ and $L = 20$], ) ] ] #slide(title: [ An Interlude into Numerical Integration #footnote[ An excellent textbook for numerical and symplectic integrator is #cite(<irseles2008numericalanalysis>, form: "prose"). ] ])[ #side-by-side(columns: (3fr, 2fr))[ To preserve volume, we need a numerical *symplectic integrator*. #v(1em) Symplectic integrators are at most second-order and demands a constant step-size $ε$. #v(1em) One of the main numerical symplectic integrator used in Hamiltonian dynamics is the *Störmer–Verlet integrator*, also known as *leapfrog integrator*. ][ #figure( image("images/mcmc/leapfrog_0_3.jpg", height: 55%), caption: [HMC numerically integrated using leapfrog with $ε = 0.3$ and $L = 20$], ) ] ] #slide(title: [Limitations of the HMC Algorithm])[ #side-by-side(columns: (3fr, 2fr))[ As you can see, HMC algorithm is highly sensible to the choice of leapfrog steps $L$ and step-size $ε$, #v(1em) More specific, the leapfrog integrator allows only a constant $ε$. #v(1em) There is a delicate balance between $L$ and $ε$, that are hyperparameters and need to be carefully adjusted. ][ #figure( image("images/mcmc/leapfrog_1_2.jpg", height: 55%), caption: [HMC numerically integrated using leapfrog with $ε = 1.2$ and $L = 20$], ) ] ] #slide(title: [No-U-Turn-Sampler (NUTS)])[ In HMC, we can adjust $ε$ during the algorithm runtime. But, for $L$, we need to to "dry run" the HMC sampler to find a good candidate value for $L$. #v(2em) Here is where the idea for No-U-Turn-Sampler (NUTS) @hoffman2014no enters: you don't need to *adjust anything*, just "press the button". #v(2em) It will automatically find $ε$ and $L$. ] #slide(title: [No-U-Turn-Sampler (NUTS)])[ More specifically, we need a criterion that informs that we performed enough Hamiltonian dynamics simulation. In other words, to simulate past beyond would not increase the distance between the proposal $bold(θ)^*$ and the current value $bold(θ)$. NUTS uses a criterion based on the dot product between the current momenta vector $bold(φ)$ and the difference between the proposal vector $bold(θ)^*$ and the current vector $bold(θ)$, which turns into the derivative with respect to time $t$ of half of the distance squared between $bold(θ)$ e $bold(θ)^*$: $ (bold(θ)^* - bold(θ)) dot bold(φ) = (bold(θ)^* - bold(θ)) dot (dif) / (dif t) (bold(θ)^* - bold(θ)) = (dif) / (dif t) ((bold(θ)^* - bold(θ)) dot (bold(θ)^* - bold(θ))) / 2 $ ] #slide(title: [No-U-Turn-Sampler (NUTS)])[ #v(2em) This suggests an algorithms that does not allow proposals be guided infinitely until the distance between the proposal $bold(θ)^*$ and the current $bold(θ)$ is less than zero. #v(2em) This means that such algorithm will *not allow u-turns*. ] #slide(title: [No-U-Turn-Sampler (NUTS)])[ #text(size: 18pt)[ NUTS uses the leapfrog integrator to create a binary tree where each leaf node is a proposal of the momenta vector $bold(φ)$ tracing both a forward ($t + 1$) as well as a backward ($t - 1$) path in a determined fictitious time $t$. The growing of the leaf nodes are *interrupted* when an u-turn is detected, both forward or backward. #figure( image("images/mcmc/nuts.jpg", height: 40%), caption: [NUTS growing leaf nodes forward], ) ] ] #slide(title: [No-U-Turn-Sampler (NUTS)])[ #v(2em) NUTS also uses a procedure called Dual Averaging @nesterov2009primal to simultaneously adjust $ε$ and $L$ by considering the product $ε dot L$. #v(2em) Such adjustment is done during the warmup phase and the defined values of $ε$ and $L$ are kept fixed during the sampling phase. ] #slide(title: [NUTS Algorithm])[ #text(size: 7pt)[ #algo(line-numbers: false)[ Define an initial set $bold(θ)^0 ∈ RR^p$ that $P(bold(θ)^0 | bold(y)) > 0$ \ #text(fill: julia-blue)[Instantiate an empty binary tree with $2^L$ leaf nodes] \ Sample $bold(φ)$ from a $"Multivariate Normal"(bold(0),bold(M))$ \ Simultaneously sample $bold(θ)^*$ and $bold(φ)$ with $L$ steps and step-size $ε$ \ Define the current value of $bold(θ)$ as the proposed value $bold(θ)^*$: $bold(θ)^* <- bold(θ)$ \ for $1, 2, dots, L$ #i \ #text(fill: julia-blue)[Choose a direction $v tilde "Uniform"({-1, 1})$] \ Use the $log$ of the posterior's gradient $bold(θ)^*$ to produce a half-step of $bold(φ)$: $bold(φ) <- bold(φ) + 1 / 2 ε (dif log P( bold(θ)^* | bold(y) )) / (dif θ)$ \ Use $bold(φ)$ to update $bold(θ)^*$: $bold(θ)^* <- bold(θ)^* + ε bold(M)^(-1) bold(φ)$ \ Use again $bold(θ)^*$ $log$ gradient to produce a half-step of $bold(φ)$: $bold(φ) <- bold(φ) + 1 / 2 ε (dif log P( bold(θ)^* | bold(y) )) / (dif θ)$ #d \ #text(fill: julia-blue)[Define the node $L_t^v$ as the proposal $bold(θ)$] \ #text(fill: julia-blue)[ if the difference between proposal vector $bold(θ)^*$ and current vector $bold(θ)$ in the direction $v$ is lower than zero: $v (dif) / (dif t) ((bold(θ)^* - bold(θ)^*) dot (bold(θ)^* - bold(θ)^*)) / 2 < 0$ or $L$ steps have been reached ] #i \ #text(fill: julia-red)[ Stop sampling $bold(θ)^*$ in the direction $v$ and continue sampling only in the direction $-v$ ] #i \ #text(fill: julia-blue)[ The difference between proposal vector $bold(θ)^*$ and current vector $bold(θ)$ in the direction $-v$ is lower than zero: $-v (dif) / (dif t) ((bold(θ)^* - bold(θ)^*) dot (bold(θ)^* - bold(θ)^*)) / 2 < 0$ or $L$ steps have been reached ] #i \ #text(fill: julia-red)[Stop sampling $bold(θ)^*$] #d #d #d\ #text(fill: julia-blue)[Choose a random node from the binary tree as the proposal] \ As an acceptance/rejection rule, compute: \ $ r = (P (bold(θ)^* | bold(y)) P (bold(φ)^*)) / (P ( bold(θ)^(t - 1) | bold(y) ) P(bold(φ)^(t - 1))) $ Assign: $ bold(θ)^t = cases(bold(θ)^* "with probability" min(r, 1), bold(θ)^(t - 1) "otherwise") $ ] ] ] #slide(title: [NUTS Animation])[ #v(4em) #align(center)[ See NUTS in action at #link( "https://chi-feng.github.io/mcmc-demo/app.html?algorithm=EfficientNUTS&target=banana", )[ `chi-feng/mcmc-demo` ]. ] ] #slide(title: [Limitations of HMC and NUTS Algorithms -- #cite(<nealSliceSampling2003>, form: "prose")'s Funnel])[ The famous "Devil's Funnel" #footnote[very common em hierarchical models.]. Here we see that HMC and NUTS, during the exploration of the posterior, have to change often $L$ and $ε$ values #footnote[ remember that $L$ and $ε$ are defined in the warmup phase and kept fixed during sampling. ]. #align(center)[#image("images/funnel/funnel.png", height: 40%)] ] #slide(title: [#cite(<nealSliceSampling2003>, form: "prose")'s Funnel and Non-Centered Parameterization (NCP)])[ #text(size: 18pt)[ The funnel occurs when we have a variable that its variance depends on another variable variance in an exponential scale. A canonical example of a centered parameterization (CP) is: $ P(y,x) = "Normal"(y | 0 ,3) dot "Normal"(x | 0, e^(y / 2)) $ This occurs often in hierarchical models, in the relationship between group-level priors and population-level hyperpriors. Hence, we reparameterize in a non-centered way, changing the posterior geometry to make life easier for our MCMC sampler: $ P(tilde(y),tilde(x)) &= "Normal"(tilde(y) | 0, 1) dot "Normal"(tilde(x) | 0, 1) \ y &= tilde(y) dot 3 + 0 \ x &= tilde(x) dot e^(y / 2) + 0 $ ] ] #slide(title: [Non-Centered Parameterization -- Varying-Intercept Model])[ This example is for linear regression: $ bold(y) &tilde "Normal"(α_j + bold(X) dot bold(β), σ) \ α_j &= z_j dot τ + α \ z_j &tilde "Normal"(0, 1) \ α &tilde "Normal"(μ_α, σ_α) \ bold(β) &tilde "Normal"(μ_bold(β), σ_bold(β)) \ τ &tilde "Cauchy"^+(0, ψ_α) \ σ &tilde "Exponential"(λ_σ) $ ] #slide(title: [Non-Centered Parameterization -- Varying-(Intercept-)Slope Model])[ This example is for linear regression: $ bold(y) &tilde "Normal"(bold(X) bold(β)_j, σ) \ bold(β)_j &= bold(γ)_j dot bold(Σ) dot bold(γ)_j \ bold(γ)_j &tilde "Multivariate Normal"(bold(0), bold(I)) "for" j ∈ {1, dots, J} \ bold(Σ) &tilde "LKJ"(η) \ σ &tilde "Exponential"(λ_σ) $ Each coefficient vector $bold(β)_j$ represents the model columns $bold(X)$ coefficients for every group $j ∈ J$. Also the first column of $bold(X)$ could be a column filled with $1$s (intercept). ] #slide(title: [Stan and NUTS])[ Stan was the first MCMC sampler to implement NUTS. Besides that, it has an automatic optimized adjustment routine for values of $L$ and $ε$ during warmup. It has the following default NUTS hyperparameters' values #footnote[ for more information about how to change those values, see #link( "https://mc-stan.org/docs/reference-manual/hmc-algorithm-parameters.html", )[ Section 15.2 of the Stan Reference Manual ]. ]: #v(2em) - *target acceptance rate of Metropolis proposals*: 0.8 - *max tree depth* (in powers of $2$): 10 (which means $2^(10) = 1024$) ] #slide(title: [Turing and NUTS])[ Turing also implements NUTS which lives, along with other MCMC samplers, inside the package AdvancedHMC.jl. It also has an automatic optimized adjustment routine for values of $L$ and $ε$ during warmup. It has the same default NUTS hyperparameters' values #footnote[ for more information about how to change those values, see #link("https://turinglang.org/dev/docs/library")[ Turing Documentation ]. ]: #v(2em) - *target acceptance rate of Metropolis proposals*: 0.65 - *max tree depth* (in powers of $2$): 10 (which means $2^(10) = 1024$) ] #slide(title: [Markov Chain Convergence])[ MCMC has an interesting property that it will *asymptotically converge to the target distribution* #footnote[ this property is not present on neural networks. ]. That means, if we have all the time in the world, it is guaranteed, irrelevant of the target distribution posterior geometry, *MCMC will give you the right answer*. However, we don't have all the time in the world Different MCMC algorithms, like HMC and NUTS, can reduce the sampling (and warmup) time necessary for convergence to the target distribution. ] #slide(title: [Convergence Metrics])[ #v(2em) We have some options on how to measure if the Markov chains converged to the target distribution, i.e. if they are "reliable": #v(2em) - *Effective Sample Size* (ESS): an approximation of the "number of independent samples" generated by a Markov chain. #v(2em) - $hat(R)$ (*Rhat*): potential scale reduction factor, a metric to measure if the Markov chain have mixed, and, potentially, converged. ] #slide(title: [Convergence Metrics -- Effective Sample Size @gelman2013bayesian])[ $ hat(n)_"eff" = (m n) / (1 + sum_(t = 1)^T hat(ρ)_t) $ where: - $m$: number of Markov chains. - $n$: total samples per Markov chain (discarding warmup). - $hat(ρ)_t$: an autocorrelation estimate. ] #slide(title: [Convergence Metrics -- Rhat @gelman2013bayesian])[ #text(size: 18pt)[ $ hat(R) = sqrt((hat("var")^+ (ψ | y)) / W) $ where $hat("var")^+ (ψ | y)$ is the Markov chains' sample variance for a certain parameter $ψ$. We calculate it by using a weighted sum of the within-chain $W$ and between-chain $B$ variances: $ hat("var")^+ (ψ | y) = (n - 1) / n W + 1 / n B $ Intuitively, the value is $1.0$ if all chains are totally convergent. As a heuristic, if $hat(R) > 1.1$, you need to worry because probably the chains have not converged adequate. ] ] #slide(title: [Traceplot -- Convergent Markov Chains])[ #align(center)[ #figure( image("images/funnel/good_chains_traceplot.svg", height: 80%), caption: [A convergent Markov chains traceplot], ) ] ] #slide(title: [Traceplot -- Divergent Markov Chains])[ #align(center)[ #figure( image("images/funnel/bad_chains_traceplot.svg", height: 80%), caption: [A divergent Markov chains traceplot], ) ] ] #slide(title: [ Stan's Warning Messages #footnote[ also see #link( "https://mc-stan.org/misc/warnings.html", )[Stan's #text(fill: julia-red)[warnings] guide]. ] ])[ #fit-to-height(1fr)[ ```shell Warning messages: 1: There were 275 divergent transitions after warmup. See http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup to find out why this is a problem and how to eliminate them. 2: Examine the pairs() plot to diagnose sampling problems 3: The largest R-hat is 1.12, indicating chains have not mixed. Running the chains for more iterations may help. See http://mc-stan.org/misc/warnings.html#r-hat 4: Bulk Effective Samples Size (ESS) is too low, indicating posterior means and medians may be unreliable. Running the chains for more iterations may help. See http://mc-stan.org/misc/warnings.html#bulk-ess 5: Tail Effective Samples Size (ESS) is too low, indicating posterior variances and tail quantiles may be unreliable. Running the chains for more iterations may help. See http://mc-stan.org/misc/warnings.html#tail-ess ``` ] ] #slide(title: [ Turing's Warning Messages ])[ #fit-to-height(1fr)[ *Turing does not give warning messages!* But you can check divergent transitions with `summarize(chn; sections=[:internals])`: ```shell Summary Statistics parameters mean std naive_se mcse ess rhat ess_per_sec Symbol Float64 Float64 Float64 Float64 Float64 Float64 Float64 lp -3.9649 1.7887 0.0200 0.1062 179.1235 1.0224 6.4133 n_steps 9.1275 11.1065 0.1242 0.7899 38.3507 1.3012 1.3731 acceptance_rate 0.5944 0.4219 0.0047 0.0322 40.5016 1.2173 1.4501 tree_depth 2.2444 1.3428 0.0150 0.1049 32.8514 1.3544 1.1762 numerical_error 0.1975 0.3981 0.0045 0.0273 59.8853 1.1117 2.1441 ``` ] ] #slide(title: [What To Do If the Markov Chains Do Not Converge?])[ *First*: before making any fine adjustments in the number of Markov chains or the number of iterations per chain, etc. #v(2em) Acknowledge that both Stan's and Turing's NUTS sampler is *very efficient and effective in exploring the most crazy and diverse target posterior densities*. #v(2em) And the standard settings, *2,000 iterations and 4 chains*, works perfectly for 99% of the time. ] #slide(title: [What To Do If the Markov Chains Do Not Converge?])[ #v(4em) #quote( block: true, attribution: [#cite(<gelmanFolkTheoremStatistical2008>, form: "prose")], )[ When you have computational problems, often there’s a problem with your model. ] ] #slide(title: [What To Do If the Markov Chains Do Not Converge?])[ If you experiencing convergence issues, *and you've discarded that something is wrong with you model*, here is a few steps to try #footnote[ besides that, maybe should be worth to do a QR decomposition in the data matrix $bold(X)$, thus having an orthogonal basis (non-correlated) for the sampler to explore. This makes the target distribution's geometry much more friendlier, in the topological/geometrical sense, for the MCMC sampler explore. Check the backup slides. ]. Here listed in increasing complexity: 1. *Increase the number of iterations and chains*: try first increasing the number of iterations, then try increasing the number of chains. (remember the default is 2,000 iterations and 4 chains). ] #slide(title: [What To Do If the Markov Chains Do Not Converge?])[ 2. *Change the HMC's warmup adaptation routine*: make the HMC sampler to be more conservative in the proposals. This can be changed by increasing the hyperparameter *target acceptance rate of Metropolis proposals* #footnote[ Stan's default is 0.8 and Turing's default is 0.65. ]. The maximum value is $1.0$ (not recommended). Then, any value between $0.8$ and $1.0$ is more conservative. 3. *Model reparameterization*: there are two approaches. Centered parameterization (CP) and non-centered parameterization (NCP). ] #slide(title: [What To Do If the Markov Chains Do Not Converge?])[ 4. *Collect more data*: sometimes the model is too complex and we need a higher sample size for stable estimates. 5. *Rethink the model*: convergence issues with an adequate sample size might be due to incompatibility between priors and likelihood function(s). In this case you need to rethink the whole data generating process underlying the model, in which the model assumptions stems from. ]
https://github.com/stephane-klein/typst-sklein-resume-poc
https://raw.githubusercontent.com/stephane-klein/typst-sklein-resume-poc/main/template.typ
typst
#let colors = ( subtlegray: rgb("#ededee"), lightgray: rgb("#343a40"), darkgray: rgb("#212529"), ) #let awesomeColors = ( skyblue: rgb("#0395DE"), red: rgb("#DC3522"), nephritis: rgb("#27AE60"), concrete: rgb("#95A5A6"), darknight: rgb("#131A28"), ) #let themeColor = awesomeColors.red #let Section( title: ("Sec", "tion title"), content: () ) = [ #for (idx, value) in content.enumerate() { block( breakable: false, [ #if (idx == 0) [ #v(1pt) #box({ text( size: 16pt, weight: "bold", fill: themeColor, title.at(0) ) text( size: 16pt, weight: "bold", fill: black, title.at(1) ) }) #h(2pt) #box(width: 1fr, line(stroke: 0.9pt, length: 100%)) #v(2pt) ] #value ] ) } #v(6pt) ] #let CvEntry( jobTitle: "Job Title", date: "Janvier 2020 - Décembre 2022", companyName: "MyCompany", location: "Metz", description: "" ) = block( breakable: false, [ #grid( columns: (1fr, auto), row-gutter: 6pt, {text(size: 10pt, weight: "bold", jobTitle)}, {align(right, text(weight: "medium", fill: themeColor, style: "oblique", date))}, {text(size: 8pt, weight: "medium", fill: themeColor, companyName)}, {align(right, text(size: 8pt, weight: "medium", fill: gray, style: "oblique", location))} ) #description #v(8pt) ] ) #let balanced-columns(count: 2, gutter: 4%, body) = { layout(size => style(styles => { let height = measure( block(width: size.width*(90% - gutter * (count - 1))/count, body), styles ).height/count block(height: height, columns(count, gutter: gutter, body)) })) }
https://github.com/JvandeLocht/assignment-template-typst-hfh
https://raw.githubusercontent.com/JvandeLocht/assignment-template-typst-hfh/main/metadata.typ
typst
MIT License
// Enter your thesis data here: #let titleEnglish = "(Title English)" #let titleGerman = "(Title German)" #let degree = "Bachelor" #let company = "Firma xyz" #let program = "Mechanical Engineering" #let supervisor = "Prof. Dr. <NAME>" #let advisors = ("<NAME>, M.Sc.",) #let author = "(Author)" #let matriculationNumber = "(0000000)" #let birthdate = datetime(day: 01, month: 01, year: 2002) // only necessary for registration certificate #let startDate = datetime(day: 1, month: 1, year: 2024) #let submissionDate = datetime(day: 1, month: 1, year: 2024) #let presentationDate = datetime(day: 1, month: 1, year: 2024) #let feedbacklogSubmissionDate = datetime(day: 1, month: 1, year: 2024)
https://github.com/Slyde-R/not-jku-thesis-template
https://raw.githubusercontent.com/Slyde-R/not-jku-thesis-template/main/template/thesis.typ
typst
MIT No Attribution
//#import "@local/not-JKU-thesis:0.1.0": jku-thesis // for development #import "@preview/not-JKU-thesis:0.1.0": jku-thesis #import "utils.typ": inwriting, draft, todo, flex-caption, flex-caption-styles #import "glossary.typ": glossary #import "@preview/glossarium:0.2.6": make-glossary, print-glossary, gls, glspl #show: make-glossary #show: flex-caption-styles /** Drafting Set the boolean variables `inwriting` and `draft` inside utils.typ. The "draft" variable is used to show DRAFT in the header and the title. This should be true until the final version is handed-in. The "inwriting" is used to change the appearance of the document for easier writing. Set to true for yourself but false for handing in a draft or so. **/ // global text settings #set text(lang: "en", weight: "regular", font: "Arial", size: 11pt) #set text(ligatures: false) #set par(leading: 1em, first-line-indent: 0em, justify: true) #show par: set block(spacing: 1.5em) // spacing after a paragraph #show raw: set text( size: 9pt) // set text for code-blocks (``) #set page(margin: (left: 2.5cm+1cm, // binding correction of 1cm for single sided printing right: 2.5cm, y: 2.9cm), // margin: (inside: 2.5cm+1cm, // binding correction of 1cm for double sided printing // outside: 2.5cm, // y:2.5cm), // binding: left ) #let date = datetime.today() // not today: datetime(year: 1969, month: 9, day: 6,) #let k-number = "k12345678" #show: jku-thesis.with( thesis-type: "Master", degree: "Master of Science", program: "Feline Behavioral Studies", supervisor: "Professor <NAME>, Ph.D.", advisors: ("Dr. <NAME>","Dr. <NAME>"), // singular advisor like this: ("Dr. <NAME>",) and no supervisor: "" department: "Department of Animal Psychology", author: "<NAME>, BSc.", date: date, place-of-submission: "Linz", title: "Purrfection: How Cats Skillfully Train and Manipulate Humans to Serve Their Every Need", abstract-en: [//max. 250 words This study explores the intricate ways in which domestic cats employ manipulation tactics to influence human behavior. Utilizing a mixed-methods approach that combines observational data, surveys, and interviews, this research investigates how cats utilize vocalizations, body language, and attention-seeking behaviors to achieve their goals, ranging from soliciting food to initiating play. The findings reveal that cats predominantly use vocalizations such as meowing, purring, and chirping to manipulate their human companions. Meowing is particularly effective for demanding attention and food, while purring is often used to enhance bonding and comfort. Chirps and trills are employed to encourage play and interaction. Additionally, body language such as kneading, tail positioning, and eye contact play significant roles in communication and manipulation. Attention-seeking behaviors, including climbing, rubbing, and bringing objects, are crucial in eliciting responses from humans. The research highlights the positive impact of these manipulation tactics on human-cat relationships, although it also acknowledges the potential for frustration and behavioral adjustments by cat owners. The study contributes valuable insights into the complexities of human-animal interactions and suggests pathways for future research, including larger sample sizes, longitudinal studies, and experimental investigations. This work offers practical implications for enhancing human-cat interactions and improving the understanding of feline behavior, fostering more harmonious relationships between cats and their human companions. ], abstract-de: none,// or specify the abbstract_de in a container [] acknowledgements: [ I would like to extend a huge thank you to Dr. <NAME>, my primary advisor, for her pawsitive support and expert guidance. Without her wisdom and occasional catnip breaks, this thesis might have turned into a hairball of confusion. A special shoutout to Dr. <NAME>, my co-advisor, for his keen insights and for keeping me from chasing my own tail during this research. Your input was invaluable and much appreciated. To the cat owners, survey respondents, and interviewees—thank you for sharing your feline escapades. Your stories made this research more entertaining than a laser pointer. Lastly, to my family and friends, thank you for tolerating the endless cat puns and my obsession with feline behavior. Your patience and encouragement kept me from becoming a full-time cat herder. To everyone who contributed to this thesis, directly or indirectly, I offer my heartfelt gratitude. You've all made this journey a little less ruff! ],//acknowledgements: none // if you are self-made show-title-in-header: false, draft: draft, ) // set equation and heading numbering #set math.equation(numbering: "(1)") #set heading(numbering: "1.1") // Set font size #show heading.where(level: 3): set text(size: 1.05em) #show heading.where(level: 4): set text(size: 1.0em) #show figure: set text(size: 0.9em) // Set spacings #set table(inset: 6.5pt) #show table: set par(justify: false) #show figure: it => [#v(1em) #it #v(1em)] #show heading.where(level: 1): set block(above: 1.95em, below: 1em) #show heading.where(level: 2): set block(above: 1.85em, below: 1em) #show heading.where(level: 3): set block(above: 1.75em, below: 1em) #show heading.where(level: 4): set block(above: 1.55em, below: 1em) // Pagebreak after level 1 headings #show heading.where(level: 1): it => [ #pagebreak(weak: true) #it ] // Set citation style #set cite(style: "iso-690-author-date") // page info visible //#set cite(style: "iso-690-numeric") // page info visible //#set cite(style: "springer-basic")// no additional info visible (page number in square brackets) //#set cite(style: "alphanumeric")// page info not visible // Table stroke #set table(stroke: 0.5pt + black) // show reference targets in brackets #show ref: it => { let el = it.element if el != none and el.func() == heading { [#it (#el.body)] } else [#it] } // color links and references for the final document // #show link: set text(fill: blue) // #show ref: set text(fill: color.olive) // style table-of-contents #show outline.entry.where( level: 1 ): it => { v(1em, weak: true) strong(it) } // Draft Settings // #show cite: set text(fill: purple) if inwriting // highlight citations #show footnote: set text(fill: purple) if inwriting #show ref: set text(fill: purple) if inwriting // Custom Footer // #set page(footer: context [ #text(size:9pt)[ #table( stroke: none, columns: (1fr, auto, 1fr), align: (left, center, right), inset: 5pt, [#date.display("[month repr:long] [day], [year]")],[#k-number],[#counter(page).display( "1", )], ) ] ]) // ------ Content ------ // Table of contents. #outline( title: { text(1.3em, weight: 700, "Contents") v(10mm) }, indent: 2em, depth: 3 )<outline> #pagebreak(weak: false) // --- Main Chapters --- #include "content/Tutorial.typ"// Some trivial, but useful snippets #include "content/Introduction.typ" #include "content/LiteratureReview.typ" #include "content/Methodology.typ" #include "content/DataCollection.typ" #include "content/Analysis.typ" #include "content/Conclusion.typ" // --- Appendixes --- // restart page numbering using roman numbers #set page(footer: context [ #text(size:9pt)[ #table( stroke: none, columns: (1fr, auto, 1fr), align: (left, center, right), inset: 5pt, [#date.display("[month repr:long] [day], [year]")],[#k-number],[#counter(page).display( "i", )], ) ] ]) #counter(page).update(1) #include("content/Appendix.typ") // List of Acronyms - comment out, if not needed (no abbreviations were used). #heading(numbering: none)[List of Acronyms] #print-glossary(glossary) // List of figures - comment out, if not needed. #heading(numbering: none)[List of Figures] #outline( title: none, target: figure.where(kind: image), ) // List of tables - comment out, if not needed. #heading(numbering: none)[List of Tables] #outline( title: none, target: figure.where(kind: table)) // --- Bibliography --- #set par(leading: 0.7em, first-line-indent: 0em, justify: true) #bibliography("items.bib", style: "apa")
https://github.com/liuxu89/liuxu89.github.io
https://raw.githubusercontent.com/liuxu89/liuxu89.github.io/main/book.typ
typst
#import "@preview/shiroa:0.1.1": * #show: book #book-meta( title: "Wiki", summary: [ = 文摘 - #chapter("src/daijinhua1.typ")[大众文化的隐形政治学] ] ) // re-export page template #import "/templates/page.typ": project #let book-page = project
https://github.com/EpicEricEE/typst-droplet
https://raw.githubusercontent.com/EpicEricEE/typst-droplet/master/tests/justify/test.typ
typst
MIT License
#import "/src/lib.typ": dropcap #set page(width: 6cm, height: auto, margin: 1em) // Test different justify values. #dropcap(justify: true, lorem(20)) #set par(justify: true) #dropcap(justify: auto, lorem(20)) #dropcap(justify: false, lorem(20))
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/documentation/docs/bibliography.md
markdown
## Bibliography: Sources that were helpful throughout the Typstdiff implementation: <li> <a href="https://docs.python.org/3/">Python documentation</a> </li> <li> <a href="https://typst.app/docs/">Typst documentation</a> </li> <li> <a href="https://www.rust-lang.org/learn">Rust documentation</a> </li> <li> <a href="https://github.com/orgs/typst/repositories">Typst repo</a> </li> <li> <a href="https://github.com/typst/typst/blob/main/crates/typst/src/foundations/content.rs">Especially content file</a></li> <li> <a href="https://github.com/typst/typst/blob/main/docs/dev/architecture.md">Typst architecture documentation</a></li> <li> <a href="https://www.overleaf.com/learn/latex/Articles/Using_Latexdiff_For_Marking_Changes_To_Tex_Documents">latexdiff tool</a></li> <li> <a href="https://www.mkdocs.org/">MkDocs documentation</a></li> <li> <a href="https://www.conventionalcommits.org/en/v1.0.0/">Good habits in managing repository</a></li> <li> <a href="https://peps.python.org/pep-0008/">Styling rules - PEP</a></li> <li> <a href="https://semver.org/">Semantic Versioning Specification</a></li> <li> <a href="https://docs.python.org/3/library/pathlib.html">Pathlib</a></li> <li> <a href="https://python-poetry.org/">Poetry</a></li> <li> <a href="https://tox.wiki/en/4.14.1/user_guide.html">Tox</a></li> <li> <a href="https://github.com/xlwings/jsondiff">JSONDiff package repository</a></li> <li> <a href="https://github.com/casey/just">Justfile repository & documentation</a></li>
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/image_06.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 8-29 file not found (searched at typ/visualize/path/does/not/exist) // #image("path/does/not/exist")
https://github.com/0x1B05/nju_os
https://raw.githubusercontent.com/0x1B05/nju_os/main/book_notes/content/02_virtualization_02_memory_04_VM.typ
typst
#import "../template.typ": * #pagebreak() = Complete Virtual Memory Systems What features are needed to realize a complete virtual memory system? How do they improve performance, increase security, or otherwise improve the system? We’ll do this by covering two systems. The first is one of the earliest examples of a “modern” virtual memory manager, that found in the *VAX/VMS* operating system; a surprising number of techniques and approaches from this system survive to this day, and thus it it is well worth studying. Some ideas, even those that are 50 years old, are still worth knowing, a thought that is well known to those in most other fields (e.g., Physics), but has to be stated in technology-driven disciplines (e.g., Computer Science). The second is that of *Linux*. Linux is a widely used system, and runs effectively on systems as small and underpowered as phones to the most scalable multi-core systems found in modern datacenters. Thus, its VM system must be flexible enough to run successfully in all of those scenarios. == VAX/VMS Virtual Memory The OS for the system was known as *VAX/VMS (or just plain VMS)*, one of whose primary architects was <NAME>. VMS had the general problem that it would be run on a broad range of machines, including very inexpensive VAXen to extremely high-end and powerful machines in the same architecture family. Thus, the OS had to have mechanisms and policies that worked (and worked well) across this huge range of systems. VMS is an excellent example of software innovations used to hide some of the inherent flaws of the architecture. === Memory Management Hardware The VAX-11 provided *a 32-bit virtual address space* per process, divided into *512-byte pages*. Thus, a virtual address consisted of *a 23-bit VPN* and *a 9-bit offset*. Further, the upper two bits of the VPN were used to differentiate which segment the page resided within; thus, the system was a *hybrid of paging and segmentation*. - The lower-half of the address space was known as *process space* and is unique to each process. - In the first half of process space (known as P0), the user program is found, as well as a *heap* which grows downward. - In the second half of process space (P1), we find the *stack*, which grows upwards. - The upper-half of the address space is known as *system space (S)*, although only half of it is used. Protected OS code and data reside here, and the OS is in this way shared across processes. ``` | unused | | S | | p0(heap) | | p1(stack) | ``` One major concern of the VMS designers was the incredibly *small size of pages* in the VAX hardware. This size(512 bytes), has the fundamental problem of making simple linear page tables excessively large. Thus, one of the first goals of the VMS designers was to ensure that VMS would not overwhelm memory with page tables. The system reduced the pressure page tables place on memory in two ways. - First, by *segmenting the user address space into two* - the VAX-11 provides *a page table for each of these regions (P0 and P1) per process*; thus, no page-table space is needed for the unused portion of the address space between the stack and the heap. *The base and bounds registers* are used as you would expect - a base register holds the address of the page table for that segment - the bounds holds its size (i.e., number of page-table entries). - Second, the OS reduces memory pressure even further by *placing user page tables (for P0 and P1, thus two per process) in kernel virtual memory*. Thus, when allocating or growing a page table, the kernel allocates space out of its own virtual memory, in segment S. If memory comes under severe pressure, the kernel can *swap pages* of these page tables out to disk, thus making physical memory available for other uses. - Putting page tables in kernel virtual memory means that address translation is even further complicated. - For example, to translate a virtual address in P0 or P1, the hardware has to first try to look up the page-table entry for that page in its page table (the P0 or P1 page table for that process); in doing so, however, the hardware may first have to consult the system page table (which lives in physical memory); with that translation complete, the hardware can learn the address of the page of the page table, and then finally learn the address of the desired memory access. All of this, fortunately, is made faster by the VAX’s hardware-managed TLBs, which usually (hopefully) circumvent this laborious lookup. === A Real Address Space #image("images/2023-12-22-08-45-17.png", width: 50%) #tip("Tip")[ we have assumed a simple address space of just user code, user data, and user heap, a real address space is notably more complex. ] The code segment never begins at page 0. This page, instead, is marked inaccessible, in order to provide some support for *detecting null-pointer* accesses. Thus, one concern when designing an address space is support for debugging, which the inaccessible zero page provides here in some form. The kernel virtual address space is a part of each user address space. On a context switch, the OS changes the `P0` and `P1` registers to point to the appropriate page tables of the soon-to-be-run process; however, it does not change the `S` base and bound registers, and as a result the “same” kernel structures are mapped into each user address space. The kernel is mapped into each address space for a number of reasons. - This construction makes life easier for the kernel; for example, when the OS is handed a pointer from a user program (e.g., on a write() system call), it is easy to copy data from that pointer to its own structures. The OS is naturally written and compiled, without worry of where the data it is accessing comes from. - If in contrast the kernel were located entirely in physical memory, it would be quite hard to do things like swap pages of the page table to disk; if the kernel were given its own address space, moving data between user applications and the kernel would again be complicated and painful. #tip("Tip")[ With this construction (now used widely), the kernel appears almost as a library to applications, albeit a protected one. ] One last point about this address space relates to protection. Clearly, the OS does not want user applications reading or writing OS data or code. Thus, the hardware must support different protection levels for pages to enable this. The VAX did so by specifying, in *protection bits* in the page table, what privilege level the CPU must be at in order to access a particular page. Thus, system data and code are set to a higher level of protection than user data and code; an attempted access to such information from user code will generate a trap into the OS, and the likely termination of the offending process. ==== WHY NULL POINTER ACCESSES CAUSE SEG FAULTS ```c int *p = NULL; // set p = 0 *p = 10; // try to store 10 to virtual addr 0 ``` The hardware tries to look up the VPN (also 0 here) in the TLB, and suffers a TLB miss. The page table is consulted, and the entry for VPN 0 is found to be marked invalid. Thus, we have an invalid access, which transfers control to the OS, which likely terminates the process. === Page Replacement The page table entry (PTE) in VAX contains the following bits: - a valid bit - a protection field (4 bits) - a modify (or dirty) bit - a field reserved for OS use (5 bits) - a physical frame number (PFN) to store the location of the page in physical memory. - No reference bit! Thus, the VMS replacement algorithm must make do without hardware support for determining which pages are active. - The developers were also concerned about *memory hogs*, programs that use a lot of memory and make it hard for other programs to run. Most of the policies we have looked at thus far are susceptible to such hogging; for example, LRU is a global policy that doesn’t share memory fairly among processes. To address these two problems, the developers came up with the segmented FIFO replacement policy. The idea is simple: each process has a maximum number of pages it can keep in memory, known as its *resident set size (RSS)*. Each of these pages is kept on a FIFO list; when a process exceeds its RSS, the “first-in” page is evicted. FIFO clearly does not need any support from the hardware, and is thus easy to implement. Of course, pure FIFO does not perform particularly well, as we saw earlier. To improve FIFO’s performance, VMS introduced *two second-chance lists* where pages are placed before getting evicted from memory, specifically *a global clean-page free list* and *dirty-page list*. When a process P exceeds its RSS, a page is removed from its per-process FIFO; - if clean (not modified), it is placed on the end of the clean-page list - if dirty (modified), it is placed on the end of the dirty-page list If another process Q needs a free page, it takes the first free page off of the global clean list. However, if the original process P faults on that page before it is reclaimed, P reclaims it from the free (or dirty) list, thus avoiding a costly disk access. The bigger these global second-chance lists are, the closer the segmented FIFO algorithm performs to LRU. Another optimization used in VMS also helps overcome the small page size in VMS. Specifically, with such small pages, disk I/O during swapping could be highly inefficient, as disks do better with large transfers. To make swapping I/O more efficient, VMS adds a number of optimizations, but most important is *clustering*. With clustering, VMS groups large batches of pages together from the global dirty list, and writes them to disk in one fell swoop (thus making them clean). Clustering is used in most modern systems, as the freedom to place pages anywhere within swap space lets the OS group pages, perform fewer and bigger writes, and thus improve performance. === Other Neat Tricks VMS had two other now-standard tricks: demand zeroing and copy-on-write. We now describe these *lazy optimizations*. ==== demand zeroing of pages One form of laziness in VMS (and most modern systems) is *demand zeroing of pages*. To understand this better, let’s consider the example of adding a page to your address space, say in your heap. In a naive implementation, the OS responds to a request to add a page to your heap by finding a page in physical memory, zeroing it (required for security; otherwise you’d be able to see what was on the page from when some other process used it!), and then mapping it into your address space (i.e., setting up the page table to refer to that physical page as desired). But the naive implementation can be costly, particularly if the page does not get used by the process. With demand zeroing, the OS instead does very little work when the page is added to your address space; it *puts an entry in the page table that marks the page inaccessible*. If the process then reads or writes the page, a trap into the OS takes place. When handling the trap, the OS notices (usually through some bits marked in the “reserved for OS” portion of the page table entry) that this is actually a demand-zero page; at this point, the OS does the needed work of finding a physical page, zeroing it, and mapping it into the process’s address space. If the process never accesses the page, all such work is avoided, and thus the virtue of demand zeroing. ==== copy-on-write Another cool optimization found in VMS is copy-on-write (COW for short). The idea, which goes at least back to the TENEX operating system, is simple: when the OS needs to copy a page from one address space to another, instead of copying it, it can map it into the target address space and mark it readonly in both address spaces. If both address spaces only read the page, no further action is taken, and thus the OS has realized a fast copy without actually moving any data. If, however, one of the address spaces does indeed try to write to the page, it will trap into the OS. The OS will then notice that the page is a COW page, and thus (lazily) allocate a new page, fill it with the data, and map this new page into the address space of the faulting process. The process then continues and now has its own private copy of the page. COW is useful for a number of reasons. Certainly any sort of shared library can be mapped copy-on-write into the address spaces of many processes, saving valuable memory space. In UNIX systems, COW is even more critical, due to the semantics of `fork()` and `exec()`. As you might recall, `fork()` creates an exact copy of the address space of the caller; with a large address space, making such a copy is slow and data intensive. Even worse, most of the address space is immediately over-written by a subsequent call to `exec()`, which overlays the calling process’s address space with that of the soon-to-be-exec’d program. By instead performing a copy-on-write `fork()`, the OS avoids much of the needless copying and thus retains the correct semantics while improving performance. == The Linux Virtual Memory System For this discussion, we’ll focus on Linux for Intel x86. === The Linux Address Space The Linux Address Space #image("images/2023-12-22-08-48-24.png", width: 60%) A Linux virtual address space1 consists of - a user portion (where user program code, stack, heap, and other parts reside) - a kernel portion (where kernel code, stacks, heap, and other parts reside) Like those other systems, upon a context switch, the user portion of the currently-running address space changes; the kernel portion is the same across processes. Like those other systems, a program running in user mode cannot access kernel virtual pages; only by trapping into the kernel and transitioning to privileged mode can such memory be accessed. In classic 32-bit Linux, the split between user and kernel portions of the address space takes place at address 0xC0000000, (3/4 the address space). - the user virtual addresses: 0 -> 0xBFFFFFFF; - the kernel virtual address space: 0xC0000000 through 0xFFFFFFFF #tip("Tip")[ 64-bit Linux has a similar split but at slightly different points. ] ==== two types of kernel VM One slightly interesting aspect of Linux is that it contains two types of kernel virtual addresses. ===== kernel logical addresses The first are known as *kernel logical addresses*. This is what you would consider the normal virtual address space of the kernel; to get more memory of this type, kernel code merely needs to call `kmalloc`. Most kernel data structures live here, such as page tables, per-process kernel stacks, and so forth. Unlike most other memory in the system, kernel logical memory cannot be swapped to disk. The most interesting aspect of kernel logical addresses is their connection to physical memory. Specifically, there is *a direct mapping between kernel logical addresses and the first portion of physical memory*. Thus, kernel logical address 0xC0000000 translates to physical address 0x00000000, 0xC0000FFF to 0x00000FFF, and so forth. This direct mapping has two implications. - The first is that it is simple to translate back and forth between kernel logical addresses and physical addresses; as a result, *these addresses are often treated as if they are indeed physical*. - The second is that if a chunk of memory is contiguous in kernel logical address space, it is also contiguous in physical memory. - This makes memory allocated in this part of the kernel’s address space suitable for operations which need contiguous physical memory to work correctly, such as I/O transfers to and from devices via directory memory access (DMA). ===== kernel virtual address The other type of kernel address is a *kernel virtual address*. To get memory of this type, kernel code calls a different allocator, `vmalloc`, which returns a pointer to a virtually contiguous region of the desired size. Kernel virtual memory is *usually not contiguous*; each kernel virtual page may map to non-contiguous physical pages. However, such memory is easier to allocate as a result, and thus used for large buffers where finding a contiguous large chunk of physical memory would be challenging. In 32-bit Linux, one other reason for the existence of kernel virtual addresses is that they *enable the kernel to address more than (roughly) 1 GB of memory*. Years ago, machines had much less memory than this, and enabling access to more than 1 GB was not an issue. However, technology progressed, and soon there was a need to enable the kernel to use larger amounts of memory. Kernel virtual addresses, and their disconnection from a strict one-to-one mapping to physical memory, make this possible. #tip("Tip")[ With the move to 64-bit Linux, the need is less urgent. ] === Page Table Structure Our discussion will center on the type of page-table structure provided by x86. As mentioned before, x86 provides *a hardware-managed, multi-level page table structure*, with one page table per process; the OS simply sets up mappings in its memory, points a privileged register at the start of the page directory, and the hardware handles the rest. The OS gets involved, as expected, at process creation, deletion, and upon context switches, making sure in each case that the correct page table is being used by the hardware MMU to perform translations. Moving to a 64-bit address affects page table structure in x86 in the expected manner. Because x86 uses a multi-level page table, current 64- bit systems use a four-level table. The full 64-bit nature of the virtual address space is not yet in use, however, rather only the bottom 48 bits. Thus, a virtual address can be viewed as follows: #image("images/2023-12-22-09-19-56.png", width: 80%) - The top 16 bits of a virtual address are unused (and thus play no role in translation), - The bottom 12 bits (due to the 4-KB page size) are used as the offset (and hence just used directly, and not translated), - The middle 36 bits of virtual address to take part in the translation. - The P1 portion of the address is used to index into the topmost page directory, and the translation proceeds from there, one level at a time, until the actual page of the page table is indexed by P4, yielding the desired page table entry. As system memories grow even larger, more parts of this voluminous address space will become enabled, leading to five-level and eventually six-level page-table tree structures. === Large Page Support Intel x86 allows for the use of multiple page sizes, not just the standard 4- KB page. Specifically, recent designs support 2-MB and even 1-GB pages in hardware. Thus, over time, Linux has evolved to allow applications to utilize these huge pages (as they are called in the world of Linux). ==== benefits Using huge pages, leads to numerous benefits. As seen in VAX/VMS, doing so reduces the number of mappings that are needed in the page table; the larger the pages, the fewer the mappings. However, fewer page-table entries is not the driving force behind huge pages; rather, it’s better TLB behavior and related performance gains. When a process actively uses a large amount of memory, it quickly fills up the TLB with translations. If those translations are for 4-KB pages, only a small amount of total memory can be accessed without inducing TLB misses. The result, for modern “big memory” workloads running on machines with many GBs of memory, is a noticeable performance cost; recent research shows that some applications spend 10% of their cycles servicing TLB misses. Huge pages allow a process to access a large tract of memory without TLB misses, by using fewer slots in the TLB, and thus is the main advantage. However, there are other benefits to huge pages: - There is a shorter TLB-miss path, meaning that when a TLB miss does occur, it is serviced more quickly. - Allocation can be quite fast (in certain scenarios), a small but sometimes important benefit. ==== How it was done incrementally One interesting aspect of Linux support for huge pages is how it was done incrementally. At first, Linux developers knew such support was only important for a few applications, such as large databases with stringent performance demands. Thus, the decision was made to allow applications to explicitly request memory allocations with large pages (either through the `mmap()` or `shmget()` calls). In this way, most applications would be unaffected and continue to use only 4-KB pages; a few demanding applications would have to be changed to use these interfaces, but for them it would be worth the pain. More recently, as the need for better TLB behavior is more common among many applications, Linux developers have added transparent huge page support. When this feature is enabled, the operating system automatically looks for opportunities to allocate huge pages (usually 2 MB, but on some systems, 1 GB) without requiring application modification. Huge pages are not without their costs. - The biggest potential cost is *internal fragmentation*, i.e., a page that is large but sparsely used. - Swapping, if enabled, also does not work well with huge pages, sometimes greatly amplifying the amount of I/O a system does. - Overhead of allocation can also be bad. ==== CONSIDER INCREMENTALISM The Linux huge page example in this chapter is an example of engineering incrementalism; instead of taking the stance of a fundamentalist and insisting large pages were the way of the future, developers took the measured approach of first introducing specialized support for it, learning more about its upsides and downsides, and, only when there was real reason for it, adding more generic support for all applications. Incrementalism, while sometimes scorned, often leads to slow, thoughtful, and sensible progress. When building systems, such an approach might just be the thing you need. Indeed, this may be true in life as well. === The Page Cache To reduce costs of accessing *persistent storage*, most systems use *aggressive caching* subsystems to keep popular data items in memory. Linux, is no different than traditional operating systems. The Linux *page cache* is unified, keeping pages in memory from three primary sources: - *memory-mapped files* - *file data* - *metadata from devices* (usually accessed by directing `read()` and `write()` calls to the file system) - *heap and stack pages* that comprise each process (sometimes called *anonymous memory*, because there is no named file underneath of it, but rather swap space). These entities are kept in *a page cache hash table*, allowing for quick lookup when said data is needed. The page cache tracks if entries are clean or dirty. Dirty data is periodically written to the backing store (i.e., to a specific file for file data, or to swap space for anonymous regions) by background threads (called `pdflush`), thus ensuring that modified data eventually is written back to persistent storage. #tip("Tip")[ This background activity either takes place after a certain time period or if too many pages are considered dirty (both configurable parameters). ] ==== 2Q replacement In some cases, a system runs low on memory, and Linux has to decide which pages to kick out of memory to free up space. To do so, Linux uses a modified form of *2Q* replacement. The basic idea is simple: standard LRU replacement is effective, but can be subverted by certain common access patterns. The Linux version of the 2Q replacement algorithm solves this problem by *keeping two lists*, and *dividing memory between them*. - When accessed for the first time, a page is placed on one queue (called A1 in the original paper, but the inactive list in Linux) - When it is re-referenced, the page is promoted to the other queue (called Aq in the original, but the ac- tive list in Linux). When replacement needs to take place, the candidate for replacement is taken from the inactive list. Linux also periodically moves pages from the bottom of the active list to the inactive list, keeping the active list to about two-thirds of the total page cache size. Linux would ideally manage these lists in perfect LRU order, but, as discussed in earlier chapters, doing so is costly. Thus, as with many OSes, an *approximation of LRU* (similar to clock replacement) is used. ==== THE UBIQUITY OF MEMORY-MAPPING Memory mapping predates Linux by some years, and is used in many places within Linux and other modern systems. The idea is simple: by calling `mmap()` on an already opened file descriptor, a process is returned a pointer to the beginning of a region of virtual memory where the contents of the file seem to be located. By then using that pointer, a process can access any part of the file with a simple pointer dereference. Accesses to parts of a memory-mapped file that have not yet been brought into memory trigger *page faults*, at which point the OS will page in the relevant data and make it accessible by updating the page table of the process accordingly (i.e., *demand paging*). Every regular Linux process uses memory-mapped files, even the code in `main()` does not call `mmap()` directly, because of how Linux loads code from the executable and shared library code into memory. Below is the output of the `pmap` command line tool, which shows what different mapping comprise the virtual address space of a running program. The output shows four columns: - the virtual address of the mapping - size - the protection bits of the region - the source of the mapping: ``` 0000000000400000 372K r-x-- tcsh 00000000019d5000 1780K rw--- [anon ] 00007f4e7cf06000 1792K r-x-- libc-2.23.so 00007f4e7d2d0000 36K r-x-- libcrypt-2.23.so 00007f4e7d508000 148K r-x-- libtinfo.so.5.9 00007f4e7d731000 152K r-x-- ld-2.23.so 00007f4e7d932000 16K rw--- [stack ] ``` As you can see from this output, the code from the tcsh binary, as well as code from `libc`, `libcrypt`, `libtinfo`, and code from the dynamic linker itself (`ld.so`) are all mapped into the address space. Also present are two anonymous regions - the heap (the second entry, labeled anon) - the stack (labeled stack). Memory-mapped files provide a straightforward and efficient way for the OS to construct a modern address space. === Security And Buffer Overflows Probably the biggest difference between modern VM systems (Linux, Solaris, or one of the BSD variants) and ancient ones (VAX/VMS) is the emphasis on security in the modern era. ==== buffer overflow attacks One major threat is found in *buffer overflow attacks*. The idea of these attacks is to find a bug in the target system which lets the attacker inject arbitrary data into the target’s address space. Such vulnerabilities sometime arise because the developer assumes (erroneously) that an input will not be overly long, and thus (trustingly) copies the input into a buffer; because the input is in fact too long, it overflows the buffer, thus overwriting memory of the target. Code as innocent as the below can be the source of the problem: ```c int some_function(char *input) { char dest_buffer[100]; strcpy(dest_buffer, input); // oops, unbounded copy! } ``` In many cases, such an overflow is not catastrophic, e.g., bad input innocently given to a user program or even the OS will probably cause it to crash, but no worse. However, malicious programmers can carefully craft the input that overflows the buffer so as to inject their own code into the targeted system, essentially allowing them to take it over and do their own bidding. - If successful upon a network-connected user program, attackers can run arbitrary computations or even rent out cycles on the compromised system. - If successful upon the operating system itself, the attack can access even more resources, and is a form of what is called privilege escalation (i.e., user code gaining kernel access rights). The first and most simple defense against buffer overflow is to *prevent execution of any code found within certain regions of an address space* (e.g., within the stack). The *NX* bit (for No-eXecute), introduced by AMD into their version of x86 (a similar *XD* bit is now available on Intel’s), is one such defense; it just prevents execution from any page which has this bit set in its corresponding page table entry. ==== return-oriented programming (ROP) However, clever attackers are ... clever, and even when injected code cannot be added explicitly by the attacker, arbitrary code sequences can be executed by malicious code. The idea is known, in its most general form, as a *return-oriented programming (ROP)*, and really it is quite brilliant. The observation behind ROP is that there are lots of bits of code (gadgets, in ROP terminology) within any program’s address space, especially C programs that link with the voluminous C library. Thus, an attacker can overwrite the stack such that the return address in the currently executing function points to a desired malicious instruction (or series of instructions), followed by a return instruction. By stringing together a large number of gadgets (i.e., ensuring each return jumps to the next gadget), the attacker can execute arbitrary code. To defend against ROP (including its earlier form, the return-to-libc attack), Linux (and other systems) add another defense, known as *address space layout randomization (ASLR)*. Instead of placing code, stack, and the heap at fixed locations within the virtual address space, the OS randomizes their placement, thus making it quite challenging to craft the intricate code sequence required to implement this class of attacks. Most attacks on vulnerable user programs will thus cause crashes, but not be able to gain control of the running program. Interestingly, you can observe this randomness in practice rather easily. Here’s a piece of code that demonstrates it on a modern Linux system: ```c int main(int argc, char *argv[]) { int stack = 0; printf("%p\n", &stack); return 0; } ``` This code just prints out the (virtual) address of a variable on the stack. In older non-ASLR systems, this value would be the same each time. But, as you can see below, the value changes with each run: ``` prompt> ./random 0x7ffd3e55d2b4 prompt> ./random 0x7ffe1033b8f4 prompt> ./random 0x7ffe45522e94 ``` ASLR is such a useful defense for user-level programs that it has also been incorporated into the kernel, in a feature unimaginatively called *kernel address space layout randomization (KASLR)*. However, it turns out the kernel may have even bigger problems to handle. === Other Security Problems: Meltdown And Spectre As we write these words (August, 2018), the world of systems security has been turned upside down by two new and related attacks. The first is called *Meltdown*, and the second *Spectre*. #tip("Tip")[ See melt downattack.com and spectreattack.com for papers describing each attack in detail. ] Spectre is considered the more problematic of the two. The general weakness exploited in each of these attacks is that the CPUs found in modern systems perform all sorts of crazy behind-the scenes tricks to improve performance. One class of technique that lies at the core of the problem is called *speculative execution*, in which the CPU guesses which instructions will soon be executed in the future, and starts executing them ahead of time. If the guesses are correct, the program runs faster; if not, the CPU undoes their effects on architectural state (e.g., registers) tries again, this time going down the right path. The problem with speculation is that it tends to leave traces of its execution in various parts of the system, such as *processor caches*, *branch predictors*, etc. And thus the problem: as the authors of the attacks show, such state can make vulnerable the contents of memory, even memory that we thought was protected by the MMU. One avenue to increasing kernel protection was thus to remove as much of the kernel address space from each user process and instead have a separate kernel page table for most kernel data (called *kernel page-table isolation, or KPTI*). Thus, instead of mapping the kernel’s code and data structures into each process, only the barest minimum is kept therein; when switching into the kernel, then, a switch to the kernel page table is now needed. Doing so improves security and avoids some attack vectors, but at a cost: performance. Switching page tables is costly. The costs of security: convenience and performance. Unfortunately, KPTI doesn’t solve all of the security problems laid out above, just some of them. And simple solutions, such as *turning off speculation*, would make little sense, because systems would run thousands of times slower. Thus, it is an interesting time to be alive, if systems security is your thing. === Summary You have now seen a top-to-bottom review of two virtual memory systems. Hopefully, most of the details were easy to follow, as you should have already had a good understanding of the basic mechanisms and policies. More detail on VAX/VMS is available in the excellent (and short) paper by <NAME> Lipman [LL82]. We encourage you to read it, as it is a great way to see what the source material behind these chapters is like. You have also learned a bit about Linux. While a large and complex system, it inherits many good ideas from the past, many of which we have not had room to discuss in detail. For example, Linux performs lazy copy-on-write copying of pages upon fork(), thus lowering overheads by avoiding unnecessary copying. Linux also demand zeroes pages (using memory-mapping of the /dev/zero device), and has a background swap daemon (`swapd`) that swaps pages to disk to reduce memory pressure. Indeed, the VM is filled with good ideas taken from the past, and also includes many of its own innovations. To learn more, check out these reasonable (but, alas, outdated) books [BC05,G04]. We encourage you to read them on your own, as we can only provide the merest drop from what is an ocean of complexity. But, you’ve got to start somewhere. What is any ocean, but a multitude of drops? [M04]
https://github.com/Br0kenSmi1e/ScatteringComputation
https://raw.githubusercontent.com/Br0kenSmi1e/ScatteringComputation/main/main.typ
typst
#import "@preview/touying:0.4.2": * #import "@preview/touying-simpl-hkustgz:0.1.0" as hkustgz-theme #import "@preview/cetz:0.2.2": canvas, draw, tree #let vertex(location, name, color) = { import draw: * circle(location, radius: 4pt, name: name, fill: color) } #let edge(from, to) = { import draw: * line(from, to, name:"line") } #let s = hkustgz-theme.register() // Global information configuration #let s = (s.methods.info)( self: s, title: [Universal Computation by Quantum Scattering], subtitle: [], author: [<NAME>], date: datetime.today(), institution: [HKUST(GZ)], ) // Extract methods #let (init, slides) = utils.methods(s) #show: init // Extract slide functions #let (slide, empty-slide, title-slide, outline-slide, new-section-slide, ending-slide) = utils.slides(s) #show: slides.with() #outline-slide() = Scattering Problem == Problem Setup + Free particles are easy to solve. + Particles in potential fields are usually hard to solve. + If the initial state and the final state are free, the potential shows up as a perturbation. == Rutherford Scattering #slide(composer: (1fr, 1fr))[ The trajectory is determined by energy and angular momentum. $ T = T(L,E), L = p b, E = frac(p^2, 2m) $ The scattered state, described by the scattered angle, is determined by the impact parameter $b$ and momentum $p$. $ theta = theta (p,b) $ ][ #place(center, dy: 0pt, image("rutherford.png") ) ] == Quantum Scattering #slide(composer: (1.2fr, 0.8fr))[ Due to superposition principle, the scattered state may be a superposition of states on different "trajectories". $ psi_("in")(k) = e^(- i omega t) e^(-i k x ), psi_("out")(k) = e^(- i omega t) sum_(k') S_(k k') e^(i k' x) , $ $ psi_("sc")(k) = e^(- i omega t) (delta_(k k') e^(-i k x )+sum_(k') S_(k k') e^(i k' x)) $ The S-matrix is vital to scattering problem. The orthonormality of $psi_"sc" (k)$ proves the unitarity of S-matrix. ][ #image("animation/quantum.gif") ] = Quantum Mechanics on Graphs == Quantum Evolution on Graphs (Quantum Walk) #slide(composer: (0.8fr, 1fr))[ For a given graph $G$, its vertices correspond to states of a system, its adjacency matrix corresponds to Hamiltonian of the system. ][ #place(top + left, dx: 10pt, dy: -20pt, canvas({ import draw: * edge((0,0),(2,0)) edge((1,0),(1,1)) edge((1,1),(0,2)) edge((1,1),(2,2)) edge((1,3),(0,2)) edge((1,3),(2,2)) vertex((0,0),"1",blue) content((0,-0.5), text(black, "1")) vertex((1,0),"2",blue) content((1,-0.5), text(black, "2")) vertex((2,0),"3",blue) content((2,-0.5), text(black, "3")) vertex((1,1),"4",blue) content((1.5,1), text(black, "4")) vertex((0,2),"5",blue) content((-0.5,2), text(black, "5")) vertex((2,2),"6",blue) content((2.5,2), text(black, "6")) vertex((1,3),"7",blue) content((1,3.5), text(black, "7")) content((8, 0), [$ H &= attach(limits(sum), b: (i,j) in E(G)) |i angle.r angle.l j| \ &= mat(0, 1, 0, 0, 0, 0, 0; 1, 0, 1, 1, 0, 0, 0; 0, 1, 0, 0, 0, 0, 0; 0, 1, 0, 0, 1, 1, 0; 0, 0, 0, 1, 0, 0, 1; 0, 0, 0, 1, 0, 0, 1; 0, 0, 0, 0, 1, 1, 0 )$]) }) ) ] == Free Particles on Graphs #place(top + center, dx: 0pt, dy: 40pt, canvas({ import draw: * edge((-2,0),(2,0)) vertex((0,0),"1",blue) content((0,-0.5), text(black, $x$)) vertex((-2,0),"2",blue) content((-2,-0.5), text(black, $x-1$)) vertex((2,0),"3",blue) content((2,-0.5), text(black, $x+1$)) content((3,0.2),text(black, "...")) content((-3,0.2),text(black, "...")) content((0,-6), [ For an infinite path graph, its Hamiltonian is $H = limits(sum)_(x in ZZ) |x angle.r angle.l x+1| + |x+1 angle.r angle.l x|.$ Consider a plane wave $|"pl"(k) angle.r = limits(sum)_(x in ZZ) e^(i k x) |x angle.r$ and we have $ H|"pl"(k) angle.r &= limits(sum)_(x in ZZ) e^(i k x)(|x-1 angle.r + |x+1 angle.r)\ &= limits(sum)_(x in ZZ) (e^(i k (x+1)) + e^(-i k (x-1)))|x angle.r\ &=2 cos k|"pl"(k) angle.r $ So a particle is "free" when it is on an infinite path graph.]) })) == Scattering Problem on Graphs #slide(composer: (1fr, 1fr))[ #place(bottom, dy: -40pt)[As defined in "normal" QM, scattering process should take a set of plane wave eigen-states to another. So the scattering process corresponds to a graph shown below.] #place(top + center, dx: 0pt, dy: 0pt, canvas({ import draw: * edge((-28.28pt,28.28pt),(-2,2)) edge((-28.28pt,-28.28pt),(-2,-2)) arc((-28.28pt,28.28pt), start: 135deg, stop: -135deg, radius: 40pt) vertex((-28.28pt,28.28pt),"1",white) vertex((-2,2),"3",blue) vertex((-28.28pt,-28.28pt),"1",white) vertex((-2,-2),"4",blue) circle((-2.3,2.3), radius: 1pt, fill: black) circle((-2.6,2.6), radius: 1pt, fill: black) circle((-2.9,2.9), radius: 1pt, fill: black) circle((-2.3,-2.3), radius: 1pt, fill: black) circle((-2.6,-2.6), radius: 1pt, fill: black) circle((-2.9,-2.9), radius: 1pt, fill: black) circle((-40pt,0), radius: 1pt, fill: black) circle((-36.96pt,15.31pt), radius: 1pt, fill: black) circle((-36.96pt,-15.31pt), radius: 1pt, fill: black) content((-35pt,55pt), text(black, $1$)) content((-35pt,-55pt), text(black, $n$)) content((0,0), text(black, $G$))})) ][ #place(top + center, dx: 0pt, dy: -120pt, canvas({ import draw: * edge((0,7),(2,7)) edge((1,7),(1,8)) edge((1,8),(0,9)) edge((1,8),(2,9)) edge((1,10),(0,9)) edge((1,10),(2,9)) vertex((0,7),"1",white) vertex((1,7),"2",blue) vertex((2,7),"3",white) vertex((1,8),"4",blue) vertex((0,9),"5",blue) vertex((2,9),"6",blue) vertex((1,10),"7",blue) content((2.8,7.2), text(black,"......")) content((-0.8,7.2), text(black,"......")) edge((-0.5,0),(2.5,0)) edge((0.5,0),(0.5,4)) edge((1.5,0),(1.5,4)) edge((-0.5,4),(2.5,4)) vertex((-0.5,0),"1",white) vertex((0.5,0),"2",blue) vertex((1.5,0),"3",blue) vertex((2.5,0),"4",white) vertex((0.5,2),"5",blue) vertex((1.5,2),"6",blue) vertex((-0.5,4),"7",white) vertex((0.5,4),"8",blue) vertex((1.5,4),"9",blue) vertex((2.5,4),"10",white) content((-1.3,0.2), text(black,"......")) content((3.3,0.2), text(black,"......")) content((-1.3,4.2), text(black,"......")) content((3.3,4.2), text(black,"......"))})) ] == Solve the S-Matrix Suppose a graph $G$ is the scattering center. The sites on tails are denoted as $|x,j angle.r$, where $x in RR ^+, 1 <= j <= n$. For the vertices with attachments, they can also be denoted as $|0,j angle.r$. The Hamiltonian should be sum of three terms $ H = H_G + sum_(1 <= j <= n) (T_j + |0,j angle.r angle.l 1,j| + |1,j angle.r angle.l 0,j|) $ The solution of time-independent #text("Schrödinger", lang: "de") equation gives #place(right+bottom, dx: -86pt, dy: -100pt)[#rect(width: 320pt,height: 32pt,fill: aqua, radius: 10%)] $ H|"sc"_q (k) angle.r = 2 cos k |"sc"_q (k)angle.r arrow.r.double S_(q j) = (1-z^2) angle.l 0,q| AA^(-1)(z)|0,q angle.r - delta_(q j), $ $ z = e^(i k), AA(z) = II-z H_G + z^2 QQ, QQ = II-sum_(1 <= j <= n) |0,j angle.r angle.l 0,j|. $ #align(right)[ #text("For detailed proof, see Appendix A.", size: 12pt) ] = S-Matrices and Universal Gate Set == Dual-Rail Encode For a scattering device with 4 tails. Two of the tails are chosen as input, the other two are chosen as output. #place(center, dx: -180pt, dy: 0pt)[#canvas({ import draw: * content((0,5),$|0 angle.r " intput:"$) rect((4,0),(7,3),radius: 10%) content((5.5,1.5),text($U$,size: 24pt)) line((4,0.5),(0,0.5)) line((4,2.5),(0,2.5)) line((7,0.5),(8,0.5)) line((7,2.5),(8,2.5)) content((-1,0.5),"1") content((-1,2.5),"2") content((9,0.5),"3") content((9,2.5),"4") for i in range(0,38, step: 3) { circle((i/10,0.5), radius:2pt, fill: black) circle((i/10,2.5), radius:2pt, fill: black) } for i in range(3,10, step: 3) { circle((7+i/10,0.5), radius:2pt, fill: black) circle((7+i/10,2.5), radius:2pt, fill: black) } catmull((1,0.7),(1.2,0.8),(1.3,1.4),(1.5,1.2),(1.7,1.3),(1.8,0.8),(2,0.7),tension: .5,stroke: blue) line((1,1.6),(2,1.6),mark:(end:">")) content((0.6,1.6),$k$) })] #place(center, dx: 160pt, dy: 0pt)[#canvas({ import draw: * content((0,5),$|1 angle.r " intput:"$) rect((4,0),(7,3),radius: 10%) content((5.5,1.5),text($U$,size: 24pt)) line((4,0.5),(0,0.5)) line((4,2.5),(0,2.5)) line((7,0.5),(8,0.5)) line((7,2.5),(8,2.5)) content((-1,0.5),"1") content((-1,2.5),"2") content((9,0.5),"3") content((9,2.5),"4") for i in range(0,38, step: 3) { circle((i/10,0.5), radius:2pt, fill: black) circle((i/10,2.5), radius:2pt, fill: black) } for i in range(3,10, step: 3) { circle((7+i/10,0.5), radius:2pt, fill: black) circle((7+i/10,2.5), radius:2pt, fill: black) } catmull((1,2.7),(1.2,2.8),(1.3,3.4),(1.5,3.2),(1.7,3.3),(1.8,2.8),(2,2.7),tension: .5,stroke: red) line((1,3.6),(2,3.6),mark:(end:">")) content((0.6,3.6),$k$) })] #v(180pt) If there is no scattered component between input tails/output tails, then the device can be served as a single-qubit gate. == S-Matrix and Unitary Operator Under the above mentioned condition, $ S = mat(0,0,a^*,c^*;0,0,b^*,d^*;a,b,0,0;c,d,0,0) = mat(0,U^dagger;U,0) $ #place(center, dx: 109pt, dy: 64pt)[ #rect(width: 185pt, height: 70pt, fill: aqua, radius: 10%) ] By definition of S-matrix, the state after scattering is $ mat(macron(psi)_(1);macron(psi)_(2);macron(psi)_(3);macron(psi)_(4)) = mat(0,0,a^*,c^*;0,0,b^*,d^*;a,b,0,0;c,d,0,0)mat(psi_(1);psi_(2);psi_(3)=0;psi_(4)=0) arrow.r.double mat(macron(psi)_(3);macron(psi)_(4)) = mat(a,b;c,d) mat(psi_(1);psi_(2)), mat(macron(psi)_(1);macron(psi)_(2)) = 0 $ == Basis Change Gate #place(top,dy: 80pt)[$ k&=pi/4\ S &= mat(0,0,1/ sqrt(2),-i/ sqrt(2); 0,0,-i/ sqrt(2), 1/ sqrt(2); 1/ sqrt(2),i/ sqrt(2),0,0; i/ sqrt(2),1/ sqrt(2),0,0) $] #place(bottom + left, dx: 250pt, dy: -34pt, image("animation/change_0_in_population.gif", height: 35%) ) #place(top + left, dx: 400pt, dy: 150pt, canvas({ import draw: * edge((0,0),(3,0)) edge((1,0),(1,4)) edge((2,0),(2,4)) edge((0,4),(3,4)) vertex((0,0),"1",white) content((0,0.5), text(black,"2")) vertex((1,0),"2",blue) vertex((2,0),"3",blue) vertex((3,0),"4",white) content((3,0.5), text(black,"4")) vertex((1,2),"5",blue) vertex((2,2),"6",blue) vertex((0,4),"7",white) content((0,4.5), text(black,"1")) vertex((1,4),"8",blue) vertex((2,4),"9",blue) vertex((3,4),"10",white) content((3,4.5), text(black,"3")) }) ) #place(top + right, dx: -102pt, dy: 62pt, image("animation/change_1_out_population.gif", height: 35%) ) #place(top + right, dx: 0pt, dy: 90pt, image("animation/change_1_out_phase.gif", width: 15%) ) #place(bottom + right, dx: -102pt, dy: -32pt, image("animation/change_0_out_population.gif", height: 35%) ) #place(bottom + right, dx: 0pt, dy: -30pt, image("animation/change_0_out_phase.gif", width: 15%) ) == Phase Gate #place(top,dy: 80pt)[$ k&=pi/4\ S &= mat(0,0,1,0; 0,0,0,e^(-i pi/4); 1,0,0,0; 0,e^(i pi/4),0,0) $] #place(bottom + left, dx: 240pt, dy: -34pt, image("animation/phase_0_in_population.gif", height: 35%) ) #place(top + left, dx: 240pt, dy: 62pt, image("animation/phase_0_in_population.gif", height: 35%) ) #place(bottom + left, dx: 390pt, dy: -33pt, canvas({ import draw: * edge((-0.5,7),(2.5,7)) edge((1,7),(1,8)) edge((1,8),(0,9)) edge((1,8),(2,9)) edge((1,10),(0,9)) edge((1,10),(2,9)) edge((-0.5,11),(2.5,11)) vertex((-0.5,7),"1",white) content((-0.5,7.5),text(black,"2")) vertex((1,7),"2",blue) vertex((2.5,7),"3",white) content((2.5,7.5),text(black,"4")) vertex((1,8),"4",blue) vertex((0,9),"5",blue) vertex((2,9),"6",blue) vertex((1,10),"7",blue) vertex((-0.5,11),"8",white) content((-0.5,11.5),text(black,"1")) vertex((0.5,11),"8",blue) vertex((1.5,11),"8",blue) vertex((2.5,11),"8",white) content((2.5,11.5),text(black,"3")) }) ) #place(top + right, dx: -112pt, dy: 62pt, image("animation/phase_1_out_population.gif", height: 35%) ) #place(top + right, dx: 0pt, dy: 90pt, image("animation/phase_1_out_phase.gif", width: 15%) ) #place(bottom + right, dx: -112pt, dy: -32pt, image("animation/phase_0_out_population.gif", height: 35%) ) #place(bottom + right, dx: 0pt, dy: -30pt, image("animation/phase_0_out_phase.gif", width: 15%) ) == Two Qubit Gate: Controlled Phase Gate Introduce one ancilla qubit (mediator qubit). $ "CP"_(i j)|a_i, b_j, 0_m angle.r &= "CNOT"_(i m)"CP"_(j m)"CNOT"_(i m)|a_i, b_j, 0_m angle.r\ &= "H"_m "CP"^2_(i m) "H"_m "CP"_(j m) "H"_m "CP"^2_(i m) "H"_m |a_i, b_j, 0_m angle.r $ // #{ // import "@preview/quill:0.3.0": * // quantum-circuit( // lstick($|0〉$), $H$, ctrl(1), rstick($(|00〉+|11〉)/√2$, n: 2), [\ ], // lstick($|0〉$), 1, targ(), 1 // ) // } Thus, gates needed to build universal computer are: #rect([ + single-qubit gates on computational qubits ($checkmark$) , + controlled phase gate between computational qubit and mediator qubit, + Hadamard gate on mediator qubit.], fill: aqua, inset: 10pt, radius: 10%) Note: only when the mediator qubit and computational qubit have different momentum, can they gain non-trivial phase after interaction. == Hadamard Gate #place(top,dy: 40pt)[$ k&=pi/2\ S &= mat(0,0,1/sqrt(2),1/sqrt(2); 0,0,1/sqrt(2),-1/sqrt(2); 1/sqrt(2),1/sqrt(2),0,0; 1/sqrt(2),-1/sqrt(2),0,0) $] #place(bottom + left, dx: 260pt, dy: -110pt, image("animation/hadamard_1_in_population.gif", height: 35%) ) #place(bottom + left, dx: 412pt, dy: -110pt, canvas({ import draw: * catmull((-1,4),(-0.5,3.9),(0.5,3.1),(1,3),stroke: (paint: orange, dash: "dashed"),tension: .5) line((-1,0),(0,0), stroke: (paint: orange, dash: "dashed")) catmull((1,1),(2.2,1.4),(2.4,3.6),(3,4),stroke: (paint: orange, dash: "dashed"),tesion: .5) catmull((2,4),(2.4,3.6),(2.6,0.5),(3,0),stroke: (paint: orange, dash: "dashed"),tesion: .5) edge((0,0),(2,0)) edge((0,0),(0,4)) edge((2,0),(2,4)) edge((0,4),(2,4)) edge((0,2),(2,2)) edge((2,0),(0,4)) edge((1,3),(2,4)) edge((1,3),(2,2)) edge((1,3),(0.75,2.75)) edge((0,2),(0.58,2.58)) edge((1,1),(0,0)) edge((1,1),(0,2)) edge((1,1),(1.25,1.25)) edge((1.42,1.42),(2,2)) vertex((0,0),"12",blue) vertex((2,0),"13",blue) vertex((1,1),"11",blue) vertex((0,2),"8",blue) vertex((1,2),"9",blue) vertex((2,2),"10",blue) vertex((1,3),"7",blue) vertex((0,4),"5",blue) vertex((2,4),"6",blue) vertex((-1,0),"2",white) vertex((-1,4),"1",white) vertex((3,0),"4",white) vertex((3,4),"3",white) content((-1,4.5),text(black,"1")) content((-1,0.5),text(black,"2")) content((3,4.5),text(black,"3")) content((3,0.5),text(black,"4")) }) ) #place(top + right, dx: -60pt, dy: -15pt, image("animation/hadamard_1_out_population.gif", height: 35%) ) #place(top + right, dx: 40pt, dy: 13pt, image("animation/hadamard_1_out_phase.gif", width: 15%) ) #place(bottom + right, dx: -60pt, dy: -109pt, image("animation/hadamard_0_out_population.gif", height: 35%) ) #place(bottom + right, dx: 40pt, dy: -107pt, image("animation/hadamard_0_out_phase.gif", width: 15%) ) #place(left+bottom, dx: 160pt, dy: 20pt)[#rect([ + single-qubit gates on computational qubits ($checkmark$) , + controlled phase gate between computational qubit and mediator qubit, + Hadamard gate on mediator qubit ($checkmark$) .], fill: aqua, inset: 10pt, radius: 10%)] == Two Interacting Bosonic Walker on Infinite Chain For Bose-Hubbard interaction $ U(r) = u delta_(r,0), $ the phase gained is $ e^(i theta) = - frac(u+4i cos ell sin k, u-4i cos ell sin k), ell = frac(p_1+p_2,2), k = frac(p_1-p_2,2) $ #align(right)[ #text("For detailed proof, see Appendix B.", size: 12pt)] == Momentum Switch #place(bottom + left, dx: 0pt, dy: -175pt, canvas({ import draw: * edge((0,0),(2,0)) edge((0,1),(3,1)) edge((1,0),(1,1)) edge((2,-1),(2,2)) edge((2,2),(1.5,3)) edge((2,2),(2.5,3)) edge((2,-1),(1.5,-2)) edge((2,-1),(2.5,-2)) vertex((0,0),"12",white) vertex((1,0),"13",blue) vertex((2,0),"11",blue) vertex((0,1),"8",white) vertex((1,1),"9",blue) vertex((2,1),"10",blue) vertex((3,1),"7",white) vertex((2,-1),"5",blue) vertex((1.5,-2),"6",blue) vertex((2.5,-2),"2",blue) vertex((2,2),"1",blue) vertex((1.5,3),"4",blue) vertex((2.5,3),"3",blue) content((-0.5,1),text(black,"1")) content((3.5,1),text(black,"2")) content((-0.5,0),text(black,"3")) circle((-6,0.5),radius: 1) edge((-6,-0.5),(-7,0.5)) edge((-6,-0.55),(-5,0.45)) edge((-6,-0.45),(-5,0.55)) vertex((-6,-0.5),"1",white) vertex((-5,0.5),"1",white) vertex((-7,0.5),"1",white) content((-7.5,0.5),"1") content((-4.5,0.5),"2") content((-6,-1),"3") }) ) #place(bottom + left, dx: 0pt, dy: 30pt)[#align(left)[Momentum switch is a gadget that leads wave with different momentum to different rail. For $k=pi/4$, perfect transmission happens only between 1 and 3. For $k=pi/2$, perfect transmission happens only between 2 and 3.]] #place(top + right, dx: -205pt, dy: 36pt, canvas({ import draw: * circle((-6,0.5),radius: 1) edge((-6,-0.5),(-7,0.5)) edge((-6,-0.55),(-5,0.45)) edge((-6,-0.45),(-5,0.55)) vertex((-6,-0.5),"1",white) vertex((-5,0.5),"1",white) vertex((-7,0.5),"1",white) }) ) #place(top + right, dx: -151pt, dy: 97pt, image("animation/switch_pi4_3_population.gif", width: 12%) ) #place(top + right, dx: -270pt, dy: -16pt, image("animation/switch_pi4_1_population.gif", width: 12%) ) #place(top + right, dx: -115pt, dy: -16pt, image("animation/switch_pi4_2_population.gif", width: 12%) ) #place(top + right, dx: 30pt, dy: 16pt, image("animation/swich_pi4_1_phase.gif", width: 18%) ) #place(top + right, dx: -205pt, dy: 206pt, canvas({ import draw: * circle((-6,0.5),radius: 1) edge((-6,-0.5),(-7,0.5)) edge((-6,-0.55),(-5,0.45)) edge((-6,-0.45),(-5,0.55)) vertex((-6,-0.5),"1",white) vertex((-5,0.5),"1",white) vertex((-7,0.5),"1",white) }) ) #place(top + right, dx: -151pt, dy: 267pt, image("animation/switch_pi2_3_population.gif", width: 12%) ) #place(top + right, dx: -270pt, dy: 154pt, image("animation/switch_pi2_1_population.gif", width: 12%) ) #place(top + right, dx: -115pt, dy: 154pt, image("animation/switch_pi2_2_population.gif", width: 12%) ) #place(top + right, dx: 30pt, dy: 184pt, image("animation/swich_pi2_2_phase.gif", width: 18%) ) == C-Phase Gate #place(top + left, dx: 136pt, dy: -16pt, image("animation/cp_comp_in.gif", height: 50%) ) #place(bottom + left, dx: 0pt, dy: 16pt, image("animation/cp_medi_in.gif", height: 50%) ) #place(bottom + left, dx: 376pt, dy: 16pt, image("animation/cp_comp_out.gif", height: 50%) ) #place(top + left, dx: 376pt, dy: -16pt, image("animation/cp_medi_out.gif", height: 50%) ) #place(bottom + right, dx: 0pt, dy: 16pt, image("animation/cp_phase.gif", height: 50%) ) #place(bottom + left, dx: 340pt, dy: -23pt, image("animation/cp_inter.gif", height: 40%) ) #place(top + right, dx: -372pt, dy: 110pt, canvas({ import draw: * circle((-6,0.5),radius: 1) edge((-6,-0.5),(-7,0.5)) edge((-6,-0.55),(-5,0.45)) edge((-6,-0.45),(-5,0.55)) vertex((-6,-0.5),"1",white) vertex((-5,0.5),"1",white) vertex((-7,0.5),"1",white) }) ) #place(bottom + right, dx: -372pt, dy: 36pt, canvas({ import draw: * circle((-6,0.5),radius: 1) edge((-6,1.55),(-7,0.55)) edge((-6,1.45),(-7,0.45)) edge((-6,1.5),(-5,0.5)) vertex((-6,1.5),"1",white) vertex((-5,0.5),"1",white) vertex((-7,0.5),"1",white) }) ) = Graph Editing and Quantum Circuits == Link Two Gadget // #place(top, dy: 30pt)[ // For two scattering setup, $G_1$ and $G_2$. // The process of connecting them can be formulated as:] #place(center, dx: -270pt, dy: 40pt,canvas({ import draw: * rect((0,0),(2,4), radius: 10%) line((-1,0.5),(-3,0.5)) line((-1,1.5),(-3,1.5)) line((-1,2.5),(-3,2.5)) line((-1,3.5),(-3,3.5)) for i in (1, 2, 3, 4) { for j in (1, 2, 3, 4) { line((-1,i - 0.5),(0,j - 0.5)) } } content((1,2),text(black,$G_1$)) vertex((-1,0.5),"1",white) vertex((-1,1.5),"1",white) vertex((-1,2.5),"1",white) vertex((-1,3.5),"1",white) vertex((-2,0.5),"1",blue) vertex((-2,1.5),"1",blue) vertex((-2,2.5),"1",blue) vertex((-2,3.5),"1",blue) vertex((-3,0.5),"1",blue) vertex((-3,1.5),"1",blue) vertex((-3,2.5),"1",blue) vertex((-3,3.5),"1",blue) content((-3.5,0.7),text("...")) content((-3.5,1.7),text("...")) content((-3.5,2.7),text("...")) content((-3.5,3.7),text("...")) content((-4.5,0.5),text($1^((1))_("out")$,size: 13pt)) content((-4.5,1.5),text($0^((1))_("out")$,size: 13pt)) content((-4.5,2.5),text($1^((1))_("in")$,size: 13pt)) content((-4.5,3.5),text($0^((1))_("in")$,size: 13pt)) })) #place(center, dx: -270pt, dy: 170pt,canvas({ import draw: * rect((0,0),(2,4), radius: 10%) line((-1,0.5),(-3,0.5)) line((-1,1.5),(-3,1.5)) line((-1,2.5),(-3,2.5)) line((-1,3.5),(-3,3.5)) for i in (1, 2, 3, 4) { for j in (1, 2, 3, 4) { line((-1,i - 0.5),(0,j - 0.5)) } } content((1,2),text(black,$G_2$)) vertex((-1,0.5),"1",white) vertex((-1,1.5),"1",white) vertex((-1,2.5),"1",white) vertex((-1,3.5),"1",white) vertex((-2,0.5),"1",blue) vertex((-2,1.5),"1",blue) vertex((-2,2.5),"1",blue) vertex((-2,3.5),"1",blue) vertex((-3,0.5),"1",blue) vertex((-3,1.5),"1",blue) vertex((-3,2.5),"1",blue) vertex((-3,3.5),"1",blue) content((-3.5,0.7),text("...")) content((-3.5,1.7),text("...")) content((-3.5,2.7),text("...")) content((-3.5,3.7),text("...")) content((-4.5,0.5),text($1^((2))_("out")$,size: 13pt)) content((-4.5,1.5),text($0^((2))_("out")$,size: 13pt)) content((-4.5,2.5),text($1^((2))_("in")$,size: 13pt)) content((-4.5,3.5),text($0^((2))_("in")$,size: 13pt)) })) #place(center, dx: 0pt, dy: 40pt,canvas({ import draw: * rect((0,0),(2,4), radius: 10%) line((-1,2.5),(-3,2.5)) line((-1,3.5),(-3,3.5)) for i in (1, 2, 3, 4) { for j in (1, 2, 3, 4) { line((-1,i - 0.5),(0,j - 0.5)) } } content((1,2),text(black,$G_1$)) vertex((-1,0.5),"1",white) vertex((-1,1.5),"1",white) vertex((-1,2.5),"1",white) vertex((-1,3.5),"1",white) vertex((-2,2.5),"1",blue) vertex((-2,3.5),"1",blue) vertex((-3,2.5),"1",blue) vertex((-3,3.5),"1",blue) content((-3.5,2.7),text("...")) content((-3.5,3.7),text("...")) content((-4.5,2.5),text($1^((1))_("in")$,size: 13pt)) content((-4.5,3.5),text($0^((1))_("in")$,size: 13pt)) })) #place(center, dx: 0pt, dy: 170pt,canvas({ import draw: * rect((0,0),(2,4), radius: 10%) line((-1,0.5),(-3,0.5)) line((-1,1.5),(-3,1.5)) for i in (1, 2, 3, 4) { for j in (1, 2, 3, 4) { line((-1,i - 0.5),(0,j - 0.5)) } } content((1,2),text(black,$G_2$)) vertex((-1,0.5),"1",white) vertex((-1,1.5),"1",white) vertex((-1,2.5),"1",white) vertex((-1,3.5),"1",white) vertex((-2,0.5),"1",blue) vertex((-2,1.5),"1",blue) vertex((-3,0.5),"1",blue) vertex((-3,1.5),"1",blue) content((-3.5,0.7),text("...")) content((-3.5,1.7),text("...")) content((-4.5,0.5),text($1^((2))_("out")$,size: 13pt)) content((-4.5,1.5),text($0^((2))_("out")$,size: 13pt)) })) #place(center, dx: 260pt, dy: 110pt,canvas({ import draw: * catmull((0,0),(-1.3,1.3),(0,2.6),tension: .4) catmull((0,-1),(-1.3,0.3),(0,1.6),tension: .4) })) #place(center, dx: 270pt, dy: 40pt,canvas({ import draw: * rect((0,0),(2,4), radius: 10%) line((-1,2.5),(-3,2.5)) line((-1,3.5),(-3,3.5)) for i in (1, 2, 3, 4) { for j in (1, 2, 3, 4) { line((-1,i - 0.5),(0,j - 0.5)) } } content((1,2),text(black,$G_1$)) vertex((-1,0.5),"1",white) vertex((-1,1.5),"1",white) vertex((-1,2.5),"1",white) vertex((-1,3.5),"1",white) vertex((-2,2.5),"1",blue) vertex((-2,3.5),"1",blue) vertex((-3,2.5),"1",blue) vertex((-3,3.5),"1",blue) content((-3.5,2.7),text("...")) content((-3.5,3.7),text("...")) content((-4.5,2.5),text($1^((1))_("in")$,size: 13pt)) content((-4.5,3.5),text($0^((1))_("in")$,size: 13pt)) })) #place(center, dx: 270pt, dy: 170pt,canvas({ import draw: * rect((0,0),(2,4), radius: 10%) line((-1,0.5),(-3,0.5)) line((-1,1.5),(-3,1.5)) for i in (1, 2, 3, 4) { for j in (1, 2, 3, 4) { line((-1,i - 0.5),(0,j - 0.5)) } } content((1,2),text(black,$G_2$)) vertex((-1,0.5),"1",white) vertex((-1,1.5),"1",white) vertex((-1,2.5),"1",white) vertex((-1,3.5),"1",white) vertex((-2,0.5),"1",blue) vertex((-2,1.5),"1",blue) vertex((-3,0.5),"1",blue) vertex((-3,1.5),"1",blue) content((-3.5,0.7),text("...")) content((-3.5,1.7),text("...")) content((-4.5,0.5),text($1^((2))_("out")$,size: 13pt)) content((-4.5,1.5),text($0^((2))_("out")$,size: 13pt)) })) #place(center, dx: -120pt, dy: 140pt)[#text(red,$arrow.r.double$, size: 48pt)] #place(center, dx: +150pt, dy: 140pt)[#text(red,$arrow.r.double$, size: 48pt)] == Link Two Gadget: Abstraction // #place(top+left, dy: 0pt)[ // The connect process can be abstracted as:] #place(center, dx: -200pt, dy: 20pt,canvas({ import draw: * rect((0,0),(2,4), radius: 10%) line((-1,0.5),(-3,0.5)) line((-1,1.5),(-3,1.5)) line((-1,2.5),(-3,2.5)) line((-1,3.5),(-3,3.5)) line((3,1),(5,1)) line((3,2),(5,2)) line((3,3),(5,3)) for i in (1, 2, 3, 4) { for j in (1, 2, 3, 4) { line((-1,i - 0.5),(0,j - 0.5)) } } for i in (1, 2, 3) { for j in (1, 2, 3) { line((3,i),(2,j)) } } content((1,2),text(black,$G$)) vertex((-1,0.5),"1",white) vertex((-1,1.5),"1",white) vertex((-1,2.5),"1",white) vertex((-1,3.5),"1",white) vertex((3,1),"1",white) vertex((3,2),"1",white) vertex((3,3),"1",white) vertex((-2,0.5),"1",blue) vertex((-2,1.5),"1",blue) vertex((-2,2.5),"1",blue) vertex((-2,3.5),"1",blue) vertex((-3,0.5),"1",blue) vertex((-3,1.5),"1",blue) vertex((-3,2.5),"1",blue) vertex((-3,3.5),"1",blue) vertex((4,1),"1",blue) vertex((4,2),"1",blue) vertex((4,3),"1",blue) vertex((5,1),"1",blue) vertex((5,2),"1",blue) vertex((5,3),"1",blue) content((-3.5,0.7),text("...")) content((-3.5,1.7),text("...")) content((-3.5,2.7),text("...")) content((-3.5,3.7),text("...")) content((5.5,1.2),text("...")) content((5.5,2.2),text("...")) content((5.5,3.2),text("...")) content((-5,0.5),text($n-k$,size: 16pt)) content((-4.5,1.5),text($dots.v$,size: 16pt)) content((-4.5,2.5),text($dots.v$,size: 16pt)) content((-4.5,3.5),text($1$,size: 16pt)) content((6.5,1),text($n$,size: 16pt)) content((6.5,2),text($dots.v$,size: 16pt)) content((7.5,3),text($n-k+1$,size: 16pt)) })) #place(center, dx: 0pt, dy: 220pt,canvas({ import draw: * rect((0,0),(2,4), radius: 10%) line((-1,0.5),(-3,0.5)) line((-1,1.5),(-3,1.5)) line((-1,2.5),(-3,2.5)) line((-1,3.5),(-3,3.5)) catmull((3,1),(3.5,1.5),(3,2),tension: .4,stroke: (dash: "dotted")) catmull((3,2),(3.5,2.5),(3,3),tension: .4) catmull((3,1),(3.5,0.8),(4.5,2),(3.5,3.2),(3,3),tension: .5) for i in (1, 2, 3, 4) { for j in (1, 2, 3, 4) { line((-1,i - 0.5),(0,j - 0.5)) } } for i in (1, 2, 3) { for j in (1, 2, 3) { line((3,i),(2,j)) } } content((1,2),text(black,$G$)) vertex((-1,0.5),"1",white) vertex((-1,1.5),"1",white) vertex((-1,2.5),"1",white) vertex((-1,3.5),"1",white) vertex((3,1),"1",white) vertex((3,2),"1",white) vertex((3,3),"1",white) vertex((-2,0.5),"1",blue) vertex((-2,1.5),"1",blue) vertex((-2,2.5),"1",blue) vertex((-2,3.5),"1",blue) vertex((-3,0.5),"1",blue) vertex((-3,1.5),"1",blue) vertex((-3,2.5),"1",blue) vertex((-3,3.5),"1",blue) content((-3.5,0.7),text("...")) content((-3.5,1.7),text("...")) content((-3.5,2.7),text("...")) content((-3.5,3.7),text("...")) content((-5,0.5),text($n-k$,size: 16pt)) content((-4.5,1.5),text($dots.v$,size: 16pt)) content((-4.5,2.5),text($dots.v$,size: 16pt)) content((-4.5,3.5),text($1$,size: 16pt)) })) #place(center, dx: 220pt, dy: 20pt,canvas({ import draw: * rect((0,0),(2,4), radius: 10%) line((-1,0.5),(-3,0.5)) line((-1,1.5),(-3,1.5)) line((-1,2.5),(-3,2.5)) line((-1,3.5),(-3,3.5)) for i in (1, 2, 3, 4) { for j in (1, 2, 3, 4) { line((-1,i - 0.5),(0,j - 0.5)) } } for i in (1, 2, 3) { for j in (1, 2, 3) { line((3,i),(2,j)) } } content((1,2),text(black,$G$)) vertex((-1,0.5),"1",white) vertex((-1,1.5),"1",white) vertex((-1,2.5),"1",white) vertex((-1,3.5),"1",white) vertex((3,1),"1",white) vertex((3,2),"1",white) vertex((3,3),"1",white) vertex((-2,0.5),"1",blue) vertex((-2,1.5),"1",blue) vertex((-2,2.5),"1",blue) vertex((-2,3.5),"1",blue) vertex((-3,0.5),"1",blue) vertex((-3,1.5),"1",blue) vertex((-3,2.5),"1",blue) vertex((-3,3.5),"1",blue) content((-3.5,0.7),text("...")) content((-3.5,1.7),text("...")) content((-3.5,2.7),text("...")) content((-3.5,3.7),text("...")) content((-5,0.5),text($n-k$,size: 16pt)) content((-4.5,1.5),text($dots.v$,size: 16pt)) content((-4.5,2.5),text($dots.v$,size: 16pt)) content((-4.5,3.5),text($1$,size: 16pt)) })) #place(center, dx: 40pt, dy: 60pt)[#text(red,$arrow.r.double$, size: 48pt)] #place(center, dx: 80pt, dy: 160pt)[#rotate(135deg)[#text(red,$arrow.r.double$, size: 48pt)]] == Link Two Gadget: Calculation The above operation results in the change of Hamiltonian $H_G$ and $QQ$ matrix. $ tilde(H)_G = H_G + sum_((alpha,beta) in tilde(E)) |alpha angle.r angle.l beta|+|beta angle.r angle.l alpha| =: H_G +h_G\ tilde(QQ) = II - sum_(j in "remained")|0,j angle.r angle.l 0,j| = QQ + sum_(j in "cutted")|0,j angle.r angle.l 0,j| =: QQ + Q\ arrow.r.double tilde(AA)(z) = II - z tilde(H)_G + z^2 tilde(QQ) = AA(z)+z^2 Q - z h_G =:AA(z)+P $ == Link Two Gadget: Result #place(center, dx: 20pt, dy: 175pt)[ #rect(width: 290pt, height: 32pt, fill: aqua, radius: 10%)] Suppose the original $S$-matrix, in block form, is $ S = mat(T_((n-k) times (n-k)), U_((n-k) times k); V_(k times (n-k)), W_(k times k)) $ $ tilde(S) &= (1-z^2)mat(II_n 0)tilde(AA)^(-1)(z)mat(II_n;0) - II_n\ &= T - U P [(1-z^2)II + P + W P]^(-1) V $ For two scattering gates, the above formula gives $ S_1=mat(0,U_1^dagger;U_1,0), S_2=mat(0,U_2^dagger;U_2,0) arrow.r.double S = mat(0,z^* U_2^dagger U_1^dagger;z U_1 U_2,0) $ = Summary == Summary #slide(composer: (1fr, 1fr))[ About A.M. Childs' construction: + no time-dependent quantum controll + error bound $tilde O(L^(-1/4))$ + numerous sites ][ Future work: + delay gadget + gadget cascade + realization in bio-systems (polymers) ] == Thank you = Appendix A == Solve the S-Matrix: take a guess! The eigen-state of Hamiltonian can be expressed as $ |"sc"_q (k) angle.r = limits(sum)_(v) alpha_(q,v) |v angle.r + limits(sum)_(1 <= j <= n)limits(sum)_(x >= 1) beta_(x,q,j) |x,j angle.r. $ Recall the quantum scattering page, here we take $ beta_(x,q,j) = angle.l x,j| "sc"_q (k) angle.r = delta_(q j)e^(-i k x) + S_(q j)e^(i k x) $ #v(50pt) (Actually, suppose this relation holds for all $x>=0$. Because $|0,j angle.r$ is also a part of path graph.) == Quantum Scattering (Re-visit) #slide(composer: (1.2fr, 0.8fr))[ Due to superposition principle, the scattered state may be a superposition of states on different "trajectories". $ psi_("in")(k) = e^(- i omega t) e^(-i k x ), psi_("out")(k) = e^(- i omega t) sum_(k') S_(k k') e^(i k' x) , $ $ psi_("sc")(k) = e^(- i omega t) (delta_(k k') e^(-i k x )+sum_(k') S_(k k') e^(i k' x)) $ The S-matrix is vital to scattering problem. The orthonormality of $psi_"sc" (k)$ proves the unitarity of S-matrix. ][ #image("animation/quantum.gif") ] == Solve the S-Matrix: for sites on tails #align(center)[#rect( $ |"sc"_q (k) angle.r &= limits(sum)_(v) alpha_(q,v) |v angle.r + limits(sum)_(1 <= j <= n)limits(sum)_(x >= 1) (delta_(q j)e^(-i k x)|x,j angle.r + S_(q j)e^(i k x) |x,j angle.r)\ &= |"sc"_q (k) angle.r^G + limits(sum)_(1 <= j <= n)limits(sum)_(x >= 1) (delta_(q j)e^(-i k x) + S_(q j)e^(i k x) )|x,j angle.r $, fill: silver, radius: 10%)] Use the result of free propagation, we have //$ angle.l x',q'|"sc"_q (k) angle.r = delta_(q q')e^(-i k x') + S_(q q')e^(i k x') $ $ angle.l x',q'|H|"sc"_q (k) angle.r &= angle.l x',q'|T_q'|"sc"_q (k) angle.r\ &= angle.l x',q'|2 cos k|"sc"_q (k) angle.r. $ Since $|"sc"_q (k) angle.r$ is an energy eigen-state, #align(center)[#rect($ H|"sc"_q (k) angle.r = 2 cos k|"sc"_q (k) angle.r $, fill: aqua, radius: 10%)] == Solve the S-Matrix #align(center)[#rect($ H = H_G + sum_(1 <= j <= n) (T_j + |0,j angle.r angle.l 1,j| + |1,j angle.r angle.l 0,j|)\ |"sc"_q (k) angle.r = |"sc"_q (k) angle.r^G + limits(sum)_(1 <= j <= n)limits(sum)_(x >= 1) (delta_(q j)e^(-i k x) + S_(q j)e^(i k x) )|x,j angle.r\ H|"sc"_q (k) angle.r = 2 cos k|"sc"_q (k) angle.r $, fill: silver, radius: 10%)] $ H|"sc"_q (k) angle.r = &H_G|"sc"_q (k) angle.r^G + \ &sum_(1 <= j <= n)(2 cos k sum_(x>=1)(delta_(q j)e^(-i k x) + S_(q j)e^(i k x) )|x,j angle.r - (delta_(q j)+S_(q j))|1,j angle.r)\ &+ sum_(1 <= j <= n) (|1,j angle.r angle.l 0,j|"sc"_q (k) angle.r^G + |0,j angle.r angle.l 1,j|(delta_(q j) e^(-i k) + S_(q j) e^(i k))|1,j angle.r) = 2 cos k|"sc"_q (k) angle.r $ == Solve the S-Matrix $ (H_G-2 cos k)|"sc"_q (k) angle.r^G + sum_(1 <= j <= n)(delta_(q j) e^(-i k) + S_(q j) e^(i k))|0,j angle.r = sum_(1 <= j <= n)(delta_(q j)+S_(q j)-angle.l 0,j|"sc"_q (k) angle.r^G)|1,j angle.r $ #align(center)[#rect($ arrow.r.double S_(q j) = angle.l 0,j|"sc"_q (k) angle.r^G - delta_(q j) $, fill: aqua, radius: 10%)] $ (H_G-2 cos k)|"sc"_q (k) angle.r^G+ sum_(1 <= j <= n) (delta_(q j) e^(-i k) - delta_(q j) e^(i k) + e^(i k) angle.l 0,j|"sc"_q (k) angle.r)|0,j angle.r = 0 $ $ (H_G-2 cos k)|"sc"_q (k) angle.r^G + (e^(-i k)-e^(i k))|0,q angle.r + sum_(1 <= j <= n) e^(i k)|0,j angle.r angle.l 0,j|"sc"_q (k) angle.r = 0 $ #align(center)[#rect($ (H_G-2 cos k + e^(i k) sum_(1 <= j <= n) |0,j angle.r angle.l 0,j|)|"sc"_q (k) angle.r^G = (e^(i k)-e^(-i k))|0,q angle.r $, fill: aqua, radius: 10%)] == Solve the S-Matrix Denote $z=e^(i k)$ and get $ AA(z)|"sc"_q (k) angle.r^G = (II-z H_G + z^2 QQ)|"sc"_q (k) angle.r^G = (1 - z^2)|0,q angle.r , QQ = II-sum_(1 <= j <= n) |0,j angle.r angle.l 0,j|. $ Then $ S_(q j) = (1-z^2) angle.l 0,q| AA^(-1)(z)|0,q angle.r - delta_(q j) $ = Appendix B == Two Interacting Walkers in Free Space The coordinates of two bosons are denoted as $x,y$. Then the sites of the system are $ |x,y angle.r = |x angle.r times.circle |y angle.r . $ #text( "Note that exchange symmetry is not considered here. But it will be considered are the very end of the proof.", size: 16pt ) The Hamiltonian is, under this "basis", $ H = sum_(x,y) (&|x+1,y angle.r angle.l x,y|+|x,y angle.r angle.l x+1,y|+\ &|x,y+1 angle.r angle.l x,y|+|x,y angle.r angle.l x,y+1|+U(|x-y|)|x,y angle.r angle.l x,y|) $ == Basis Transformation Consider a set of new coordinates $s=x+y,r=x-y$, the Hamiltonian can be expressed as $ H &= sum_(s,r) (|s+1,r+1 angle.r angle.l s,r| + |s,r angle.r angle.l s+1,r+1|+\ &|s+1,r-1 angle.r angle.l s,r|+|s,r angle.r angle.l s+1,r-1|+U(|r|)|s,r angle.r angle.l s,r|)\ &= sum_(s,r) (|s+1 angle.r angle.l s| times.circle |r+1 angle.r angle.l r| + |s angle.r angle.l s+1| times.circle |r angle.r angle.l r+1| +\ &|s+1 angle.r angle.l s| times.circle |r-1 angle.r angle.l r| + |s angle.r angle.l s+1| times.circle |r angle.r angle.l r-1|+U(|r|)|s angle.r angle.l s| times.circle |r angle.r angle.l r|)\ &= H_("free")^((s)) times.circle H_("free")^((r)) + II^((s)) times.circle sum_(r) U(|r|)|r angle.r angle.l r| \ &=: F_s times.circle F_r + II_s times.circle U_r $ == Eigen-State Notice that $s$-part Hamiltonian is just free particle. $ angle.l s,r|"cr"(ell,k)angle.r = e^(-i ell s) angle.l r| psi_r (ell, k) angle.r $ Assume the interaction $U(|r|)$ is of range $C$, i.e., $U(|r|)=0$ for $|r|>C$. So for $|r|>C$, the $r$-part Hamiltonian is also free particle. $ angle.l r|psi_r (ell,k) angle.r = e^(-i k r) + alpha(ell,k) e^(i k r) , " for " r< -C\ angle.l r|psi_r (ell,k) angle.r = beta(ell,k) e^(-i k r), " for " r> C $ Again, for $|r|>C$ $ angle.l s,r|H|"cr"(ell,k)angle.r &= angle.l s,r|F_s times.circle F_r|"cr"(ell,k)angle.r\ &=4 cos ell cos k angle.l s,r|"cr"(ell,k)angle.r $ == Time-Independent Schrödinger Equation The eigen-state, plugged in konwn information, is of the form $ |psi_r (ell,k) angle.r = sum_(-C <= r <= C) phi_r |r angle.r + sum_(r< -C) (e^(-i k r) + alpha(ell,k) e^(i k r))|r angle.r + sum_(r> C) beta(ell,k) e^(-i k r)|r angle.r\ |"cr"(ell,k) angle.r = |"pl"(ell) angle.r times.circle |psi_r (ell,k) angle.r $ Consider the Schrödinger equation for eigen-state $|"cr"(ell,k) angle.r$, $ H|"cr"(ell,k) angle.r = 2 cos ell|"pl"(ell) angle.r times.circle F_r|psi_r (ell,k) angle.r + |"pl"(ell) angle.r times.circle U_r|psi_r (ell,k) angle.r = 4 cos ell cos k|"cr"(ell,k) angle.r\ \ \ arrow.r.double 2 cos ell F_r|psi_r (ell,k) angle.r + U_r|psi_r (ell,k) angle.r = 4 cos ell cos k|psi_k (ell,k) angle.r $ == Exchange Symmetry By swapping the particle coordinates $x$ and $y$, we have $ "Sym"(|x,y angle.r) &= frac(1,sqrt(2))(|x,y angle.r plus.minus |y,x angle.r) \ &=frac(1,sqrt(2))(|s,r angle.r plus.minus |s,-r angle.r) \ & = |s angle.r times.circle "Sym"(|r angle.r). $ As for the eigen-state, we have $ |psi_(-r) (ell,k) angle.r = sum_(-C <= r <= C) phi_(-r) |r angle.r + sum_(r> C) (e^(i k r) + alpha(ell,k) e^(-i k r))|r angle.r + sum_(r< -C) beta(ell,k) e^(i k r)|r angle.r = |psi_r (ell,-k) angle.r $ is another eigen-state with same energy ($E=4 cos ell cos k$ is even in $k$). == Exchange Symmetry: Continued The "true" eigen-state that satisfies exchange symmetry is $ "Sym"(|psi_r (ell,k) angle.r) = &frac(1,sqrt(2)) sum_(-C <= r <= C) ( phi_r plus.minus phi_(-r)) |r angle.r+\ &frac(1,sqrt(2))sum_(r> C) [e^(i k r) + (alpha plus.minus beta) e^(-i k r)]|r angle.r + frac(1,sqrt(2))sum_(r< -C) [e^(-i k r) + (alpha plus.minus beta) e^(i k r)]|r angle.r. $ Clearly, the phase gained through interaction is $ e^(i theta) = alpha(ell,k) plus.minus beta(ell,k). $ == Bose-Hubbard Model For Bose-Hubbard model, $U(r)=u delta_(r,0)$, $C=0$. $ |psi_r (ell,k) angle.r = phi_0 |0 angle.r + sum_(r< 0) (e^(-i k r) + alpha(ell,k) e^(i k r))|r angle.r + sum_(r> 0) beta(ell,k) e^(-i k r)|r angle.r $ And the Schrödinger equation gives $ 2 cos ell [phi_0|1 angle.r + phi_0|-1 angle.r + (e^(i k)+alpha(ell,k) e^(i k))|0 angle.r - (1+ alpha)|-1 angle.r + beta e^(-i k)|0 angle.r - beta |1 angle.r]\ + u phi_0|0 angle.r = 4 cos ell cos k phi_0 |0 angle.r\ \ $ #place(center, dx: -160pt)[ $ phi_0 &= 1+ alpha \ phi_0 &= beta \ u phi_0 &= 4i cos ell sin k (phi_0 -1) $] #place(center, dx: 160pt, dy: 25pt)[ $ arrow.r.double e^(i theta) = frac(4i cos ell sin k +u, 4i cos ell sin k -u) $]
https://github.com/Jollywatt/typst-fletcher
https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/src/utils.typ
typst
MIT License
#import "deps.typ": cetz #import cetz: vector #let error(message, ..args) = { let pairs = args.pos().enumerate() + args.named().pairs() let ticks(x) = "`" + if type(x) == str { x } else { repr(x) } + "`" for (k, v) in pairs { if type(v) == array { message = message.replace("#.." + str(k), v.map(ticks).join(", ")) } if type(v) != str { v = repr(v) } message = message.replace("#" + str(k), ticks(v)) } assert(false, message: message) } // Replace `auto` with a value #let map-auto(value, fallback) = if value == auto { fallback } else { value } // Make a function propagate `auto` #let pass-auto(f) = x => if x == auto { x } else { f(x) } // Make a function propagage `none` #let pass-none(f) = x => if x == none { x } else { f(x) } // for when `stroke` is already in namespace #let as-stroke(x) = stroke(x) #let as-label(x) = { if type(x) == label { x } else if type(x) == str { label(x) } else { error("Expected label or string; got #0.", repr(x)) } } #let as-pair(obj) = { if type(obj) == array { if obj.len() == 2 { obj } else { error("Expected a pair (array of length 2); got #0.", repr(obj))} } else { (obj, obj) } } #let as-array(obj) = if type(obj) == array { obj } else { (obj,) } #let as-number-or-length(obj, message: "Expected a number or length") = { if type(obj) in (int, float, length) { obj } else { error(message + "; got #0.", repr(obj)) } } #let as-length(obj, message: "Expected a length") = { if type(obj) == length { obj } else { error(message + "; got #0.", repr(obj)) } } #let stroke-to-dict(s) = { let s = as-stroke(s) let d = ( paint: s.paint, thickness: s.thickness, cap: s.cap, join: s.join, dash: s.dash, miter-limit: s.miter-limit, ) // remove auto entries to allow folding strokes by joining dicts for (key, value) in d { if value == auto { let _ = d.remove(key) } } d } #let to-abs-length(len, em-size) = len.abs + len.em*em-size #let sign(x) = if float(x) = 0 { 1 } else { x/calc.abs(x) } #let min-max(array) = (calc.min(..array), calc.max(..array)) #let cumsum(array) = { let sum = array.at(0) for i in range(1, array.len()) { sum += array.at(i) array.at(i) = sum } array } #let vector-len((x, y)) = 1pt*calc.sqrt((x/1pt)*(x/1pt) + (y/1pt)*(y/1pt)) #let vector-set-len(len, v) = vector.scale(v, len/vector-len(v)) #let vector-unitless(v) = v.map(x => if type(x) == length { x.pt() } else { x }) #let vector-2d((x, y, ..z)) = (x, y) #let vector-max(a, b) = array.zip(a, b).map(vals => calc.max(..vals)) #let vector-polar(r, θ) = (r*calc.cos(θ), r*calc.sin(θ)) #let vector-angle(v) = calc.atan2(..vector-unitless(v)) #let angle-between(from, to) = vector-angle(vector.sub(to, from)) // Ensure angle is in range 0deg <= θ < 360deg #let wrap-angle-360(θ) = calc.rem-euclid(θ/360deg, 1)*360deg // Ensure angle is in range -180deg <= θ <= 180deg #let wrap-angle-180(θ) = (θ/360deg - calc.round(θ/360deg))*360deg #let angle-to-anchor(θ) = { let i = calc.rem(8*θ/1rad/calc.tau, 8) ( "east", "north-east", "north", "north-west", "west", "south-west", "south", "south-east", ).at(int(calc.round(i))) } #let is-length-vector(v) = v.all(x => type(x) == length) #let is-number-vector(v) = v.all(x => type(x) in (int, float)) #let is-nan-vector(v) = is-number-vector(v) and v.all(x => float(x).is-nan()) #let lerp(a, b, t) = a*(1 - t) + b*t /// Linearly interpolate an array with linear behaviour outside bounds /// /// - values (array): Array of lengths defining interpolation function. /// - index (int, float): Index-coordinate to sample. /// - spacing (length): Gradient for linear extrapolation beyond array bounds. #let interp(values, index, spacing: 0pt) = { let max-index = values.len() - 1 if index < 0 { values.at(0) + spacing*index } else if index > max-index { values.at(-1) + spacing*(index - max-index) } else { lerp( values.at(calc.floor(index)), values.at(calc.ceil(index)), calc.fract(index), ) } } /// Inverse of `interp()`. /// /// - values (array): Array of lengths defining interpolation function. /// - value: Value to find the interpolated index of. /// - spacing (length): Gradient for linear extrapolation beyond array bounds. #let interp-inv(values, value, spacing: 0pt) = { let i = 0 while i < values.len() { if values.at(i) >= value { break } i += 1 } let (first, last) = (values.at(0), values.at(-1)) // avoids division by zero when numerator and denominator both vanishe let div(a, b) = if calc.abs(a) < 1e-3pt { 0 } else { a/b } if value < first { div(value - first, spacing) } else if value >= last { values.len() - 1 + div(value - last, spacing) } else { let (prev, nearest) = (values.at(i - 1), values.at(i)) i - 1 + div(value - prev, nearest - prev) } } #let rect-at(origin, size) = (-1, +1).map(dir => { vector.add(origin, vector.scale(size, dir/2)) }) #let point-is-in-rect(point, (center, size)) = { point.zip(center, size).all(((x, o, s)) => { calc.abs(x - o) <= s/2 }) } #let bounding-rect(points) = { let (xs, ys) = array.zip(..points) let p1 = (calc.min(..xs), calc.min(..ys)) let p2 = (calc.max(..xs), calc.max(..ys)) ( center: vector.scale(vector.add(p1, p2), 0.5), size: vector.sub(p2, p1) ) } /// Determine arc between two points with a given bend angle /// /// The bend angle is the angle between chord of the arc (line connecting the /// points) and the tangent to the arc and the first point. /// /// Returns a dictionary containing: /// - `center`: the center of the arc's curvature /// - `radius` /// - `start`: the start angle of the arc /// - `stop`: the end angle of the arc /// /// - from (point): 2D vector of initial point. /// - to (point): 2D vector of final point. /// - angle (angle): The bend angle between chord of the arc (line connecting the /// points) and the tangent to the arc and the first point. /// -> dictionary /// /// #diagram(spacing: 2cm, { /// for (i, θ) in (0deg, 45deg, -90deg).enumerate() { /// edge((2*i, 0), (2*i + 1, 0), marks: (none, "head"), bend: θ) /// edge((2*i, 0), (2*i + 1, 0), [#θ], label-side: center, dash: /// "dotted") /// } /// }) #let get-arc-connecting-points(from, to, angle) = { // TODO: properly handle trivial arcs if from == to { to = vector.add(to, (0pt, 1e-4pt)) } let mid = vector.scale(vector.add(from, to), 0.5) let (dx, dy) = vector.sub(to, from) let perp = (dy, -dx) let center = vector.add(mid, vector.scale(perp, 0.5/calc.tan(angle))) let radius = vector-len(vector.sub(to, center)) let start = angle-between(center, from) let stop = angle-between(center, to) if start < stop and angle > 0deg { start += 360deg } if start > stop and angle < 0deg { start -= 360deg } (center: center, radius: radius, start: start, stop: stop) } /// Return true if a content element is a space or sequence of spaces #let is-space(el) = { if el == none { return true } if repr(el.func()) == "space" { return true } if repr(el.func()) == "sequence" { return el.children.all(is-space) } return false } // find a node near a given uv coordinate #let find-node-at(nodes, uv) = { nodes.filter(node => { if is-nan-vector(node.pos.uv) { return false } // node must be within a one-unit block around pos vector.sub(node.pos.uv, uv).all(Δ => calc.abs(Δ) < 1) }) .sorted(key: node => vector.len(vector.sub(node.pos.uv, uv))) .at(0, default: none) } #let find-node(nodes, key, snap: false) = { if type(key) == label { let node = nodes.find(node => node.name == key) assert(node != none, message: "Couldn't find node with name " + repr(key)) node } else if type(key) == array and is-number-vector(key) { find-node-at(nodes, key) } else { none } }
https://github.com/WinstonMDP/knowledge
https://raw.githubusercontent.com/WinstonMDP/knowledge/master/cardinals.typ
typst
#import "cfg.typ": cfg #show: cfg = Кардиналы $x lt.tilde y := exists z$ - инъекця из $x$ в $y$. $x$ равномощно $y := x tilde y := exists z$ - биекция между $x$ и $y$. $|x| :=$ кардинальное число $x$. $|x| = |y| := x tilde y$. Теорема Кантора-Бернштейна-Шрёдера: $cases(x lt.tilde y, y lt.tilde x) <-> x tilde y$. $|{0, ..., n - 1}| := n$. $aleph_0 := |NN|$. $x$ конечное $:= exists n = |x|$. $x$ бесконечное $:= x$ не конечное. $x$ конечное $-> y subset.eq x -> |x| = |y| -> x = y$. $|x| <= |y| <-> exists z subset.eq y space |x| = |z|$. $x$ бесконечное $<-> aleph_0 <= |x|$. $x$ бесконечное $<-> exists y subset x space |x| = |y|$. Теорема Кантора: $|x| < |op(cal(P)) x|$. $|op(cal(P)) NN| = |RR|$.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10C00.typ
typst
Apache License 2.0
#let data = ( ("OLD TURKIC LETTER ORKHON A", "Lo", 0), ("OLD TURKIC LETTER YENISEI A", "Lo", 0), ("OLD TURKIC LETTER YENISEI AE", "Lo", 0), ("OLD TURKIC LETTER ORKHON I", "Lo", 0), ("OLD TURKIC LETTER YENISEI I", "Lo", 0), ("OLD TURKIC LETTER YENISEI E", "Lo", 0), ("OLD TURKIC LETTER ORKHON O", "Lo", 0), ("OLD TURKIC LETTER ORKHON OE", "Lo", 0), ("OLD TURKIC LETTER YENISEI OE", "Lo", 0), ("OLD TURKIC LETTER ORKHON AB", "Lo", 0), ("OLD TURKIC LETTER YENISEI AB", "Lo", 0), ("OLD TURKIC LETTER ORKHON AEB", "Lo", 0), ("OLD TURKIC LETTER YENISEI AEB", "Lo", 0), ("OLD TURKIC LETTER ORKHON AG", "Lo", 0), ("OLD TURKIC LETTER YENISEI AG", "Lo", 0), ("OLD TURKIC LETTER ORKHON AEG", "Lo", 0), ("OLD TURKIC LETTER YENISEI AEG", "Lo", 0), ("OLD TURKIC LETTER ORKHON AD", "Lo", 0), ("OLD TURKIC LETTER YENISEI AD", "Lo", 0), ("OLD TURKIC LETTER ORKHON AED", "Lo", 0), ("OLD TURKIC LETTER ORKHON EZ", "Lo", 0), ("OLD TURKIC LETTER YENISEI EZ", "Lo", 0), ("OLD TURKIC LETTER ORKHON AY", "Lo", 0), ("OLD TURKIC LETTER YENISEI AY", "Lo", 0), ("OLD TURKIC LETTER ORKHON AEY", "Lo", 0), ("OLD TURKIC LETTER YENISEI AEY", "Lo", 0), ("OLD TURKIC LETTER ORKHON AEK", "Lo", 0), ("OLD TURKIC LETTER YENISEI AEK", "Lo", 0), ("OLD TURKIC LETTER ORKHON OEK", "Lo", 0), ("OLD TURKIC LETTER YENISEI OEK", "Lo", 0), ("OLD TURKIC LETTER ORKHON AL", "Lo", 0), ("OLD TURKIC LETTER YENISEI AL", "Lo", 0), ("OLD TURKIC LETTER ORKHON AEL", "Lo", 0), ("OLD TURKIC LETTER ORKHON ELT", "Lo", 0), ("OLD TURKIC LETTER ORKHON EM", "Lo", 0), ("OLD TURKIC LETTER ORKHON AN", "Lo", 0), ("OLD TURKIC LETTER ORKHON AEN", "Lo", 0), ("OLD TURKIC LETTER YENISEI AEN", "Lo", 0), ("OLD TURKIC LETTER ORKHON ENT", "Lo", 0), ("OLD TURKIC LETTER YENISEI ENT", "Lo", 0), ("OLD TURKIC LETTER ORKHON ENC", "Lo", 0), ("OLD TURKIC LETTER YENISEI ENC", "Lo", 0), ("OLD TURKIC LETTER ORKHON ENY", "Lo", 0), ("OLD TURKIC LETTER YENISEI ENY", "Lo", 0), ("OLD TURKIC LETTER YENISEI ANG", "Lo", 0), ("OLD TURKIC LETTER ORKHON ENG", "Lo", 0), ("OLD TURKIC LETTER YENISEI AENG", "Lo", 0), ("OLD TURKIC LETTER ORKHON EP", "Lo", 0), ("OLD TURKIC LETTER ORKHON OP", "Lo", 0), ("OLD TURKIC LETTER ORKHON IC", "Lo", 0), ("OLD TURKIC LETTER ORKHON EC", "Lo", 0), ("OLD TURKIC LETTER YENISEI EC", "Lo", 0), ("OLD TURKIC LETTER ORKHON AQ", "Lo", 0), ("OLD TURKIC LETTER YENISEI AQ", "Lo", 0), ("OLD TURKIC LETTER ORKHON IQ", "Lo", 0), ("OLD TURKIC LETTER YENISEI IQ", "Lo", 0), ("OLD TURKIC LETTER ORKHON OQ", "Lo", 0), ("OLD TURKIC LETTER YENISEI OQ", "Lo", 0), ("OLD TURKIC LETTER ORKHON AR", "Lo", 0), ("OLD TURKIC LETTER YENISEI AR", "Lo", 0), ("OLD TURKIC LETTER ORKHON AER", "Lo", 0), ("OLD TURKIC LETTER ORKHON AS", "Lo", 0), ("OLD TURKIC LETTER ORKHON AES", "Lo", 0), ("OLD TURKIC LETTER ORKHON ASH", "Lo", 0), ("OLD TURKIC LETTER YENISEI ASH", "Lo", 0), ("OLD TURKIC LETTER ORKHON ESH", "Lo", 0), ("OLD TURKIC LETTER YENISEI ESH", "Lo", 0), ("OLD TURKIC LETTER ORKHON AT", "Lo", 0), ("OLD TURKIC LETTER YENISEI AT", "Lo", 0), ("OLD TURKIC LETTER ORKHON AET", "Lo", 0), ("OLD TURKIC LETTER YENISEI AET", "Lo", 0), ("OLD TURKIC LETTER ORKHON OT", "Lo", 0), ("OLD TURKIC LETTER ORKHON BASH", "Lo", 0), )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/terms_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test joining. #for word in lorem(4).split().map(s => s.trim(".")) [ / #word: Latin stuff. ]
https://github.com/japanoise/strategos-m
https://raw.githubusercontent.com/japanoise/strategos-m/main/format.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#let heading-font = "Cooper*" #let body-font = "Hyde" #let format-modern(doc) = { // Set up page set page( header: context { // Reset the footnote counter on each page counter(footnote).update(0) }, footer: context { // Don't show page number on preamble or end pages if (counter(page).get().first() < 2) [ // Align page numbers to page orientation ] else if (calc.rem(counter(page).get().first(), 2) == 0) [ #counter(page).display( "1" ) #h(1fr) Strategos M #h(1fr) ] else [ #h(1fr) Japanoise #h(1fr) #counter(page).display( "1" ) ] }, margin: 1cm, "us-letter" ) show heading: set text( font: heading-font, weight: "black" ) set text(font: body-font, 11pt) show heading.where(level: 1): set align(center) show heading.where(level: 1): set text(18pt) show heading.where(level: 2): set text(16pt) show heading.where(level: 3): set text(14pt) show heading.where(level: 4): set text(12pt) show heading.where(level: 3): set heading(outlined: false, bookmarked: true) show heading.where(level: 4): set heading(outlined: false, bookmarked: true) /* * Per docs: https://typst.app/docs/guides/table-guide/ * "We are using a show rule with a selector for cell * coordinates here instead of applying our styles directly * to table.header. This is due to a current limitation of * Typst that will be fixed in a future release." */ show table.cell.where(y: 0): strong set table( gutter: auto, inset: (x: 3pt, y: 3.7pt), fill: (_, y) => (none, none, none, rgb("CFCFCF"), rgb("CFCFCF"), rgb("CFCFCF")).at(calc.rem(y+2, 6)), stroke: (x, y) => ( x: 1pt, top: if y <= 1 { 1pt } else { 0pt }, bottom: 1pt ), ) set table.hline(stroke: 1pt) doc } #let alt-fill(_, y) = (none, none, none, rgb("CFCFCF"), rgb("CFCFCF"), rgb("CFCFCF")).at(calc.rem(y+1, 6)) #let logo(size: 110pt) = text(font: "Old Cupboard", size)[Strategos M] #let modern-frontispiece = align(center)[ #align(center)[ #set block(spacing: 0em) #logo() #v(1fr) #text(font: "Combat", 48pt)[Rules for Medieval Wargaming] #v(3fr) #image(width: 100%, "img/war.png") #v(2fr) #text(font: "Old Cupboard", 48pt)[By the Princess Japanoise] ] #pagebreak() #counter(page).update(0) ] #let subheader( rowspan: 1, colspan: 1, content ) = table.cell(rowspan: rowspan, colspan: colspan, strong(content)) #let frac( numerator, denominator, ) = text(fractions: true)[#(numerator)/#(denominator)]
https://github.com/crd2333/crd2333.github.io
https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Courses/计算机视觉导论.typ
typst
#import "/src/components/TypstTemplate/lib.typ": * #show: project.with( title: "计算机视觉导论", lang: "zh", ) #info()[ - 部分参考 #link("https://lhxcs.github.io/note/AI/cv/icv/")[lhxcs 的计算机视觉笔记] ] = Introduction == What's Computer Vision - Computer vision tasks - 3D reconstruction 3D 重建 3D reconstruction 3D重建, localization 定位, SLAM 即时定位重建, …… - Image undestanding 图像理解 Image recognition 图像识别, object detection 物体识别, image segmentation 图像分割, action recognition 动作识别, deep learning 深度学习, …… - Image synthesis 图像合成 Colorization 着色, super-resolution 超采样, debluring 去模糊, HDR 合成, panorama stitching 全景拼接, free-viewpoint rendering 自由视角渲染, GANs 生成对抗网络, …… - 我们人类看到的是图像,而计算机看到的是像素值 - computers can be better at computing - humans are better at understanding - 但具体为什么,还有待对人类智能的研究 - 人类视觉常常被误导 == What's Computer Vision used for - 计算机视觉的各种应用,略 == Course Overview - Basics (Lec.2 - Lec.4) - Reconstruction (Lec.5 - Lec.8) - Understanding (Lec.9 - Lec.11) - Synthesis (Lec.12 - Lec.13) == Review of Linear Algebra - 向量的各种运算 - 矩阵的各种运算 - 仿射变换 - 齐次坐标 - 行列式(marix determinant):几何意义为行向量或列向量张成的有向面积(体积) - 特征值和特征向量 - 矩阵的特征分解 - 矩阵的奇异值分解 = Image Formation - 针孔相机模型 - 假如直接在物体面前放一个底片,由于像平面上的一个点接收到物体上各个方向的光线,因此无法成像 - 使用小孔成像使得一一对应关系成立 - 但是当孔太小时,会产生光的衍射现象;并且孔太小也会导致通光量不足 == 透镜成像 - 放大率 $m=(h_i)/(h_o)=i/o$,当 $o$ 较大时,$i$ 近似等于 $f$,可以说焦距也决定了图像放大率(拍照调焦的原理) - Field of View(FOV) 取决于焦距与底片(sensor)的大小。从成像质量来看,底片越大越好(每个像素收到的光更多,信噪比更好),因此现在的工业目标就是在缩小底片的同时维持好的信噪比 - 光圈(Aperture)与光圈数(F-number) 通过放大/缩小光圈来控制图像的亮度。$N=f/D$,$f$ 是焦距,$D$ 是光圈直径,光圈数越大,光圈越小,进光量越少。 - Lens Defocus & Blur Circle 当 $f$ 和 $i$ 固定时,理论上只有一个面(深度)在成像平面上是清楚的,所以我们需要对焦(略微调整底片位置或透镜位置,i.e. 调整 $i$)。 弥散圆(Blur circle diameter):$b=D/i' |i'-i|$ #fig("/public/assets/Courses/CV/2024-09-19-11-22-07.png") - 景深(Depth of Field) 虽然有了弥散圆与 defocus 的概念,但是我们可能会疑惑生活中的照片并非仅有一个深度才是清晰的,这是因为图像并非连续的,而是由一个个方格(像素)构成的,当弥散圆落在一个像素内时,它表现出来也是清晰的,这就引入了景深的概念 #fig("/public/assets/Courses/CV/2024-09-19-11-25-42.png") $ c = (f^2 (o-o_1))/(N o_1(o-f)) = (f^2 (o_2-o))/(N o_2(o-f))\ "Depth of Field" o_2 - o_1 = (2o f^2 c N (o-f))/(f^4 - c^2 N^2 (o-f)^2) $ - 综合利用以上概念,可以得到背景虚化、人物清晰的照片 + Large aperture,增大进光量 + Long focal length,把上式分子分母同除以 $f(o-f)$,可以得到 $f arrow.tr ~~=>~~ "depth of filed" arrow.br$ + Near foreground & Far Background,使人物落入景深而背景不在景深内 == Geometric image formation - 透视投影 #fig("/public/assets/Courses/CV/2024-09-20-17-00-54.png", width: 70%) - 引入齐次坐标,将投影表示为线性变换 $ mat(f,0,0,0;0,f,0,0;0,0,1,0) vec(x,y,z,1) = vec(f x,f y,z) #sym.tilde.equiv vec(f x/z, f y/z, 1) $ #fig("/public/assets/Courses/CV/2024-09-19-11-41-05.png", width: 70%) - 在透视投影中,直线仍然是直的,但长度和角度丢失了。深度信息部分丢失,虽然近大远小,但同一个图像对应无穷多三维形状 - Vanishing points & Vanishing lines - 铁路汇聚的尽头就是消失点;两个消失点的连线就是消失线 - 平面上的任何一组平行线都定义了一个消失点,所有这些消失点的结合就是消失线 - 不同的平面唯一定义了不同的消失线 - 投影失真 Perspective distortion - Problem for architectural photography: converging verticals #fig("/public/assets/Courses/CV/2024-09-20-19-38-53.png") - Solution: 取景器(view camera),镜头相对胶片可以移动 - The distortion is not due to lens flaws. - 径向失真 Radial distortion #fig("/public/assets/Courses/CV/2024-09-20-19-40-21.png", width: 60%) - 由现实镜头的非理想性引起,对于穿过透镜边缘的光线更为明显。 - 分为桶形畸变(barrel distortion)和枕形畸变(pin cushion distortion) - Orthographic projection 正交投影 == Photometric image formation - 描述了 3D 世界物理性质与 2D 图像颜色之间的关系 - Image sensor - Shutter - The pixel value is equal to the integral of the light intensity within the exposure time - Color spaces: RGB, HSV - Bayer filter - 对于彩色图像,需要采集多种基本的颜色,最简单的方法是用滤镜的方法 - 如果要采集 RGB 三种颜色,则需要三种滤镜,价格昂贵。 - 而 Bayre Filter 在一块滤镜上设置不同颜色,由于人眼对绿色比较敏感,因此绿色较多 - Model the light reflected by an object : Shading - 后面的内容是直接 copy from GAMES101,参见 #link("https://crd2333.github.io/note/Courses/%E8%AE%A1%E7%AE%97%E6%9C%BA%E5%9B%BE%E5%BD%A2%E5%AD%A6/index/")[计算机图形学笔记] = Image Processing == Image processing basics #let blur = math.text("blur") - 一些基本处理 + Increase contrast + Invert + Blur + Sharpen - Convolution - Padding - 几种 filter - Guassian blur & Sharpen - $f(i, j)= 1/(2 pi sigma^2) e^(- (i^2+j^2)/(2 sigma^2))$ - $sigma$ 越大越模糊 - Sharpen - Let $I$ be the original image - High frequencies in image $I=I-blur()$ - Sharpened image $I'= I+(I-blur())$ - Edge detection filter - Gradient detection filters - Bilateral filter - 保持边缘的同时去除噪声 == Image Sampling - 采样时有可能发生失真(反走样/锯齿)现象 - 主要原因是 —— 采样的速度跟不上信号变化的速度(高频信号采样不足) === Fourier Transform - 傅里叶变换本质上是把函数与不同频率的三角函数做内积,得到它在不同频率下的分量 - 即:用不同频率的正余弦函数加权表示原函数 #fig("/public/assets/Courses/CV/2024-09-26-11-49-09.png", width: 70%) - PPT 里展示了一些常见的信号的傅里叶变换 === Signal & Frequency - Convolution Theorem #fig("/public/assets/Courses/CV/2024-09-26-12-00-47.png") - Box filter = low-pass filter - Wider kernel = lower frequency - Sampling - Sampling a signal = multiply the single by a Dirac comb function(狄拉克函数) - Sampling = Repeating Frequency Contents - Nyquist-Shannon theorem - Consider a band-limited signal: has no frequencies above $f_0$ - The signal can be perfectly reconstructed if sampled with a frequency larger than $2 f_0$ - anti-alisaing - 其实基本也都是图形学的内容 == Image magnification & minification - 图像放大时基本使用 Interpolation 或者上采样(AI) - Interpolation - Nearest neighbor - Bilinear - Bicubic - How to change aspect ratio - 最简单的方法就是在长宽方面进行不同的缩放,但会导致形变 - Challenge + Changing aspect ratio causes distortion + Cropping may remove important contents - Solution: Seam Carving for Content-Aware Image Resizing - Basic idea: remove unimportant pixels, and edges are important $ E(I) = |(diff I) / (diff x)| + |(diff I) / (diff y)| $ - Find connected path of pixels from top to bottom of which the edge energy is minimal,可以认为就是寻找最短路算法(DP 算法)。然后把这条路的像素扔掉 #fig("/public/assets/Courses/CV/2024-10-10-10-17-49.png", width: 70%) #mitex(`\mathbf{M}(i,j)=E(i,j)+\min\big(\mathbf{M}(i-1,j-1),\mathbf{M}(i-1,j),\mathbf{M}(i-1,j+1)\big)`) - seam carving 方法也可以应用于 enlarge image,原理类似 = Model Fitting and Optimization == Optimization - 优化的基本范式,与优化基本理论与方法没什么差别 - 一个有趣的 example: Image deblurring - 已知模糊图像 $Y$ 和卷积核 $F$,通过优化的方法得到去噪后的图像 $X$ - 想法是找到清晰的图像 $X$,使得它做模糊处理后与已知的图像 $Y$ 差别尽可能小,于是得到目标函数: $ min_X norm(Y - F*X)_2^2 $ === Model Fitting - 一个经典的例子:Linear Mean Square Error (MSE) - 如果假设数据噪声服从*高斯分布*,那么可以与*极大似然估计*联系起来 (Linear MSE = MLE with Gaussian noise assumption) $ b_i = a_i^T + n, ~~~ n tilde.op G(0, sigma^2) \ P[(a_i, b_i)|x] = P[b_i - a_i^T x] #sym.prop exp(- (b_i - a_i^T x)^2 / (2 sigma^2)) \ P[(a_1, b_1) (a_2, b_2) ... (a_n, b_n)|x] #sym.prop exp(- sum_i (b_i - a_i^T x)^2 / (2 sigma^2)) = exp(- norm(A x - b)_2^2 / (2 sigma^2)) $ == Numerical methods - 一些问题有 analytical solution,但是大多数问题需要 numerical solution - Recap: Taylor expansion === 梯度下降法 Gradient Descent ==== Steepest descent method - Advantage + Easy to implement + Perform well when far from the minimum - Disadvantage + Converge slowly when near the minimum + Waste a lot of computation - Why converge slowly? + Only use first-order derivative + Does not use curvature ==== Newton's method - 考虑二阶导数 - Advantage: fast convergence near the minimum - Disadvantage: Hessian requires a lot of computation ==== Gauss-Newton method - 使用 Jacobian 矩阵 $J_R^T J_R$ 近似 Hessian 矩阵 $H_F$ - Advantage: faster than Newton's method - Disadvantage: $J_R^T J_R$ 不正定,未必可逆 ==== Levenberg-Marquardt method $ Delta x = -(J_R^T J_R + lambda I)^(-1) J_R^T R(x_k) $ - Start quickly(远离目标点时使用最速梯度下降) - Converge quickly(接近目标点时近似高斯牛顿法,保证收敛速度快) - $J_R^T J_R + lambda I$ 正定,保证高斯牛顿法成立 === Robust estimation - Outliers: 使得最小二乘法受很大影响,它会过度放大偏离较大的误差 - Huber loss function $ L_"huber" (e) =cases( 1/2 e^2\, |e| =< delta, delta dot |e| - 1/2 delta^2\, |e| > delta) $ - 在误差较小时,与 MSE 一样,但是在误差较大时,它的影响会减小(减小 outliers 的影响) - RANSAC: Random Sample Concensus - The most powerful method to handle outliers - 主要思想:首先我们知道拟合一条直线只需要两个点,因此首先随机找两个点拟合一条直线,然后检查有多少点符合该直线(点到直线的距离小于一定的阈值,就 count++),一直重复该过程,选择 count 最高的直线。 === Regularization - L1-norm, L2-norm = Image Matching and Motion Estimation == Image Matching - Main Components of Feature matching - Detection: identify the interest points - Description: extract vector feature descriptor surrounding each interest point - Matching: determine correspondence between descriptors in two views === Detection - 特征点需要满足独特性(至少要在局部唯一) - 使用一个小的像素窗口去探测像素的变化(用梯度分布来衡量) - 可以用 PCA 算梯度分布的主方向(特征值) + flat: $l1, l2$ are small + edge: $l1 >> l2$ or $l1 << l2$ + corner: $l1, l2$ are large, $l1 wave l2$ - 为了方便计算,引入 Harris operator - Harris operator $ f = frac(l1 l2, l1 + l2) = "determinant"(H)/"tr"(H) $ - pipeline: + Compute derivatives at each pixel + Computer matrix $H$ in a Gaussian window around each pixel + Compute corner response $f$ + Threshold $f$(阈值过滤) + Find local maxima of response function - 除了独特性之外,我们还希望特征点在图像变换(如光学变换和几何变换)中保持不变 - Corner response is invariant w.r.t image translation and rotation, but not scaling #fig("/public/assets/Courses/CV/2024-10-17-10-56-43.png", width: 60%) - 一个解决办法是使用不同尺度的 window,但一般我们固定住窗口大小,而去改变图像的大小,形成一个图像金字塔(image pyramid),二者效果上是等价的(可以想象成是在三维的体素上去找极值) - Blob detector - 除了角点很重要以外,我们也关注斑点 - 由于斑点的局部性质(在一个小区域内,且一般是闭合的),在像素上具有比较大的二阶导 - 所以我们的步骤是计算图像的拉普拉斯,然后找到局部最大与最小值 $ na^2 = frac(diff^2, diff x^2) + frac(diff^2, diff y^2) $ - 由于 Laplacian 对噪声比较敏感(实际上求导对噪声都很敏感,更何况二阶导),我们通常使用 Laplacian of Gaussian(LoG) filter 进行处理,即首先对图片作高斯模糊,再计算拉普拉斯算子。由卷积的交换律 $ na^2 (f * g) = f * na^2 g $ - 同样有 scale 的问题,由高斯分布的方差 $si$ 控制,同样可以用不同尺度来解决,不过这里我们放缩的是 LoG 的 $si$ - 但我们调 OpenCV 的时候会发现它用的一半是 DoG,它的思想是用两个相邻 $si$ 的 Guassian 近似 Laplacian(因为我们构建图像金字塔的时候本来就要去做前者) $ na^2 G_si approx G_si_1 - G_si_2 $ === Description - 现在我们已经知道哪些点比较独特,接下来我们要描述这些点(才能匹配),如何做? - 首先很容易想到的就是将特征点以及其周围区域像素值 concat 成一个特征向量,但这对位移、旋转非常敏感(i.e.,not invariant) - 这里我们介绍 SIFT 描述子 - SIFT(Scale Invariant Feature Transform) - SIFT 使用 patch 的梯度方向分布作为描述子。方向位于 $[0, 2 pi]$ 之间,因此 SIFT 构建一个直方图,来统计在每个区间(例如十等分)有多少个像素。等分个数即为描述子的维度 #fig("/public/assets/Courses/CV/2024-10-17-11-35-18.png") - SIFT 对于图像的平移显然不会有影响,而对于旋转,会导致直方图循环平移。但这个情况很好处理:选中最大的分量放在第一个进行平移对齐,称作直方图的归一化(朝向归一化) - 对于 scaling,很显然地,SIFT 描述子本身是 not invariant to scaling 的,但其实 SIFT 不仅包括 Description,也包括 Detection,经过 DoG 处理后已经确定了 scale 的大小(最佳的 $si$),所以此时不用考虑 scale 的影响 - Properties of SIFT: Extraodinarily robust matching technique + Can handle changes in viewpoint + Can handle significant changes in illumination + Fast and efficient-can run in real time - SIFT algorithm + Run DoG detector: find maxima in location/scale space + Find dominate orientation + For each $(x, y, "orientation")$, create descriptor === Matching - 有了描述子之后,我们要做的就是将描述相似的特征点匹配起来 - 简单的思路就是计算两个描述子向量之间的距离,并与最小的匹配,但会造成有歧义的分配 #fig("/public/assets/Courses/CV/2024-10-17-11-49-36.png", width: 70%) - 两种传统解决办法 + Ratio test: $norm(f1 - f2)/norm(f1-f2')$,容易得知,ambigous matches 会使得这个值比较大 + Mutual nearest neighbour: 如果 $f1$ 到 $f2$ 匹配正确的话,对 $f2$ 寻找最佳匹配也应该是 $f1$. - Deep learning for feature matching - 表现比传统方法好得多 - Example: SuperPoint == Motion Estimation - Motion estimation problems - Feature-tracking - 给出两帧画面,估计特征点的运动方向 - Optical flow - Recover image motion at each pixel - Output: dense displacement field (optical flow) - 二者的主要区别在于 feature tracking 仅限于某些特征点;而 optical flow 估计的是整张图片。但二者使用的方法是一样的:Lucas-Kanade method - LK 算法的三个主要假设和能推出的方程: + *brightness constancy*: same point looks the same in every frame $ I(x,y,t) = I(x+u,y+v,t+1) $ + *small motion*: points do not move very far $ 0 approx I(x+u,y+v,t+1) - I(x,y,t) approx I_x u + I_y v + I_t, " i.e. " na I dot [u,v]^T = -I_t $ + *spatial coherence*: points move like their neighbours。如果使用 $5 times 5$ 的窗口,可以得到 $25$ 个方程 $ mat(I_x (p_1), I_y (p_1); dots.v, dots.v; I_x (p_25), I_y (p_25)) dot vec(u,v) = - vec(I_t (p_1), dots.v, I_t (p_25)) => A d = b $ - 这时我们就可以使用最小二乘法来求解 $u,v$,它的解 given by $(A^T A) d = A^T b$,即 $ mat(Si I_x I_x, Si I_x I_y; I_x I_y, I_y I_y) vec(u,v) = - vec(Si I_x I_t, Si I_y I_t) $ - 当 $A^T A$ 可逆且两个特征值不能太小的时候,该方程有解,这个条件和之前介绍的 Harris corner detector 的条件是一样的 - 或者说,纹理很丰富,变化很大的角点才有解。反过来,Low Texture Region 和 Edge Region 时会出现问题 - 再另外,当不符合上述三个假设时,LK 算法*也*会出现问题 - *Brightness constancy* is not satisfied - The motion is *not small* - A point does *not* move *like its neighbors* - 对于不满足 small motion 的情况(比如说特征点实际上移动了八个像素),我们有方法可以解决 —— *降采样*! - 一个直观的想法就是将图片缩小到原来的八分之一,在缩小后的图片中就满足 small motion 了,处理之后再放大回去。缺点就是在缩小图片的过程中会丢失信息,这样图像移动距离的精度就无法保证 - 一个想法就是使用*像素金字塔*(*Coarse-to-fine*)。其中金字塔一是时间为 $t$ 时的图像,金字塔二是时间为 $t + 1$ 时的图像。在金字塔上逐层估计,并逐步细化。例如先估计运动距离小于一个像素的最上层图像,根据此估计在金字塔一中的第二层恢复出运动(做一个补偿),再与金字塔二进行比较,此时特征点移动的距离经过较为准确的估计后也小于一个像素,以此类推 #fig("/public/assets/Courses/CV/2024-10-24-10-11-11.png", width: 80%) #hline() Anyway,这些都是相对 old-fashion 的东西,现在效果最好害得看 Deep learning for optical flow #info(caption: "Takeaways")[ - Feature matching - Detector: Harris corner detector, LoG, DoG - Descriptor: SIFT … - Matching: ratio test - Invariance - Motion estimation - Feature tracking - Optical flow - Lucas-Kanade - Three assumptions - Both feature matching and motion estimation are called correspondence problems ] = Image stitching - 图像拼接,比如全景图、VR 等 - 核心问题是,给定两张图片,怎么把它们做一定的几何变换(warping),然后把它们拼接在一起(stitching) == Image warping - 与 lec3 介绍的 image filtering 相比较,filtering 改变的是图像的像素值(intensity),而 warping 改变的是图像的形状(shape) == Parametric global warping - 参数化全局变形,即图像的每一个坐标都遵循同一个变换函数 $ p' = T(p) $ - 比如 translation, rotation, aspect - 这个 $T$ 可以用 matrix 来描述 - 使用非齐次坐标系的矩阵,都可以叫做*线性变换*,但前面说了不能描述平移(translation),为此引入其次坐标 - 仿射变换:Affine map = linear map + translation,并且矩阵最后一行是 $[0, 0, 1]$ - 如果不是,那就称为 perspective transformation 投影变换,或者叫单应变换(Homography) == Projective Transformation(Homography) - Homography \ $ vec(x'_i, y'_i, 1) approx mat(h_00, h_01, h_02; h_10, h_11, h_12; h_20, h_21, h_22) vec(x_i,yi,1) $ - $9$ 个系数但自由度为 $8$,因为在其次坐标系里,对整个矩阵乘以一个非零常数不会改变结果 - 在什么情况下两张图片的 transformation 是 homography? - Camera rotated with its center unmoved #fig("/public/assets/Courses/CV/2024-10-24-10-46-00.png", width: 50%) - Camera center moved and the scene is a plane - 比如,投影仪的结果,在教室左边和右边的人看来还是一样的 - Summary of 2D transformations #fig("/public/assets/Courses/CV/2024-10-24-10-54-37.png", width: 70%) == Implementing image warping - 或许我们会想,实现 warping 不是很容易吗,只要把当前图片的坐标值根据变化函数映射到另一个坐标上就行了 - 但是考虑一个问题:当前的像素坐标映射后不一定是整数(可以理解为像素值是存放在格点上的,映射后的像素位置不一定在格点上) - 所以这里我们采取逆变换,即对于每一个需要找的像素点,去找变换前的坐标,同样,大多数时候不会是整数,这时候可以用周围的像素进行插值得到结果 == Image stitching === compute transformation - 现在我们的问题就是给定两张图片, 如何计算出变换矩阵?可以采用如下的方法(DLT) - 这一块大多是矩阵和公式,懒得打了,看 PPT 吧 - 核心思路就是利用两张图的特征点,列方程组,求解优化问题 - 对于 outliers - Recap the idea of RANSAC: - All the inliers will agree with each other on the translation vector; - The outliers will disagree with each other (RANSAC only ha guarantees if there are $< 50%$ outliers) #q[All good matches are alike; every bad match is bad in its own way. ——Tolstoy via Alyosha Efros] #info(caption: "Summary for image stitching")[ - Input images - Feature matching - Compute transformation matrix with RANSAC - Fix image 1 and warp image 2. ] === Panoramas - 对于全景,我们处理的是多张图片的拼接 - 最朴素的方法就是取最中间的图片作为参考,其它所有的图片与中间那张对齐 - 一个问题是,如果投影到屏幕上,会使得边缘图像的形变很明显 #h(1fr) #fig("/public/assets/Courses/CV/2024-10-24-11-31-02.png", width: 70%) - Cylindrical panoramas #fig("/public/assets/Courses/CV/2024-10-24-11-36-52.png", width: 80%) - How to compute the transformation on cylinder? - A rotation of the camera is a translation of the cylinder! 相机的旋转在柱面上是平移 - Assembling the panorama - 在柱形投影的基础上还是会出现问题,就是误差的积累,导致漂移 #fig("/public/assets/Courses/CV/2024-10-24-11-39-23.png", width: 70%) - 我们希望整体误差的和为 $0$,一个解决办法就是将最后一张图和第一张图之间也进行个约束 #fig("/public/assets/Courses/CV/2024-10-24-11-44-52.png", width: 70%) - 不过,最终得到的全景图还是会有一些问题,比如直线变弧形、无法应对运动场景等 = Structure from Motion - Recover *camera poses* and *3D structure* of a scene - SfM's extension: SLAM - 二者的区别在于,SLAM 更注重实时性,而且可以有额外的传感器输入 - 需要解决的几个关键问题 - 相机是如何将三维坐标点映射到图像平面上的?(camera model) - 如何计算相机在世界坐标系下的位置和方向?(camera calibration and pose estimation) - 如何从图像中重建出不知道的三维结构?(structure from motion) == Camera Model #fig("/public/assets/Courses/CV/2024-10-24-11-59-15.png") - 这整个过程可以总结为三个步骤: + 坐标系变换:将世界坐标系的点变换到相机坐标系 + 透视投影:将相机坐标系的点投影到像平面上 + 成像平面转化为像素平面:完成透视投影后我们得到的坐标单位是长度单位(毫米、米等),但是计算机上表示坐标是以像素为基本单元的,这就需要我们进行一个转化 - 如果读者对 CG 有所了解的话,就对应于 MVP 里的视图变换 View 和投影变换 Projection,以及视口变换 Viewport - 而这一系列过程可以定义为两个矩阵(两次变换): + 外参矩阵(Extrinsic Matrix): 坐标系变换 + 内参矩阵(Intrinsic Matrix): 透视投影与转化为像素平面
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/genealotree/0.1.0/draw-functions.typ
typst
Apache License 2.0
#import "calc-functions.typ": get-person-by-name, set-generations, set-subtree-unions, set-unions-sizes-compact, get-root-couples, get-root-spacings #import "@preview/cetz:0.2.2": draw #import draw: * #let draw-infos(person) = { let paddings = if person.partners-names == () { (0.4em, 1.5em) } else { (0.7, 2em) } let geno = if person.geno-label != none { [(#person.geno-label.at(0)\/\/#person.geno-label.at(1))] } else {none} let pheno = if person.pheno-label != none { [\[#person.pheno-label\]] } else {none} let i = 0 for info in (geno, pheno).filter(el => {el != none}) { content( (name: person.name, anchor: "south"), info, anchor: "north", padding: paddings.at(i), ) move-to((name: person.name, anchor: "center")) i += 1 } } #let calc-radius(angle) = { let remangle = calc.rem-euclid(angle.deg(), 90) if remangle < 45 { 1/calc.cos(remangle*1deg) } else { 1/calc.cos(90deg - remangle*1deg) } } #let draw-male-pheno(geneal, person, pheno, start: 90deg, delta: 360deg) = { let stop = start + delta let angles = ( 90deg, 135deg, 225deg, 315deg, 405deg, 450deg ) angles.push(start) angles.push(stop) let angles = angles.dedup().sorted() let start-index = angles.position(el => {el == start}) let stop-index = angles.position(el => {el == stop}) let angles = angles.slice(start-index, stop-index + 1) let lines = () for angle in angles { let line-name = person.name + "-" + str(angle.deg()) set-origin((name: person.name, anchor: "center")) hide(line( (name: person.name, anchor: "center"), ( angle: angle, radius: geneal.config.person-radius*calc-radius(angle) ), name: line-name )) set-origin((0,0)) lines.push(line-name + ".end") } if delta == 360deg { line( (name: person.name, anchor: "north"), ..lines, close: true, fill: geneal.phenos.at(pheno) ) } else { line( (name: person.name, anchor: "center"), ..lines, close: true, fill: geneal.phenos.at(pheno) ) } } #let draw-phenos(geneal, person, position) = { let phenos = person.phenos.filter(el => {el in geneal.phenos}) let nb-phenos = phenos.len() if nb-phenos == 0 {none} else if person.sex == "f" { let i = 0 for pheno in phenos { arc( (name: person.name, anchor: "center"), radius: geneal.config.person-radius, start: 90deg + i/nb-phenos*360deg, delta: 1/nb-phenos*360deg, fill: geneal.phenos.at(pheno), mode: "PIE", anchor: "origin" ) i+=1 } } else if person.sex == "m" { let i = 0 for pheno in phenos { draw-male-pheno( geneal, person, pheno, start: 90deg + i/nb-phenos*360deg, delta: 1/nb-phenos*360deg ) i+=1 } } move-to((name: person.name, anchor: "center")) } #let draw-person(geneal, person, position) = { let radius = geneal.config.person-radius if person.sex == "f" { circle( position, radius: radius, name: person.name, ) } else if person.sex == "m" { move-to(position) rect( (rel: (-radius, -radius)), (rel: (2*radius, 2*radius)), name: person.name, ) move-to((rel: (-radius, -radius))) } draw-phenos(geneal, person, position) if not person.alive { line((rel: (-1.5*radius, -radius)), (rel: (3*radius, 2*radius))) move-to((name: person.name, anchor: "center")) } draw-infos(person) } #let make-label(parent-names) = { parent-names.sorted().join("") } #let draw-partner(geneal, person-name, partner-name, orient: "r", position) = { let u-dist = geneal.config.union-dist let switch-val = if orient == "r" {-u-dist/2} else if orient == "l" {u-dist/2} let person = get-person-by-name(geneal, person-name) let partner = get-person-by-name(geneal, partner-name) get-ctx(ctx => { if person.name not in ctx.nodes.keys() { move-to(position) draw-person(geneal, person, (rel: (switch-val, 0))) } if partner.name not in ctx.nodes.keys() { move-to((rel: (-switch-val, 0))) draw-person(geneal, partner, (rel: (-switch-val, 0))) } }) line( (name: person.name, anchor: "south"), (rel: (0, -geneal.config.person-botline)), name: person.name + "--vb--" ) line( (name: partner.name, anchor: "south"), (rel: (0, -geneal.config.person-botline)), name: partner.name + "--vb--" ) line( (name: person.name + "--vb--", anchor: 100%), (name: partner.name + "--vb--", anchor: 100%), name: make-label((person.name, partner.name)) + "--h--" ) line( (name: make-label( (person.name, partner.name) ) + "--h--", anchor: 50%), (rel: (0, -geneal.config.union-vline)), name: make-label((person.name, partner.name)) + "--v--" ) move-to(( name: make-label((person.name, partner.name)) + "--h--", anchor: 50% )) } #let draw-siblings(geneal, union) = { let radius = geneal.config.person-radius let topline = geneal.config.person-topline let sib-dist = geneal.config.siblings-dist move-to((name: make-label(union.parents-names) + "--v--", anchor: 100%)) move-to((rel: (union.size.at(0).l, - topline - radius))) for child-name in union.children-names { let child = get-person-by-name(geneal, child-name) if child.partners-names == () { let child-pos = (rel: (sib-dist/2,0)) draw-person(geneal, child, child-pos) line( (name: child.name, anchor: "north"), (rel: (0, topline)), name: child.name + "--vt--" ) move-to((name: child.name, anchor: "center")) move-to((rel: (sib-dist/2, 0))) } else { let partner-name = child.partners-names.at(0) let child-union = geneal.unions.find(el => { child-name in el.parents-names and partner-name in el.parents-names }) let pos = union.children-names.position(el => { el == child.name }) let orient = if pos == 0 and union.children-names.len() != 1 {"l"} else {"r"} draw-partner( geneal, child.name, partner-name, orient: orient, (rel: (sib-dist, 0)) ) line( (name: child.name, anchor: "north"), (rel: (0, topline)), name: child.name + "--vt--" ) move-to(( name: make-label(child-union.parents-names) + "--h--", anchor: "50%" )) move-to((rel: (-sib-dist, radius + topline))) move-to((rel: (union.spacings.at(child.name), 0))) } } // draw siblings line // line for 1 child is only useful if the only child has a partner. if union.children-names.len() == 1 { line( (name: union.children-names.at(0) + "--vt--", anchor: "end"), (name: make-label(union.parents-names) + "--v--", anchor: "end"), name: make-label(union.parents-names) + "--s--" ) } else { line( (name: union.children-names.at(0) + "--vt--", anchor: "end"), (name: union.children-names.at(-1) + "--vt--", anchor: "end"), name: make-label(union.parents-names) + "--s--" ) } } #let draw-roots(geneal) = { let radius = geneal.config.person-radius let botline = geneal.config.person-botline let topline = geneal.config.person-topline let vline = geneal.config.union-vline let gen-height = radius*2 + botline + vline + topline move-to((0, -2*radius - botline)) let root-couples = get-root-couples(geneal) let root-spacings = get-root-spacings(geneal) for parents-names in root-couples { let union = geneal.unions.find(el => { el.parents-names == parents-names }) move-to((rel: ( 0, -gen-height*(union.parents-generation - 1) + botline + radius) )) draw-partner(geneal, ..parents-names, ()) move-to((rel: ( root-spacings.at(parents-names.join(), default: 0), gen-height*(union.parents-generation - 1) ))) } }
https://github.com/yonatanmgr/university-notes
https://raw.githubusercontent.com/yonatanmgr/university-notes/main/0366-%5BMath%5D/03661111-%5BLinear%20Algebra%201A%5D/src/lectures/03661111_lecture_4.typ
typst
#import "/0366-[Math]/globals/template.typ": * #show: project.with( title: "אלגברה לינארית 1א׳ - שיעור 4", authors: ("<NAME>",), date: "11 בינואר, 2024", ) #set enum(numbering: "(1.א)") = מערכות משוואות לינאריות == הגדרה מערכות משוואות לינאריות באותן נעלמים נקראות *שקולות* אם יש להן את אותו אוסף פתרונות. === דוגמה $ cases(x+y=1, x-y=1) $ אוסף הפתרונות $S = {(1,0)}$. $ cases(x=1, y=0) $ גם פה, אוסף הפתרונות $S = {(1,0)}$. כלומר, שתי המערכות *שקולות*. == הגדרה שלושת הפעולות הבאות המבוצעות על מע׳ משוואות נקראות *פעולות אלמנטריות*: + החלפת סדר המשוואות במערכת. + מכפלת משוואה בסקלר שאינו 0. + הוספת מכפלה בסקלר של משוואה אחת למשוואה אחרת. == פעולות אלמנטריות מעבירות בין מע׳ משוואות שקולות === הוכחה נתונה מערכת משוואות לינארית $ (M) = cases(a_11 x_1 + a_12 x_2 + dots + a_(1n) x_n = b_1, a_21 x_1 + a_22 x_2 + dots + a_(2n) x_n = b_2, dots.v, a_(m 1) x_1 + a_(m 2) x_2 + dots + a_(m n) x_n = b_m) $ נסמן ב-$tilde(M)$ את המערכת המתקבלת מ-$M$ לאחר הפעלת פעולה אלמנטרית אחת. לכאורה עלינו להראות הכלה דו-כיוונית בין אוסף הפתרונות של $M$ לזה של $tilde(M)$. בפועל, אם נשים לב שלכל פעולה אלמנטרית יש פעולה אלמנטרית הופכית, נוכל להסיק שמספיק להראות שכל פתרון של $M$ הוא גם פתרון של $tilde(M)$. ואמנם: + הפעולה ההופכית להחלפת שתי משוואות היא החלפה נוספת של אותן שתי משוואות. + אם נכפול משוואה בסקלר $lambda !=0$ אחרי מכפלה של אותה משוואה ב-$lambda^(-1)$ נחזור למשוואה המקורית. + על מנת לחזור למשוואה המקורית לאחר שהוספנו לה מכפלה בסקלר של משוואה אחרת, עלינו להוסיף לה גם מכפלה של אותה משוואה אך בסקלר הנגדי. #pagebreak() יהי $(c_1, c_2, dots, c_n)$ פתרון של המערכת $M$: $ cases( a_11 c_1 + dots + a_(1n) c_n = b_1, dots.v, a_(i 1) c_1 + dots + a_(i n) c_n = b_i, dots.v, a_(j 1) c_1 + dots + a_(j n) c_n = b_j, dots.v, a_(m 1) c_1 + dots + a_(m n) c_n = b_m ) $ + ברור שהחלפת סדר המשוואות אינה משנה את נכונותן, ולכן $(c_1, c_2, dots, c_n)$ פתרון גם לאחריה. + אם נכפול את המשוואה ה-$i$-ית ב-$lambda !=0$, יתר המשוואות לא משתנות, קיומן לא משתנה והמשוואה החדשה מתקיימת. + אם נוסיף למשוואה ה-$i$-ית את מכפלת המשוואה ה-$j$-ית ב-$lambda$, כל יתר המשוואות יתקיימו כמקודם והמשוואה החדשה מתקיימת. #QED = מטריצה מטריצה מגודל $m xx n$ מעל השדה $FF$ היא טבלה שבה $m$ שורות ו-$n$ עמודות, וכל רכיביה סקלרים מ-$FF$: $ mat( a_11, a_12, dots, a_(1 n); a_21, a_22, dots, a_(2 n); dots.v; a_(m 1), a_(m 2), dots, a_(m n); ) = mat(-, R_1, -; -, R_2, -;,dots.v,; -, R_m, -;) = mat(|, |, dots, |; C_1, C_2, dots, C_m; |, |, dots, |) $ כאן, $R_1, dots, R_m in FF^n$ (השורות) ו-$C_1, dots, C_n in FF^m$ (העמודות). נסמן ב-$M_(m xx n) (FF)$ את אוסף כל המטריצות מגודל $m xx n$ מעל $FF$ ואם $m = n$ נסמן $M_n (FF)$ ונאמר שהמטריצה ריבועית. אם $A in M_(m xx n) (FF)$ נסמן ב-$A_(i j)$ את האיבר שבשורה ה-$i$ ובעמודה ה-$j$-ית במטריצה $A$. == דוגמאות למטריצות $ mat(2,3,1;2,9,8) in M_(2 xx 3) (RR) \ mat(1,8; 0,1; 2,0; 0,1) in M_(4 xx 2) (QQ) \ mat(1;7;1;2) in M_(4 xx 1) (ZZ slash 11 ZZ) \ mat(1,7,1,2) in M_(1 xx 4) (ZZ slash 11 ZZ) $ #pagebreak() == הגדרה בהינתן מע׳ משוואות לינאריות מעל השדה $FF$: $ cases(a_11 x_1 + a_12 x_2 + dots + a_(1n) x_n = b_1, dots.v, a_(m 1) x_1 + a_(m 2) x_2 + dots + a_(m n) x_n = b_m) $ נבנה מטריצה מגודל $m xx (n+1)$ מעל השדה $FF$ שבה כל שורה מייצגת משוואה כל עמודה מייצגת נעלם, והמקדמים החופשיים מיוצגים בעמודה נוספת: $ mat( a_11, a_12, dots, a_(1 n), b_1; a_21, a_22, dots, a_(2 n), b_2; dots.v,,,,dots.v; a_(m 1), a_(m 2), dots, a_(m n), b_m ; augment: #4 ) in M_(m xx (n+1)) (FF) $ מטריצה זו נקראת *מטריצת המקדמים (המורחבת)* של המערכת. במידה ונבנה מטריצה ללא עמודת המקדמים החופשיים נקרא לה *המטריצה המצומצמת*. === הגדרה נוכל לבצע *פעולות שורה אלמנטריות* על מטריצה. פעולות אלה הן: + החלפה בין שתי שורות $R_i <-> R_j$. + מכפלת שורה בסקלר שונה מאפס $R_i-> lambda dot R_i, lambda !=0$ + הוספת מכפלה בסקלר של שורה אחרת לאחרת $R_i -> R_i+ lambda dot R_j$ זוג מטריצות נקראות *שקולות שורה* אם ניתן לעבור מאחת לשניה על ידי מספר סופי של פעולות שורה אלמנטריות, ונסמן $A tilde B$. == שקילות שורה של מטריצות היא יחס שקילות === הוכחה - *רפלקסיביות*: אם נבצע 0 פעולות שורה אלמנטריות, נקבל שכל מטריצה שקולת שורה לעצמה. - *סימטריות*: אם ניתן להגיע מ-$A$ ל-$B$ על ידי סדרה סופית של פעולות שורה אלמנטריות, נבצע את אותן פעולות אך הופכיות ובסדר הפוך כדי להגיע מ-$B$ ל-$A$. - *טרנזיטיביות*: אם אפשר להגיע מ-$A$ ל-$B$ על ידי סדרה סופית של פעולות שורה אלמנטריות, וכך גם מ-$B$ ל-$C$, אז אם נבצע את שתי סדרות הפעולות ברצף נגיע מ-$A$ ל-$C$ כנדרש. #QED === מסקנה: מטריצות שקולות שורה מייצגות מערכות משוואות שקולות. == הגדרה - שורה במטריצה שבה יש רק אפסים נקראת *שורת אפסים*. - האיבר הראשון שאינו אפס בשורה שאינה שורת אפסים נקרא *איבר פותח (מוביל)*. - מטריצה נקראת *מדורגת* אם: + כל איבר פותח נמצא מימין לאיברים הפותחים בשורות שמעליו. + שורות אפסים (אם קיימות) בתחתית המטריצה. - מטריצה מדורגת נקראת *מדורגת קנונית* אם: + כל איבר פותח הוא $.1$ + בעמודה שבה מופיע איבר פותח, יתר הרכיבים הם אפסים. - משתנה שמיוצג בעמודה שבה איבר פותח במטריצה מדורגת נקרא *משתנה תלוי (קשור)*. אחרת, נאמר שהמשתנה *חופשי*. #pagebreak() == כל מטריצה היא שקולת שורה למטריצה מדורגת קנונית כלשהי === הסבר לפי שיטת האלימינציה של גאוס, נוכל להעביר כל מטריצה למטריצה שקולת שורה ומדורגת שבה כל האיברים הפותחים הם אחדוֹת. כעת ניתן יהיה לאפס את יתר רכיבי העמודה שבה אחד פותח בעזרת הוספה מתאימה של מכפלת השורה שבה האחד הפותח באחרות. === דוגמה $ cases(x+2y+3z=4, 5x+6y+7z=8, 9x+10y+a z = b), a,b in RR $ נבנה את מטריצת המקדמים המורחבת של המערכת, ונבצע פעולות שורה אלמנטריות עד שנגיע למטריצה מדורגת קנונית: $ mat(1, 2, 3, 4; 5,6,7,8; 9,10,a,b; augment: #3) $ + בעזרת החלפת שורות נוודא שהאיבר בעמודה והשורה הראשונות אינו אפס. אם כל העמודה הראשונה היא אפסים, נתעלם ממנה. + בעזרת מכפלה מתאימה של השורה הראשונה נוודא שהאיבר הפותח בה הוא $1$. + נאפס את יתר רכיבי העמודה בעזרת הוספה של מכפלות מתאימות של השורה הראשונה באחרות (לאפס את כל העמודה, לא רק כלפי מטה). $ mat(1, 2, 3, 4; 5,6,7,8; 9,10,a,b; augment: #3) arrow.long.r^(R_2->R_2 -5 R_1)_(R_3 -> R_3 - 9 R_1) mat(1, 2, 3, 4; 0,-4,-8,-12; 0,-8,a-27,b-36; augment: #3) $ 4. נתעלם מהשורה והעמודה הראשונות ונחזור על פעולות (1) - (4). $ mat(1, 2, 3, 4; 0,-4,-8,-12; 0,-8,a-27,b-36; augment: #3) arrow.long.r^(R_2->-1/4 R_2) mat(1, 2, 3, 4; 0,1,2,3; 0,-8,a-27,b-36; augment: #3) -> $ $ -> mat(1, 2, 3, 4; 0,1,2,3; 0,-8,a-27,b-36; augment: #3) arrow.long.r^(R_1->R_1 - 2 R_2)_(R_3 -> R_3 + 8R_2) mat(1, 0, -1, -2; 0,1,2,3; 0,0,a-11,b-12; augment: #3) $ אם $a=11$ המטריצה המצומצמת מדורגת קנונית במקרה הזה, והיא מייצגת את המערכת השקולה: $ cases(x-z=-2, y+2z=3, 0 = b-12) $ כעת עבור $b!=12$, המשוואה האחרונה תהיה $0=b-12 != 0$ וקיבלנו סתירה, ולמערכת אין אף פתרון במקרה הזה. ואם $b=12$ נבודד את המשתנים התלויים $x,y$ לפי המשתנה החופשי שהוא $z$, ונקבל: $ cases(x=z-2, y=3-2z) => S = {mat(z-2;3-2z;z) | z in RR} $ אם $a!=11$, נמשיך: $ arrow.long.r^(R_3->(a-11)^(-1)dot R_3) mat(1,0,-1,-2;0,1,2,3;0,0,1,frac(b-12, a-11); augment: #3) arrow.long.r^(R_1->R_1 + R_3)_(R_2->R_2-2R_3) mat(1,0,0,-2+frac(b-12, a-11); 0,1,0,3-2 dot frac(b-12, a-11); 0,0,1, frac(b-12, a-11); augment: #3) $ המטריצה המצומצמת מדורגת קנונית ומייצגת את המע׳ השקולה: $ cases(x=-2+frac(b-12, a-11), y=3-2 dot frac(b-12, a-11), z=frac(b-12, a-11)) $ למערכת פתרון *יחיד* כי כל המשתנים *תלויים*. == תוספת למשפט: כל מטריצה שקולת שורה למטריצה מדורגת קנונית *יחידה*
https://github.com/angelcerveraroldan/notes
https://raw.githubusercontent.com/angelcerveraroldan/notes/main/algorithms_ds/algorithms_ds.typ
typst
#import "../preamble.typ" : * #let abstract = [ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ] #show: project.with( title: "Algos & DS", subtitle: "Competitive Programming Notes", topright: "Competitive Programming", abstract: abstract, quote: "Some fun quote here!", ) #pagebreak() #include("inner/fenwick.typ")
https://github.com/fufexan/cv
https://raw.githubusercontent.com/fufexan/cv/typst/README.md
markdown
# Mihai Fufezan CV Resume written in [Typst](https://typst.app), built using Nix. ### Building - `nix build github:fufexan/cv` - English version - `nix build github:fufexan/cv#romanian` - Romanian version Now open `result/CV[_ro]_MihaiFufezan.pdf` using your preferred PDF viewer. ### Prebuilt You can find a PDF copy of the CV here: - [English](https://github.com/fufexan/cv/files/14628063/CV_MihaiFufezan.pdf) - [Romanian](https://github.com/fufexan/cv/files/14628066/CV_ro_MihaiFufezan.pdf)
https://github.com/FA555/ignite
https://raw.githubusercontent.com/FA555/ignite/main/readme_zh.md
markdown
MIT License
Ignite 是一个美观的索引文档生成工具,适用于开卷考试、文档等场景。 Readme 中文 | [English](readme.md) ## 前置 - Python 3.4+ (with pip) - Typst ## 如何使用 ### 索引文件语法 首先将索引内容写入 `data/index.txt` 中。索引文件由若干行构成。除空行(会被忽略)外,任何一行应当符合两种格式之一: 1. 以 `<` 开头且以 `>` 结尾,表示章节划分。尖括号以内的内容会被视为章节标题。 2. 由任意内容加末尾的一个数字构成,表示一个条目。数字的语义是该条目的页码。 ### 生成文档 ```bash python3 -m pip install -r requirements.txt python3 main.py typst compile index.typ # 将生成 index.pdf ``` 调整格式细节请自行查看并修改 `index.typ`。 ## 示例 我们已经在 `example/` 下提供了一组示例。你可以通过以下命令生成示例文档: ```bash typst compile index.typ --input data-dir=example # 将生成 index.pdf ``` ![示例文档 P1](img/1.png) ![示例文档 P2](img/2.png)
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/kurzentwuerfe/uebung01/main.typ
typst
Other
#import "/src/kurzentwuerfe/template.typ": * #schedule(class: 9, title-lesson: "Descartes' cogito-Argument", title-series: "Erkenntnistheorie", justification: [ Gemäß der Themen des Rahmenplans für die 9. Klasse sollen die SuS hier im Themenbereich 1 Bedingungen der Möglichkeit der Selbsterkenntnis erkennen und reflektieren.#footnote[Vgl. Ministerium für Bildung, Wissenschaft und Kultur des Landes Mecklenburg-Vorpommern (Hg.): Rahmenplan Jahrgangsstufen 7--10. Philosophieren mit Kindern. Erprobungsfassung. Schwerin 2002. S. 25] Der Rahmenplan füllt 60% der Unterrichtszeit verbindlichen Inhalte, weitere Zeit kann von der Lehrkraft zur Festigung und Vertiefung benutzt werden.#footnote[Vgl. Ministerium für Bildung, Wissenschaft und Kultur des Landes Mecklenburg-Vorpommern (Hg.): Rahmenplan Jahrgangsstufen 7--10. Philosophieren mit Kindern. Erprobungsfassung. Schwerin 2002. S. 8.] Das Behandeln von Descartes' cogito-Argument wird hier als Vertiefung zur Grundlegenden Frage nach der Erkenntnis eines Selbst verstanden. ], time: [90 min], main-objective: [Die Schüler setzen sich kritisch mit Descartes' cogito-Argument auseinander.], fine-objectives: ( [Die SuS erweitern ihre Methodenkompetenz, indem sie ein philosophisches Problem des Matrix-Trailers zusammenfassen.], [Die SuS erweitern ihre Sachkompetenz, indem Sie das Ausgangsproblem und die Grundannahmen wiedergeben, aus denen Descartes sein Argument entwirft.], [Die SuS erweitern ihre Sozialkompetenz, indem Sie in einer Gruppenarbeit den Argumentationsgang von Descartes' cogito-Argument darstellen.], [Die SuS erweitern ihre Methodenkompetenz, indem die Einleitung für einen philosophischen Essay zu Descartes cogito-Argument gestalten.] ), date: the-date)[ *Motivationsphase*\ /10 min, 9:00 Uhr ][ - Einleitung durch den Trailer zum Film "Matrix" (1999) ][ #task[ Fassen Sie ein philosophisches Problem des Trailers in eigenen Worten zusammen! ] - Aufgabenstellung auf Tafel festhalten ][ Mögliche Fragen: - Ist die Welt real? - Leben wir in einer Matrix? - Wie viel Verantwortung dürfen wir Computern geben? - Ist künstliche Intelligenz gefährlich? ][ Lehrervortrag, \ Plenumsdiskussion ][ Tafel, Stift, \ #smallcaps[<NAME>. Entertainment]: _Matrix Trailer_. https://www.youtube.com/watch?v=ETvkaFGs6d4. (Letzter Zugriff #the-date.) ][ *Problemati-\ sierungsphase*\ /10 min, 9:10 Uhr ][ - Descartes' Grundfrage erarbeiten - Bezug auf Matrix und die Moderne herstellen - philosophsiches Problem fokussieren: Kann ich mir sicher sein, dass ich existiere? - gemeinsamer Vergleich des philosophischen Problems in Matrix mit Descartes' Problem ][ #task[ Geben Sie das Ausgangsproblem und die Grundannahmen wieder, aus denen Descartes sein cogito-Argument entwirft. ] - Aufgabenstellung auf Tafel festhalten - Moderieren der Plenumsdiskussion ][ - _Descartes könnte folgendes Problem lösen wollen:_ einen Ausweg aus der vorher aufgestellten skeptischen Grundhaltung des methodischen Zweifels finden - _welche Grundannahmen er macht:_ es gibt einen bösen Geist, der mich in allem täuscht - _ähnliche Punkte zu Matrix:_ grundlegende skeptische Haltung; es gibt einen Täuscher (Dämon und KI) - _unterschiedliche Punkte zu Matrix:_ unterschiedliche Lebensrealität: Renaissance vs. moderne Welt, Täuschergott vs. künstliche Intelligenz; Matrix kritisiert nicht die Existenz der Subjekte ][ Partnerarbeit, \ Plenumsdiskussion ][ Tafel, Stift, \ Auszüge aus: #smallcaps[Renè Descartes]: AT VII, S. 23--25. ][ *Erarbeitungsphase*\ /40 min, 9:20 Uhr ][ - Auseinandersetzung mit Descartes cogito-Argument in einer Gruppenarbeit ][ #task[ Stellen Sie den Argumentationsgang des cogito-Arguments von Descartes in einem Kurzvortrag dar. ] - Aufgabenstellung auf Tafel festhalten ][ - Ausgangspunkt darstellen: skeptizistische Grundhaltung nach dem methodischen Zweifel, der schlimmste Fall ist: der Täuschergott täuscht alle - Frage: Kann der Täuschergott einen auch in der eigenen Existenz täuschen? - Widerspruch: jemand, der nicht existiert, kann nicht getäuscht werden ][ Gruppenarbeit ][ Tafel, Stift, \ #smallcaps[Renè Descartes]: AT VII, S. 23--25. ][ *Sicherungsphase*\ /10 min, 10:00 Uhr ][ - eine Gruppe stellt ihre Ergebnisse vor ][ // #task[Präsentieren Sie Ihr Ergebnis vor der Klasse! #todo[(Kein EPA-Operator, trotzdem okay?)]] ][ - ein Großteil der oben genannten Punkte wird abgedeckt - die erarbeiteten Inhalte wird kohärent vorgetragen - die Vortragsweise ist akkustisch verständlich ][ Schülervortrag ][ ][ *Transferphase*\ /20 min, 10:10 Uhr ][ - 10 min arbeiten an Essay-Einleitung - 10 min vergleichen (5 min Text des Partners lesen, 5 min gegenseitig besprechen) ][ #task[ Gestalten Sie die Einleitung für ein philosophisches Essay zu dem Thema: "Kann ich mir sicher sein, dass ich existiere?" ] - Aufgabenstellung auf Tafel festhalten - moderieren der Plenumsdiskussion ][ - das Problem wird eingeleitet - die Fragestellung wird herausgestellt - es gibt eine inhaltliche Verbindung zwischen der Einleitung und dem Entwickeln der Fragestellung ][ Einzelarbeit, \ Partnerarbeit ][ Tafel, Stift ][ *Reservephase*\ /10 min ][ - Einleitung mit bekommenen Feedback überarbeiten // Überarbeiten Sie die Einleitung Ihres Essays mit dem Feedback, das Sie bekommen haben! #todo[(Kein EPA-Operator, trotzdem okay?)] ][ ][ (gleiche wie oben) ][ Einzelarbeit ][ ]
https://github.com/Skimmeroni/Appunti
https://raw.githubusercontent.com/Skimmeroni/Appunti/main/C++/Introduzione/Compilazione.typ
typst
Creative Commons Zero v1.0 Universal
#import "@preview/showybox:2.0.1": showybox // Aggiungere disegno preso dalle slide, da fare con Graphviz Un programma scritto nel linguaggio C++ é in genere costituito da uno o piú *file sorgente*, dei file di testo ciascuno contiene una parte del codice. Quando la compilazione viene invocata, prima che avvenga la compilazione vera e propria ciascun file viene modificato da una componente specifica del compilatore chiamata *preprocessore*. Questo converte il file di testo originale in un altro file di testo, nel quale sono state peró fatte delle specifiche sostituzioni sulla base di *direttive*, contenute nel file stesso. Il risultato dell'operato del preprocessore é un file testuale di codice "puro", dove le direttive sono sostituite dalle rispettive valutazioni. Ciascuno di questi file viene detto *unitá di compilazione*. Tale file esiste solo in memoria e viene passato al compilatore. Per ciascuno di questi il compilatore lo converte in un *file oggetto*, file che contiene la rappresentazione in codice binario dell'unitá di compilazione in input. Tali file non sono portabili, perché il loro contenuto dipende sia dall'architettura su cui il compilatore é stato eseguito, sia dal sistema operativo su cui il compilatore é stato eseguito sia dal compilatore stesso. Tali file di per loro non sono eseguibili; un'ultima componente del compilatore é il linker, che unisce tutti i file oggetto in un solo eseguibile. Il preprocessore interpreta delle istruzioni speciali (direttive), riconoscibili perché vi viene anteposto il simbolo `#`. Le direttive piú importanti e piú utilizzate sono: - `#define` e `#undef`. Permettono la definizione di *macro* o di *tag*. Una macro é una stringa che, in ogni posizione del codice in cui viene individuata, deve venire sostituita una seconda stringa. Tale sostituzione non viene interpretata semanticamente dal compilatore, pertanto puó essere sia una sostituzione tra due stringhe vere e proprie oppure la sostituzione di una stringa con una espressione. Una tag é una etichetta che viene registrata nella memoria del compilatore, da usarsi nelle direttive condizionali di seguito riportate. Macro e tag sono spesso riportate in maiuscolo per distinguerle dalle variabili vere e proprie, ma non vi sono restrizioni vere e proprie (al di lá di quelle che giá esistono) sul loro nome; - `#if`, `#else`, `#elif` e `#endif`. Hanno la stessa funzionalitá del costrutto `if-else`, ma operano rispetto al codice e non rispetto alla sua logica. Possono essere usate, in combinazione con i tag, per rendere parti di codice bypassate durante la compilazione. Una loro possibile utilitá consiste nel rendere il codice cross-platform, istruendo il compilatore ad operare in modi diversi a seconda della piattaforma su cui il codice viene eseguito; - `#ifdef` e `#ifndef`. Come i precedenti, ma anziché effettuare una valutazione di espressioni logiche valutano se una certa macro o tag é stata definita oppure no; - `#include`. Permette di riportare il nome di un file sorgente esterno da includere nel file sorgente attuale, di modo da avere accesso alle variabili e ai metodi in questo definito. Esiste in due forme: `#include "filename"` e `#include <filename>`. Entrambe hanno la stessa funzionalitá, l'unica differenza sta nella posizione del filesystem in cui tali file vengono cercati. La prima predilige la ricerca di file usando percorsi assoluti (partendo quindi dalla cartella in esame) mentre la seconda predilige la ricerca di file usando il percorso standard in cui i file delle librerie si trovano (questo dipende da sistema operativo a sistema operativo, su Linux `/usr/include`). #showybox[ #grid( columns: (0.4fr, 0.25fr, 0.35fr), [ ``` #include "File2" #define PIPPO 1234 #define FUNZ(a) 2 * a + 3 double d = PIPPO + 10 #ifdef PLUTO int j = 900; #else int j = 1000; #endif double k = FUNZ(j); ``` ], [ ``` int v1; double v2; char v3; ``` ], [ ``` int v1; double v2; char v3; double d = 1234 + 10; int j = 1000; double k = 2 * j + 3 ``` ] ) ] Il compilatore analizza sintatticamente il codice sorgente per verificare che non siano presenti typo. Effettua inoltre una parziale analisi semantica, in particolare il *type checking* (ad esempio, valutare che un valore passato ad una funzione sia del tipo specificato nella firma della funzione, oppure che una variabile venga inizializzata con un dato coerente col suo tipo) e l'identificazione di variabili e funzioni esterne, che non possono essere incluse immediatamente ma che devono attendere la fase di linking, ed é quindi necessario riportare dei "placeholder". Il compilatore, oltre a convertire le istruzioni dal formato testuale a quello binario, aggiunge (se necessario) delle informazioni di debug aggiuntive utili per la fase di testing. I riferimenti a componenti esterne al file oggetto vengono risolti dal linker, che cerca negli altri file oggetto le variabili e le funzioni che nel file in esame hanno un nome ma non una implementazione, sostituendo il "placeholder" con l'indirizzo di memoria della variabile/funzione presa dal file oggetto dove é contenuta. Un errore tipico che il linker puó emettere é `Unresolved External Symbol`, che avviene quando in un file oggetto é riportato il nome di una funzione/variabile che non é presente in nessun file oggetto che il linker ha esaminato. Il linker unifica i vari file oggetto in un solo eseguibile, ed introduce del codice di *startup* per renderlo riconoscibile dal sistema operativo come tale. Oltre ai file oggetto del codice in esame, il linker si occupa anche di aggiungere (se necessario) le librerie esterne. Queste, tranne la libreria standard (che viene inclusa sempre in automatica) devono essere specificate manualmente. Sebbene, come giá detto, i file sorgente possono avere estensioni a piacere (fintanto che sono file di testo), per convenzione i file sorgente si dividono in due categorie: - I file con estensione `.cxx`: contengono la definizione vera e propria di funzioni (il loro corpo) e variabili (il loro effettivo valore). Possono essere visti come l'implementazione di una libreria della quale é nota l'interfaccia. Tali file sono quelli che vengono effettivamente compilati. - I file con estensione `.h`, anche chiamati *file header*: contengono la dichiarazione di funzioni (la loro firma), variabili (il loro tipo) e tipi di dato definiti dall'utente (classi e simili). Possono essere visti come l'interfaccia di una libreria, ovvero riportano solamente _cosa_ é necessario implementare ma non l'implementazione in sé e per sé. Tali file non vengono in genere compilati, ma vengono inclusi nei file `.cxx` per rendere loro disponibili le interfacce da implementare. Per tale motivo, i file sorgente dei codici C++ sono in genere a coppie: un file `.h` che contiene l'interfaccia ed il corrispettivo file `.cpp` che ne implementa le funzionalitá. C++ non supporta le *forward declarations*: se nel codice é presente una funzione che non ha una firma (anche se non é nota l'implementazione), viene restituito un errore. Riportare le firme delle funzioni in file header permette di rendere nota al compilatore la firma di una funzione prima che questa venga implementata, di modo che non sia necessario rivedere l'ordine della dichiarazione delle funzioni ad ogni cambiamento. // Aggiungere un esempio? Sebbene non sia impedito l'usare `#include` per includere un file `.cpp` in un file `.cpp`, questo comportamento viene in genere scoraggiato perché rende i due file non piú indipendenti. Se si vuole avere del codice condiviso fra piú file, é preferibile che si trovi in un header file. Puó capitare che un header file venga incluso piú volte nello stesso file `.cpp`, specialmente quando il progetto é molto grande. Di base questo non é un problema, dato che ció che accade é che il preprocessore deve eseguire piú volte "a vuoto" una stessa sostituzione della direttiva `#include`; sebbene non sia un comportamento problematico, potrebbe comunque far sprecare tempo al preprocessore e rallentare il processo di compilazione. Per prevenirlo é possibile introdurre la cosiddetta *guardia*, che non é altro che una struttura del tipo: ``` #ifndef something_H #define something_H ... #endif ``` In questo modo, il preprocessore include `something.h` solamente se non é mai stato finora incluso. // Aggiungere un esempio? La suddivisione del codice in piú file oggetto permette la *compilazione separata*: un file sorgente deve venire ricompilato solamente se viene modificato direttamente. Nel C++ si distingue tra *dichiarazione* e *definizione* di una funzione o di una variabile. Dichiarare una funzione significa riportare il tipo del valore di ritorno di tale funzione, il suo nome ed il numero e tipo dei suoi argomenti. Definire una funzione significa, oltre a dichiararla, anche riportarne il corpo. ``` // definition return_value_type function_name(type_arg1 name_arg1, ..., type_argN name_argN) // declaration return_value_type function_name(type_arg1 name_arg1, ..., type_argN name_argN) { // body goes here... } ``` Definire una variabile significa notificare al compilatore che tale variabile esiste ed ha un certo nome, ma quale sia il suo valore non é da cercarsi nel file attuale (in genere questo viene fatto per la definizione di costanti globali in sostituzione a `#define`). Dichiarare una variabile significa sia esplicitarne il suo tipo, sia *inizializzarla*, ovvero assegnarle un valore iniziale; le due operazioni possono essere compiute separatamente o contemporaneamente. Una variabile non inizializzata assume in genere un valore casuale, che dipende dal contenuto della memoria che prima occupava tale variabile. ``` extern variable_type variable_name // define a variable, without declaring variable_type variable_name = initial_value // declare a variable and initialise variable_type variable_name // first declare a variable... variable_name = initial_value // then initialise it ``` Come giá detto, il compilatore non dá errori fintanto che esiste una firma di una funzione o il nome e tipo di una variabile. In altre parole, non dá errori fintanto che una variabile/funzione é _dichiarata_. É il linker a dare un errore nel caso in cui una variabile/funzione non é stata _definita_. Si noti come una dichiarazione implichi anche una definizione, mentre non é necessariamente vero il contrario. Inoltre, dichiarare piú volte una stessa variable/funzione non dá errore, perché si sta semplicemente ripetendo piú volte la stessa operazione, mentre definire piú volte una stessa variabile/funzione da spesso errore perché il linker non é in grado di distinguere quale "versione" della variabile/funzione debba venire utilizzata. #showybox[ ``` float euclidean_distance(int x1, int y1, int x2, int y2) double temperature; temperature = 4.2; extern float gamma_constant; ``` ] L'entry point di un programma C++ é una funzione avente nome `main`. Tale funzione deve essere globale e ne deve esistere una ed una sola copia. Il suo tipo di ritorno deve essere `int`, perché ció che viene restituito é il valore di successo o di errore dell'esecuzione del programma. Il suo numero di argomenti é variabile (anche zero), e tali argomenti vengono forniti al programma direttamente dall'utente quando il programma viene avviato. ``` int main() { ... return 0; } ``` Il programma `Hello, World!` per il linguaggio C++, che stampa sullo standard output tale stringa, é il seguente: ``` #include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; } ``` `std::cout` é un oggetto definito nella libreria standard del C++ (nello specifico, definito nell'header `iostream`, che viene importato) preposto alla stampa sullo standard output. A prescindere di quale sia il tipo di dato che `std::cout` debba stampare, questo lo restituisce come carattere. La dicitura `std` rappresenta il *namespace*, ovvero uno spazio logico dentro al quale sono definite delle funzionalitá. I namespace vengono in genere utilizzati per suddividere le entitá di una libreria da tutte le altre, e specificare che tali entitá appartengono allo stesso gruppo. Nello specifico, `std` indica che l'entitá di cui `std` é prefisso proviene dalla libreria standard. In questo modo, é anche possibile avere funzioni/variabili che hanno lo stesso nome ma che hanno un significato diverso a seconda del namespace a cui appartengono. In maniera molto simile, per leggere input da tastiera é possibile sfruttare `std::cin` #showybox[ ``` #include <iostream> int main() { int something; std::cin >> something; std::cout << "I got " << something << std::endl; return 0; } ``` ] Nel caso in cui si voglia mostrare un messaggio di errore, é possibile scrivere sullo standard error mediante `std::cerr`. Questo é in genere piú rapido che scrivere sullo standard output perché lo standard error non fa buffering, e quindi l'overhead é minore. Aiuta inoltre a separare i messaggi di errore dal normale flusso di esecuzione del programma. Gli operatori `<<` e `>>` sono operatori che rispettivamente inseriscono dati in uno stream ed estraggono dati da uno stream. C++ supporta la *ridefinizione* degli operatori, pertanto é possibile assegnare ad un operatore una funzione diversa a seconda del tipo di dato che si richiede che questo manipoli. In effetti, tali operatori sono essi stessi una ridefinizione, dato che il loro uso di "default" é lo shift logico (a sinistra e a destra rispettivamente). Sebbene i namespace abbiano il pregio di separare in maniera elegante diversi package, riportarne il nome ogni volta che viene riportato un suo oggetto o funzione puó diventare tedioso. Per questo motivo é possibile includere l'istruzione `using namespace` per specificare al compilatore che, all'interno del file corrente, tutte le funzioni e gli oggetti potrebbero provenire da tale namespace. Dato che l'effetto di questa istruzione viene propagato, é preferibile evitare di riportarla nei file header. Il C++ é retrocompatibile con C, pertanto é possibile importare normalmente librerie C; tali funzionalitá non sono legate ad un namespace vero e proprio, ma si trovano nel namespace globale. Spesso le librerie pensate per il linguaggio C possono venire utilizzate nel C++ in maniera nativa incapsulando tali funzionalitá in un namespace. La differenza fra le due, ovvero fra le librerie per C importate in C++ e librerie in C++ propriamente dette, sta nel nome dell'header importato: le seconde sono importate specificando il file per intero, estensione inclusa, mentre le seconde vengono importante troncando l'estensione. Nel caso specifico della libreria standard del C, molte delle funzionalitá di tale libreria sono incapsulate dalla libreria standard del C++ in header che hanno il medesimo nome ed una 'c' come prefisso. #showybox[ La libreria standard del C `math.h` contiene alcune funzioni matematiche piú elaborate delle operazioni standard, come ad esempio il calcolo della radice quadrata (`sqrt`) o l'arrotondamento per eccesso o per difetto (`floor` e `ceiling`). Per importarla in un codice C++ é sufficiente specificare la direttiva `#include <math.h>` e le funzioni da questa fornite sono disponibili senza dover specificare un namespace (non avendolo). In alternativa, la libreria standard del C++ incapsula `math.h` nel namespace `std` (senza modificarne le funzionalitá) pertanto é anche possibile accedere alle funzioni di `math.h` mediante la direttiva `#include <cmath>`, e tali funzioni avranno `std` come namespace. #grid( columns: (0.5fr, 0.5fr), [ ``` #include <math.h> sqrt(16); ``` ], [ ``` #include <cmath> std::sqrt(16); ``` ] ) ]
https://github.com/Otto-AA/tt-flaky-mre
https://raw.githubusercontent.com/Otto-AA/tt-flaky-mre/main/tests/example%20copy%202/test.typ
typst
#import "@preview/linguify:0.4.1": linguify, set-database Test
https://github.com/mismorgano/UG-FunctionalAnalyisis-24
https://raw.githubusercontent.com/mismorgano/UG-FunctionalAnalyisis-24/main/config.typ
typst
#import "./lemmify/src/lib.typ": * // lemmify setup #let ( proof, rules: thm-rules ) = default-theorems("thm-group", lang: "es") // The template setup #let config(title, doc) = { show: thm-rules // latex-like setup set text(12pt, font: "New Computer Modern") set par(leading: 0.55em, first-line-indent: 0em, justify: true) show raw: set text(font: "New Computer Modern Mono") show par: set block(spacing: 0.55em) show heading: set block(above: 1.4em, below: 1em) set enum(numbering: "i)") // title setup align(center)[ #text(17pt)[ Análisis Funcional I ] \ // subject #text(15pt)[#title] #text(12pt)[ #grid( columns: (1fr, 1fr), align(center)[ <NAME>. \ #link("mailto:<EMAIL>") ], align(center)[ <NAME>. \ #link("mailto:<EMAIL>") ] ) ] ] // shortcuts show "e.B": [espacio de Banach] show "e.H": _ => [espacio de Hilbert] show "e.n": _ => [espacio normado] show "e.v": _ => [espacio vectorial] show "f.l": _ => [funcional lineal] show "o.l": _ => [operador lineal] show "ssi": _ => [si y solo si] // show "eps": [epsilon] doc } // My own exercise environment #let e = counter("exercise") #let exercise(label, body, number: none) = { // label: of the problem in the book if number != none { e.update(number) // let problema = [*Problema #label*] } else { e.step() } // let problema = [*Problema #e.display() #label*] box(width: 100%,stroke: 1pt, inset: 1em, [#text(size: 1.6em)[*Problema #context e.display()*] #text(blue)[ #label] \ #body],) } #let ip(x, y) = $angle.l #x, #y angle.r$ // internal product #let cls(S) = $overline(#S)$ // closure #let conv(S) = $"conv"(#S)$ // convex hull #let span(S) = $"span"(#S)$ #let int(S) = $"Int"(#S)$ // interior #let eps = $epsilon$
https://github.com/konradroesler/edym-skript
https://raw.githubusercontent.com/konradroesler/edym-skript/main/skript.typ
typst
#import "@preview/physica:0.9.3": * #import "utils.typ": * #import "template.typ": uni-script-template #show: doc => uni-script-template( title: [Vorlesungsskript], author: [<NAME>], module-name: [Elektrodynamik], doc ) = Worum geht es in der Elektrodynamik? #bold[In der klassischen Mechanik:] fundamentale Konzepte: Länge, Zeit, #underline[Masse] $arrow.long$ Trägheit + Gravitation Newtonsche Bew. gl.: $arrow(F) = m dot arrow(a)$, $arrow(F) = G dot (M dot m)/r^2 arrow(e)_r$ wobei $underbrace(arrow(r),"Ort") underbrace((t), "Zeit") ==> arrow(a) = (d^2 arrow(r))/(d t^2) = dot.double(arrow(r))$ comment(Zeichung 2D system mit massepunkt, e eingezeichnet) Lagrange-Funktion: $arrow.long$ Wirkung $ S = integral d t L(arrow(r), dot(arrow(r))) $ $N$ Teilchen $arrow(r)_i (t), i = 1, ..., N$ $ L(arrow(r)_i, dot(arrow(r))_i) = sum_(i = 1)^N 1/2 m_i abs(dot(arrow(r))_i)^2 - V(arrow(r)_i) \ V(arrow(r)_i) = - G/2 limits(sum_(i, j = 1)^N)_(i != j) (m_i m_j)/abs(arrow(r)_i - arrow(r)_j) $ #bold[Neue fundamentale Größe:] - elektrische Ladung $q$ (positiv oder negativ) - gequantelt mit #underline[Elementarladung $e$] $ &q = n dot e, n in ZZ \ &q > 0 "(Proton, Positron," n = +1")" \ &q < 0 "(Elektron," n = -1")" $ #bold[Coulomb-Gesetz:] Kraft zwischen elektrisch geladenen Teilchen $ arrow(F)_1 = k dot q_1 q_2 (arrow(r)_1 - arrow(r)_2)/abs(arrow(r)_1 - arrow(r)_2)^3 = - arrow(F)_2 $ comment(Zeichung zweier Punktteilchen, Coloumbgesetz geometrisch $q_1 q_2 > 0$ (Ladungen haben dasselbe Vorzeichen) $==>$ abstoßend $q_1 q_2 < 0$ (Ladungen haben verschiedene Vorzeichen) $==>$ anziehend #bold[Was ist $k$? (Einheitensysteme)] #underline[1) Gausssche System:] $k = 1$ #underline[2) SI System:] $k = 1/(4 pi epsilon_0)$ #underline[3) Heavyside-Lorentz-System:] $k = 1/(4 pi)$ Umrechnen: SI $->$ Gauss: $e_0 = 1/(4 pi)$, SI $->$ Heavyside: $epsilon_0 = 1$ #bold[Zusätzliche Realität:] magenetische Felder, elektromagnetische Wellen $ --> #bold[Feldtheorie] "(Maxwell's Theorie, erstes Beispiel)" $ $arrow(x)_i (t), quad i = 1, ..., N quad$ diskrete Zahl an freiheitsgrade $= 3N$ $-->$ Elektrodynamik $arrow(E)(t, arrow(x)), arrow(B)(t, arrow(x))$ Betrachte ein Kraftfeld, erzeugt durch $N$ Punktladungen $q_i, 1 = 1, ..., N$ wirkend auf eine Testladung $abs(q) << abs(q_i)$ $ ==> arrow(F) = q arrow(E)(arrow(x)), quad arrow(E)(arrow(x)) = 1/(4 pi epsilon_0) sum_(i = 1)^N q_i (arrow(x) - arrow(x)_i)/abs(arrow(x) - arrow(x)_i)^3 \ "das Elektrische Feld" $ eine fixierte Ladung an $arrow(x)_1$ $ arrow(E)(arrow(x) #text(fill: red)[$, t$]) = 1/(4 pi epsilon_0) q_1 (arrow(x) - arrow(x)_1 #text(fill: red)[$(t)$])/abs(arrow(x) - arrow(x)_1 #text(fill: red)[$(t)$])^3 $ comment(Zeichung Punktteilchen, Ladung) Diese (naive) Zeitabhängigkeit ist empirisch falsch und im Widerspruch zur (speziellen) Relativitätstheorie (SR) $-->$ Maxwell's Theorie, kompatibel mit SR == Plan der Vorlesung 1. Wiederholung - Euklidische Geometrie im $RR^3$, Vektoranalysis (Differentialformen) 2. Spezielle Relativitätstheorie - (Psuedo-) Euklidische Geometrie des Minkowski-Raum $RR^(3, 1)$ 3. Maxwell's Theorie 4. Anwendungen 1. Elektrostatik 2. Magnetostatik 3. Elektro- und Magnetostatik in Materie #pagebreak() = Wiederholung: Vektoranalysis im $RR^3$ Der euklidische $RR^3$: $arrow(x) = arrow(r) = (x^1, x^2, x^3) = (x^i), quad i = 1,2,3$ #underline[Metrik:] $ ip(arrow(x)_1 - arrow(x)_2, arrow(x)_1 - arrow(x)_2) = abs(arrow(x)_1 - arrow(x)_2)^2 = sum_(i = 1)^3 (x_1^i - x_2^i)(x_1^i - x_2^i) $ Geometrie invariant unter Rotationen $ x^i --> x'^i = sum_(j = 1)^3 R^i_j x^j underbrace(=, "Einstein Konvention") R^i_j x^j $ $ abs(arrow(x))^2 = delta_(i j) x^i x^j quad "wobei" delta_(i j) = cases(1 quad i = j, 0 quad i != j) $ $ abs(arrow(x)')^2 &= delta_(i j) x'^i x'^j = delta_(i j) R^i_k x^k R^j_l x^l \ &= (delta_(i j) R^i_k R^j_l) x^k x^l = abs(arrow(x))^2 = delta_(k l) x^k x^l $ $ ==> delta_(i j) R^i_k R^j_l = delta_(k l) $ Matrix-Notation: $R = (R^i_j), bb(1) = (delta_(i j))$ $ delta_(k l) = R^i_k delta_(i j) R^j_l ==> bb(1) = R^T R \ ==> det(R) = plus.minus 1 $ Rotationsgruppe: $"SO"(3): det(R) = +1$ --- Im $RR^3$ hat man das #bold[Kreuz-Produkt] Epsilon-Tensor / Levi-Civita-Symbol $ epsilon^(i j k), epsilon_(i j k): quad epsilon^(1 2 3) = - epsilon^(2 1 3) = epsilon^(2 3 1) = 1 $ total antisymmetrisch, da $epsilon^(1 1 2) = 0 = - epsilon^(1 1 2)$ $==>$ invariant unter Rotation / $"SO"(3)$ $ epsilon^(i j k) --> R^i_m R^j_n R^K_l epsilon^(m n l) underbrace(=, det(R) = 1) epsilon^(i j k) $ Im euklidischen $RR^3$ darf man nur folgende Objekte benutzen: $ delta_(i j), delta^(i j), epsilon^(i j k), epsilon_(i j k) $ #underline[Skalarprodukt:] $ip(arrow(x), arrow(y)) = delta_(i j) x^i y^j$ #underline[Kreuzprodukt:] $arrow(u) times arrow(v) = - arrow(v) times arrow(u), (arrow(u) times arrow(v))^i := delta^(i l) epsilon_(l j k) u^j v^k$ #underline[Skalare/Funktionen auf $RR^3$:] $F = F(arrow(x)) in RR$ #underline[Vektorfeld auf RR^3:] $arrow(V) = arrow(V)(arrow(x))$ #underline[Gradient:] $diff_i := pdv(,x^i)$, Skalar $-->$ Vektor $ arrow(grad)F = "grad" F, quad ("grad" F)^i = delta^(i j) diff_j F = (pdv(F,x^1), pdv(F,x^2), pdv(F,x^3)) $ #underline[Divergenz:] Vektor $-->$ Skalar $ "div" arrow(V) &= div arrow(V) = diff_i V^i \ &= pdv(V^1,x^1) + pdv(V^2,x^2) + pdv(V^3,x^3) $ #underline[Rotation:] Vektor $-->$ Vektor $ "rot" arrow(V) = curl arrow(V) ==> ("rot" V)^i = epsilon^(i j k) diff_j V_k $ $ "Skalare" -->^"grad" "Vektoren" -->^"rot" "Vektoren" -->^"div" "Skalare" $ Identitäten (Kettenkomplex): $ "rot" compose "grad" = 0 \ "div" compose "rot" = 0 $ #bold[Differentialformen im $RR^3$:] - #underline[0-Formen:] Skalar - #underline[1-Formen:] "dual" zu Vektoren, $A_i (arrow(x))$ $ "[Im Euklidischen: " V_i (arrow(x)) = delta_(i j) V^j (arrow(x)) "]" $ - #underline[2-Formen:] Antisymmetrischer Tensor $ B_(i j) (arrow(x)) = - B_(i j) (arrow(x)) $ - #underline[3-Formen:] $C_(i j k) (arrow(x)) = - C_(i k j) (arrow(x)) = ...$ (wie Levi-Civita) #underline[Effiziente indexfreie Notation:] Basis-Elemente $d x^i$ - 1-Form: $A = A_i dd(x^i)$ - 2-Form: $B = 1/2 B_(i j) dd(x^i,x^j,p:and)$ - 3-Form: $C = 1/3! C_(i j k) dd(x^i,x^j,x^k,p:and)$ wobei $dd(x^i,x^j,p:and) = - dd(x^j,x^i,p:and)$ #bold[Wedge Product:] $ A and B = (A_i dd(x^i)) and (1/2 B_(j k) dd(x^j,x^k,p:and)) = 1/2 A_i B_(j k) dd(x^i,x^j,x^k,p:and) "(3-Form)" $ $p$-Form $A$, $q$-Form $B$ $ ==> A and B /* space */ "ist" (p+q)-"Form" \ A and B = (-1)^(p q) B and A "(gradiert Kommutativ)" \ (A and B) and C = A and (B and C) "(assoziativ)" $ #underline[deRham Differential:] $ d := diff_i dd(x^i) and $ Beispiel: $ d A &= d (A_j d x^j) \ &= diff_i d x^i and (A_j d x^j) \ &= diff_i A_j d x^i and d x^j \ &= 1/2 (diff_i A_j - diff_j A_i) underbrace(d x^i and d x^j, - d x^j and d x^i) $ $Omega^p:$ $p$-Formen, $d: Omega^p --> Omega^(p+1)$, $d^2 = 0$ (Übungsaufgabe) #underline[Hodge Operator:] $ star: Omega^p <--> Omega^(3-p) \ star: Omega^1 <--> Omega^(2) \ star: Omega^3 <--> Omega^(0) \ $ $A$ ist 1-Form, $B$ ist 2-Form, $C$ ist 3-Form $ star A &= 1/2 epsilon_(i j)^k A_k d x^i and d x^j \ star B &= 1/2 epsilon_i^(j k) B_(j k) d x^i \ star C &= 1/3! epsilon^(i j k) C_(i j k) $ Wir erweitern das Diagramm von vorher: $ &"Skalare" -->^"grad" "Vektoren" -->^"rot" "Vektoren" -->^"div" "Skalare" \ &arrow.b.t i d #h(1.6cm) arrow.b.t ♡ #h(1.9cm) arrow.b.t star, ♡ #h(1.5cm) arrow.b.t star\ &Omega^0 #h(1cm) -->^d Omega^1 #h(1.35cm) -->^d Omega^2 #h(1.35cm) -->^d Omega^3 $ Dieses Diagramm kommutiert. (Alle Pfade, die zwei Punkte verbinden, sind äquivalent.) $ d^2 = 0 <==> "rot" compose "grad" = 0, "div" compose "rot" = 0 $
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/数学模型/作业/hw6.typ
typst
#import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark, proposition,der, partialDer, Spec #import "../../template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: note.with( title: "作业6", author: "YHTQ", date: none, logo: none, withOutlined : false, withTitle :false, ) (应交事件为5月13日) #set heading(numbering: none) = 4.22 == 1 #let xi2 = $x_i$ #let xi1 = $x_(i-1)$ #let uxi2 = $u(xi2)$ #let uxi1 = $u(xi1)$ #let di = $x_(i) - x_(i-1)$ #let din = $x_(i-1) - x_i$ 任取 $x$ 使得 $x_(i-1) <= x <= x_i$,将有: $ &quad abs(u(x) - u_I (x)) = abs(u(x) - (x - x_i)/(x_(i-1) - x_i) u(x_(i-1)) - (x - x_(i-1))/(x_i - x_(i-1)) u(x_i))\ &= abs(((x - x_(i-1))/(x_i - x_(i-1)) + (x - x_i)/(x_(i-1) - x_i))u(x) - (x - x_i)/(x_(i-1) - x_i) u(x_(i-1)) - (x - x_(i-1))/(x_i - x_(i-1)) u(x_i))\ &= abs((x - x_i)/(x_(i-1) - x_i)(u(x) - u(x_(i-1))) + (x - x_(i-1))/(x_i - x_(i-1))(u(x) - u(x_i)))\ &= abs((x - x_i)/(x_(i-1) - x_i)(u(x_(i-1)) - u(x)) + (x - x_(i-1))/(x_i - x_(i-1))(u(x_i) - u(x)))\ &= abs((x - x_i)/(x_(i-1) - x_i)((x_(i-1) - x) u'(x) + 1/2 (x_(i-1) - x) u''(xi_1)) \ &quad + (x - x_(i-1))/(x_i - x_(i-1))((x_i - x)u'(x) + 1/2 (x_i - x)^2 u''(xi_2)))\ &= 1/2 abs(((x-x_i)(x-x_(i-1)))/(x_(i-1) - x_i)) abs((x - x_(i-1)) u''(xi_1) - (x_i - x) u''(xi_2))\ &<= 1/2 abs(((x-x_i)(x-x_(i-1)))/(x_(i-1) - x_i)) abs(x - x_(i-1) + x_i - x) norm(u'')_infinity\ &<= 1/2 abs(((x_i - x)(x-x_(i-1)))) norm(u'')_infinity\ &<= 1/8 h^2 norm(u'')_infinity //= abs(((x-x_i)(x-x_(i-1)))/(x_(i-1) - x_i)) abs(u'(xi_1) - u'(xi_2))\ //= abs(((x-x_i)(x-x_(i-1)))/(x_(i-1) - x_i)) abs(xi_1 - xi_2) abs(u''(xi_3))\ //= abs(((x_i - x)(x-x_(i-1)))/(x_(i-1) - x_i)) abs(xi_1 - xi_2) abs(u''(xi_3))\ //<= 1/4 h^2 abs((xi_1 - xi_2)/(x_(i-1) - x_i)) norm(u'')_infinity $ $ u'_I (x) &= uxi1/din + uxi2/di\ abs(u'_I (x) - u'(x)) &= abs(uxi1/din + uxi2/di - u'(x))\ &= abs(((xi1 - x)u'(x) + 1/2 (xi1 - x)^2 u''(xi_1))/din + ((xi2 - x)u'(x) + 1/2 (xi2 - x)^2 u''(xi_2))/di - u'(x))\ &= 1/2 1/abs(di) abs((xi2 - x)^2 u''(xi_2) - (xi1 - x)^2 u''(xi_1))\ &<= 1/2 1/abs(di) abs((xi2 - x)^2 + (xi1 - x)^2) norm(u'')_infinity\ $ 其中 $(xi2 - x)^2 + (xi1 - x)^2$ 是正的,最大值在边界处取得,为 $(di)^2$,上式不超过: $ 1/2 abs(di) <= 1/2 h norm(u'')_infinity $ (不确定何处会引入 $sqrt(b-a)$,看起来也不是很合理,在每个点处的近似似乎应该和区间大小没有什么关系) = 5.6 == 1 #answer[ 对于中点公式 $Q f = (b - a) f((a + b) / 2)$ 和梯形公式 $Q f = (b - a) (f(a) + f(b)) / 2$,不难验证它们在线性函数上的估计都是准确的,而设: $ f = (x - 1/2)^2 g = x(1-x) $ 均考虑 $[0, 1]$ 上的积分,则中点公式显然在 $f$ 上不准确,梯形公式在 $g$ 上不准确,因此两者恰有一阶代数精度 对于辛普森公式: $ Q f = (b - a) (f(a) + 4 f((a + b) / 2) + f(b)) / 6 $ 同样不妨简化为 $[0, 1]$ 上积分,公式变为: $ Q f = 1/6 (f(0) + 4 f(1/2) + f(1)) $ 容易验证它对线性函数估计是准确的,而取 $f = x(1-x)$ 有: $ integral_(0)^(1) x(1-x) dif x = 1/6 = 1/6 (0 + 4 * 1/4 + 0) $ 任做线性组合可得辛普森公式对于任何不超过二次的多项式都是准确的。\ 再取 $f = x^3$,有: $ integral_(0)^(1) x^3 dif x = 1/4 = 1/6 (0 + 4 * 1/8 + 1) $ 类似的对于任何不超过三次的多项式都是准确的。\ 再取 $f = x^4$,有: $ integral_(0)^(1) x^4 dif x = 1/5 != 1/6 (0 + 4 * 1/16 + 1) $ 从而恰好有三阶代数精度 ] == 2 #answer[ #lemmaLinear[][ + 每个 $p_n (x)$ 都是首项为 $k_n$ 的 $n$ 次多项式 + 每个 $p_n (x)$ 都与 $p_i (x), i < n$ 正交 ] #proofLinear[ 归纳证明,以上性质当然对 $n = 0, 1$ 正确,假设它们对 $0, 1, 2, ..., n$ 都正确,对 $n + 1$ 时情形分别证明三者: + 由递推式 $p_(n+1) (x) = (a_n x - b_n) p_n (x) - c_n p_(n-1) (x)$ 及归纳假设,当然 $p_(n+1) (x)$ 是首项为 $k_n$ 的 $n$ 次多项式 + 计算: - $ inner(p_(n+1), p_n) &= inner((a_n x - b_n) p_n , p_n)\ &= a_n inner(x p_n, p_n) - b_n inner(p_n, p_n)\ &= a_n inner(x p_n, p_n) - a_n inner(x p_n, p_n)/inner(p_n, p_n) inner(p_n, p_n)\ &= 0 $ - $ inner(p_(n+1), p_(n-1)) &= a_n inner(x p_n, p_(n-1)) - c_n inner(p_(n-1), p_(n-1))\ &= a_n inner(x p_n, p_(n-1)) - a_n/a_(n-1) inner(p_n ,p_n)\ &= a_n/a_(n-1) (inner(p_n, a_(n-1) x p_(n-1)) - inner(p_n ,p_n))\ &= a_n/a_(n-1) inner(p_n, a_(n-1) x p_(n-1) - p_n)\ &= a_n/a_(n-1) inner(p_n, b_n p_(n-1) + c_n p_(n-2))\ &= 0 $ 证毕 ] 由引理,$p_0, p_1, ..., p_n$ 一定构成 $generatedBy(1\, x\, ... \, x^n)$ 的一组基,进而 $p_(n+1)$ 与其中元素都正交,当然是正交多项式,证毕 ]
https://github.com/mitex-rs/mitex
https://raw.githubusercontent.com/mitex-rs/mitex/main/packages/mitex/specs/mod.typ
typst
Apache License 2.0
#import "prelude.typ": * #import "latex/standard.typ": package as latex-std // 1. import all the packages and form a mitex-scope for mitex to use #let packages = (latex-std,) #let mitex-scope = packages.map(pkg => pkg.scope).sum() // 2. export all packages with specs by metadata and <mitex-packages> label, // mitex-cli can fetch them by // `typst query --root . ./packages/mitex/specs/mod.typ "<mitex-packages>"` #metadata(packages) <mitex-packages>
https://github.com/jianqih/Hopenhayn-Replicate-Julia
https://raw.githubusercontent.com/jianqih/Hopenhayn-Replicate-Julia/main/main.typ
typst
#set text(size: 14pt,font: "Linux Libertine") #set page("a4",number-align: center, numbering: "1") #let title = [Firm Dynamics] #align(center, text(18pt)[*#title*]) #set heading(numbering: "1.") #set math.equation(numbering: "(1)") #import "@preview/physica:0.9.2": * #set cite(style: "chicago-author-date") #let pc = (citation) => { set cite(form: "prose") citation } This two papers #pc[@hopenhayn1992entry] and #pc[@hopenhayn1993job] are important papers in firm dynamics. - Workhorse model of industry dynamics - Output price $p$ endogenous - Endogenous measure of heterogeneous firms - *DRS* production function - Perfect competition in product and labor market - No aggregate shocks - Idiosyncratic risk - Entry-exit dynamics - fixed cost to enter - fixed cost to operate each period. - Partial equilibrium: exogenous industry demand / Heterogeneous firms: productivity $z$ and the output $ f(z,n)=z n^alpha, alpha in (0,1) $ - Static firm-level profits $ pi (z;p)=max p dot f(z,n)-n -p dot c_o $ $c_o$ operating costs per period. - optimal employment $ n(z;p)=(p dot alpha dot z)^(1/(1-alpha)) $ - Incumbents enter the period with states $z_(-1)$ - Exit decision: if stay, firms draw new productivity level $z tilde.op $ / Dynamic problem of the firm: There is a large pool of identical potential entrants deciding whether to become active or not. = Model I - General equilibrium version of @hopenhayn1992entry - Non-convex adjustment cost (firing costs) $arrow$ firm-level employment additional state variable - No aggregate shocks - Optimal employment policy characterized by _inaction_ region. - Endogenous _Misallocation_ across heterogeneous plants. / Overview: time is discrete, the wage is the model numeraire, and output price $p$ is endogenous. representative household. Endogenous measure of heterogeneous firms. = Model II A stochastic production function: $ p_t f(n_t,s_t)-n_t-p_t f_t -g(n_t,n_(t-1)) $ - $c_f$: fixed operating cost. - $n_t,p_t$: hire $n_t$ and output $p_t$. - $s_t$: firm-specific shock to production opportunities. - $F(s,s')$: each current value of the shock. - $g(n_t,n_(t-1))=tau dot max(0,n_(t-1)-n_t)$ captures the presence of adjustment costs. // firm has a shock equal - $c_e$ one-time enter cost. Each new entrant receives its current value of $s$ as a draw from the dist. $nu$. / Preference: $ sum_(t=1)^(oo)beta^t [u(c_t)-v(n_t)] $ They have idiosyncratic risks: $ sum_(t=1)^(oo)beta^t [u(c_t)-a N_t] $ - $N_t$ is the fraction of individuals employed in period $t$. - discount factor $beta = 1/(1+r)$ / Equilibrium: The Bellman equation is $ W(s,n;p)=max_(n'>=0){p f(n',s)-n'-p c_f -g(n',n)}\ +beta max[E_s W(s',n';p)-g(0,n')] $ - list $p$ as a stationary price level. / Value function: the value of entering gross of entry costs, $W^e$ can be computed by given $W(s,0;p)$ $ W^e (p)=integral W(s,0;p)dif nu(s) $ - state variable pairs $(s,n)$ we denote $mu(s,n)$ / Output $Y$: it takes $ Y(mu,M;p)=integral [f(N(s,n;p),s)-c_f]dif mu(s,n)\ +M integral f(N(s,0;p),s)dif nu(s). $ The first integral, output for a firm with state variable $(s,n)$ is computed using the optimal employment rule $N$. / Labor demand and profits: $ L^d(mu,M,p)=integral N(s,n;p)dif mu(s,n)+M integral N(s,0;p)dif nu(s), \ Pi(mu,M,p)=p Y(mu,M,p)-L^d(mu,M,p)-R(mu,M,p)-M p c_e. $ / Individual optimization problem: $ max u(c)- a N \ s.t. quad p c<= N+Pi+R (w=1 "is the numeraire") $ solution: $ N=L^s (p,Pi+R) $ / Equilibrium: output price $p^*>=0$ a mass of entrants $M^*>=0$, and a measure of incumbents $mu^*$, such that - Labor market clearing: $L^d (mu^*,M^*,p^*)=L^s (p^*,Pi(mu^*,M^*,p^*)+R(mu^*,M^*,p^*))$ - $T = mu^*$ // - $W^e (p^*)<= p^* c_e$ with equality if $M^*>0$ - Free-entry: $nu^e = c_e$ = Algorithm The stationary equilibrium can be characterized by - production function: concave and differentiable. - $L_2^s$ and income effect: negative. - $F$: continuous and decreasing in the first argument. + compute $p$, any given $p$ can be used for computing $W(s,n;p)$ and $W^e (p)$ + determine whether an equilibrium: if not, finds $mu^*$ to compute transition function $T$. The fixed point exists if the firm's inflow equals outflow. + determines the scale factor $M^*$. (from market clearing condition) = Benchmark model $ f(n,s)=s n^theta ,quad 0<= theta <=1 \ g(n_t,n_(t-1))=0, quad \ log(s_t) = a + rho log(s_(t-1))+epsilon_t, quad epsilon_t \ u(c)=ln(c), quad nu(n)=A n,quad A>0. $ Two decision rules $ log(n_(t+1))=(1-rho)/(1-theta)(log theta +log p+a/(1-rho)) \ + rho(log(n_(t-1)))+(1/(1-theta))epsilon_t. $ / MPL: $ pdv(f(z,n),n)=1/p $ optimal employment decision given by: $ n'= (alpha p z)^(1/(1-alpha)) $ Labor is a fully flexible input production. MPL is the solution of two necessary conditions: $ p pdv(f(z,n),n)+1/(1+r)pdv(tilde(nu)(z,n),n)=1 quad "if " n>n_(-1) \ p pdv(f(z,n),n)+1/(1+r)pdv(tilde(nu)(z,n),n)=[1+pdv(g(n,n_(-1)),n)] quad "if " n <n_(-1) $ == Role of volatility $sigma_epsilon$ + When shocks are less volatile, efficient employment does not change often. - Adj. costs are more important. + More vol. $arrow$ efficient employment changes much more often. - Adj. costs are less important. + While reducing dispersion of $"MPL"$, lower vol. also reduces selection. = Embedded Searching and Match - <NAME>. and <NAME>. 2013. “Marginal Jobs, Heterogeneous Firms, and Unemployment Flows.” American Economic Journal: Macro, Vol. 5, No. 1, pp. 1-48 - Multi-worker heterogeneous firms $arrow$ well-defined firm-size. - Idiosyncratic productivity shocks $arrow$ endogenous job. - Search frictions $arrow$ unemployment - Wage bargaining $arrow$ wage dispersion. = Financial Markets and Firm Dynamics @Cooley2001 - financial frictions can account for the simultaneous dependence of firm dynamics on size. - In each period, firms have access to a production technology. - $y=(z+epsilon)G(k,l)$ where $epsilon$ is the idiosyncratic shock. - As in @hopenhayn1992entry, assume there exists a fixed cost of production. - Maximization of expected profits, $ max_k {integral_epsilon (z+epsilon)F(k)f(dif epsilon)-(r+phi.alt)k} \ =max_k {z F(k)-(r+phi.alt)k}. $ and $phi.alt$ is the cost of labor and capital. $phi.alt k=[delta+w(l/k)]k$, where $w$ is the wage rate. - In partial eqbm, the mass of new entrant firms is nondegenerate only if the surplus from creating new firms is nonpositive, $V(z)-kappa<=0$. / The firm's problem: each period, after the realization of the revenues and the observation of the new $z$, but before issuring new shares or paying dividends, the firm decides whether to default on its debt. $ pi(e,b,z+epsilon)=(1-phi.alt)(e+b)+(z+epsilon)F(e+b)-(1+tilde(r))b $ - $tilde(r)$: interest rate charged by intermediary. - $z$: tech level, - $e$: assets held by firms. $b$: firm's debt. $k=e+b$ is the input capital. Firm needs to borrow from intermediary, it takes $lambda$ peri unit of funds. If firm choose to default, it will charge a cost $xi$. - Denote $underline(e)(z')$ the value of net worth if defaults. And denote $underline(epsilon)(z,e,b,z')$ as threhold shock. $ pi(e,b,z+underline(e))=(1-phi.alt)(e+b)+(z+underline(epsilon))F(e+b)-(1+tilde(r))b=underline(e)(z) $ As the lender, she needs to consider default probability. Using the distribution to describe the risk. $ (1+r)b=underbracket(integral_(-oo)^(underline(epsilon))[(1-phi.alt)(e+b)\ +(z+epsilon)F(e+b)-xi]f(dif epsilon),"Default ")+underbracket((1+tilde(r))b integral_(underline(epsilon))^oo f(dif epsilon),"pay back") $ Eliminate $tilde(r)$ in Proposition 3: There exists a unique function $Omega^*(z,e)$ that satisfies the functional equation. #bibliography("ref.bib")
https://github.com/alberto-lazari/computer-science
https://raw.githubusercontent.com/alberto-lazari/computer-science/main/type-theory/theory-exercises/exercises/singleton.typ
typst
#import "/common.typ": * #exercise( section: (num: "3.1", title: "Singleton type and exercises"), ex: 3, solution: false, [Show that the rule #ES is derivable in the type theory $T_1$ replacing the rule #ES elimination with the E-$N1prog)$ rule and adding the substitution and weakening rules and the sanitary checks rules set out in the previous sections.] ) - Rule E-S) $ #prooftree( axiom($t in N1 ctx(Gamma)$), axiom($M(z) type ctx(Gamma, z in N1)$), axiom($c in M(star) ctx(Gamma)$), rule(n: 3, label: ES, $ElN1(t, c) in M(t) ctx(Gamma)$), ) $ - Rule E-$N1prog)$ $ #prooftree( axiom($D(w) type ctx(Sigma, w in N1)$), axiom($d in D(star) ctx(Sigma)$), rule(n: 2, label: $"E-"N1prog)$, $ElN1(w, d) in D(w) ctx(Sigma, w in N1)$), ) $ == Solution Assuming: #a-enum[ + $t in N1 ctx(Gamma)$ + $M(z) type ctx(Gamma, z in N1)$ + $c in M(star) ctx(Gamma)$ ] The rule E-S) is derivable: $ #prooftree( axiom(label: $a_2$, $M(z) type ctx(Gamma, z in N1)$), axiom(label: $a_3$, $c in M(star) ctx(Gamma)$), rule(n: 2, label: $"E-"N1prog)$, $ElN1(z, c) in M(z) ctx(Gamma, z in N1)$), axiom(label: $a_1$, $t in N1 ctx(Gamma)$), rule(n: 2, label: "sub-ter)", $ElN1(t, c) in M(t) ctx(Gamma)$), ) $
https://github.com/MattiaOldani/Generatore-Turni-Grest
https://raw.githubusercontent.com/MattiaOldani/Generatore-Turni-Grest/master/README.md
markdown
# Generatore turni Grest Questo "progetto" nasce dall'esigenza dei coordinatori del Grest di Capralba di poter organizzare i turni degli animatori in modo rapido e senza perdite di tempo. ## Workflow ### Fase preliminare La fase preliminare di tutto il workflow è il __setup dell'environment__, che viene effettuato modificando il file __`.env`__ dentro la cartella __`generator`__. Devono essere inserite le seguenti variabili d'ambiente: - per quanto riguarda il package `form`: - `FORM_API_KEY`: token fornito da Wufoo per accedere alle API; - `FORM_ENDPOINT`: link al quale trovare le risposte del form; - `ANIMATORS_PER_SLOT`: numero di animatori per turno; - `MAX_NUMBER_DAILY_SLOTS`: massimo numero di turni giornalieri; - `MAX_REPETITION_SAME_SLOT`: massima ripetizione dello stesso turno; - per quanto riguarda il package `telegram`: - `CHANNEL_ID`: canale nel quale verrano inviati i risultati del workflow; - `TELEGRAM_API_KEY`: token fornito da telegram per accedere al bot. ### Prima fase La prima fase è la __creazione del file `data.dat`__, un file che contiene le informazioni su: - __fasce orarie__ da coprire; - __giorni__ nei quali c'è il Grest; - __animatori__ presenti per quella settimana; - __disponibilità__ degli stessi; - __numero di animatori per turno__; - __massima ripetizione dello stesso turno__; - __massimo numero di turni giornalieri__. #### Compilazione del form Ogni animatore compila un [form Wufoo](https://www.wufoo.com/) tra venerdì mattina e domenica pomeriggio, dove inserisce: * __nome__; * __cognome__; * __disponibilità__ per le seguenti fasce orarie: * pre (dalle 08:00 alle 08:45); * mensa (dalle 12:00 alle 13:30); * post (dalle 17:00 alle 18:00). #### Creazione del file data.dat Domenica sera, tramite gli script presenti nel package __`form`__, vengono effettuate delle richieste HTTP alle API fornite da Wufoo per scaricare le risposte date dagli animatori e popolare il file __`data.dat`__. ### Seconda fase La seconda fase è la __creazione del file `turni.pdf`__, il quale conterrà i turni che ogni animatore dovrà svolgere nell nella settimana di Grest. Questa fase è la più lunga poiché richiede una prima fase di __creazione dei turni__, poi una seconda di __formattazione dei risultati__ e infine una di __compilazione__ per la creazione del file `turni.pdf`. #### Creazione dei turni Il file `data.dat`, creato nella fase precedente, viene dato in pasto al programma __`turni.mod`__, che viene compilato tramite __ampl__ da riga di comando. Questa operazione viene eseguita dagli script del package __`template`__, che successivamente catturano l'output di ampl e lo passano alla successiva fase di formattazione. Il risultato di questa operazione è una __matrice di assegnamento tridimensionale__, che indica, per ogni fascia oraria, quale animatore è presente e in quale giorno. #### Formattazione dei risultati La matrice risultante dal programma `turni.mod` viene salvata, assieme ad altre informazioni, all'interno di una classe presente nel package __`utils`__. L'ultimo compito degli script del package `template` e della classe appena citata è quello di popolare il file __`template.typ`__, che contiene il template base per la creazione della tabella dei turni. La tabella contiene tre righe, una per ogni fascia oraria, e cinque colonne, una per ogni giorno di Grest. #### Compilazione Il file `template.typ` viene compilato tramite [__typst__](https://github.com/typst/typst) per generare il file __`turni.pdf`__. Viene preferito il formato `typ` a quello `md` per la sua semplicità e facilità nella compilazione per generare il file PDF dei turni. ### Terza fase La terza e ultima fase è l'__invio__, tramite bot Telegram, dei turni generati alla fase precedente in un canale privato. Questa fase è la più semplice ed è gestita dagli script presenti nel package __`telegram`__, che inviano, oltre al PDF dei turni, anche il numero di turni che ogni animatore deve fare durante la settimana.
https://github.com/Dioprz/Notes
https://raw.githubusercontent.com/Dioprz/Notes/main/Haskell/Haskell_Programming_from_first_principles/Chapter_1/Chapter_1.typ
typst
#let eq = math.attach(sym.equiv, t: sym.alpha) #let eqn = math.attach(sym.equiv.not, t: sym.alpha) = Chapter 1: All You Need is Lambda == Contexto #block( inset: 10pt, )[ _Even the greatest mathematicians, the ones that we would put into our mythology of great mathematicians, had to do a gread deal of leg work in order to get to the solution in the end._ #h(80%) _<NAME>_ ] - El cálculo lambda es la base de la programación funcional. Su desarrollo fue gracia a Alonzo Church en los 30's, y es un modelo de computación equivalente a las máquinas de Turing. (*Nota*: Es, además, capaz de expresar toda la lógica de primer orden y más. A esta área se le llama lógica combinatoria.) - La motivación para estudiar programación funcional en un lenguaje _puro_ como Haskell, es la búsqueda de transparencia referencial. Esta base permite un mayor grado de abstracción y composibilidad. == Calculo lambda - Existen 3 términos o "componentes" en el cálculo lambda: expresiones, variables y abstracciones. + Una _expresión_ puede referirse a cualquiera de los demás términos, o a una combinación de ellos. + Una _variable_ es un nombre asociado a un potencial input de una función. + Una _abstracción_ o _lambda_ es una función. Este término tiene la siguiente estructura: $ lambda x . E $ Donde: - Llamamos _head_ a todo lo que precede al punto, es decir, al símbolo $lambda$ junto a una variable. - Llamamos _body_ a todo lo que sucede al punto, es decir, la expresión E. La variable de la cabeza liga todas las ocurrencias de dicha variable en el cuerpo; por lo que, al aplicar la función a un argumento, cada $x$ en el cuerpo de la función tendrá el valor de tal argumento. - Definimos el término _alpha equivalence_ para referirnos al hecho de qué, dada una abstracción del cálculo lambda, las variables de la cabeza no tienen importancia semántica; por lo que salvo variables libres (noción que se verá más adelante), existe una equivalencia entre términos lambda al reemplazar el nombre de la variable usada en la cabeza, y todas sus ocurrencias ligadas en el cuerpo. $lambda x.x eq lambda z.z$. - Llamamos al proceso de aplicar una función a un argumento _beta reduction_, proceso que consiste en reemplazar todas las instancias del cuerpo ligadas a la variable de la cabeza, por el argumento; para luego remover la cabeza de la abstracción. Ejemplo: $(lambda x.x) 2 => 2$ o $ (lambda x.x) (lambda y.y) \ [x:=(lambda y.y)] \ lambda y.y $ *Nota:* Las aplicaciones en el cálculo lambda son _asociativas a izquierda_. - Introducimos la noción de _variable libre_ como aquellas variables en el cuerpo de una abstracción, que no están en la cabeza. Note que esto introduce un caso sobre el cuál tener cuidado al aplicar alpha equivalencia ya que esta no aplica a variables libres, es decir, $lambda x.x z eqn lambda x. x y$ porque $x$ y $y$ pueden ser expresiones diferentes. Sin embargo $lambda x. x z eq lambda a. a z$ - Decimos que una computación consiste en una expresión lambda inicial (función + input) y una secuencia finita de términos lambda donde cada una representan la beta reducción de la expresión anterior. Esta comptuación termina cuando no hay más heads para evaluar, o más argumentos a los cuáles aplicarlas. - Cada lambda puede tener un solo parámetro y recibir un único argumento. Esto nos permite representar funciones multivariadas como funciones de múltiples heads anidadas. $ lambda x y. x y equiv lambda x.(lambda y. x y) $ Al proceso de convertir una función multivariada en múltiples funciones univariadas anidadas, se le llama _Currying_. Además, la evaluación sobre este tipo de funciones se hace aplicando primero los argumentos a la cabeza (reducible) más a la izquierda, y continuando a partir de ahí. - Haremos alución a la _forma normal_ de una expresión para referirnos a la _beta normal form_, es decir, a la expresión resultante cuando no se puede aplicar ninguna beta reducción a los términos. Esto corresponde en computación a una ejecución completa, o a una expresión completamente evaluada. - Definimos los _combinadores_ como lambdas sin términos libres. Este nombre es natural ya qué, dado un lambda sin variables libres, lo más que puede hacer con las variables de su cabeza es combinarlas. - Es interesante resaltar el hecho de que no todas las expresiones son reducibles a una forma beta normal, ya que _divergen_. Un ejemplo de expresión con este comportamiento es $ (lambda x.x x)(lambda x. x x) $ == Glosario de términos / Lambda abstraction: Es una función anónima o término lambda. / Aplicación: Procedimiento con el que se evalúan o reducen lambdas. Note que son las funciones las que se aplican a los argumentos y no al revés, ya qué, una vez se reemplaza el argumento en la función, la función se _"consume"_. / Normal order: Es la estrategia de evaluación común en el cálculo lambda. Este orden consiste en evaluar primero los lambdas "más afuera y a la izquierda" que se pueda, evaluando los términos anidados una vez que se queda sin argumentos para aplicar. Aunque esta es la estrategia estándar en el cálculo lambda, *no* es la usada por Haskell.
https://github.com/Toniolo-Marco/git-for-dummies
https://raw.githubusercontent.com/Toniolo-Marco/git-for-dummies/main/slides/practice/status-analysis.typ
typst
#import "@preview/touying:0.5.2": * #import themes.university: * #import "@preview/numbly:0.1.0": numbly #import "@preview/fletcher:0.5.1" as fletcher: node, edge #let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide) #import "../components/gh-button.typ": gh_button #import "../components/git-graph.typ": branch_indicator, commit_node, connect_nodes, branch To view the list of files in the staging area and other general information, we can use the command: ```bash ➜ git status On branch main # Current branch No commits yet Changes to be committed: # File in stage (use "git rm --cached <file>..." to unstage) new file: README.md # File added to stage (new file) ``` This is the case where we just created the repository and added the README.md file. --- If, on the other hand, we have modifications in stage and others that are not, we will get: ```bash ➜ git status On branch git-basics # The current branch Your branch is up to date with 'origin/git-basics'. # Last commit is the same as the remote Changes to be committed: # List of staged files (use "git restore --staged <file>..." to unstage) modified: src/git-basics-theory.typ Changes not staged for commit: # List of not staged files (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: src/git-basics-practice.typ Untracked files: # List of Untracked files (use "git add <file>..." to include in what will be committed) src/untracked-file.ops ``` --- Similarly with `git checkout` we can have a coarse summary; in the output we will see only the changed files, without further details and no *untracked* files will be shown. #v(10%) ```bash ➜ git checkout M src/git-basics-practice.typ # Show only modified files M src/git-basics-theory.typ # Your branch is up to date with 'origin/git-basics'. # ``` --- In addition to status to examine all differences between the last commit and current files we can use the command `git status -vv`, short for `git status -v -v`. Alternatively we can use `git diff @` from version 1.8.5, or `git diff HEAD` for earlier versions. #footnote([Neither shows the contents of *untracked* files; `git stastus -vv` just shows that they exist.]) For now, with `HEAD` we refer to the last commit we are in, later we will provide a full description. --- If we have made *changes* to *multiple files*, it would be very useful to have a *fine-grained control* over the *differences* we want to display: - To view the changes made on the individual file we can use the `git diff <filename>` command. - To view all the changes to staged files we can use `git diff --cached` (or its alias `--staged`). Otherwise we can use `git status -v`. - To instead visulize changes the changes of files that are not in stage we can use `git diff`. #footnote([the `--no-index` argument is needed if we are not in a git repository.])
https://github.com/JakMobius/courses
https://raw.githubusercontent.com/JakMobius/courses/main/mipt-os-basic-2024/sem05/main.typ
typst
#import "@preview/polylux:0.3.1": * #import "@preview/cetz:0.2.2" #import "../theme/theme.typ": * #import "../theme/asm.typ": * #import "./utils.typ": * #show: theme #title-slide[ #align(horizon + center)[ = Ассемблер (AArch64) АКОС, МФТИ 10 октября, 2024 ] ] #show: enable-handout #slide(background-image: none)[ #place(horizon + center)[ #set text(weight: "semibold") #let header-index = 3 #table( inset: (x, y) => { if y == 0 { (bottom: 18pt) } else if (y == header-index) { (top: 18pt, bottom: 18pt) } else { 8pt } }, columns: 2, align: (x, y) => { if y == 0 or y == header-index { left } else if x == 0 { right } else { left } }, stroke: (x, y) => { if x == 1 { return (left: 3pt + gray) } else { none } }, table.cell( colspan: 2, [= Регистры AArch64 общего назначения:] ), register("x0-x30"), [64-битные регистры общего назначения], register("w0-w30"), [Их нижние половинки], table.cell( colspan: 2, [= Специальные регистры:], ), register("sp"), [Stack pointer], register("xzr"), [64-битный нулевой регистр], register("wzr"), [32-битный нулевой регистр], register("pc"), [Program counter], register("nzcv"), [Скрытый регистр флагов: переполнение, знак, обнуление.], ) ] #place(center + bottom)[ Двух- и однобайтных регистров, как в x86, нет. ] ] #slide(background-image: none, place-location: horizon)[ #let asm(str) = codebox(lang: "asm", str) #let codeboxes(arr) = { arr.split(" ").map(a => codebox("0x"+ a)).join(" ") } #let table-settings = ( columns: (12cm, 24cm), align: left, inset: (x: 20pt, y: 7pt), stroke: (x, y) => { if(x == 0) { return (right: 2pt + gray) } return none } ) #let asmtable(arr) = { arr.map(a => { ( [#lightasm(a.at(0))], { set text(fill: asmcolors-light.number, weight: "semibold") raw(a.at(1).split(" ").map(a => "0x" + a).join(" ")) } ) }).flatten() } #set text(size: 25pt) == #codebox("x86") : инструкции могут иметь разную длину #table(..table-settings, ..asmtable(( ("nop", "90"), ("mov rbx, rax", "48 89 C3"), ("cmovg rax, r15", "49 0F 4F C7"), ("mov rax, 0xBADBADBEEF", "48 B8 EF BE AD DB BA 00 00 00") )) ) == #codebox("AArch64") : все инструкции равнодлинные #table(..table-settings, ..asmtable(( ("nop", "1F 20 03 D5"), ("mov x1, x0", "E0 03 01 AA"), ("csel x0, x15, x0, gt", "E0 C1 80 9A"), )), [*#raw("???")*], [*#raw("???")*] ) ] #slide(background-image: none)[ #place(horizon)[ #set text(size: 27pt) #let headerbox = (content, index: 0) => { set text(weight: "semibold", size: 40pt) box( stroke: 4pt + cell-color(palette.at(index)).stroke-color, fill: cell-color(palette.at(index)).background-color, inset: 25pt, radius: 20pt )[ #content ] } #table( columns: (45%, 55%), rows: 2, align: (x, y) => { if y == 0 { return center + horizon } if x == 0 { return center + horizon } return left + horizon }, stroke: (x, y) => { if y == 0 { return none } if x == 0 { return (right: 4pt + gray) } return none }, inset: (x, y) => { if y == 0 { return (bottom: 40pt); } if x == 0 { return (right: 40pt); } return (left: 40pt) }, [#headerbox("x86_64", index: 2)], [#headerbox("AArch64", index: 0)], [ #lightasm("mov rax, 0xBADBADBEEF") ], [ #lightasm("mov x8, 0xBEEF") #lightasm("movk x8, 0xDBAD, lsl 16") #lightasm("movk x8, 0xBA, lsl 32") ] ); #v(2em) ] #place(bottom + center)[ #set text(size: 24pt) В AArch64 #semibold([все инструкции 4-байтные]), поэтому загрузка длинных значений в регистры происходит #semibold([поэтапно]). #v(1em) ] ] #slide(background-image: none)[ = Работа с памятью #set block(spacing: 18pt) #headerbox("x86_64")[ #v(0.5em) Многие инструкции принимают аргументы из памяти: #text(size: 20pt)[ #table( columns: 1, stroke: none, inset: (x: 15pt), lightasm("mov rax, [rbx]"), lightasm("add rax, [rbx + 8]"), lightasm("xor [rbx + 8], rax") ) ] Это называется "#link("https://en.wikipedia.org/wiki/Register–memory_architecture")[*Архитектура регистр-память*]". ] #headerbox("AArch64")[ #v(0.5em) Все инструкции работают *только с регистрами*. Для работы с памятью используются специальные инструкции: #text(size: 20pt)[ #table(columns: 2, stroke: (x, y) => { if x == 0 { return (right: 3pt + gray) } }, inset: (x: 15pt), lightasm("ldr x0, [x1]"), [#lightasm("load")#text(size: 18pt)[, из памяти в регистр]], lightasm("str x0, [x1]"), [#lightasm("store")#text(size: 18pt)[, из регистра в память]] ) ] Это называется "*Архитектура регистр-регистр*" (или #link("https://en.wikipedia.org/wiki/Load–store_architecture")[*load-store*]). ] ] #slide(header: [Зачем это всё?], background-image: none, place-location: horizon)[ #table( columns: (50%, 50%), align: (x, y) => { if y == 0 { return center + bottom } return center + top }, stroke: (x, y) => { if y == 0 { return (bottom: 3pt + gray) } return none }, inset: 20pt, [ #set text(size: 30pt) #lightasm("add rax, [rbx + 8]") ], [ #box[ #set text(size: 30pt) #set align(left) #set list(marker: none) - #lightasm("ldr x0, [x1]") - #lightasm("add x0, x0, 8") ] ], [ *Инструкций меньше*, но процессор всё равно разбивает их на простые операции. ], [ Инструкций больше, но *процессор~проще* ]) - *Сокращённый набор инструкций* и load-store архитектура упрощает ядро. - *Инструкции фиксированного размера* проще декодировать. - Проще ядро - *выше эффективность*. ] #slide(background-image: none)[ = Больше упрощений! #let instr(content) = { box(width: 100%, stroke: (right: 3pt + gray), inset: (right: 10pt, y: 3pt), content) } #let cross(content) = { cetz.canvas(length: 1cm, { let lx = -2 let rx = 2 cetz.draw.content((0, 0.1), content) cetz.draw.set-style(stroke: 5pt + black) cetz.draw.line((lx - .02, 1.02), (rx + .02, -1.02)) cetz.draw.line((rx + .02, 1.02), (lx - .02, -1.02)) cetz.draw.set-style(stroke: 4pt + red) cetz.draw.line((lx, 1), (rx, -1)) cetz.draw.line((rx, 1), (lx, -1)) }) } #place(horizon)[ #text(size: 40pt)[ #table( columns: (50%, 50%), stroke: none, align: center, [#cross(lightasm("push rax"))], [#cross(lightasm("pop rax"))] ) ] #align(center)[ = Стек на AArch64 выровнен по 16 байт. #v(1em) #box(width: 20cm)[ #set align(left) - Регистры - *до 8 байт*, #mnemonic("push") и #mnemonic("pop") реализовать не получится; - Сдвигать #register("sp") и записывать стек нужно вручную; - Адрес возврата тоже не запушить; - *Опять нужно переизобретать #mnemonic("call")?* ] ] ] ] #slide(header: [Как работал #mnemonic("call") на x86_64], background-image: none)[ #set text(weight: "semibold", size: 30pt) #place(center + horizon)[ #table( columns: (12cm, 12cm), align: horizon, stroke: none, lightasmtable( ```asm # Вызов функции lea rax, [rip + X] push rax jmp _my_func ``` ), lightasmtable( ```asm # Выход из функции pop rax jmp rax ``` ) ) ] ] #slide(header: ["Эквивалентный" код на AArch64], background-image: none)[ #place(center + horizon, dy: -1cm)[ #set text(size: 30pt) #table( columns: (12cm, 12cm), align: horizon, stroke: none, lightasmtable( ```asm # Вызов функции adr x30, 12 str x30, [sp, -16]! b _my_func ``` ), lightasmtable( ```asm # Выход из функции ldr x30, [sp], 16 br x30 ``` ) ) ] #uncover((beginning: 2))[ #place(bottom, dy: -1cm)[ #set text(size: 20pt) - Сдвиг #register("pc") *всегда будет по 16 байт* (размер инструкций фиксирован); - Но наш аналог #lightasm("push x30") *теряет 8 байт стека* (из-за выравнивания по 16 байт). ] ] ] #slide(header: [Вспомним про стековый фрейм], background-image: none)[ #headerbox("x86_64")[ #place(horizon + center)[ #set text(size: 25pt, weight: "semibold") #cetz.canvas(length: 1cm, { cetz.draw.content((-15, 6.5), (15, -1.6), []); cetz.draw.set-style(stroke: 3pt) cetz.draw.rect( (-15, 5), (15, 2.85), fill: blue.desaturate(95%), stroke: none ) cetz.draw.rect( (-15, 1.8), (15, -0.27), fill: blue.desaturate(95%), stroke: none ) cetz.draw.line( (3.5, 5), (3.5, 2.85), flip: false, stroke: white + 4pt, ) cetz.draw.line( (3.5, 1.8), (3.5, -0.27), flip: false, stroke: white + 4pt, ) cetz.draw.content((4.5, 5), (15, 2.85))[ #set align(horizon) #raw("Создание фрейма") ] cetz.draw.content((4.5, 1.8), (15, -0.27))[ #set align(horizon) #raw("Очистка фрейма") ] }) ] #text(size: 25pt)[ #lightasmtable(numbers: true, ```asm _my_func: push rbp mov rbp, rsp # ... mov rsp, rbp pop rbp ret ``` ) ] ] - В начале вызванной процедуры происходит *ещё один* #mnemonic("push") ; - Перед возвратом происходит *ещё один* #mnemonic("pop") ; - Каждый такой #mnemonic("push") и #mnemonic("pop") в AArch64 *потерял бы лишние 8 байт стека*. ] #focus-slide[ #text(size: 40pt)[*Можно ли не терять стек?*] ] #let cellpos = (i) => { i * 3cm } #let cellright = (i) => { cellpos(i) + 2.5cm / 2 } #let cellleft = (i) => { cellpos(i) - 2.5cm / 2 } #let cellmid = (a, b) => { (cellleft(a) + cellright(b)) / 2 } #let callstep = (palette, insn, i, black: false, width: 1.0) => { let width = 2.5cm + (3cm) * (width - 1) cetz.draw.content((cellleft(i), 1.5), (cellleft(i) + width, -1.5))[ #box(width: 100%, height: 100%, fill: palette.background-color, stroke: 3pt + palette.stroke-color, radius: 10pt)[ #set align(horizon + center) #if type(insn) == str { if black { set text(size: 1.2em, fill: luma(150), weight: "bold") raw(insn) } else { mnemonic(insn) } } else { if black { set text(fill: luma(150)) insn } else { insn } } ] ] } #slide(header: [Этапы вызова функции в x86_64])[ #let outer = cell-color(palette.at(1)) #let inner = cell-color(palette.at(5)) #let body = cell-color(palette.at(0)) #align(horizon + center)[ #cetz.canvas(length: 1cm, { cetz.draw.content((cellleft(0), 4), (cellright(7), -5), []) callstep(outer, "push", 0) callstep(outer, "jmp", 1) callstep(inner, "push", 2) callstep(body, [*Тело функции*], 3.3, width: 1.4) callstep(inner, "pop", 5) callstep(outer, "pop", 6) callstep(outer, "jmp", 7) cetz.draw.set-style(stroke: 3pt) cetz.decorations.flat-brace((cellleft(0), 2), (cellright(1), 2)) cetz.draw.content((cellmid(0, 1), 3), [#mnemonic("call")]) cetz.decorations.flat-brace((cellleft(6), 2), (cellright(7), 2)) cetz.draw.content((cellmid(6, 7), 3), [#mnemonic("ret")]) cetz.draw.set-style(mark: (start: ">")) cetz.draw.bezier((cellmid(2, 2), -2), (cellmid(3, 3), -4), (cellmid(2, 2), -3), (cellmid(3, 3), -3)) cetz.draw.bezier((cellmid(5, 5), -2), (cellmid(4, 4), -4), (cellmid(5, 5), -3), (cellmid(4, 4), -3)) cetz.draw.content((cellmid(2, 5) - 3.5cm, -4.5), (cellmid(2, 5) + 3.5cm, -6.5), [ #set align(center) *Создание / очистка стекового фрейма* ]) cetz.draw.set-style(stroke: 2pt + black, fill: black, mark: (start: none, end: ">")) cetz.draw.line((cellright(2) + 0.3cm, 0), (cellleft(3.5) - 0.9cm, 0)) cetz.draw.line((cellright(3.5) + 1.0cm, 0), (cellleft(5) - 0.2cm, 0)) }) ] ] #slide[ #let push = cell-color(palette.at(1)) #let pop = cell-color(palette.at(1)) #let unneeded = ( stroke-color: luma(150), background-color: none ) #align(horizon + center)[ #cetz.canvas(length: 1cm, { cetz.draw.content((cellleft(0), 4), (cellright(7), -5), []) callstep(push, "push", 0) callstep(unneeded, "jmp", 1, black: true) callstep(push, "push", 2) callstep(unneeded, [*Тело функции*], 3.3, width: 1.4, black: true) callstep(pop, "pop", 5) callstep(pop, "pop", 6) callstep(unneeded, "jmp", 7, black: true) cetz.draw.set-style(stroke: 2pt + black, fill: black, mark: (start: none, end: ">")) cetz.draw.line((cellright(2) + 0.3cm, 0), (cellleft(3.5) - 0.9cm, 0)) cetz.draw.line((cellright(3.5) + 1.0cm, 0), (cellleft(5) - 0.2cm, 0)) }) ] #place(center + horizon, dy: 3cm)[ *Проблема:* каждый #mnemonic("push") использует только половину 16-байтной ячейки стека. *Что, если склеить вместе два #mnemonic("push") и два #mnemonic("pop"), и использовать все 16 байт*? ] ] #slide(header: [Как объединить два #mnemonic("push")?], background-image: none)[ #let push = cell-color(palette.at(1)) #let pop = cell-color(palette.at(1)) #let jmp = cell-color(palette.at(0)) #let unneeded = ( stroke-color: luma(150), background-color: none ) #let rest = { cetz.draw.content((cellleft(0), 2), (cellright(7), -2), []) callstep(unneeded, [*Тело функции*], 3.3, width: 1.4, black: true) callstep(unneeded, "double pop", 5, width: 2, black: true) callstep(unneeded, "jmp", 7, black: true) cetz.draw.set-style(stroke: 2pt + black, fill: black, mark: (start: none, end: ">")) cetz.draw.line((cellright(2) + 0.3cm, 0), (cellleft(3.5) - 0.9cm, 0)) cetz.draw.line((cellright(3.5) + 1.0cm, 0), (cellleft(5) - 0.2cm, 0)) } #align(horizon + center)[ #cetz.canvas(length: 1cm, { rest callstep(push, "double push", 0, width: 2) callstep(jmp, "jmp", 2) }) #align(horizon)[ #box(height: 1em)[#line(stroke: 3pt, length: 40%)] #h(1em) #box(height: 1em)[Или] #h(1em) #box(height: 1em)[#line(stroke: 3pt, length: 40%)] ] #cetz.canvas(length: 1cm, { rest callstep(jmp, "jmp", 0) callstep(push, "double push", 1, width: 2) }) ] #place(left + bottom)[ #uncover((beginning: 2))[ #colbox(color: green)[*Ответ: *] *Оба варианта сработают*, но верхний запретит функции без фрейма. ] ] ] #slide(header: [Объединение #mnemonic("push") и #mnemonic("pop")], background-image: none)[ #set text(size: 30pt) #place(center + horizon, dx: -1.5cm)[ #table( columns: (15cm, 15cm), align: horizon + center, stroke: none, lightasmtable( ```asm _main: adr x30, 12 str x30, [sp, -16]! b _my_func # ... ``` ), lightasmtable( ```asm _my_func: str x29, [sp, -16]! mov x29, sp # Тело функции ldr x29, [sp], 16 ldr x30, [sp], 16 br x30 ``` ) ) ] ] #slide(header: [Объединение #mnemonic("push") и #mnemonic("pop") -- шаг 1 / 2], background-image: none)[ #set text(size: 30pt) #place(center + horizon, dx: -1.5cm)[ #table( columns: (15cm, 15cm), align: horizon + center, stroke: none, lightasmtable( ```asm _main: adr x30, 8 str x30, [sp, -16]! b _my_func # ... ``` ), lightasmtable( ```asm _my_func: str x30, [sp, -16]! str x29, [sp, -16]! mov x29, sp # Тело функции ldr x29, [sp], 16 ldr x30, [sp], 16 br x30 ``` ) ) ] #place(horizon + center)[ #cetz.canvas(length: 1cm, { cetz.draw.set-style(stroke: 4pt + black) cetz.draw.content((-15, 10), (15, -10), []) cetz.draw.bezier((-1, 0.2), (2, 3.6), (2, 0.2), (0, 3.6)) cetz.draw.line((2, 3.6), (2.5, 3.6), mark: (end: ">")) cetz.draw.set-style(stroke: none) cetz.draw.rect((-7.4, 2.3), (-6.5, 1.2), fill: green.transparentize(70%)) cetz.draw.rect((3, 3.3), (13, 4.5), fill: green.transparentize(70%)) cetz.draw.rect((-12, 1.2), (-2, -0.1), fill: red.transparentize(70%)) }) ] ] #slide(header: [Объединение #mnemonic("push") и #mnemonic("pop") -- шаг 2 / 2], background-image: none)[ #set text(size: 30pt) #place(center + horizon, dx: -1.5cm)[ #table( columns: (15cm, 15cm), align: horizon + center, stroke: none, lightasmtable( ```asm _main: adr x30, 8 b _my_func # ... ``` ), lightasmtable( ```asm _my_func: stp x29, x30, [sp, -16]! mov x29, sp # Тело функции ldp x29, x30, [sp], 16 br x30 ``` ) ) ] #place(horizon + center)[ #cetz.canvas(length: 1cm, { cetz.draw.content((-15, 10), (15, -10), []) cetz.draw.set-style(stroke: none) cetz.draw.rect((1.7, 2.2), (14.3, 3.4), fill: green.transparentize(70%)) cetz.draw.rect((1.7, -3.4), (14.3, -2.3), fill: green.transparentize(70%)) }) ] ] #slide(header: [Объединение #mnemonic("push") и #mnemonic("pop") -- шаг 3 / 2], background-image: none)[ #set text(size: 30pt) #place(center + horizon, dx: -1.5cm)[ #table( columns: (15cm, 15cm), align: horizon + center, stroke: none, lightasmtable( ```asm _main: adr x30, 8 b _my_func bl _my_func # ... ``` ), lightasmtable( ```asm _my_func: stp x29, x30, [sp, -16]! mov x29, sp # Тело функции ldp x29, x30, [sp], 16 ret ``` ) ) ] #place(horizon + center)[ #cetz.canvas(length: 1cm, { cetz.draw.content((-15, 10), (15, -10), []) cetz.draw.set-style(stroke: none) cetz.draw.rect((1.6, -2.9), (13.5, -1.7), fill: red.transparentize(70%)) cetz.draw.rect((1.6, -4.1), (13.5, -2.9), fill: green.transparentize(70%)) cetz.draw.rect((-10, 1.2), (-4.2, 0), fill: red.transparentize(70%)) cetz.draw.rect((-10, 2.4), (-3.8, 1.2), fill: red.transparentize(70%)) cetz.draw.rect((-10, 0), (-3.8, -1.2), fill: green.transparentize(70%)) }) ] #place(bottom + center, dy: -0.2cm)[ #set text(size: 20pt) #set block(spacing: 12pt) #mnemonic("bl") и #mnemonic("ret") устроены *значительно проще*, чем #mnemonic("call") и #mnemonic("ret") в x86. Они работают *только с регистрами*. ] ] #slide(background-image: none)[ = Cоглашение о вызове #align(horizon)[ #table(columns: 2, stroke: (x, y) => { if x == 0 { (right: gray + 3pt) } none }, inset: (x: 10pt, y: 7pt), [#register("x0") - #register("x7")], [Передача *аргументов* и *возвращаемого значения*], [#register("x8")], [Указатель на возвращаемую структуру], [#register("x0") - #register("x15")], [*Caller-saved* - регистры], [#register("x16") - #register("x18")], [Intra-procedure-call corruptible registers. Проще говоря - *Caller-saved*.], [#register("x19") - #register("x28"), #register("sp")], [*Callee-saved* - регистры], [#register("x29")], [Frame pointer], [#register("x30")], [Link register, или *адрес возврата*], ) *Аргументы* передаются через первые 8 регистров. Лишнее передаётся через стек. ] ] #focus-slide[ #text(size: 40pt)[*Флаги*] ] #slide(header: [Регистр флагов AArch64], background-image: none, { set align(horizon + center) set text(size: 30pt) let color(i) = { if i < 4 { palette.at(0) } else { black } } box(baseline: 0.65cm + 2cm)[ #table( columns: (1.6cm,) * 4 + (14cm,), rows: 2.0cm, fill: (x, y) => { if y == 1 { return none } cell-color(color(x)).background-color }, stroke: (x, y) => { if y == 1 { return none } 2pt + cell-color(color(x)).stroke-color }, ..("N", "Z", "C", "V", [И еще 28 неиспользуемых бит]).map(a => { if(type(a) == str) { text(weight: "bold", raw(a)) } else { text(size: 20pt, weight: "semibold")[ #a ] } }), ..( [*Negative Condition Flag* -- результат меньше нуля], [*Zero Condition Flag* -- результат нулевой], [*Carry Condition Flag* -- результат беззнаково переполнился], [*Overflow Condition Flag* -- результат знаково переполнился], ).map(a => { set text(size: 16pt) set align(left) move(dx: 0.5cm)[ #rotate(25deg)[ #box(width: 17cm, height: 1cm)[ #a ] ] ] }) ) ] h(0.8em) lightasm("=") register(" NZCV") h(2em) v(4cm) }) #slide(background-image: none)[ = Установка флагов - По умолчанию, инструкции *не меняют регистр флагов*; - Это делают только их *версии с суффиксом #mnemonic("s")*. - Исключения: #mnemonic("CMP") , #mnemonic("CMN") , #mnemonic("CCMP") , #mnemonic("CCMN") , #mnemonic("TST") -- всегда обновляют флаги. = Условные инструкции К некоторым инструкциям можно добавить #link("https://developer.arm.com/documentation/dui0801/a/Condition-Codes/Condition-code-suffixes?lang=en")[условный суффикс]. #table( columns: (4cm, 6cm, 10cm, 8cm), align: (horizon + center,) * 3 + (left, ), stroke: (x, y) => { if x == 0 or x == 1 or x == 2 { (right: 2pt + gray) } none }, inset: (x: 20pt, y: 3pt), [#mnemonic("EQ")], [#codebox("Z")], [Равно, ноль], [Обратный -- #mnemonic("NE")], [#mnemonic("CS"), #mnemonic("HS")], [#codebox("C")], [Беззнаково >=], [Обратный -- #mnemonic("CC"), #mnemonic("LO")], [#mnemonic("MI")], [#codebox("N")], [Меньше нуля], [Обратный -- #mnemonic("PL")], [#mnemonic("VS")], [#codebox("V")], [Переполнение], [Обратный -- #mnemonic("VC")], [#mnemonic("HI")], [#codebox("C && !Z")], [Беззнаково >], [Обратный -- #mnemonic("LS")], [#mnemonic("GE")], [#codebox("N == V")], [Знаково >= ], [Обратный -- #mnemonic("LT")], [#mnemonic("GT")], [#codebox("!Z && N == V")], [Знаково > ], [Обратный -- #mnemonic("LE")], ) ] #slide(header: [Пример: подсчёт $3^n$], background-image: none)[ #align(horizon + center)[ #set text(size: 30pt) #lightasmtable(numbers: true, ```asm _pow3: mov x8, 1 tst x0, x0 b.eq exit loop: add x8, x8, x8, lsl 1 subs x0, x0, 1 b.ne loop exit: mov x0, x8 ret ``` ) ] ] #focus-slide[ #text(size: 40pt)[*Интерактив*] ] #title-slide[ #place(horizon + center)[ = Спасибо за внимание! ] #place( bottom + center, )[ // #qr-code("https://github.com/JakMobius/courses/tree/main/mipt-os-basic-2024", width: 5cm) #box( baseline: 0.2em + 4pt, inset: (x: 15pt, y: 15pt), radius: 5pt, stroke: 3pt + rgb(185, 186, 187), fill: rgb(240, 240, 240), )[ 🔗 #link( "https://github.com/JakMobius/courses/tree/main/mipt-os-basic-2024", )[*github.com/JakMobius/courses/tree/main/mipt-os-basic-2024*] ] ] ]
https://github.com/r8vnhill/apunte-bibliotecas-de-software
https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/Unit1/Kotlin.typ
typst
== Kotlin Kotlin es un lenguaje de programación multiplataforma, desarrollado por JetBrains, que integra características de la programación orientada a objetos y funcional. Es conocido por su sintaxis concisa y capacidad para compilar no solo en JavaScript (JS) y WebAssembly (WASM) para ejecución en navegadores, sino también en Java Virtual Machine (JVM) para servidores y aplicaciones Android, así como en LLVM para aplicaciones de escritorio y sistemas embebidos. En este curso, nos centraremos en la programación en Kotlin para la JVM, que es la plataforma más utilizada para este lenguaje. Sin embargo, los conceptos y técnicas que aprenderás son ampliamente aplicables a otras plataformas que soporta Kotlin y pueden ser útiles incluso en el aprendizaje de otros lenguajes de programación modernos. === A Taste of Kotlin A continuación, te presentamos un ejemplo simple de Kotlin para darte una idea de cómo se ve y se siente el lenguaje. ```kotlin data class Person( // (1) val name: String, val age: Int? = null // (2) ) fun main() { val persons = listOf( // (3) Person("<NAME>"), Person("<NAME>", age = 43) // (4) ) val youngest = persons.minByOrNull { it.age ?: Int.MAX_VALUE } // (5) println("The youngest is: $youngest") // (6) } // Output: The youngest is: Person(name=<NAME>, age=43) ``` 1. Declara una clase de datos `Person` con dos propiedades: `name` de tipo `String` y `age` de tipo `Int` opcional. 2. La propiedad `age` tiene un valor predeterminado de `null`. 3. Declara una lista inmutable de personas con dos elementos. 4. El segundo elemento de la lista tiene un valor de edad nombrado de 43. 5. Encuentra la persona más joven en la lista utilizando `minByOrNull` y el operador de elvis `?:`. 6. Interpola la variable `youngest` en una cadena y la imprime en la consola.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1E2C0.typ
typst
Apache License 2.0
#let data = ( ("WANCHO LETTER AA", "Lo", 0), ("WANCHO LETTER A", "Lo", 0), ("WANCHO LETTER BA", "Lo", 0), ("WANCHO LETTER CA", "Lo", 0), ("WANCHO LETTER DA", "Lo", 0), ("WANCHO LETTER GA", "Lo", 0), ("WANCHO LETTER YA", "Lo", 0), ("WANCHO LETTER PHA", "Lo", 0), ("WANCHO LETTER LA", "Lo", 0), ("WANCHO LETTER NA", "Lo", 0), ("WANCHO LETTER PA", "Lo", 0), ("WANCHO LETTER TA", "Lo", 0), ("WANCHO LETTER THA", "Lo", 0), ("WANCHO LETTER FA", "Lo", 0), ("WANCHO LETTER SA", "Lo", 0), ("WANCHO LETTER SHA", "Lo", 0), ("WANCHO LETTER JA", "Lo", 0), ("WANCHO LETTER ZA", "Lo", 0), ("WANCHO LETTER WA", "Lo", 0), ("WANCHO LETTER VA", "Lo", 0), ("WANCHO LETTER KA", "Lo", 0), ("WANCHO LETTER O", "Lo", 0), ("WANCHO LETTER AU", "Lo", 0), ("WANCHO LETTER RA", "Lo", 0), ("WANCHO LETTER MA", "Lo", 0), ("WANCHO LETTER KHA", "Lo", 0), ("WANCHO LETTER HA", "Lo", 0), ("WANCHO LETTER E", "Lo", 0), ("WANCHO LETTER I", "Lo", 0), ("WANCHO LETTER NGA", "Lo", 0), ("WANCHO LETTER U", "Lo", 0), ("WANCHO LETTER LLHA", "Lo", 0), ("WANCHO LETTER TSA", "Lo", 0), ("WANCHO LETTER TRA", "Lo", 0), ("WANCHO LETTER ONG", "Lo", 0), ("WANCHO LETTER AANG", "Lo", 0), ("WANCHO LETTER ANG", "Lo", 0), ("WANCHO LETTER ING", "Lo", 0), ("WANCHO LETTER ON", "Lo", 0), ("WANCHO LETTER EN", "Lo", 0), ("WANCHO LETTER AAN", "Lo", 0), ("WANCHO LETTER NYA", "Lo", 0), ("WANCHO LETTER UEN", "Lo", 0), ("WANCHO LETTER YIH", "Lo", 0), ("WANCHO TONE TUP", "Mn", 230), ("WANCHO TONE TUPNI", "Mn", 230), ("WANCHO TONE KOI", "Mn", 230), ("WANCHO TONE KOINI", "Mn", 230), ("WANCHO DIGIT ZERO", "Nd", 0), ("WANCHO DIGIT ONE", "Nd", 0), ("WANCHO DIGIT TWO", "Nd", 0), ("WANCHO DIGIT THREE", "Nd", 0), ("WANCHO DIGIT FOUR", "Nd", 0), ("WANCHO DIGIT FIVE", "Nd", 0), ("WANCHO DIGIT SIX", "Nd", 0), ("WANCHO DIGIT SEVEN", "Nd", 0), ("WANCHO DIGIT EIGHT", "Nd", 0), ("WANCHO DIGIT NINE", "Nd", 0), (), (), (), (), (), ("WANCHO NGUN SIGN", "Sc", 0), )
https://github.com/frosty884/vex-typst-notebook
https://raw.githubusercontent.com/frosty884/vex-typst-notebook/main/main.typ
typst
#import "template.typ": * #show: notebook.with( title: "Engineering Notebook 2023-2024", authors: "<NAME>, <NAME>", organization: "Illinois Institute of Technology", location: "Chicago, Illinois", header: "header.jpg", ) // We generated the example code below so you can see how // your document will look. Go ahead and replace it with // your own content! #table( columns: (auto, auto, auto), inset: 10pt, align: horizon, [], [*Area*], [*Parameters*], [], $ pi h (D^2 - d^2) / 4 $, [ $h$: height \ $D$: outer radius \ $d$: inner radius ], [], $ sqrt(2) / 12 a^3 $, [$a$: edge length] ) #counter(heading).display() = Introduction #lorem(60) == In this paper #lorem(20) === Contributions #lorem(40) = Related Work #lorem(1400)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/colorful-boxes/1.0.0/lib.typ
typst
Apache License 2.0
#let colorbox(title: "title", color: none, radius: 2pt, width: auto, body) = { let stroke-color = luma(70) let background-color = white if color == "red" { stroke-color = rgb(237, 32, 84) background-color = rgb(253, 228, 224) } else if color == "green" { stroke-color = rgb(102, 174, 62) background-color = rgb(235, 244, 222) } else if color == "blue" { stroke-color = rgb(29, 144, 208) background-color = rgb(232, 246, 253) } return box( fill: background-color, stroke: 2pt + stroke-color, radius: radius, width: width )[ #block( fill: stroke-color, inset: 8pt, radius: (top-left: radius, bottom-right: radius), )[ #text(fill: white, weight: "bold")[#title] ] #block( width: 100%, inset: (x: 8pt, bottom: 8pt) )[ #body ] ] } #let slanted-background(color: black, body) = { set text(fill: white, weight: "bold") style(styles => { let size = measure(body, styles) let inset = 8pt [#block()[ #polygon( fill: color, (0pt, 0pt), (0pt, size.height + (2*inset)), (size.width + (2*inset), size.height + (2*inset)), (size.width + (2*inset) + 6pt, 0cm) ) #place(center + top, dy: size.height, dx: -3pt)[#body] ]] }) } #let slanted-colorbox(title: "title", color: none, radius: 0pt, width: auto, body) = { let stroke-color = luma(70) let background-color = white if color == "red" { stroke-color = rgb(237, 32, 84) background-color = rgb(253, 228, 224) } else if color == "green" { stroke-color = rgb(102, 174, 62) background-color = rgb(235, 244, 222) } else if color == "blue" { stroke-color = rgb(29, 144, 208) background-color = rgb(232, 246, 253) } return box( fill: background-color, stroke: 2pt + stroke-color, radius: radius, width: width )[ #slanted-background(color: stroke-color)[#title] #block( width: 100%, inset: (top: -2pt, x: 10pt, bottom: 10pt) )[ #body ] ] } #let outlinebox(title: "title",color: none, width: 100%, radius: 2pt, centering: false, body) = { let stroke-color = luma(70) if color == "red" { stroke-color = rgb(237, 32, 84) } else if color == "green" { stroke-color = rgb(102, 174, 62) } else if color == "blue" { stroke-color = rgb(29, 144, 208) } return block( stroke: 2pt + stroke-color, radius: radius, width: width, above: 26pt, )[ #if centering [ #place(top + center, dy: -12pt)[ #block( fill: stroke-color, inset: 8pt, radius: radius, )[ #text(fill: white, weight: "bold")[#title] ] ] ] else [ #place(top + start, dy: -12pt, dx:20pt)[ #block( fill: stroke-color, inset: 8pt, radius: radius, )[ #text(fill: white, weight: "bold")[#title] ] ] ] #block( width: 100%, inset: (top:20pt, x: 10pt, bottom: 10pt) )[ #body ] ] } #let stickybox(rotation: 0deg, width: 100%, body) = { let sticky-yellow = rgb(255, 240, 172) return rotate(rotation)[ #block( fill: sticky-yellow, width: width )[ #place(top + center, dy: -10pt)[ #block( fill: rgb(0,0,0,25), width: 1.5in, height: 20pt, ) ] #block( width: 100%, inset: (top: 18pt, x: 8pt, bottom: 8pt) )[ #body ] ] ] }
https://github.com/profetia/me
https://raw.githubusercontent.com/profetia/me/main/src/lib.typ
typst
#import "option.typ" as option #import "option_ext.typ" as option_ext
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-0D80.typ
typst
Apache License 2.0
#let data = ( (), ("SINHALA SIGN CANDRABINDU", "Mn", 0), ("SINHALA SIGN ANUSVARAYA", "Mc", 0), ("SINHALA SIGN VISARGAYA", "Mc", 0), (), ("SINHALA LETTER AYANNA", "Lo", 0), ("SINHALA LETTER AAYANNA", "Lo", 0), ("SINHALA LETTER AEYANNA", "Lo", 0), ("SINHALA LETTER AEEYANNA", "Lo", 0), ("SINHALA LETTER IYANNA", "Lo", 0), ("SINHALA LETTER IIYANNA", "Lo", 0), ("SINHALA LETTER UYANNA", "Lo", 0), ("SINHALA LETTER UUYANNA", "Lo", 0), ("SINHALA LETTER IRUYANNA", "Lo", 0), ("SINHALA LETTER IRUUYANNA", "Lo", 0), ("SINHALA LETTER ILUYANNA", "Lo", 0), ("SINHALA LETTER ILUUYANNA", "Lo", 0), ("SINHALA LETTER EYANNA", "Lo", 0), ("SINHALA LETTER EEYANNA", "Lo", 0), ("SINHALA LETTER AIYANNA", "Lo", 0), ("SINHALA LETTER OYANNA", "Lo", 0), ("SINHALA LETTER OOYANNA", "Lo", 0), ("SINHALA LETTER AUYANNA", "Lo", 0), (), (), (), ("SINHALA LETTER ALPAPRAANA KAYANNA", "Lo", 0), ("SINHALA LETTER MAHAAPRAANA KAYANNA", "Lo", 0), ("SINHALA LETTER ALPAPRAANA GAYANNA", "Lo", 0), ("SINHALA LETTER MAHAAPRAANA GAYANNA", "Lo", 0), ("SINHALA LETTER KANTAJA NAASIKYAYA", "Lo", 0), ("SINHALA LETTER SANYAKA GAYANNA", "Lo", 0), ("SINHALA LETTER ALPAPRAANA CAYANNA", "Lo", 0), ("SINHALA LETTER MAHAAPRAANA CAYANNA", "Lo", 0), ("SINHALA LETTER ALPAPRAANA JAYANNA", "Lo", 0), ("SINHALA LETTER MAHAAPRAANA JAYANNA", "Lo", 0), ("SINHALA LETTER TAALUJA NAASIKYAYA", "Lo", 0), ("SINHALA LETTER TAALUJA SANYOOGA NAAKSIKYAYA", "Lo", 0), ("SINHALA LETTER SANYAKA JAYANNA", "Lo", 0), ("SINHALA LETTER ALPAPRAANA TTAYANNA", "Lo", 0), ("SINHALA LETTER MAHAAPRAANA TTAYANNA", "Lo", 0), ("SINHALA LETTER ALPAPRAANA DDAYANNA", "Lo", 0), ("SINHALA LETTER MAHAAPRAANA DDAYANNA", "Lo", 0), ("SINHALA LETTER MUURDHAJA NAYANNA", "Lo", 0), ("SINHALA LETTER SANYAKA DDAYANNA", "Lo", 0), ("SINHALA LETTER ALPAPRAANA TAYANNA", "Lo", 0), ("SINHALA LETTER MAHAAPRAANA TAYANNA", "Lo", 0), ("SINHALA LETTER ALPAPRAANA DAYANNA", "Lo", 0), ("SINHALA LETTER MAHAAPRAANA DAYANNA", "Lo", 0), ("SINHALA LETTER DANTAJA NAYANNA", "Lo", 0), (), ("SINHALA LETTER SANYAKA DAYANNA", "Lo", 0), ("SINHALA LETTER ALPAPRAANA PAYANNA", "Lo", 0), ("SINHALA LETTER MAHAAPRAANA PAYANNA", "Lo", 0), ("SINHALA LETTER ALPAPRAANA BAYANNA", "Lo", 0), ("SINHALA LETTER MAHAAPRAANA BAYANNA", "Lo", 0), ("SINHALA LETTER MAYANNA", "Lo", 0), ("SINHALA LETTER <NAME>", "Lo", 0), ("SINHALA LETTER YAYANNA", "Lo", 0), ("SINHALA LETTER RAYANNA", "Lo", 0), (), ("SINHALA LETTER <NAME>", "Lo", 0), (), (), ("SINHALA LETTER VAYANNA", "Lo", 0), ("SINHALA LETTER <NAME>", "Lo", 0), ("SINHALA LETTER <NAME>", "Lo", 0), ("SINHALA LETTER <NAME>", "Lo", 0), ("SINHALA LETTER HAYANNA", "Lo", 0), ("SINHALA LETTER <NAME>", "Lo", 0), ("SINHALA LETTER FAYANNA", "Lo", 0), (), (), (), ("SINHALA SIGN AL-LAKUNA", "Mn", 9), (), (), (), (), ("SINHALA VOWEL SIGN AELA-PILLA", "Mc", 0), ("SINHALA VOWEL SIGN KETTI AEDA-PILLA", "Mc", 0), ("SINHALA VOWEL SIGN DIGA AEDA-PILLA", "Mc", 0), ("SINHALA VOWEL SIGN KETTI IS-PILLA", "Mn", 0), ("SINHALA VOWEL SIGN DIGA IS-PILLA", "Mn", 0), ("SINHALA VOWEL SIGN KETTI PAA-PILLA", "Mn", 0), (), ("SINHALA VOWEL SIGN DIGA PAA-PILLA", "Mn", 0), (), ("SINHALA VOWEL SIGN GAETTA-PILLA", "Mc", 0), ("SINHALA VOWEL SIGN KOMBUVA", "Mc", 0), ("SINHALA VOWEL SIGN DIGA KOMBUVA", "Mc", 0), ("SINHALA VOWEL SIGN KOMBU DEKA", "Mc", 0), ("SINHALA VOWEL SIGN KOMBUVA HAA AELA-PILLA", "Mc", 0), ("SINHALA VOWEL SIGN KOMBUVA HAA DIGA AELA-PILLA", "Mc", 0), ("SINHALA VOWEL SIGN KOMBUVA HAA GAYANUKITTA", "Mc", 0), ("SINHALA VOWEL SIGN GAYANUKITTA", "Mc", 0), (), (), (), (), (), (), ("SINHALA LITH DIGIT ZERO", "Nd", 0), ("SINHALA LITH DIGIT ONE", "Nd", 0), ("SINHALA LITH DIGIT TWO", "Nd", 0), ("SINHALA LITH DIGIT THREE", "Nd", 0), ("SINHALA LITH DIGIT FOUR", "Nd", 0), ("SINHALA LITH DIGIT FIVE", "Nd", 0), ("SINHALA LITH DIGIT SIX", "Nd", 0), ("SINHALA LITH DIGIT SEVEN", "Nd", 0), ("SINHALA LITH DIGIT EIGHT", "Nd", 0), ("SINHALA LITH DIGIT NINE", "Nd", 0), (), (), ("SINHALA VOWEL SIGN DIGA GAETTA-PILLA", "Mc", 0), ("SINHALA VOWEL SIGN DIGA GAYANUKITTA", "Mc", 0), ("SINHALA PUNCTUATION KUNDDALIYA", "Po", 0), )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/space-06.typ
typst
Other
// Test that trailing space does not force a line break. LLLLLLLLLLLLLLLLLL R _L_
https://github.com/felsenhower/kbs-typst
https://raw.githubusercontent.com/felsenhower/kbs-typst/master/examples/03.typ
typst
MIT License
$ H psi_n = E_n psi_n \ H = - hbar/(2m) dv(,x,2) + 1/2 m omega^2 x^2 \ E_n = hbar omega (n + 1/2) \ braket(psi_n, psi_m) = delta_(n m) $
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.1.2/src/lib/decorations.typ
typst
Apache License 2.0
#import "../vector.typ" #import "../matrix.typ" #import "../util.typ" #import "../draw.typ": * /// Rotates the vector 'ab' around 'a' and scales it to 'len', returns the absolute point 'c'. #let _rotate-around(a, b, angle: 90deg, len: auto) = { let rel = vector.sub(b, a) let rotated = util.apply-transform(matrix.transform-rotate-z(angle), rel) let scaled = if len == auto { rotated } else { vector.scale(vector.norm(rotated), len) } return vector.add(a, scaled) } #let brace-default-style = ( amplitude: .7, pointiness: 15deg, content-offset: .3, ) /// Draw a curly brace between two points. /// /// *Style root:* `brace`. /// /// *Additional styles keys:* /// / amplitude (number): Determines how much the brace rises above the base line. /// / pointiness (angle): How pointy the spike should be. /// #0deg or #0 for maximum pointiness, #90deg or #1 for minimum. /// / content-offset (number): Offset of the `content` anchor from the spike. /// /// *Anchors:* /// / start: Where the brace starts, same as the `start` parameter. /// / end: Where the brace end, same as the `end` parameter. /// / spike: Point of the spike, halfway between `start` and `end` and shifted /// by `amplitude` towards the pointing direction. /// / content: Point to place content/text at, in front of the spike. /// / center: Center of the enclosing rectangle. /// / (a-i): Debug points `a` through `i`. /// /// - start (coordinate): Start point /// - end (coordinate): End point /// - flip (bool): Flip the brace around, same as swapping the start and end points /// - debug (bool): Show debug lines and points /// - name (string, none): Element name /// - ..style (style): Style attributes #let brace( start, end, flip: false, debug: false, name: none, ..style, ) = { // validate coordinates let t = (start, end).map(coordinate.resolve-system) // flipping is achieved by swapping the start and end points, the parameter is just for convenience if flip { (start, end) = (end, start) } group(name: name, ctx => { let style = util.merge-dictionary(brace-default-style, styles.resolve(ctx.style, style.named(), root: "brace")) let amplitude = style.amplitude assert( type(amplitude) in (int, float), message: "amplitude must be a number", ) // get pointiness from styles let pointiness = style.pointiness assert( (type(pointiness) in (int, float) and pointiness >= 0 and pointiness <= 1 or type(pointiness) == angle and pointiness >= 0deg and pointiness <= 90deg), message: "pointiness must be a factor between 0 and 1 or an angle between 0deg and 90deg", ) let pointiness = if type(pointiness) == angle { pointiness } else { pointiness * 90deg } let content-offset = style.content-offset assert( type(content-offset) in (int, float), message: "content-offset must be a number", ) // 'abcd' is a rectangle with the base line 'ab' and the height 'amplitude' let a = start let b = end let c = (_rotate-around.with(len: amplitude, angle: -90deg), b, a) let d = (_rotate-around.with(len: amplitude, angle: +90deg), a, b) if debug { line(a, b, stroke: red) line(b, c, stroke: blue) line(c, d, stroke: olive) line(d, a, stroke: yellow) } // 'ef' is the perpendicular line in the center of that rectangle, with length 'amplitude' let e = (a, .5, b) let f = (c, .5, d) if debug { line(e, f, stroke: eastern) } // 'g' and 'h' are the control points for the middle spike let g = (_rotate-around.with(angle: -pointiness), f, e) let h = (_rotate-around.with(angle: +pointiness), f, e) if debug { line(f, g, stroke: purple) line(f, h, stroke: orange) } // 'i' is the point where the content should be placed. It is offset from the spike (point 'f') // by 'content-offset' in the direction the spike is pointing let i = ((a, b) => { let rel = vector.sub(b, a) let scaled = vector.scale(vector.norm(rel), vector.len(rel) + content-offset) return vector.add(a, scaled) }, e, f) let points = (a: a, b: b, c: c, d: d, e: e, f: f, g: g, h: h, i: i) // combine the two bezier curves using 'merge-path' and apply styling merge-path({ bezier(a, f, d, g) bezier(f, b, h, c) }, ..style) // define some named anchors anchor("spike", f) anchor("content", i) anchor("start", a) anchor("end", b) anchor("center", (e, .5, f)) // define anchors for all points for (name, point) in points { anchor(name, point) } // label all points in debug mode if debug { for (name, point) in points { content(point, box(fill: luma(240), inset: .5pt, text(6pt, raw(name)))) } } }) // move to end point so the current position after this is the end position move-to(end) }
https://github.com/Edubmstr/typst_public
https://raw.githubusercontent.com/Edubmstr/typst_public/main/supercharged-dhbw1/lib.typ
typst
#import "@preview/codelst:2.0.1": * #import "acronym-lib.typ": init-acronyms, print-acronyms, acr, acrpl, acrs, acrspl, acrl, acrlpl, acrf, acrfpl #import "titlepage.typ": * #import "confidentiality-statement.typ": * #import "declaration-of-authorship.typ": * #import "check-attributes.typ": * // Workaround for the lack of an `std` scope. #let std-bibliography = bibliography #let supercharged-dhbw( title: none, authors: (:), language: none, at-university: none, confidentiality-marker: (display: false), type-of-thesis: "Praxisarbeit 1", type-of-degree: none, type-of-degree-specification: none, time-of-thesis: none, show-confidentiality-statement: true, show-declaration-of-authorship: true, show-table-of-contents: true, show-acronyms: true, show-list-of-figures: true, show-list-of-tables: true, show-code-snippets: true, show-appendix: false, show-abstract: true, show-header: true, show-title-in-header: true, show-left-logo-in-header: true, show-right-logo-in-header: true, show-header-divider: true, numbering-alignment: center, toc-depth: 3, acronym-spacing: 5em, abstract: none, appendix: none, acronyms: none, confidentiality-statement-content: none, university: none, university-location: none, city: none, supervisor: (:), date: none, date-format: "[day].[month].[year]", bibliography: none, bib-style: "ieee", logo-left: image("sap-logo.png"), logo-right: image("dhbw.svg"), logo-size-ratio: "1:1", body, ) = { // check required attributes check-attributes( title, authors, language, at-university, confidentiality-marker, type-of-thesis, type-of-degree, show-confidentiality-statement, show-declaration-of-authorship, show-table-of-contents, show-acronyms, show-list-of-figures, show-list-of-tables, show-code-snippets, show-appendix, show-abstract, show-header, show-title-in-header, show-left-logo-in-header, show-right-logo-in-header, show-header-divider, numbering-alignment, toc-depth, acronym-spacing, abstract, appendix, acronyms, university, university-location, supervisor, date, city, bibliography, bib-style, logo-left, logo-right, logo-size-ratio, ) // set the document's basic properties set document(title: title, author: authors.map(author => author.name)) let many-authors = authors.len() > 3 init-acronyms(acronyms) // define logo size with given ration let left-logo-height = 2.4cm // left logo is always 2.4cm high let right-logo-height = 2.4cm // right logo defaults to 1.2cm but is adjusted below let logo-ratio = logo-size-ratio.split(":") if (logo-ratio.len() == 2) { right-logo-height = right-logo-height * (float(logo-ratio.at(1)) / float(logo-ratio.at(0))) } // save heading and body font families in variables let body-font = "Open Sans" let heading-font = "Montserrat" // customize look of figure set figure.caption(separator: [ --- ], position: bottom) // set body font family set text(font: body-font, lang: language, 12pt) show heading: set text(weight: "semibold", font: heading-font) //heading numbering set heading(numbering: "1.") // set link style for links that are not acronyms show link: it => if ( str(it.dest) not in (acronyms.keys().map(acr => ("acronym-" + acr))) ) { text(fill: blue, it) } else { it } show heading.where(level: 1): it => { pagebreak() v(2em) + it + v(1em) } show heading.where(level: 2): it => v(1em) + it + v(0.5em) show heading.where(level: 3): it => v(0.5em) + it + v(0.25em) titlepage( authors, date, heading-font, language, left-logo-height, logo-left, logo-right, many-authors, right-logo-height, supervisor, title, type-of-degree, type-of-degree-specification, type-of-thesis, time-of-thesis, university, university-location, at-university, date-format, show-confidentiality-statement, confidentiality-marker, ) set page( margin: (top: 8em, bottom: 8em), header: { if (show-header) { grid( columns: (1fr, auto), align: (left, right), gutter: 2em, if (show-title-in-header) { emph(align(center + horizon, text(size: 10pt, title))) }, stack(dir: ltr, spacing: 1em, if (show-left-logo-in-header and logo-left != none) { set image(height: left-logo-height / 2) logo-left }, if (show-right-logo-in-header and logo-right != none) { set image(height: right-logo-height / 2) logo-right } ) ) v(-0.75em) if (show-header-divider) { line(length: 100%) } } } ) // set page numbering to roman numbering set page( numbering: "I", number-align: numbering-alignment, ) counter(page).update(1) if (not at-university and show-confidentiality-statement) { confidentiality-statement( authors, title, confidentiality-statement-content, university, university-location, date, language, many-authors, date-format ) } if (show-declaration-of-authorship) { declaration-of-authorship( authors, title, date, language, many-authors, at-university, city, date-format ) } show outline.entry.where( level: 1, ): it => { v(18pt, weak: true) strong(it) } context { let elems = query(figure.where(kind: image), here()) let count = elems.len() if (show-list-of-figures and count > 0) { outline( title: [#heading(level: 3)[#if (language == "de") { [Abbildungsverzeichnis] } else { [List of Figures] }]], target: figure.where(kind: image), ) } } context { let elems = query(figure.where(kind: table), here()) let count = elems.len() if (show-list-of-tables and count > 0) { outline( title: [#heading(level: 3)[#if (language == "de") { [Tabellenverzeichnis] } else { [List of Tables] }]], target: figure.where(kind: table), ) } } context { let elems = query(figure.where(kind: raw), here()) let count = elems.len() if (show-code-snippets and count > 0) { outline( title: [#heading(level: 3)[#if (language == "de") { [Codeverzeichnis] } else { [Code Snippets] }]], target: figure.where(kind: raw), ) } } if (show-table-of-contents) { outline(title: [#if (language == "de") { [Inhaltsverzeichnis] } else { [Table of Contents] }], indent: auto, depth: toc-depth) } if (show-acronyms and acronyms != none and acronyms.len() > 0) { print-acronyms(language, acronym-spacing) } set par(justify: true, leading: 1em) set block(spacing: 2em) if (show-abstract and abstract != none) { align(center + horizon, heading(level: 1, numbering: none)[Abstract]) text(abstract) } // reset page numbering and set to arabic numbering set page( numbering: "1", footer: context align(numbering-alignment, numbering( "1 / 1", ..counter(page).get(), ..counter(page).at(<end>), )) ) counter(page).update(1) body [#metadata(none)<end>] // reset page numbering and set to alphabetic numbering set page( numbering: "a", footer: context align(numbering-alignment, numbering( "a", ..counter(page).get(), )) ) counter(page).update(1) // Display bibliography. if bibliography != none { set std-bibliography(title: [#if (language == "de") { [Literatur] } else { [References] }], style: bib-style) bibliography } if (show-appendix and appendix != none) { heading(level: 1, numbering: none)[#if (language == "de") { [Anhang] } else { [Appendix] }] appendix } }
https://github.com/sitandr/conchord
https://raw.githubusercontent.com/sitandr/conchord/main/tabs/gen.typ
typst
MIT License
#let to-int(s) = { if s.matches(regex("^\d+$")).len() != 0 { int(s) } else { panic("Bad number: " + s) } } #let parse-note(n, s-num: 6) = { if n == "p" { return () } return n.split("+").map( n => { let cont = if n.starts-with("^") { "^" } else if n.starts-with("`") { "`" } else { none } if cont != none { n = n.slice(1) } let bend = n.split("b") let bend-return = false if bend.len() > 1 { n = bend.at(0) bend = bend.at(-1) if bend.ends-with("r") { bend = bend.slice(0, -1) bend-return = true } } else { bend = none } let vib = n.ends-with("v") if vib {n = n.slice(0, -1)} let coords = n.split("/").map(to-int) if coords.len() != 2 { panic("Specify fret and string numbers separated by `/`: " + n) } if coords.at(1) > s-num { panic("Too large string number: " + n.at(1)) } let res = (fret: coords.at(0), string: coords.at(1)) res.connect = cont res.bend = bend res.bend-return = bend-return res.vib = vib return res }, ) } #let gen(s, s-num: 6) = { if type(s) == "content" { s = s.text } let bars = () let cur-bar = () let cur-dur = 2 let code-mode = false let code = () for (n, s,) in s.split(regex("\s+")).zip(s.matches(regex("\s+")) + ("",)) { if n == "##" and not code-mode { code-mode = true continue } if code-mode { if n.starts-with("##") { code-mode = false cur-bar.push(("##", n.slice(2), code.join())) code = () continue } code.push(n) code.push(s.text) continue } if n == "<" { cur-bar.push(n) continue } if n == ":|" { cur-bar.push(":") cur-bar.push("|") cur-bar.push("<") cur-bar.push("||") bars.push(cur-bar) cur-bar = () n = n.slice(2) continue } if n == "|:" { cur-bar.push("||") cur-bar.push("|") cur-bar.push(":") bars.push(cur-bar) cur-bar = () n = n.slice(2) continue } if n == "||" { cur-bar.push("|") cur-bar.push("<") cur-bar.push("||") bars.push(cur-bar) cur-bar = () continue } if n == "|" { cur-bar.push("|") bars.push(cur-bar) cur-bar = () continue } if n == "\\" { //cur-bar.push("|") cur-bar.push("\\") bars.push(cur-bar) cur-bar = () continue } if n == "" { continue } let note-and-dur = n.split("-") if note-and-dur.len() > 2 or note-and-dur == 0 { panic("Specify one duration per note") } if note-and-dur.len() == 2 { let dur = note-and-dur.at(1) let mul = 0.0 while dur.ends-with(".") { mul -= calc.log(1.5) / calc.log(2) dur = dur.slice(0, -1) } cur-dur = to-int(dur) + mul } cur-bar.push((notes: parse-note(note-and-dur.at(0), s-num: s-num), duration: cur-dur)) } if cur-bar.len() > 0 { bars.push(cur-bar) } if bars.len() > 0 and bars.at(-1) != ("\\") { bars.push(("\\",)) } return bars }
https://github.com/jneug/typst-ccicons
https://raw.githubusercontent.com/jneug/typst-ccicons/main/docs/ccicons-manual.typ
typst
MIT License
#import "../src/ccicons.typ" as ccicons: * // Official creative commons color palette #let cctomato = rgb("#ed592f") #let ccdarkslategray = rgb("#333333") #let ccgold = rgb("#efbe00") #let ccorange = rgb("#fb7729") #let ccforestgreen = rgb("#04a635") #let ccdarkturquoise = rgb("#05b5da") #let ccdarkslateblue = rgb("#3c5c99") #let color-header = ccdarkturquoise.lighten(50%) #let color-default = ccgold.lighten(90%) #let color-muted = ccforestgreen.lighten(90%) #let color-empty = cctomato.lighten(50%) #let pkg = toml("../typst.toml").package #let ccico = text(cctomato, pkg.name) #let command-map = ( ccAttribution: "by", ccShareAlike: "sa", ccNoDerivatives: "nd", ccNonCommercial: "nc", ccNonCommercialEU: "nceu", ccNonCommercialJP: "ncjp", ccPublicDomain: "pd", ccZero: "zero", ccShare: "share", ccRemix: "remix", ccSampling: "sampling", ccSamplingPlus: "sampling.plus", cc-by: "cc-by", cc-by-sa: "cc-by-sa", cc-by-nd: "cc-by-nd", cc-by-nc: "cc-by-nc", cc-by-nc-sa: "cc-by-nc-sa", cc-by-nc-sa-eu: "cc-by-nceu-sa", cc-by-nc-sa-jp: "cc-by-ncjp-sa", cc-by-nc-nd: "cc-by-nc-nd", cc-by-nc-nd-eu: "cc-by-nceu-nd", cc-by-nc-nd-jp: "cc-by-ncjp-nd", cc-zero: "cc-zero", cc-pd: "cc-pd", ) // Page setup #set page(paper: "a4") #set text(font: ("Source Sans Pro", "Roboto"), 12pt, ccdarkslategray) #show link: set text(ccorange) #set heading(numbering: "1.1.a") #show heading: it => { set text(fill: cctomato) block( width: 100%, inset: (bottom: .33em), stroke: (bottom: .6pt + ccdarkturquoise), [#if it.numbering != none { text( weight: "semibold", ccdarkturquoise, counter(heading.where(level: it.level)).display(it.numbering), ) + h(1.28em) } #it.body], ) } #show raw.where(block: true, lang: "typst"): it => { show "{{VERSION}}": pkg.version show "{{NAME}}": pkg.name block( width: 100%, stroke: .6pt + ccdarkturquoise, radius: 2pt, inset: 1.28em, it, ) } #let example = block.with( width: 100%, stroke: .6pt + ccforestgreen, radius: 2pt, inset: 1.28em, ) #let show-example(code) = grid( columns: 1, row-gutter: .64em, code, { example( eval("#import ccicons: *\n" + code.text, mode: "markup", scope: (ccicons: ccicons)), ) place( right + top, dy: -7mm, polygon( fill: gradient.linear(ccdarkturquoise, ccforestgreen, angle: 90deg), stroke: none, (-5mm, 0mm), (5mm, 0mm), (5mm, 5mm), (10mm, 5mm), (0mm, 11mm), (-10mm, 5mm), (-5mm, 5mm), (-5mm, 0mm), ), ) }, ) #let ex(code) = { raw(lang: "typst", code.text) sym.arrow.r eval("#import ccicons: *; " + code.text, mode: "markup", scope: (ccicons: ccicons)) } #set align(center) #v(2fr) #block( width: 100%, inset: (y: 1.28em), stroke: (bottom: 2pt + ccdarkturquoise), [ #set text(40pt) The #text(cctomato, weight: 600, pkg.name) package ], ) #text(14pt)[Version #pkg.version] #v(1fr) A port of the `ccicon` LaTeX package for Typst. #v(2fr) #block(width: 100%, inset: (x: 10%), outline()) #v(2fr) #pagebreak() #set align(left) = About #ccico adds commands to add Creative Commons license logos to your document. It is a port of the LaTeX package by the same name by <NAME>. Please note that all icons in this package are trademarks of Creative Commons and are subject to the Creative Commons trademark policy (see #link("http://creativecommons.org/policies", "http://creativecommons.org/policies")). The SVG files distributed in this package are available on #link("https://creativecommons.org/mission/downloads/", "the Creative Commons website") and licensed under #link("https://creativecommons.org/licenses/by/4.0/", "Creative Commons Attribution 4.0 International license"). = Usage Add the package to your document by importing it at the top: ```typst #import "@preview/{{NAME}}:{{VERSION}}": * ``` After the package has been imported, simply add a license icon to your document by using one of the shorthands provided (see @shorthands): #table( columns: (1fr, 1fr, 1fr), align: center, `#cc-by-nc-sa`, `#cc-by-nc-sa-shield`, `#cc-by-nc-sa-badge`, cc-by-nc-sa, cc-by-nc-sa-shield, cc-by-nc-sa-badge, ) If you need more control over the output, consider using the `#ccicon` function (see @ccicon). The logos will scale and change color with the surrounding text: #show-example(```typst Lorem ipsum #cc-by-sa dolor sit amet #set text(16pt, rgb("#ed592f")) Lorem ipsum #cc-by-sa dolor sit amet #set text(1.5em, rgb("#05b5da")) Lorem ipsum #cc-by-sa dolor sit amet ```) #pagebreak() = Shorthand logo commands <shorthands> The following commands can be used to typeset the icons provided by Creative Commons. Licenses are a combination of the individual icons joined by a dash (`-`) and can be displayed as a set of icons, a "shield" or a "badge", by adding the format as a suffix. #align( center, table( columns: (auto, 4cm, 4cm, 4cm), align: center + horizon, fill: color-default, inset: .26em, table.header( table.cell(rowspan: 2, fill: color-header)[*Markup*], table.cell(colspan: 3, fill: color-header)[*Result by suffix*], table.cell(fill: color-muted, ""), table.cell(fill: color-muted, `-shield`), table.cell(fill: color-muted, `-badge`), ), table.cell(fill: color-muted, raw(block: false, "#cc-logo")), ccicon("logo", scale: 2), table.cell(inset: 0pt, fill: color-empty)[], table.cell(fill: color-empty)[], table.cell(fill: color-muted, raw(block: false, "#cc")), ccicon("cc", scale: 2), table.cell(inset: 0pt, fill: color-empty)[], table.cell(fill: color-empty)[], ..for (name, icon) in command-map { ( table.cell(fill: color-muted, raw(block: false, "#" + name)), ccicon(icon, scale: 2), if cc-is-valid(name + "-shield") { ccicon(icon, scale: 2, format: "shield") } else { table.cell(fill: color-empty)[] }, if cc-is-valid(name + "-badge") { ccicon(icon, scale: 2.5, format: "badge") } else { table.cell(fill: color-empty)[] }, ) }, ), ) = The `ccicon` function <ccicon> If you need more control over the output, you can use the `#ccicon` function. It can create an icon from the license name and takes the following options: / name: #[ Name of the icon / license as a string (like `"cc-by-sa"`). - #ex(`#ccicon("nc")`) - #ex(`#ccicon("cc-by-sa")`) Append `-shield` or `-badge` to generate the other formats. - #ex(`#ccicon("cc-by-sa-shield")`) - #ex(`#ccicon("cc-by-sa-badge")`) You can also append a version number and language code each separated by a slash (`/`) to make the license version / language aware. This won't change the icon, but might be useful for using the `link` option (see below). ] / format: One of #auto, `"icon"`, `"badge"` or `"shield"`. Defaults to #auto. This will override the format detected in the license name. - #ex(`#ccicon("cc-by-sa-shield", format:"badge")`) - #ex(`#ccicon("cc-by-sa-badge", format:"icon")`) / scale: A scaling factor for the icon. - #ex(`#ccicon("cc-by-sa-shield", scale:2)`) - #ex(`#ccicon("cc-by-sa-badge", scale:.88)`) / baseline: Sets the `baseline` of the surronding `#box`. - #ex(`#ccicon("cc-by-sa", baseline:5pt)`) - #ex(`#ccicon("cc-by-sa-badge", baseline:-5pt)`) / link: #[ If #true, the icon will be a clickable link to the license text. - #ex(`#ccicon("cc-by-sa", link:true)`) You can change the language of the license text, by appending a language code to the license name, separated by `/`: - #ex(`#ccicon("cc-by-sa-badge/de", link:true)`) Similarly, the license version may be provided: - #ex(`#ccicon("cc-by-sa-shield/3.0/de", link:true)`) ] / fill: Either #auto or a #color. #auto is the default and the icon will use the color of the surronding text. Otherwise, the `fill` will be used to color the icon. - #ex(`#text(fill: red, ccicon("cc-by-sa"))`) - #ex(`#ccicon("cc-by-sa", fill:red)`) Note that shields and badges will not be colored. - #ex(`#ccicon("cc-by-sa", format:"shield", fill:red)`) = Other utilities #ccico provides the following additional helper functions: / ```typst #cc-url(license-name)```: Creates an url to the license text on the Creative Commons website. - #ex(`#cc-url("cc-by-sa/de")`) / ```typst #cc-is-valid(license-name)```: Checks if the provided license name is valid and can be parsed by #ccico. - #ex(`#cc-is-valid("cc-by-sa")`) - #ex(`#cc-is-valid("cc-by-nc-sa-badge")`) - #ex(`#cc-is-valid("sa")`) - #ex(`#cc-is-valid("sa-badge")`) - #ex(`#cc-is-valid("not-a-license")`)
https://github.com/veilkev/jvvslead
https://raw.githubusercontent.com/veilkev/jvvslead/Typst/files/91_bank99.typ
typst
#import "../sys/packages.typ": * #import "../sys/sys.typ": * #import "../sys/header.typ": * #import "@preview/bob-draw:0.1.0": * // Space between header #v(150pt) // Shows heading #text(size: 12pt )[= Bank 99] #note("Bank 99 (operator 99) is a term used in bookeeping to refer to the forms of currency that have not been loaned or deposited and is currently available for store use") #show raw.where(lang: "bob"): it => render(it) #grid(columns: (1fr, 1fr, 1fr), fill: none, column-gutter: 2pt, [ #render( ``` __________________________________ | BANK TILL | | ______ ______ ______ ______ | | | || || || | | | | __ || __ || __ || __ | | | | / \ || / \ || / \ || / \ | | | |______||______||______||______| | | ______ ______ ______ ______ | | | o o || o o || o o || o o | | | | o || o || o || o | | | |______||______||______||______| | |__________________________________| ```, width: 90%, ) ],[ #render( ``` __________________________________ | "BUSINESS CENTER - YESTERDAY" | | ______ ______ ______ ______ | | | || || || | | | | __ || __ || __ || __ | | | | / \ || / \ || / \ || / \ | | | |______||______||______||______| | | ______ ______ ______ ______ | | | o o || o o || o o || o o | | | | o || o || o || o | | | |______||______||______||______| | |__________________________________| ```, width: 90%, ) ],[ #render( ``` __________________________________ | "BUSINESS CENTER - NEW TILL" | | ______ ______ ______ ______ | | | || || || | | | | __ || __ || __ || __ | | | | / \ || / \ || / \ || / \ | | | |______||______||______||______| | | ______ ______ ______ ______ | | | o o || o o || o o || o o | | | | o || o || o || o | | | |______||______||______||______| | |__________________________________| ```, width: 90%, ) ] ) #v(20pt) #grid(columns: (1fr,1fr, 1fr), column-gutter: 2pt,[ #pin(7) ],[ #pin(8) ],[ #pin(9) ] ) #pinit-point-from( pin-dx: 80pt, pin-dy: -30pt, offset-dx: 80pt, offset-dy: 20pt, body-dx: -65pt, body-dy: 5pt, (7))[ This is *always* part of Bank 99\ and is for general store use. ] #pinit-point-from( pin-dx: 80pt, pin-dy: -30pt, offset-dx: 80pt, offset-dy: 20pt, body-dx: -50pt, body-dy: 5pt, (8))[ This is *not* part of Bank 99\ *until* you _settle_ it. You must\ _rebuild_ it back to \$285 for\ subsequent use. ] #pinit-point-from( pin-dx: 80pt, pin-dy: -30pt, offset-dx: 80pt, offset-dy: 20pt, body-dx: -50pt, body-dy: 5pt, (9))[ This *is* part of Bank 99 \ *until* you _loan_ it to your \ assigned operator. It\ contains \$285. ] #v(80pt) == Terminology #v(10pt) #show "empha": text("center") #show "decreases": text(weight: "bold")[decreases] #show "increases": text(weight: "bold")[increases] #stack(dir: ltr, "A", empha("loan", 3), "decreases the amount available in bank 99 and is typically performed when giving money to registers,", ) #v(-10pt) #stack(dir: ltr, "or other partners." ) #stack(dir: ltr, "A", empha("pickup", 3), "increases the amount available in bank 99 and is typically performed to pickup money from registers," ) #v(-10pt) #stack(dir: ltr, "business center tills, lottery, tax-exempt forms, and partner checks." ) #stack(dir: ltr, "A", empha("settlement", 3), "increases the amount available in bank 99 and occurs when money is taken from a register or till" ) #v(-10pt) #stack(dir: ltr, "for the purpose of verifying that all counts are accurately represented before a pickup/rebuild is done." ) #stack(dir: ltr, "A", empha("deposit", 3), "decreases the amount available in bank 99 and occurs after the pickup of lottery, tax-exempt forms," ) #v(-10pt) #stack(dir: ltr, "partner checks, or money picked up from registers, which can then be made into bundles of $20s, $50, or $100s." ) #important("Settlements are performed on business center tills and on registers. Both are rebuild to the amounts $285 and $1270 respectively. Money that is deposited is taken from the store bank to an actual bank.")
https://github.com/jackkyyh/ZXCSS
https://raw.githubusercontent.com/jackkyyh/ZXCSS/main/scripts/1_qec.typ
typst
#import "../import.typ": * #slide(title: [Stabilizer codes])[ #write_footer[<NAME>. (1997). Stabilizer codes and quantum error correction. California Institute of Technology.] / Stabilizers: an Abelian subgroup $cal(S) < cal(P)_n$ #pause / Codespace: $cal(C):={ket(psi) in cal(H)^(times.circle n): S ket(psi)=+ket(psi),forall S in cal(S)}$ #pause #align(center)[#cbox[$dim cal(S) + log_2 dim cal(C) = n$]] ] #slide(title: [Examples])[ #reset_footer() #set align(top) #grid(columns: 2, column-gutter: 20pt, row-gutter: 30pt, uncover("2-")[$cal(S):=angle.l Z Z I, Z I Z angle.r$], uncover("2-")[$=>cal(C) &={alpha ket(000)+beta ket(111): alpha, beta in CC}\ &=op("span"){ket(000), ket(111)} tilde.equiv cal(H)^(times.circle 1)#h(-5pt)=op("span"){ket(0), ket(1)}$], uncover("3-")[$cal(S):=angle.l Z Z, X X angle.r$], uncover("3-")[$=>cal(C) ={1 / sqrt(2)(ket(00)+ket(11))}tilde.equiv cal(H)^(times.circle 0)$], uncover("4-")[$cal(S):=angle.l Z Z Z Z, X X X X angle.r $], uncover("4-")[$=> cal(C) = ?$] + uncover("5-")[$#h(200pt) tilde.equiv cal(H)^(times.circle 2)$\ $log_2 dim cal(C) = 4 - 2 = 2$] ) #align(center)[#cbox[$dim cal(S) + log_2 dim cal(C) = n$]] ] #slide(title: [Stabilizer codes])[ #write_footer[<NAME>. (1997). Stabilizer codes and quantum error correction. California Institute of Technology.] / Stabilizers: an Abelian subgroup $cal(S) < cal(P)_n$ / Codespace: $cal(C):={ket(psi) in cal(H)^(times.circle n): S ket(psi)=+ket(psi),forall S in cal(S)}$ #pause / Encoder: $E: cal(H)^(times.circle k) -> cal(C) subset cal(H)^(times.circle n)$ #pause #alternatives(start: 3, position: horizon)[ $k cases(#hide[1],#hide[1])$][$ket(alpha)$] #box(baseline: 40%)[#image("../figs/pte/encoder.svg", width: 7cm) #place(dx: 25pt, dy:-55pt)[$dots.v #h(50pt) E #h(60pt) dots.v$]] #box(baseline: 30%)[#alternatives(start: 3, position: horizon)[ $cases(reverse: #true, #hide[1],#hide[1],#hide[1]) n$][$ket(overline(alpha)):= E ket(alpha)$: *logical states*]] ] #slide(title: [Logical operators])[ #let la = xarrow.with(sym: sym.arrow, width: 50pt) $ket(alpha) la(U) ket(beta) quad in cal(H)^(times.circle k)$\ #pause $#rotate(90deg)[$-->$] #h(-10pt) #text(0.7em)[$E$] #h(55pt) #rotate(90deg)[$-->$] #h(-10pt) #text(0.7em)[$E$]$\ $ket(overline(alpha))#uncover("3-")[$la(overline(U)?)$]ket(overline(beta))quad in cal(H)^(times.circle n)$ #pause#pause $=> overline(U) E = E U$ #pause $=> overline(U):=E U E^dagger$: *logical operators* #pause / Logical Paulis: $overline(P) = E P E^dagger, forall P in cal(P)_k$ #pause #place(dx: 470pt, dy: -260pt)[ #cbox[$[|n, k, d|]$ notation: #h(20pt)$k cases(#hide[1],#hide[1])$#h(-10pt) #box(baseline: 40%)[ #image("../figs/pte/encoder.svg", width: 150pt) #place(dx: 20pt, dy:-45pt)[ $dots.v #h(30pt) E #h(35pt) dots.v$]] #h(-10pt) $cases(reverse: #true, #hide[1],#hide[1],#hide[1]) n$ #h(20pt)$d:= min\{op("wt")(overline(P))\}$ ]] // #pause // In general, $overline(U)$ can be very complicated! ] #slide(title: [Logical operators])[ #reset_footer() $overline(U) E = E U$ #pause #image("../figs/pte/UE=EU.svg", width: 600pt) #place(dx:30pt, dy:-60pt)[ $dots.v #h(35pt) U #h(40pt) dots.v #h(40pt) E #h(40pt) dots.v #h(50pt) = #h(60pt) dots.v #h(40pt) E #h(40pt) dots.v #h(40pt) overline(U) #h(40pt) dots.v$] ]
https://github.com/dismint/docmint
https://raw.githubusercontent.com/dismint/docmint/main/multicore/pset1.typ
typst
#import "template.typ": * #show: template.with( title: "6.5081 Problem Set #1", subtitle: "<NAME>", pset: true ) _Collaborators: <NAME>_ = Problem 1 / Safety: Something bad will never happen. / Liveness: Something good will eventually happen. I will consider "good" and "bad" to be placeholders for arbitrary events. + *Liveness*: Eventually, a customer will be seated. + *Safety*: It is never the case that something that can go wrong, will not go wrong. + *Safety*: It is never the case that someone wants to die. + *Liveness*: Eventually, you will either die or be taxed. + *Liveness*: Eventually we will die. + *Liveness*: Eventually the error will be printed. + *Safety*: It is never the case that an interrupt occurs and a message is not printed. + *Safety*: It is never the case that something Darth Vader starts will not be finished. + *Safety*: It is never the case that the cost of living decreases. + *Safety*: It is never the case that you can't tell a Harvard man. = Problem 2 == Initial Winning Strategy Designate one person as the "counter". This person is the only person who is allowed to turn the switch off. In fact, if the switch is on when they enter the room, they will take note and turn it off. For every other person, they will turn the switch *on* when it is their first time visiting the room while the switch is *off*. Once the "counter" sees that the switch has been turned *on* $P-1$ times, they signal that everyone has visited at least once. This strategy works since - Each switch can only be turned on by a specific prisoner once. - The switch is only off if it's the first visit ever, or the "counter" resets it, meaning that the "counter" never misses an instance of the switch being *on*. Thus eventually with enough time passing the "counter" will realize that every other prisoner has visited the room after counting every other prisoner's first and only signal. == Warden Interference Assume $k$ is a number that the prisoners know ahead of time. Now the Warden can interrupt and inject noise into our previous algorithm. In addition, the initial switch state can be viewed as another source of noise. It's possible for our "counter" to now see anywhere between $0$ to $k+1$ extra switches in the *on* state, or $0$ to $k$ less switches on the *on* state. I propose the following changes to the previous algorithm: - Each prisoner now turns the switch *on* the first $2 k + 2$ times they enter the room with the switch *off*. - The "counter" follows a similar strategy as above, but instead only signals that everyone has visited the room at least once when the total count of *on* switches he has seen is at least $2 k P - 3 k + 2 P - 2$ To see why this works, let's think about one of the most adversarial cases - the highest number of *on* switches the "counter" can see without everyone having gone once. In this scenario, every other prisoner will have turned the switch on $3 k$ times, with some final prisoner not having been to the room a single time. If the switch starts on and the Warden manages to turn a previously *off* switch to *on* on every single one of the $k$ visits, then the highest count they can achieve is: $ (2 k + 2)(P - 2) + k + 1 &= 2 k P - 4 k + 2 P - 4 + k + 1\ &= 2 k P - 3 k + 2 P - 3 $ And we can then show that: $ 2 k P - 3 k + 2 P - 3 &< 2 k P - 3 k + 2 P - 2\ -3 &< -2 $ Thus it is impossible for us to reach the desired number for the "counter" and still be tricked by the Warden. There's one last case to consider, which is the possibility that the Warden can turn enough switches off to the point where we fail to hit the quota the "counter" expects. Let's compute how much the Warden can make this number fall. If the initial switch starts off, and the Warden manages to visit at $k$ times when the switch is *on* and turns it *off*, then he can achieve: $ (2 k + 2)(P - 1) - k &= 2 k P - 2 k + 2 P - 2 - k\ &= 2 k P - 3 k + 2P - 2 $ We can show this is trivially at least as large as our desired target for the counter. $ 2 k P - 3 k + 2P - 2 &>= 2 k P - 3 k + 2P - 2\ 0 &>= 0 $ And we can now conclusively say that with this strategy, it is still possible to beat the game, even with the Warden's interference. = Problem 4 == Algorithm Suppose there is another can on Bob's side since he cannot see. We then propose the following protocol: - Assume we start in the state where food has just run out in the pond. If so, then Bob's can starts down and Alice's can starts up. - When food in the pond runs out, Alice turns her can up and knocks Bob's can down. - When Bob sees his can down, his fills the pond with food, then raises his can and knocks Alice's can down. == Correctness - *Mutual Exclusion*: Only one person's can is down at a time. The person whose can is down is the person who is allowed to act. The flipping of cans is an atomic operation and always results a similar state of one can up, one can down. This double flipping always occurs as the last action of either Alice or Bob. - *No Starvation*: If Bob always has food to give out and the pets are always hungry, then the pets will eat infinitely often. - *Producer/Consumer*: Bob only refills the food if his can is down, meaning that there is no food in the pool. Alice only lets her pets out to eat when her can is down, meaning Bob has finished stocking the pool. = Problem 5 #define( title: "Amdahl's Law" )[ $ "Speedup" = 1 / (1 - p + p / n) $ ] == $n => infinity$ We need to solve for $p$ given the two pieces of information we have: - 24 hours on 3 processors. - 15 hours on 6 processors. There is no way to tell how much the speedup was compared to the original, so we will instead have to use the two measurements against each other to derive this information. We will use the fact that: $ "Speedup" = "Original Time" / "Concurrent Time" $ To achieve the two equations: $ "Original" / 24 = 1 / (1 - p + p / 3)\ "Original" / 15 = 1 / (1 - p + p / 6) $ Now to solve for $p$, we can simply divide two instances of Amdahl's together. $ 15 / 24 &= (1 - p + p/6) / (1 - p + p/3)\ 15 - 15 p + 5 p &= 24 - 24 p + 4 p\ 10 p &= 9\ p &= 9 / 10 $ Therefore using the first equation we can find the original time as well now. $ "Original" / 24 &= 1 / (1 - p + p / 3)\ "Original" / 24 &= 1 / (1 - 9 / 10 + 9 / 30)\ "Original" / 24 &= 5 / 2\ "Original" &= 60\ $ As $n$ approaches $infinity$, the overall speedup for a model will be equal to: $ 1 / (1 - p) = 1 / (1 - 9 / 10) = boxed(10) $ == Maximizing Profit We view profit as: $ "Profit"(t) = 54000 (1 - t / 48) - 0.05 dot "Processor Hours" $ How do we find the number of processor hours? Well, we know it is possible to find the amount of total time it takes given $n$ processors since we can use a modified version of Amdahl's with the constants we calculated above. $ "Original" / "Concurrent" &= 1 / (1 - p + p / n)\ "Concurrent" &= "Original" dot (1 - p + p / n)\ "Concurrent" &= (6 n + 54) / n\ $ However, we should multiply this expression by an additional $n$, as we must get the *total* number of processor hours. Thus we end up with: $ "Profit"(t) = 54000 (1 - t / 48) - 0.05 (6 n + 54) $ $t$ is really just a function of $n$ as we saw above, so we can make a further simplification: $ "Profit"(n) = 54000 (1 - (6 n + 54) / (48 n)) - 5 (6 n + 54) $ Notice that we also multiplied the last term by 100 (the number of models). Solving this equation reveals that our optimal number of processors per machine is 45, meaning the total number we need is $n = boxed(4500)$ Thus we can maximize our profit at $4500$ processors as $\$44,547.3$ = Problem 6 #define( title: "Amdahl's Law" )[ $ "Speedup" = 1 / (1 - p + p / n) $ ] Similar to the before question, let us derive two equations and solve for the first unknown, $p$ $ S_3 &= 1 / (1 - p + p / 3)\ S_n &= 1 / (1 - p + p / n) $ Let's solve for $p$ in the first equation. $ S_3 &= 1 / (1 - p + p / 3)\ S_3 (1 - 2 / 3 p) &= 1\ 2 / 3 p dot S_3 &= S_3 - 1\ p &= (3 (S_3 - 1)) / (2 dot S_3)\ $ Now plugging into the second equation, we get: $ S_n &= 1 / (1 - (3 (S_3 - 1)) / (2 dot S_3) + (3 (S_3 - 1)) / (2 n dot S_3))\ S_n &= 1 / ((3 - S_3) / (2 dot S_3) + (3 (S_3 - 1)) / (2 n dot S_3))\ S_n &= boxed((2 n dot S_3) / (3 n - n dot S_3 + 3 dot S_3 - 3))\ $
https://github.com/MattiaOldani/Informatica-Teorica
https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/calcolabilità/09_calcolabilità.typ
typst
#import "../alias.typ": * #import "@preview/algo:0.3.3": code #import "@preview/lemmify:0.1.5": * #let ( theorem, lemma, corollary, remark, proposition, example, proof, rules: thm-rules ) = default-theorems("thm-group", lang: "it") #show: thm-rules #show thm-selector("thm-group", subgroup: "theorem"): it => block( it, stroke: red + 1pt, inset: 1em, breakable: true ) #show thm-selector("thm-group", subgroup: "proof"): it => block( it, stroke: green + 1pt, inset: 1em, breakable: true ) = Calcolabilità Seguiremo la seguente roadmap: + *ELEM*: definiamo un insieme di tre funzioni che _qualunque_ idea di calcolabile si voglia proporre deve considerare calcolabili. ELEM non può esaurire il concetto di calcolabilità, quindi lo espanderemo con altre funzioni; + $bold(Omega)$: definiamo insieme di operazioni su funzioni che _costruiscono nuove funzioni_. Le operazioni in $Omega$ sono banalmente implementabili e, applicandole a funzioni calcolabili, riesco a generare nuove funzioni calcolabili. + $bold(elem^Omega = cal(P))$: definiamo la classe delle *funzioni ricorsive parziali*. Questa sarà la nostra idea astratta della classe delle funzioni calcolabili secondo Kleene. Quello che faremo dopo la definizione di $cal(P)$ sarà chiederci se questa idea di calcolabile che abbiamo _"catturato"_ coincida o meno con le funzioni presenti in $F(ram) = F(mwhile)$. == Primo passo: ELEM Definiamo l'insieme ELEM con le seguenti funzioni: $ elem = {"successore" &: s(x) = x + 1 bar.v x in NN, \ "zero" &: 0^n (x_1, dots, x_n) = 0 bar.v x_i in NN, \ "proiettori" &: "pro"_k^n (x_1, dots, x_n) = x_k bar.v x_i in NN} quad . $ Questo insieme è un _onesto punto di partenza_: sono funzioni basilari che qualsiasi idea data teoricamente non può non considerare come calcolabile. Ovviamente, ELEM non può essere considerato come l'idea teorica di _TUTTO_ ciò che è calcolabile: infatti, la funzione $f(x) = x + 2$ non appartiene a ELEM ma è sicuramente calcolabile. Quindi, ELEM è troppo povero e deve essere ampliato. == Secondo passo: $Omega$ Definiamo ora un insieme $Omega$ di operazioni che amplino le funzioni di ELEM per permetterci di coprire tutte le funzioni calcolabili. === Composizione Il primo operatore che ci viene in mente di utilizzare è quello di *composizione*. Siano: - $h : NN^k arrow.long NN$ *funzione di composizione*, - $g_1, dots, g_k : NN^n arrow.long NN$ _"funzioni intermedie"_ e - $wstato(x) in NN^n$ input. Allora definiamo $ comp(h, g_1, dots, g_k) : NN^n arrow.long NN $ la funzione tale che $ comp(h, g_1, dots, g_k)(wstato(x)) = h(g_1 (wstato(x)), dots, g_k (wstato(x))). $ #v(12pt) #figure( image("assets/composizione.svg", width: 50%) ) #v(12pt) COMP è una funzione _intuitivamente calcolabile_ se parto da funzioni calcolabili: infatti, prima eseguo le singole funzioni $g_1, dots, g_k$ e poi applico la funzione $h$ sui risultati delle funzioni $g_i$. Calcoliamo ora la *chiusura* di ELEM rispetto a COMP, ovvero l'insieme $elem^comp$. Vediamo subito come la funzione $f(x) = x + 2$ appartenga a questo insieme perché $ comp(s,s)(x) = s(s(x)) = (x+1)+1 = x + 2. $ _Che altre funzioni ci sono in questo insieme?_ Sicuramente tutte le funzioni lineari del tipo $f(x) = x + k$, _ma la somma?_ La funzione $ "somma"(x,y) = x + y $ non appartiene a questo insieme perché il valore $y$ non è prefissato e non abbiamo ancora definito il concetto di iterazione di una funzione (in questo caso, la funzione successore). Dobbiamo ampliare ancora $elem^comp$ con altre operazioni. === Ricorsione primitiva Definiamo un'operazione che ci permetta di *iterare* sull'operatore di composizione, la *ricorsione primitiva*, usata per definire *funzioni ricorsive*. Siano: - $g: NN^n arrow.long NN$ *funzione caso base*, - $h: NN^(n+2) arrow.long NN$ *funzione passo ricorsivo* e - $wstato(x) in NN^n$ input. Definiamo $ rp(h,g) = f(wstato(x),y) = cases(g(wstato(x)) & "se" y = 0, h(f(wstato(x),y-1), y-1, wstato(x)) quad & "se" y > 0) quad $ funzione che generalizza la definizione ricorsiva di funzioni. Come prima, *chiudiamo* $elem^comp$ rispetto a RP, ovvero calcoliamo l'insieme $elem^({comp,rp})$. Chiamiamo $ ricprim = elem^({comp, rp}) $ l'insieme ottenuto dalla chiusura, cioè l'insieme delle *funzioni ricorsive primitive*. In questo insieme abbiamo la somma: infatti, $ "somma"(x,y) = cases(x = "Pro"^2_1 (x,y) & "se" y = 0, s("somma"(x,y-1)) quad & "se" y > 0) quad . $ Altre funzioni che stanno in RICPRIM sono: $ "prodotto"(x,y) = cases(0 = 0^2 (x,y) & "se" y = 0, "somma"(x, "prodotto"(x,y-1)) quad & "se" y > 0) quad ; \ "predecessore" P(x) = cases(0 & "se" x = 0, x - 1 quad & "se" x > 0) quad arrow.long.double quad x overset(-,.) y = cases(x & "se" y = 0, P(x) overset(-,.) (y-1) quad & "se" y > 0) quad . $ === RICPRIM vs WHILE L'insieme RICPRIM contiene molte funzioni, _ma abbiamo raggiunto l'insieme $F(mwhile)$?_ Vediamo come è definita RICPRIM: - $forall f in elem arrow.long.double f in ricprim$; - se $h, g_1, dots, g_k in ricprim arrow.long.double comp(h, g_1, dots, g_k) in ricprim$; - se $g,h in ricprim arrow.long.double rp(g,h) in ricprim$; - nient'altro sta in RICPRIM. #theorem(numbering: none)[ $ricprim subset.eq F(mwhile)$. ] #proof[ \ $underline("Passo base")$: \ Le funzioni di ELEM sono ovviamente while programmabili, le avevamo mostrate in precedenza. $underline("Passo induttivo:")$ \ Per COMP, assumiamo per ipotesi induttiva che $h, g_1, dots, g_k in ricprim$ siano while programmabili, allora esistono $H, G_1, dots, G_k in wprogrammi$ tali che $Psi_H = h, Psi_G_1 = g_1, dots, Psi_g_k = g_k$. Mostro allora un programma WHILE che calcola COMP. #code( fill: luma(240), indent-guides: 0.2pt + red, inset: 10pt, line-numbers: false, radius: 4pt, row-gutter: 6pt, stroke: 1pt + black )[ ```py input(x) # In x1 inizialmente ho x begin # nella forma <a1,...,an> x0 := G1(x1); x0 := [x0, G2(x1)]; ... x0 := [x0, Gk(x1)]; x1 := H(x0); end ``` ] Quindi abbiamo $Psi_w (wstato(x)) = comp(h,g_1, dots, g_k)(wstato(x))$. Per RP, assumiamo che $h, g in ricprim$ siano while programmabili, allora esistono $H,G in wprogrammi$ tali che $Psi_H = h$ e $Psi_G = g$. Le funzioni ricorsive primitive le possiamo vedere come delle iterazioni che, partendo dal caso base $G$, mano a mano compongono con $H$ fino a quando non si raggiunge $y$ (escluso). Mostriamo un programma WHILE che calcola $ rp(h,g) = f(wstato(x),y) = cases(g(wstato(x)) & "se" y=0 \ h(f(wstato(x), y-1), y-1, wstato(x)) quad & "se" y>0) quad . $ #code( fill: luma(240), indent-guides: 0.2pt + red, inset: 10pt, line-numbers: false, radius: 4pt, row-gutter: 6pt, stroke: 1pt + black )[ ```py input(x,y) # In x1 inizialmente ho <x,y> begin t := G(x); # t contiene f(x,y) k := 1; while k <= y do begin t := H(t, k-1, x); k := k + 1; end end ``` ] Quindi $Psi_w (cantor(x,y)) = rp(h,g)(wstato(x), y)$. ] Abbiamo quindi dimostrato che $ricprim subset.eq F(mwhile)$, _ma questa inclusione è propria?_ Notiamo subito che nel linguaggio WHILE posso fare dei cicli infiniti, mentre in RICPRIM no: RICPRIM contiene solo funzioni totali (_si dimostra per induzione strutturale_) mentre WHILE contiene anche delle funzioni parziali. Di conseguenza $ ricprim subset.neq F(mwhile). $ Per poter raggiungere $F(mwhile)$ dovremo ampliare nuovamente RICPRIM. Visto che le funzioni in RICPRIM sono tutte totali, possiamo dire che ogni ciclo in RICPRIM ha un inizio e una fine ben definiti: il costrutto utilizzato per dimostrare che $rp in F(mwhile)$ nella dimostrazione precedente, ci permette di definire un nuovo tipo di ciclo, il *ciclo FOR*. #code( fill: luma(240), indent-guides: 0.2pt + red, inset: 10pt, line-numbers: false, radius: 4pt, row-gutter: 6pt, stroke: 1pt + black )[ ```py input(x,y) begin t := G(x); for k := 1 to y do t := H(t, k-1, x); end ``` ] Il FOR che viene utilizzato è quello _originale_, cioè quel costrutto che si serve di una *variabile di controllo* che parte da un preciso valore e arriva ad un valore limite, senza che la variabile di controllo venga toccata. In Pascal veniva implementato mettendo la variabile di controllo in un registro particolare, per non permettere la sua scrittura. Il FOR language è quindi un linguaggio WHILE dove l'istruzione di loop è un FOR. Possiamo quindi dire che $lfor = ricprim$, e quindi che $F(lfor) subset F(mwhile)$. Dato che WHILE vince su RICPRIM solo per i loop infiniti, restringiamo WHILE imponendo dei loop finiti. Creiamo l'insieme $ overset(F,tilde)(mwhile) = {Psi_W : W in wprogrammi and Psi_W "totale"}. $ _Dove si posizione questo insieme rispetto a RICPRIM? L'inclusione è propria?_ Anche in questo caso, "vince" ancora WHILE, perché ci sono funzioni in $overset(F,tilde)(mwhile)$ che non sono scrivibili come funzioni in RICPRIM. Ad esempio, la funzione di Ackermann (1928), definita come $ cal(A)(m,n) = cases(n+1 & "se" m = 0, cal(A)(m-1, 1) & "se" m > 0 and n = 0, cal(A)(m-1, cal(A)(m, n-1)) quad & "se" m > 0 and n > 0) $ è una funzione che non appartiene a RICPRIM, perché a causa della doppia ricorsione cresce troppo in fretta. Di conseguenza, vogliamo ampliare anche RICPRIM. #v(12pt) #figure( image("assets/calcolabilità-venn.svg", width: 100%) ) #v(12pt) Siamo nella direzione giusta: non abbiamo catturato _"cose strane"_ che non avrei catturato in $F(ram)$, ma questo non basta: non abbiamo ancora catturato le funzioni parziali. === Minimalizzazione Introduciamo quindi un ultimo operatore per permettere la presenza di funzioni parziali. L'operatore scelto è l'operatore di *minimalizzazione* di funzione. Sia $f: NN^(n+1) arrow.long NN$ con $f(wstato(x), y)$ e $wstato(x) in NN^n$, allora: $ min(f)(wstato(x)) = g(wstato(x)) = cases(y & "se" f(wstato(x), y) = 0 and (forall y' < y quad f(wstato(x),y') arrow.b and f(wstato(x),y') eq.not 0), bot quad & "altrimenti") quad . $ Un'altra definizione di MIN è $ mu_y (f(wstato(x),y)=0). $ Più informalmente, questa funzione restituisce il più piccolo valore di $y$ che azzera $f(underline(x), y)$, ovunque precedentemente definita su $y'$. Vediamo alcuni esempi con $f: NN^2 arrow NN$. #align(center)[ #table( columns: (30%, 30%), inset: 10pt, align: horizon, [$f(x,y)$], [$min(f)(x)=g(x)$], [$x+y+1$], [$bot$], [$x overset(-,.) y$], [$x$], [$y overset(-,.) x$], [$0$], [$x overset(-,.) y^2$], [$ceil(sqrt(x))$], [$floor(x/y)$], [$bot$], ) ] == $cal(P)$ Ampliamo RICPRIM chiudendolo con la nuova operazione MIN: $ elem^({comp,rp,min}) = cal(P) = {"Funzioni Ricorsive Parziali"}. $ Abbiamo ottenuto la classe delle *funzioni ricorsive parziali*. Vediamo qualche confronto con le classi che abbiamo già definito in precedenza. === $cal(P)$ vs WHILE Sicuramente $cal(P)$, che grazie a MIN ora contiene anche funzioni parziali, amplia RICPRIM, fatto solo di funzioni totali. _Ma come si pone rispetto a $F(mwhile)$?_ #theorem(numbering: none)[ $cal(P) subset.eq F(mwhile)$. ] #proof[ \ $cal(P)$ è definito per chiusura, ma in realtà è definito induttivamente in questo modo: - le funzioni ELEM sono in $cal(P)$; - se $h, g_1, dots, g_k in cal(P)$ allora $comp(h, g_1, dots, g_k) in cal(P)$; - se $h, g in cal(P)$ allora $rp(h,g) in cal(P)$; - se $f in cal(P)$ allora $min(f) in cal(P)$; - nient'altro è in $cal(P)$. Di conseguenza, per induzione strutturale su $cal(P)$, dimostriamo: - *passo base*: le funzioni elementari sono WHILE programmabili, lo abbiamo già dimostrato; - *passi induttivi*: - siano $h, g_1, dots, g_k in cal(P)$ WHILE programmabili per ipotesi induttiva, allora mostro che $comp(h, g_1, dots, g_k)$ è WHILE programmabile, ma questo lo abbiamo già fatto per RICPRIM; - siano $h, g in cal(P)$ WHILE programmabili per ipotesi induttiva, allora mostro che $rp(h,g)$ è WHILE programmabile, ma anche questo lo abbiamo già fatto per RICPRIM; - sia $f in cal(P)$ WHILE programmabile per ipotesi induttiva, allora mostro che $min(f)$ è WHILE programmabile. Devo trovare un programma WHILE che calcoli la minimizzazione: il programma WHILE $ P equiv & "input"(wstato(x)) \ & "begin" \ & quad y := 0 \ & quad "while" f(wstato(x),y) eq.not 0 "do" \ & quad quad y := y + 1 \ & "end" $ è un programma che calcola la minimizzazione: infatti, se non esiste un $y$ che azzeri $f(wstato(x),y)$ il programma va in loop, quindi la semantica di $P$ è $bot$ secondo MIN. Concludiamo quindi che $cal(P) subset.eq F(mwhile)$. ] Viene naturale chiedersi se vale la relazione inversa, cioè se $F(mwhile) subset.eq cal(P)$ oppure no. #theorem(numbering: none)[ $F(mwhile) subset.eq cal(P)$. ] #proof[ \ Sappiamo che $ F(mwhile) = {Psi_W : W in wprogrammi}. $ Consideriamo un $Psi_W in F(mwhile)$ e facciamo vedere che $Psi_W in cal(P)$, mostrando che può essere espressa come composizione, ricorsione primitiva e minimalizzazione a partire dalle funzioni in ELEM. Le funzione in $wprogrammi$ sono nella forma $ Psi_W = "Pro"^21_0 ([|W|](winizializzazione(wstato(x)))), $ con $[|C|](wstato(x)) = wstato(y)$ la funzione che calcola lo stato prossimo $wstato(y) in NN^21$ a seguito dell'esecuzione del comando C a partire dallo stato corrente $wstato(x) in NN^21$. In sostanza, $[||]() : NN^21 arrow.long NN^21$ rappresenta la funzione di stato prossimo definita induttivamente per via della struttura induttiva del linguaggio WHILE. Abbiamo definito $Psi_W$ come composizione delle funzioni $"Pro"^21_0$ e $[|W|](winizializzazione(wstato(x)))$, ma allora: + $"Pro"^21_0 in elem arrow.long.double "Pro"^21_0 in cal(P)$; + $cal(P)$ è chiuso rispetto alla composizione; + a causa delle due precedenti, se dimostro che la funzione di stato prossimo è ricorsiva parziale allora $Psi_W in cal(P)$ per la definizione induttiva di $cal(P)$. La funzione di stato prossimo restituisce elementi in $NN^21$, mentre gli elementi in $cal(P)$ hanno codominio $NN$. Per risolvere questo piccolo problema tramite le liste di Cantor riesco a condensare il vettore in un numero. Consideriamo quindi $f_C (x) = y$ *funzione numero prossimo*, con $x = [wstato(x)]$ e $y = [wstato(y)]$. #v(12pt) #figure( image("assets/funzione-stato-prossimo.svg", width: 70%) ) #v(12pt) Ovviamente $ f_C in cal(P) arrow.long.double.l.r [|C|] in cal(P) $ dato che posso passare da una all'altra usando funzioni in $cal(P)$ quali Cantor e proiezioni. Dimostriamo, tramite induzione strutturale, sul comando while $C$: - *caso base*: i comandi base WHILE devono stare in $cal(P)$. - *azzeramento* $C equiv x_k := 0$: $ f_(x_k := 0) (x) = ["Pro"(0,x), dots, underbracket(0(x), k), dots, "Pro"(20,x)] . $ Tutte le funzioni usate sono in $cal(P)$, così come la loro composizione; - *incremento/decremento* $C equiv x_k := x_j plus.minus 1$: $ f_(x_k := x_j plus.minus 1) (x) = ["Pro"(x,0), dots, "Pro"(j,x) plus.minus 1, dots, "Pro"(20,x)]. $ Tutte le funzioni usate sono in $cal(P)$, così come la loro composizione; - *passi induttivi*: i comandi "complessi" WHILE devono stare in $cal(P)$. - *comando composto* $C equiv composto$ sapendo che $f_(C_i) in cal(P)$: $ f_C (x) = f_(C_n) (dots (f_(C_2)(f_(C_1)(x))) dots ). $ Ogni $f_(C_i) in cal(P)$ per ipotesi induttiva, così come la loro composizione; - *comando while* $C' equiv comandowhile$, sapendo che $f_C in cal(P)$: $ f_(C') (x) = f_C^e(x) (x), $ con $ e(x) = mu_y ("Pro"(k,f_c^y (x)) = 0). $ $f_C^e(x)$ è la composizione di $f_C$ per $e(x)$ volte, che non è un numero costante dato che dipende dallo stato iniziale $x$, ma questo è problema: grazie all'operatore di composizione sappiamo comporre un numero predeterminato di volte, _ma come facciamo con un numero non costante?_ Rinominiamo $ f_C^y (x) = T(x,y) = cases(x & "se" y = 0, f_C (T(x,y-1)) quad & "se" y > 1) quad . $ Come rappresento $T(x,y)$ in $cal(P)$? Notiamo come $T(x,y)$ sia un operatore ottenuto tramite RP su una funzione $f_C in cal(P)$, di conseguenza anche lei starà in $cal(P)$. L'ultima cosa da sistemare è $e(x)$. Questa funzione è la minimizzazione di $T(x,y)$: infatti, $ e(x) = mu_y ("Pro"(k, T(x,y)) = 0) $ cerca il primo numero che azzera il registro $k$, quindi $e(x) in cal(P)$. In conclusione, $ f_(C') (x) = f_C^e(x) = T(x,e(x)) $ è composizione di funzioni in $cal(P)$, quindi $f_(C') in cal(P)$. ] Visti i risultati ottenuti dai due teoremi precedenti, possiamo concludere che $ F(mwhile) = cal(P). $ Abbiamo ottenuto che la classe delle funzioni ricorsive parziali, che dà un'idea di _calcolabile_ in termini matematici, coincide con quello che noi intuitivamente consideriamo _calcolabile_, dove con "intuitivamente calcolabile" intendiamo tutti quei problemi di cui vediamo una macchina che li risolva. === Tesi di Church-Turing Il risultato principale di questo studio è aver trovato due classi di funzioni molto importanti: - $cal(P)$ insieme delle *funzioni ricorsive parziali*; - $cal(T)$ insieme delle *funzioni ricorsive totali*. Il secondo insieme presentato contiene tutte le funzioni di $cal(P)$ che sono totali, ma allora $ cal(T) subset cal(P). $ Inoltre vale $ ricprim subset cal(T) $ perché, ad esempio, la funzione di Ackermann $cal(A)(m,n)$ non sta in RICPRIM (già dimostrato) ma è sicuramente calcolabile e totale. L'insieme $cal(P)$ cattura tutti i sistemi di calcolo esistenti: WHILE, RAM, Macchine Di Turing, Lambda-calcolo di Church, paradigma quantistico, grammatiche, circuiti, sistemi di riscrittura, eccetera. In poche parole, tutti i sistemi creati dal 1930 ad oggi. Infatti, dal 1930 in poi sono stati proposti un sacco di modelli di calcolo che volevano catturare ciò che è calcolabile, ma tutti questi modelli individuavano sempre la classe delle funzioni ricorsive parziali. Visti questi risultati, negli anni 1930/1940 *Church* e *Turing* decidono di enunciare un risultato molto importante. #rect( stroke: red )[ *Tesi di Church-Turing*: la classe delle funzioni intuitivamente calcolabili coincide con la classe $cal(P)$ delle funzioni ricorsive parziali. ] Questa tesi non è un teorema, è una *congettura*, un'opinione. Non può essere un teorema in quanto non è possibile caratterizzare i modelli di calcolo ragionevoli che sono stati e saranno proposti in maniera completa. Possiamo semplicemente decidere se aderire o meno a questa tesi. Per noi un problema è _calcolabile_ quando esiste un modello di calcolo che riesce a risolverlo ragionevolmente. Se volessimo aderire alla tesi di Church-Turing, potremmo dire, in maniera più formale, che: - _problema ricorsivo parziale_ è sinonimo di *calcolabile*; - _problema ricorsivo totale_ è sinonimo di *calcolabile da un programma che si arresta su ogni input*, quindi che non va mai in loop.
https://github.com/pascalguttmann/git-presentation
https://raw.githubusercontent.com/pascalguttmann/git-presentation/master/git-presentation.typ
typst
#import "@preview/polylux:0.3.1": * #import themes.university: * #let title = "Version Control with Git" #let subtitle = "" #let author = ("<NAME>") #let institution-name = "<NAME>" #let date = datetime.today().display( "[day padding:space] [month repr:short] [year repr:full]" ) #let accent-color = rgb("#03B670") #let accent-focus-slide(body) = focus-slide(background-color: accent-color)[#body] #let def-block(body) = block( breakable: false, width: 100%, fill: accent-color, inset: 0.5em, radius: 0.5em, )[#body] #show raw.where(block: false): box.with( fill: luma(240), inset: (x: 0.25em, y: 0em), outset: (y: 0.25em), radius: 0.25em, ) #show raw.where(block: true): block.with( fill: luma(240), width: 100%, inset: 0.5em, radius: 0.5em, ) #set align(horizon) #show: university-theme.with( aspect-ratio: "16-9", short-author: author, short-title: title, short-date: date, color-a: accent-color, //main decoration (headings, footer) color-b: rgb("#808080"), //accent color (footer line) //color-c: rgb("#FBFEF9"), //secondary accent (header background) progress-bar: true, ) #title-slide( authors: author, title: title, subtitle: subtitle, date: date, institution-name: institution-name, // logo: image("dummy-logo.png", width: 60mm) ) #slide(title: [A Sincere Confession], new-section: [Why Git?])[ #side-by-side(columns: (1fr, 2fr))[ I have been there. You too? #emoji.eyes ][ #image("./img/suffix_versioning.png") ] ] #slide(title: [There is Hope!])[ #side-by-side[ - Version Control Systems (VCS) - Git - Subversion - Mercurial - Bitkeeper - ... ][ #figure( image(".\img\linus_torvalds.jpeg", height: 75%), caption: [<NAME> #footnote[Linuxmag.com, December 2002 https://upload.wikimedia.org/wikipedia/commons/6/69/Linus_Torvalds.jpeg]], ) <img_linus_torvalds> ] ] #matrix-slide(columns: (1fr, 2fr, 2fr), rows: (1fr, 1fr))[ Online Service ][ - GitHub - GitLab #image("./img/github_logo.png", width: 50%) ][ - Youtube - DailyMotion - AtoPlay #image("./img/youtube_logo.png", width: 50%) ][ Local Application ][ - Git #image(".\img\Git-Logo-2Color.svg", width: 50%) ][ - VLC Player - Windows Media Player #image(".\img\vlc_player.png", width: 50%) ] #accent-focus-slide()[ = Git - local - distributed - command line interface ] #slide(title: [Command Line Interface? Really!?])[ #side-by-side(columns: (1fr, 1fr))[ There are graphical user interfaces. Choose what you like: - https://git-scm.com/downloads/guis Git is also integrated in many IDEs: - eg. Visual Studio Code #footnote[ https://code.visualstudio.com/ ] #footnote[ https://code.visualstudio.com/docs/sourcecontrol/intro-to-git ] - recommendation: extension: `GitGraph` ][ #align(center)[ #image("./img/gui-sourcetree.png") ] ] ] #slide(title: [Repository], new-section: [Git Basics])[ #side-by-side(columns: (1fr, 1fr))[ #def-block[ = Repository \ - `.git` directory - tracked files - all versions of files - meta data ] ][ ```bash # initialize a new (empty) repository git init ``` ] ] #slide(title: [Commits])[ #side-by-side(columns: (1fr, 2fr))[ #def-block[ = Commit \ - "Version" of files in repo - Stores `snapshot` of files - *No* "delta" ] ][ #image(".\img\snapshots.png") ] ] #slide(title: [Staging and Committing])[ #image("./img/lifecycle.png") ] #slide(title: [Staging and Committing])[ ```bash git add newFile.txt # adding an untracked file git add modifiedFile.txt # staging a modified file git add . # adding / staging all files git commit -m "My commit message here" # committing ``` ] #slide(title: [Staging and Committing])[ ```bash git status # observing the status of the staging area git diff # differences (modified <-> unmodified) git diff --staged # differences (staged <-> unmodified) git log # log of commits git log --graph # log + "commit graph" git log --patch # log + "patch" (changes) ``` ] #accent-focus-slide()[ = Live Demo ! - Poems and Code ] #slide(title: [Branching])[ #side-by-side(columns: (1fr, 2fr))[ #def-block[ = Branch \ - history of commits - can be named - can diverge ] ```bash # view branches git branch ``` ][ #image("./img/head-to-master-no-testing.png") ] ] #slide(title: [Branching])[ #side-by-side(columns: (1fr, 2fr))[ ```bash # create branch testing git branch testing ``` ][ #image("./img/head-to-master.png") ] ] #slide(title: [Branching])[ #side-by-side(columns: (1fr, 2fr))[ ```bash # switch to branch testing git switch testing ``` ][ #image("./img/head-to-testing.png") ] ] #slide(title: [Branching])[ #side-by-side(columns: (1fr, 2fr))[ ```bash # commit to branch testing git commit -a -m "My experiments" ``` ][ #image("./img/advance-testing.png") ] ] #slide(title: [Branching])[ #side-by-side(columns: (1fr, 2fr))[ ```bash # switch to branch master git switch master ``` ][ #image("./img/checkout-master.png") ] ] #slide(title: [Branching])[ #side-by-side(columns: (1fr, 2fr))[ ```bash # commit to branch master git commit -a -m "My other changes" ``` ][ #image("./img/advance-master.png") ] ] #accent-focus-slide()[ = Live Demo ! - More Poems and Code ] #slide(title: [Merging])[ #side-by-side(columns: (1fr, 2fr))[ #def-block[ = Merge \ - combining branches ] ][ #image("./img/code-poem.svg") ] ] #slide(title: [Merging])[ #side-by-side(columns: (1fr, 1fr))[ ```bash git switch main # get changes from 'more_peoms' into main git merge more_poems ``` ][ #image("./img/poems-ff-merge.svg") ] ] #slide(title: [Merging])[ #side-by-side(columns: (1fr, 1fr))[ ```bash git switch main # get changes from 'more_code' into main git merge more_code ``` ][ #image("./img/code-merge.svg") ] ] #slide(title: [Gitflow])[ #image("./img/git-flow.svg") ] #accent-focus-slide()[ = Live Demo ! - Merging Poems and Code - Merge Conflict ] #slide(title: [Decentralized Multi-Repository Git])[ #side-by-side(columns: (1fr, 2fr))[ #def-block[ = Remote \ - upstream repository - external (web or local) ] ```bash # Clone an existing repo git clone <repository> ``` ][ #image("./img/remote-branches-1.png") ] ] #slide(title: [Decentralized Multi-Repository Git])[ #side-by-side(columns: (1fr, 2fr))[ ```bash # do work git commit # colleagues do work in remote ``` ][ #image("./img/remote-branches-2.png") ] ] #slide(title: [Decentralized Multi-Repository Git])[ #side-by-side(columns: (1fr, 2fr))[ ```bash # fetch changes from remote git fetch origin ``` ][ #image("./img/remote-branches-3.png") ] ] #slide(title: [Decentralized Multi-Repository Git])[ #side-by-side(columns: (1fr, 2fr))[ ```bash # local merge git merge origin/master ``` ][ #image("./img/remote-branches-4.png") ] ] #slide(title: [Decentralized Multi-Repository Git])[ #side-by-side(columns: (1fr, 2fr))[ ```bash # push changes to remote git push origin ``` ][ #image("./img/remote-branches-5.png") ] ] #accent-focus-slide()[ = Live Demo ! - Repositories for Everyone ] #accent-focus-slide()[ = GitHub - Hosting Git Server Online - Collaboration Features ] #slide(title: [Pull Requests])[ #side-by-side(columns: (1fr, 2fr))[ #def-block()[ = Pull Request \ - Request to merge changes - Review ] ][ #align(center)[ #image("./img/github-pr.png") ] ] ] #slide(title: [Code Owners])[ #side-by-side(columns: (1fr, 2fr))[ - define owners of file - file change: approval of codeowner required ][ #align(center)[ #image("./img/codeowners.png") ] ] ] #accent-focus-slide()[ = Live Demo ! - GitHub Website - Creating a Pull Request ] #slide(title: [Force Pushing])[ #side-by-side[ - Rewriting history is kind of lying... Don't do that. At least try to do it locally. (Squashing, etc) - Force pushing is rewriting history on the remote. This will typically cause a lot of confusion. Don't do that. #footnote[Conditions apply: Sensitive data committed, etc.] ][ #align(center)[ #image("./img/meme-force-push.jpg") ] ] ] #slide(title: [Data Recovery & Sensitive Information], new-section: [Don't Do])[ - When data #text(red)[*is committed*], it is very hard to completely loose it. #footnote[Advanced rescue strategies might be needed.] - Do not commit sensitive or personal data. If it happens: - remove it yourself - ask your administrator for help ] #slide(title: [Binary Data])[ - Git itself *can* easily store and merge binary data - If not compressible the repository size might increase #footnote[Solution: Git Large File System (Git LFS)] - Merge conflicts *must* be resolved by you! That is very hard for binary data. #footnote[External Diff and Mergetools can by utilized if necessary] ] #accent-focus-slide[ = Installation & Setup ] #slide(title: [Installing Git], new-section: [Installation & Setup])[ #def-block[ Installation Help:\ https://git-scm.com/book/en/v2/Getting-Started-Installing-Git ] On Linux (using `apt`): ```bash sudo apt install git-all ``` On Windows:\ https://git-scm.com/download/win On Mac OS:\ https://git-scm.com/download/mac ] #slide(title: [Configuration])[ ```bash # setup identity git config --global user.name "<NAME>" git config --global user.email <EMAIL> # avoid hassle exiting vim git config --global core.editor notepad # for comfort git config --global push.default current git config --global push.autoSetupRemote true git config --global push.followtags true ``` ] #slide(title: [Configuration])[ ```bash # use ssh for GitHub (avoid passwords -> ssh keypair) git config --global url.ssh://[email protected]/.insteadof https://github.com/ # alias `git lg` to print a fancy log git config --global alias.lg "log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%ah%C(reset) %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all" ``` ] #slide(title: [Setting up GitHub])[ 1. Sign up at: (Select free plan)\ https://github.com/ 2. Sign into your newly created account:\ https://github.com/login 3. Generate ssh key:\ https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent ] #slide(title: [Setting up GitHub])[ 4. Set up ssh keys:\ https://docs.github.com/de/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account 5. Test the authentication:\ https://docs.github.com/en/authentication/connecting-to-github-with-ssh/testing-your-ssh-connection ] #slide(title: [Setting up GitHub])[ == Generate SSH key Start `Git Bash` Run command: ```bash ssh-keygen -t rsa -b 4096 -C "same_email_as_github<EMAIL>" ``` If prompted for file path: Specify or use default with enter. If prompted passphrase: Hit enter. (Confirm: enter again). #align(center)[ #image("./img/generate-ssh-key.png") ] ] #slide(title: [Setting up GitHub])[ #align(center)[ #image("./img/ssh-key-copy.png") ] ] #slide(title: [Setting up GitHub])[ == Set up SSH key in GitHub 1. Settings 2. SSH and GPG Keys 3. New SSH key 4. Give name to key 5. Paste public SSH key 6. Confirm ] #slide(title: [Setting up GitHub])[ #side-by-side(columns: (1fr, 2fr))[ #align(center)[ #image("./img/github-sidebar.png") ] ][ #align(center)[ #image("./img/github-ssh-setting.png") ] ] ] #slide(title: [Setting up GitHub])[ #align(center)[ #image("./img/github-ssh-paste.png") ] ] #slide(title: [Setting up GitHub])[ == Test the authentication ```bash ssh -T [email protected] ``` If "authenticity cannot be established, are you sure you want to continue?" Type `yes` and hit enter. ] #slide(title: [Getting Help])[ #def-block[ = Getting Help\ 1. https://git-scm.com/book/en/v2 2. ```bash git <command> --help # by default opens online help``` 3. https://docs.github.com/en/get-started/start-your-journey 4. ```bash git help # show commandline help``` 5. https://training.github.com/downloads/github-git-cheat-sheet.pdf ] ]
https://github.com/yaoyuanArtemis/resume
https://raw.githubusercontent.com/yaoyuanArtemis/resume/main/cv_1-zh.typ
typst
Do What The F*ck You Want To Public License
#import "template.typ": * #import "data.typ": * #show: project.with( title: namezh, author: authorzh, ) #section[ #titleemj("curl.svg") #selftitlezh ] #selfzh #section[ #titleemj("mortarboard.svg") #edutitlezh ] #eduzh #section[ #titleemj("seedling.svg") #techtitlezh ] #techzh #section[ #titleemj("telescope.svg") #projecttitlezh ] #projectexperiencezh #section[ #titleemj("darts.svg") #activitytitlezh ] #activityzh #section[ #titleemj("football.svg") #hobbiestitlezh ] #hobbieszh
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas2/0_Nedela.typ
typst
#let M = ( "HV": ( ("", "", "Préžde vík ot Otcá róždšemusja Bóžiju Slóvu, voplóščšemusja ot Ďívy Maríji, prijidíte poklonímsja: krest bo preterpív, pohrebéniju predadésja, jáko sám voschoťí: i voskrés iz mértvych, spasé mja zabluždájuščaho čelovíka."), ("", "", "Préžde vík ot Otcá róždšemusja Bóžiju Slóvu, voplóščšemusja ot Ďívy Maríji, prijidíte poklonímsja: krest bo preterpív, pohrebéniju predadésja, jáko sám voschoťí: i voskrés iz mértvych, spasé mja zabluždájuščaho čelovíka."), ("", "", "<NAME> náš, jéže na ný rukopisánije prihvozdív na kresťí zahládi, i smértnuju deržávu uprazdní: poklaňájemsja jehó tridnévnomu voskreséniju."), ("", "", "So archánhely vospojím Christóvo voskresénije: tój bo jésť izbáviteľ i Spás dúš nášich, i v slávi strášňij i krípcij síľi, páki hrjadét sudíti míru, jehóže sozdá."), ("Dogmat", "", "O prevélija tájinstva! Zrjá čudesá, propovíduju Božestvó, Jemmanújil bo jestestvá úbo vratá otvérze jáko čelovikoľúbec, ďívstva že kľučí ne razruší jáko Bóh: no síce ot utróby prójde, jákože slúchom vníde: táko voplotísja, jákože začátsja: bezstrástno vníde, neskazánno izýde, po proróku hlahóľuščemu: sijá vratá zakľučéna búdut: niktóže prójdet ími, tókmo jedín Hospóď Bóh Izráijlev, imíjaj véliju mílosť."), ), "S": ( ("", "", "Voskresénije tvojé Christé Spáse, vsjú prosvití vselénnuju i prizvál jesí tvojé sozdánije: vsesíľne Hóspodi sláva tebí."), ("", "Jehdá ot dréva", "Vsích skorbjáščich rádoste, i obídimych predstáteľnice, i ubóhich pitáteľnice, stránnych že uťišénije, i žézle sľipých, nemoščných posiščénije, truždájuščichsja pokróve i zastúpnice, i sírych pomóščnice, Máti Bóha výšňaho, tý jesí prečístaja: potščísja, mólimsja, spastísja rabóm tvojím."), ("", "", "Vsjákoje bezzakónije neščádno, vsjákij hrích nevozdéržno okajánnyj soďílach: vsjákaho osuždénija dostójin jésm! Viný pokajánija mňí podážď Ďívo, jáko da ne osuždén támo javľúsja, ťá bo napisúju molítvennicu, ťá prizyváju predstáteľnicu, ne posramí mené Bohonevístnaja."), ("", "", "Inóho pribížišča čístaja, k tvorcú i Vladýci mý ne ímamy, rázvi tebé Bohonevísto: da ne otríneši nás téplym tvojím predstáteľstvom, nižé posramíši ľubóviju pritekájuščich pod króv tvój, Máti Bóha nášeho: potščísja, i tvojú pómošč dážď, i nýňišňaho hňíva nás spasí."), ("Dogmat", "", "Któ ťa po dostojániju pochválit i ublažít, otrokovíce Bohonevístnaja, o jéže tobóju bývšem mírovi izbavléniji: blahodarjášče úbo zovém tí, hlahóľušče: rádujsja, jáže Adáma obožívšaja, i razstojáščaja sovokupívšaja. rádujsja, prosvitívšaja ród náš svitonósnym voskresénijem Sýna tvojehó i Bóha nášeho: ťá bo christiánskij ród neprestánno ublažájem."), ) ) #let V = ( "HV": ( ("", "", "Préžde vík ot Otcá róždšemusja Bóžiju Slóvu, voplóščšemusja ot Ďívy Maríji, prijidíte poklonímsja: krest bo preterpív, pohrebéniju predadésja, jáko sám voschoťí: i voskrés iz mértvych, spasé mja zabluždájuščaho čelovíka."), ("", "", "Christós Spás náš, jéže na ný rukopisánije prihvozdív na kresťí zahládi, i smértnuju deržávu uprazdní: poklaňájemsja jehó tridnévnomu voskreséniju."), ("", "", "So archánhely vospojím Christóvo voskresénije: tój bo jésť izbáviteľ i Spás dúš nášich, i v slávi strášňij i krípcij síľi, páki hrjadét sudíti míru, jehóže sozdá."), ("", "", "Tebé raspénšahosja i pohrebénnaho, ánhel propovída Vladýku, i hlahólaše ženám: prijidíte vídite, iďíže ležáše Hospóď: voskrése bo, jákože rečé, jáko vsesílen. Ťímže tebí poklaňájemsja jedínomu bezsmértnomu: žiznodávče Christé, pomíluj nás."), ("", "", "Krestóm tvojím uprazdníl jesí, júže ot dréva kľátvu, pohrebénijem tvojím umertvíl jesí smérti deržávu: vostánijem že tvojím prosvitíl jesí ród čelovíčeskij. sehó rádi vopijém tí: blahoďíteľu Christé Bóže náš, sláva tebí."), ("", "", "Otverzóšasja tebí Hóspodi, stráchom vratá smértnaja, vrátnicy že ádovy víďivše ťá, ubojášasja: vratá bo mídnaja sokrušíl jesí, i verejí žeľíznyja stérl jesí, i izvél jesí nás ot ťmý i síni smértnyja, i úzy náša rasterzál jesí."), ("", "", "Spasíteľnuju písň pojúšče, ot úst vozslém: prijidíte vsí v domú Hospódnem pripadém, hlahóľušče: na dréve raspnýjsja, i iz mértvych voskresýj, i sýj v ňídrech Ótčich, očísti hrichí náša."), ("", "Otčájannaja žitijá rádi", "Jáže nenadéžnych upovánije izvístnoje, i sohrišájuščich spasénije, Maríje vsepítaja čístaja Bohoródice, prijimí molénije mojé sijé, i isprosí mi razrišénija vsích, jáže sohriších v žitií, máternimi tvojími molítvami, i spasí ot bíd i búduščaho sudá Vladýčice, velíkija rádi tvojejá mílosti."), ("", "", "Lukávo vrémja životá mojehó, lukávo i ispólň vsjákija zlóby, sataňi lukávomu ľúťi mjá smuščájušču, tý mja Bohorodíteľnice, izbávi tohó pákosti, tý mja ot úst ónaho istórhni presvjatája: na ťá bo vsé vozložích čájanije mojé, spasí mja tvojími bódrymi molítvami."), ("", "", "Rádujsja, nepostýdnaja predstáteľnice. Rádujsja, preblahája Bohoródice. Rádujsja, očistílišče míra. Rádujsja, rádoste skorbjáščich, i pristánišče oburevájemym. Rádujsja, jáže vsím pomohájuščaja súščym v núždach. Tý úbo sochraní i mené Ďívo, vsích skórbnych, preneporóčnaja Vladýčice."), ("Dogmat", "", "Préjde síň zakónnaja, blahodáti prišédši: jákože bo kupiná ne sharáše opaľájema, táko Ďívo rodilá jesí, i Ďíva prebylá jesí. Vmísto stolpá óhnennaho, právednoje vozsijá sólnce: vmísto Moiséa, Christós, spasénije dúš nášich."), ), "S": ( ("", "", "Voskresénije tvojé Christé Spáse, vsjú prosvití vselénnuju i prizvál jesí tvojé sozdánije: vsesíľne Hóspodi sláva tebí."), ("", "", "Drévom Spáse uprazdníl jesí, júže ot dréva kľátvu, deržávu smérti pohrebénijem tvojím umertvíl jesí, prosvitíl že jesí ród náš vostánijem tvojím. Ťímže vopijém tebí: životodávče Christé Bóže náš, sláva tebí."), ("", "", "Na kresťí jávľsja Christé prihvoždájem, izminíl jesí dobrótu zdánij: i bezčelovíčije úbo vójini pokazújušče, kopijém rébra tvojá probodóša, jevréji že pečátati hróba prosíša, tvojejá vlásti ne vídušče. No za milosérdije utrób tvojích, prijémyj pohrebénije, i tridnéven voskrésýj Hóspodi sláva tebí."), ("", "", "Životodávče Christé, vóleju strásť preterpívyj smértnych rádi, vo ád že snizšéd jáko sílen, támo tvojehó prišéstvija ožidájuščyja, ischítiv jáko ot zvírja krípkaho, ráj vmísto áda žíti darovál jesí. Ťímže i nám slávjaščym tridnévnoje tvojé vostánije, dáruj očiščénije hrichóv, i véliju mílosť."), ("Dogmat", "", "O čudesé nóvaho vsích drévnich čudés! Któ bo pozná máter bez múža róždšuju, i na rukú nosjáščuju, vsjú tvár soderžáščaho? Bóžije jésť izvolénije, róždšejesja. Jehóže jáko mladénca prečístaja, tvojíma rukáma nosívšaja, i máterne derznovénije k nemú imúščaja, ne prestáj moľášči o čtúščich ťá, uščédriti i spastí dúšy náša."), ), "T": ( ("", "", "Jehdá snizšél jesí k smérti, životé bezsmértnyj, tohdá ád umertvíl jesí blistánijem božestvá. Jehdá že i uméršyja ot preispódnich voskresíl jesí, vsjá síly nebésnyja vzyváchu: žiznodávče Christé Bóže náš, sláva tebí."), ("Bohoródičen", "", "Vsjá páče smýsla, vsjá preslávnaja tvojá Bohoródice, tájinstva, čistoťí zapečátannoj, i ďívstvu chranímu Máti poználasja jesí nelóžna, Bóha róždši ístinnaho: tohó molí spastísja dušám nášym."), ), ) #let P = ( "1": ( ("", "", "Vo hlubiňí postlá inohdá, faraonítskoje vsevójinstvo preoružénnaja síla, voplóščšejesja že Slóvo vsezlóbnyj hrích potrebílo jésť: preproslávlennyj Hospóď slávno bo proslávisja."), ("", "", "Jáže vsím udób poslúšnaja v skórbi, i v pečáli pomohájuščaja, Bohoródice blahája, blahodáť podážď píti ťá derzájuščym, Vladýčice skorbjáščich rádoste."), ("", "", "Mnohobohátnuju blahodáť sťažávši Vladýčice, derznovénnoju tvojéju molítvoju, preslávno izmí mja ot napástej, ubóhaho rabá tvojehó, skorbjáščich rádoste."), ("", "", "Ot vráh vídimych i nevídimych izbávi, mólimsja, k tebí pribihájuščich Bohoródice, i razorí vsják sovít borjúščich nás."), ("", "", "Otimí ponošénije čelovíčeskoje, i klevetý navítnik ot mené, Bohoródice, moľú ťa: da usérdno slávľu Hóspoda, jehóže pitála jesí."), ), "3": ( ("", "", "Utverdí nás v tebí Hóspodi, drévom umerščvéj hrích, i strách tvój vsadí v serdcá nás pojúščich ťá."), ("", "", "Vrahóv navíty razorí sújetnyja, vsepítaja Bohoródice: ne oskuďíj molítvami tvojími, snabďášči nás voschvaľájuščich ťá."), ("", "", "Prízri čístaja, mílostivnym tvojím ókom, i izbávi mjá vsjákaho navíta vídimych i nevídimych vrahóv, osľipívši zínicy očés ích."), ("", "", "Zlóje napadénije vrahóv, jáko óhň paľáščeje, íščuščich vsehdá pohubíti nás Ďívo, rosóju molítv tvojích uhasí."), ("", "", "Neuhasímaja lampádo, zaré prisnosijáteľnaja, nóščiju mjá skorbéj oderžíma, prosvití molítvami tvojími, róždšaja sólnce slávy Christá."), ), "4": ( ("", "", "Uslýšach Hóspodi hlás tvój, jehóže rékl jesí, hlás vopijúščaho v pustýni, jáko vozhremíl jesí nad vodámi mnóhimi, tvojemú sviďíteľstvujaj Sýnu, vés býv sošédšaho Dúcha, vozopí: tý jesí Christós, Bóžija múdrosť i síla."), ("", "", "Spasénija ťá móst, molítvu neusýpnu, zastuplénije tvérdo mólim: umilosérdisja i vížď nášu nesterpímuju pečáľ, boľízni, skórbi, strásti, i blahopremínno posití Máti Bóžija, rádosť skóruju podajúšči."), ("", "", "Ne nepričástni jesmý Vladýčice, tvojehó zastuplénija v skórbech: ťímže i nýňi nám pomozí vskóri, ľúťi oburevájemym rúku prostirájušči čístaja: búdi mílostiva boľíznem nášym, Máti Bóžija, rádosť skóruju podajúšči."), ("", "", "Ne upováša Vladýčice na ťá bezzakónnujuščiji, no upováša na jazýk veleríčiv, na jazýk čelovíč, prísno zavístno izlijávšijsja, neprávedno prolijáti króv ískrenňaho, rykájušče: tý že čístaja, čéľusti ích sokruší."), ("", "", "Smirí Vladýčice, vrahóv voznesénnuju výju veleríčujuščich, sovíty i zlonrávija, i serdcá poučájuščajasja zlým na mjá po vsjá dní: kríposť že i pobídu podážď prizyvájuščym ťá, Máti Bóžija, rádosť skóruju podajúšči."), ), "5": ( ("", "", "Úhľ Isáiji projavléjsja, sólnce iz ďívstvennyja utróby vozsijá, vo ťmí zablúždšym, Bohorazúmija prosviščénije dáruja."), ("", "", "Molítvennice nelóžnaja, upovánije christiján, obrádovannaja, prijimí moľbý ot nás priľížno prizyvájuščich i moľáščichsja tebí."), ("", "", "Istóčnik ťá žízni súšči čístaja, bezsmértija istočájuščij vódy, zemnoródniji poznávše ublažájem."), ("", "", "Vooružísja na ný lukávno vráh, jazýkom jákože mečém pohubíti choťá: no tvojéju, Bohorodíteľnice, krípostiju predvarí."), ("", "", "Pučínu, čístaja, zastupléniju któ izočtét síly tvojejá? Ťímže nás súščich v núžďi skóro predvarí."), ), "6": ( ("", "", "V bézdňi hrichóvňij vaľájasja, neizsľídnuju milosérdija tvojehó prizyváju bézdnu: ot tlí Bóže mjá vozvedí."), ("", "", "Cilomúdrija súšči chodátaica, prizyvájuščym ťá nýňi javísja, i ot vsjákich izbávi napástej i bíd, Bohonevísto."), ("", "", "Zloďíjstva vrážija razorí, i klevetý neprávednyja ustávi, blahoslovénnaja prečístaja, izbavľájušči nepovínnyja ot skórbi."), ("", "", "Ľútymi hrichí okružéni, i napástnymi bidámi potopľájemi, pod božéstvennyj pokróv tvój pribihájem, Máti Christá Bóha."), ("", "", "Neiskusomúžno róždši Hóspoda, javísja po roždeství páki ďívstvujušči: o preslávnaho čudesé, v tebí soďílannaho, Bohonevísto!"), ), "S": ( ("", "", "Molénije téploje, i sťiná neoborímaja, mílosti istóčniče, mírovi pribížišče, priľížno vopijém tí: Bohoródice Vladýčice predvarí, i ot bíd izbávi nás, jedína vskóri predstáteľstvujuščaja."), ), "7": ( ("", "", "Da preslávnoje roždestvó tvojé Christé, jéže ot Ďívy proobrazíši jávi, neopalímy v peščí ótroki sochraníl jesí, písňmi pojúščyja tebí: otcév Bóže blahoslovén jesí."), ("", "", "O blahoutróbija tvojehó Ďívo čístaja! Rišíši bo bezmírnyja pečáli i napásti, prizyvájuščym v núžďi i obstojániji: ťímže i nýňi pomozí blahoslovénnaja, ťá voschvaľájuščym."), ("", "", "Pokaží skóroje tvojé zastuplénije, pokaží jáko móžeši, jáko Máti Bóhu, prizyvájem ťá ot sérdca so slezámi pripádajušče, skórb ukrotí i boľízň rabóv tvojích vskóri."), ("", "", "Ustá čelovíkom jáko ľvóm ľútym, hróba ťažčájše otverzóšasja, hórko pohlotíti mjá: no tý Bohoródice, javísja nadéžda nenaďíjuščymsja, i nizloží kríposť ích blahoslovénnaja."), ("", "", "Da úzrjat vrazí i postyďátsja, da razumíjut i víďat tvojú, jéže po nám soprotív borjúščuju sílu, i v própasť preispódňuju nizloží ích blahoslovénnaja, nadéždo nenaďíjuščichsja."), ), "8": ( ("", "", "Péšč inohdá óhnennaja v Vavilóňi ďíjstva razďiľáše, Bóžijim veľínijem chaldéji opaľájuščaja, vírnyja že orošájuščaja, pojúščyja: blahoslovíte vsjá ďilá Hospódňa Hóspoda."), ("", "", "Pribížišče náše, i míru rádovanije, Bohorodíteľnice, umilosérditisja potščísja, i spíšno blahodáť tvojú podážď nám oskorblénnym, i zastupí blahája, tvojá rabý."), ("", "", "Sovít súeten soviščáša ľúťi na ný bezbóžnych sónmišča, jákože préžde Achitofél. No vopijém: tvojími molítvami séj razorí, nizlóžši sích kríposť Bohoródice."), ("", "", "Prizyvájuščich ťá Bohoródice, ot duší nelóžno, vo vsjákoj skórbi i v boľíznech razlíčnych, i bidách ľútych, spíšno uslýši Vladýčice, sích izbavľájušči prísno molítvami tvojími."), ("", "", "Da ímja tvojé Bohoródice, na zemlí slavoslóvitsja, íže iz tebé vozsijáv, hríšnikom deržávnuju nadéždu i sťínu ťá darová: tobóju bo vsjákoje dychánije k Bóhu pritekájet."), ), "9": ( ("", "", "Nedoumíjet vsják jazýk blahochvalíti po dostojániju, izumivájet že úm i premírnyj píti ťá Bohoródice: obáče blahája súšči, víru prijimí, íbo ľubóv vési božéstvennuju nášu, tý bo christiján jesí predstáteľnica, ťá veličájem."), ("", "", "Da zahradítsja vsják jazýk, lukávym poučájajsja: da molčát ustná ľstívaja, i ustá neprávedno hlahóľuščaja na právednaho bezzakónije, hordýneju i závistiju vraždébnoju vkúpi, Bohoródicy molítvoju, i svjatých Christóvych."), ("", "", "Íže v molítvach bódruju, čístuju Bohoródicu, prizyvájem vsí boľízniju i skórbiju oderžími, vzyvájušče: Vladýčice čístaja, skóro izbávi ot oderžáščich boľíznej rabý tvojá prísno, jáko po Bóze zastúpnicy inýja ne ímamy."), ("", "", "Otčájavšichsja vélije pribížišče, oburevájemych tíchoje pristánišče, tý jesí Bohoródice. ťímže i mý pritekájem, vzyvájušče: da ne postydímsja Máti ístinnaho životá, no da blahodarjášče usérdno ťá veličájem."), ("", "", "Prijimí, otrokovíce prečístaja, božéstvennuju písň, vozdavájušči blahodáť na ťá naďíjuščymsja, i mír isprosí cérkvam prísno posláti, da christijánskij vsják jazýk ťá veličájet."), ), ) #let N = ( "1": ( ("", "", "Vo hlubiňí postlá inohdá, faraonítskoje vsevójinstvo preoružénnaja síla, voplóščšejesja že Slóvo vsezlóbnyj hrích potrebílo jésť, preproslávlennyj Hospóď, slávno bo proslávisja."), ("", "", "Trójičnoje i jedinonačáľnoje jestestvó božestvá, písnenno vospojím hlahóľušče: mílosti pučínu neizčerpájemuju, suščéstvennuju jáko imúšči, tebí kláňajuščichsja sobľudí i spasí, jáko čelovikoľúbec."), ("", "", "Íže istóčnik, i kóreň Otéc sýj, jáko vinóven, íže v Sýňi, i svjaťím tvojém Dúsi, sráslennaho božestvá trisólnečnyj sérdcu mojemú istočí svít, i pričástijem osijáj, Bohoďíteľnaho sijánija."), ("", "", "Trisvítlaja jedínice Bohonačáľnaja, vés razorí hrichóv i strastéj mojích mrák, svítlych lučéj tvojích sladčájšimi pričaščéňmi, i sotvorí mja tvojejá nepristúpnyja slávy chrám i síň prečístuju."), ("Bohoródičen", "", "Tók drévnij jestestvá nášeho, stradávšij bezmístno, i k tlí popólzšijsja prečístaja, voplóščsja vo utróbi tvojéj Bóh Slóvo, čelovikoľúbňi osijá, i Bohonačáliju trisvítlomu nás tájno naučí."), ), "3": ( ("", "", "Na kámeni mjá víry utverdív, razširíl jesí ustá mojá na vrahí mojá, vozveselí bo sja dúch mój, vnehdá píti: ňísť svját, jákože Bóh náš, i ňísť práveden, páče tebé Hóspodi."), ("", "", "Rávenstvom jestestvá Bohonačálije jedinočéstnoje slávľu ťá lícy: živót bo ot životá tý proizšéd netľínno, jedín sýj Bóh náš, i ňísť svját, páče tebé Hóspodi."), ("", "", "Tý číny neveščéstvennyja i nebésnyja sostávil jesí, jáko zercála tvojejá dobróty: Tróice nerazďíľnoje jedinonačálije, píti neprestánno tebí: no i nýňi náše ot brénnych úst prijimí chvalénije."), ("", "", "Utverdí na kámeni víry, i razširí ľubvé tvojejá pučínoju serdcá i mýsľ tvojích ráb, jedínice trisólnečnaja: tý bo Bóh náš, na nehóže upovájušče, da ne posramímsja."), ("Bohoródičen", "", "Íže vsják préžde sostáv osuščestvovávyj tvári, vo utróbi tvojéj osuščestvovásja, neizčétnoju bláhostiju Bohoródice, i svít trisólnečnyj vsím vozsijá jedínaho Božestvá i Hospóďstva."), ), "S1": ( ("", "Blahoutróbija", "Jehdá v načáľi Adáma sozdál jesí Hóspodi, tohdá Slóvu tvojemú ipostásnomu vozopíl jesí blahoutróbne: sotvorím po nášemu podóbiju, Dúch že svjatýj soprisútstvovaše soďíteľ. Ťímže vopijém tí: tvórče Bóže náš, sláva tebí."), ("Bohoródičen", "", "Jehdá k nám Bóh prijití izvóli, tohdá v tvojú prečístaja, čisťíjšuju utróbu vselísja, i spasé tobóju čelovíčeskoje smišénije, darovávyj vsím cárstvo nebésnoje. Ťímže vopijém tí, Bohoródice čístaja, rádujsja Vladýčice."), ), "4": ( ("", "", "Pojú ťa, slúchom bo Hóspodi uslýšach i užasóchsja, do mené bo ídeši, mené iščjá zablúždšaho. Ťím mnóhoje tvojé snizchoždénije, jéže na mjá, proslavľáju mnohomílostive."), ("", "", "Razumíti ťá nižé čínove móhut neveščéstvenniji ánheľstiji, jedínice, Tróice beznačáľnaja: no úbo mý brénnym jazýkom tvojú súščestvennuju bláhosť vospivájem, i víroju slávim."), ("", "", "Sýj sozdáteľ jestestvá čelovíčeskaho, vsederžíteľu, vsé mojé vídiši nýňi, jáko vsevídec nemožénije: ťímže uščédri rabá tvojehó, i k žízni lúčšej páki vozvedí."), ("", "", "Jedínicy načáľnyja nesmísna trí líca vospivájem, jáko svójstvenne imúščaja, i razďíľňi ipostási: no úbo sojedinéna i nerazďíľna, v sovíťi že, i slávi, i Božeství."), ("Bohoródičen", "", "Chrám ťá číst i preneporóčen, prisnoďívo Bohoródice, vseďíteľ obríte jedínu jávi ot víka, v ňúže vséľsja: voobrazí čelovíčeskoje jestestvó, jáko čelovikoľúbec."), ), "5": ( ("", "", "Prosviščénije vo ťmí ležáščich, spasénije otčájannych Christé Spáse mój, k tebí útreňuju carjú míra, prosvití mja sijánijem tvojím: inóho bo rázvi tebé Bóha ne znáju."), ("", "", "Jáko vsjáčeski na vsjá súščyja tvojehó prómysla, mirodárnyja prostirájaj lučý, i spasíteľnyja, carjú míra, sobľudí mja v míri tvojém: tý bo živót i mír vsjáčeskomu."), ("", "", "Mojséju v kupiňí jáko javílsja jesí v viďíniji óhnenňi, ánhel naréklsja jesí Ótčeje Slóvo, jéže k nám tvojé predjavľája prišéstvije: ímže vsím jávi vozvistíl jesí deržávu Bohonačálija jedínaho, trijipostásnuju."), ("", "", "Jáže jestéstvennuju, soprisnosúščnuju slávu predlóžiši, jedinonačáľňijšaja Tróice svjatája, vospivájuščich ťá pravoslávnoju víroju, tvojejá slávy víďiti spodóbi, beznačáľnuju, i jedínu zarjú trisólnečnuju."), ("Bohoródičen", "", "Soderžíteľnyj po suščestvú sýj Bóh Slóvo, vsím vikóm, Ďívo Máti, vo črévi tvojém uderžásja neizrečénno, čelovíki prizyvája ko jedínstvu jedínaho Hospóďstva."), ), "6": ( ("", "", "V bézdňi hrichóvňij vaľájasja, neizsľídnuju milosérdija tvojehó prizyváju bézdnu: ot tlí Bóže mjá vozvedí."), ("", "", "Volíteľu mílosti, pomíluj v ťá vírujuščich, Bóže trisólnečne, i prehrišénij izbávi, i strastéj, i bíd, rabý tvojá."), ("", "", "Volíteľu mílosti, pomíluj v ťá vírujuščich, Bóže trisólnečne, i prehrišénij izbávi, i strastéj, i bíd, rabý tvojá."), ("", "", "Neizrečénnoju pučínoju bláhosti, neobmýslimuju tvojehó sijánija, i trisijánnaho Božestvá svitodáteľnuju zarjú podážď mí."), ("Bohoródičen", "", "Neizrečénne Ďívo, výšnij čelovík býsť iz tebé, v čelovíka po vsemú obólksja, i svítom mjá trisólnčnym ozarí."), ), "S2": ( ("", "Blahoutróbija", "Blahoutróbija pučínu nám prostrýj, prijimí nás mílostive, prízri na ľúdi ťá slávjaščyja, prijimí písň prosjáščich ťá, Tróice jedínice beznačáľnaja: na ťá bo upovájem vsích Bóha, prehrišénij dáti proščénije."), ("Bohoródičen", "", "Blahoutróbija róždši istóčnik, mílostiva tý jesí blahája Bohoródice: tý bo vírnych jedíno zastuplénije, tý skorbjáščich uťišénije. Ťímže tebí nýňi vsí víroju pripádajem, obristí razrišénije ľútych, obohaťíjuščesja jedínoju tebé pómoščiju."), ), "7": ( ("", "", "Óbrazu zlatómu na póli deíri služímu, trijé tvojí ótrocy nebrehóša bezbóžnaho veľínija: posreďí že ohňá vvérženi, orošájemi pojáchu: blahoslovén jesí Bóže otéc nášich."), ("", "", "Ustavľáješi prísno ánheľskaja vójinstva k nepreložéniju, jedíne sýj neizmínne i trijipostásne Hóspodi: pokaží úbo i mojé sérdce neprelóžno vsehdá, vo jéže sláviti ťá tépľi, i vospiváti blahočéstno."), ("", "", "Ustavľáješi prísno ánheľskaja vójinstva k nepreložéniju, jedíne sýj neizmínne i trijipostásne Hóspodi: pokaží úbo i mojé sérdce neprelóžno vsehdá, vo jéže sláviti ťá tépľi, i vospiváti blahočéstno."), ("", "", "Lícy úmniji neveščéstvennych suščéstv, tvojími lučámi Bóže jedinonačáľne, i trisólnečne, ozarjájemi byvájut, položénijem vtoríji svítove: íchže i mené sijáňmi, i pričástijem pokaží svít, jáko svetoďíteľ trisijánen."), ("Bohoródičen", "", "Napravľáti nás i vozvyšáti k nebesém ne oskuďíj, tebé ľúbjaščich, íže za neizrečénnoje čelovikoľúbije, býv čelovík vo utróbi Ďívy, i obožív čelovíka, i na prestóľi slávy so Otcém siďáj."), ), "8": ( ("", "", "O podóbiji zláťi nebréhše treblážénniji júnoši, neizménnyj i živýj Bóžij óbraz víďivše, sredí ohňá vospiváchu: osuščestvovánnaja da pojét Hóspoda vsjá tvár, i prevoznósit vo vsjá víki."), ("", "", "Nepristúpnaja Tróice soprisnosúščnaja, sobeznačáľnaja, Bohonačáľnaja, neizmínnaja vo vsích, kromí svitonósnych svójstv, vsjákij lukávyj uprazdní soprotivoležáščich sovít, i stužénija démonov, nevrédna sobľudájaj mjá prísno, Hóspodi vsích."), ("", "", "Nepristúpnaja Tróice soprisnosúščnaja, sobeznačáľnaja, Bohonačáľnaja, neizmínnaja vo vsích, kromí svitonósnych svójstv, vsjákij lukávyj uprazdní soprotivoležáščich sovít, i stužénija démonov, nevrédna sobľudájaj mjá prísno, Hóspodi vsích."), ("", "", "Premúdri i vsemóščňie, neopísannoje, trisólnečnoje jedinonačálije sostávľšeje mír, i sobľudájuščeje v nevredímom číňi vsesoveršénnom, vselísja v mojé sérdce, píti i sláviti ťá nemólčno s líki ánheľskimi vo vsjá víki."), ("", "", "Premúdroste Ótčaja, nepostižíme, neizrečénne, Bóžij Slóve, neprelóžnoje tvojé jestestvó ne izminív, jestestvó čelovíčeskoje mílostivne vosprijál jesí: i jedínstvennuju Tróicu čestí vsích naučíl jesí, jáko Hóspodonačálije vsích vikóv."), // TODO: Tu je rozdiel oproti Lvovskemu oktoichu ), "9": ( ("", "", "Jáže préžde sólnca svitíľnika Bóha vozsijávšaho, plótski k nám prišédšaho, iz bokú ďivíču neizrečénno voplotívšaja, blahoslovénnaja vsečístaja, ťá Bohoródice veličájem."), ("", "", "Ot svíta beznačáľna, sobeznačálen Sýn svít vozsijá, i sojestéstvennyj svít Dúch izýde, neizrečénno Bohoľípno, netľínnu roždestvú uverjájemi, vkúpi že i neizrečénnomu ischoždéniju."), ("", "", "Vozsijáj v serdcách trisólnečnoje Božestvó, vospivájuščich ťá, trisijánnym svítom tvojím: i dážď rázum jéže vo vsích razumíti, i ďíjati tvojé choťínije blahóje i soveršénnoje, i veličáti i sláviti ťá."), ("", "", "Neizčéten jestestvóm sýj jáko Bóh, neizčétnuju pučínu ščedrót jáko imíja, uščédrila jesí Tróice préžde: táko i nýňi uščédri rabý tvojá, i ot prehrišénij izbávi, i napástej i obstojánij."), ("Bohoródičen", "", "Spasí mja Bóže mój, ot vsjákaho iskušénija i ozloblénija, íže v trijéch lícich vospivájemyj neskazánno, jedínstvenňi Bóh i vsesíľnyj, i tvojé stádo sochraní, Bohoródicy molítvami."), ), ) #let U = ( "T": ( ("", "", "Jehdá snizšél jesí k smérti, životé bezsmértnyj, tohdá ád umertvíl jesí blistánijem božestvá. Jehdá že i uméršyja ot preispódnich voskresíl jesí, vsjá síly nebésnyja vzyváchu: žiznodávče Christé Bóže náš, sláva tebí."), ("Bohoródičen", "", "Vsjá páče smýsla, vsjá preslávnaja tvojá Bohoródice, tájinstva, čistoťí zapečátannoj, i ďívstvu chranímu Máti poználasja jesí nelóžna, Bóha róždši ístinnaho: tohó molí spastísja dušám nášym."), ), "S1": ( ("", "", "Blahoobráz<NAME>, s dréva sném prečístoje tvojé ťílo, plaščaníceju čístoju obvív, i blahoucháňmi vo hróbi nóve zakrýv položí: no tridnéven voskrésl jesí Hóspodi, podajá mírovi véliju mílosť."), ("", "", "Mironósicam ženám pri hróbi predstáv ánhel vopijáše: míra mértvym súť prilíčna, Christós že istľínija javísja čúžď. No vozopíjte: voskrése Hospóď, podajá mírovi véliju mílosť."), ("Bohoródičen", "", "Preproslávlenna jesí Bohoródice Ďívo, pojém ťá: krestóm bo Sýna tvojehó nizložísja ád, i smérť umertvísja, umerščvlénniji vostáchom, i životá spodóbichomsja: ráj vosprijáchom drévneje naslaždénije. Ťím bláhodarjášče, slavoslóvim jáko deržávnaho Christá Bóha nášeho, i jedínaho mnohomílostivaho."), ), "S2": ( ("", "", "Kámeň hróbnyj zapečátati ne vozbranív, kámeň víry voskrés pódal jesí vsím, Hóspodi sláva tebí."), ("", "", "Učenikóv tvojích lík s mironósicami ženámi rádujetsja sohlásno: óbščij bo prázdnik s ními prázdnujut, v slávu i čésť tvojehó voskresénija. I ťími vopijém tí, čelovikoľúbče Hóspodi: ľúdem tvojím podážď véliju mílosť."), ("Bohoródičen", "", "Preblahoslovénna jesí Bohoródice Ďívo, voplóščšim bo sja iz tebé ád pľinísja, Adám vozzvásja, kľátva potrebísja, Jéva svobodísja, smérť umertvísja, i mý ožíchom. Ťím vospivájušče vopijém: blahoslovén Christós Bóh blahovolívyj táko, sláva tebí."), ), "Y": ( ("", "", "Po strásti šédša vo hrób žený, vo jéže pomázati ťílo tvojé Christé Bóže, víďiša ánhely vo hróbi, i užasóšasja: hlás bo slýšachu ot ních, jáko voskrése Hospóď, dáruja mírovi véliju mílosť."), ), "A1": ( ("", "", "Na nébo óči puščáju mojehó sérdca, k tebí Spáse, spasí mja tvojím osijánijem."), ("", "", "Pomíluj nás sohrišájuščich tebí mnóho, na vsjákij čás, o Christé mój, i dážď óbraz préžde koncá pokájatisja tebí."), ("", "", "Svjatómu Dúchu, jéže cárstvovati podobájet, osvjaščáti, podvizáti tvár: Bóh bo jésť, jedinosúščen Otcú i Slóvu."), ("", "", "Svjatómu Dúchu, jéže cárstvovati podobájet, osvjaščáti, podvizáti tvár: Bóh bo jésť, jedinosúščen Otcú i Slóvu."), ), "A2": ( ("", "", "Ášče ne Hospóď by býl v nás, któ dovólen cíl sochranén býti ot vrahá, kúpno i čelovikoubíjcy?"), ("", "", "Zubóm ích ne predážď Spáse, tvojehó rabá: íbo ľvóvym óbrazom na mjá podvizájutsja vrazí mojí."), ("", "", "Svjatómu Dúchu živonačálije i čésť: vsjá bo sozdánnaja, jáko Bóh sýj síloju sobľudájet vo otcé, Sýnom že."), ("", "", "Svjatómu Dúchu živonačálije i čésť: vsjá bo sozdánnaja, jáko Bóh sýj síloju sobľudájet vo otcé, Sýnom že."), ), "A3": ( ("", "", "Naďíjuščijisja na Hóspoda, upodóbišasja horí svjaťíj: íže nikákože dvížutsja prilóhi vrážijimi."), ("", "", "V bezzakóniji rúk svojích da ne próstrut božéstvenňi živúščiji: ne ostavľájet vo Christós žezlá na žrébiji svojém."), ("", "", "Svjátým Dúchom tóčitsja vsjáka premúdrosť: otsjúdu blahodáť apóstolom, i stradáľčestvy vinčájutsja múčenicy, i prorócy zrját."), ("", "", "Svjátým Dúchom tóčitsja vsjáka premúdrosť: otsjúdu blahodáť apóstolom, i stradáľčestvy vinčájutsja múčenicy, i prorócy zrját."), ), "P": ( ("", "", "Vostáni Hóspodi Bóže mój poveľínijem, ímže zapovídal jesí, i sónm ľudéj obýdet ťá"), ("", "", "Hóspodi Bóže mój na ťá upovách, spasí mja."), ), "K": ( "P1": ( "1": ( ("", "", "Vo hlubiňí postlá inohdá, faraonítskoje vsevójinstvo preoružénnaja síla, voplóščšejesja že Slóvo vsezlóbnyj hrích potrebílo jésť, preproslávlennyj Hospóď, slávno bo proslávisja."), ("", "", "Mirskíj kňáz bláže, jemúže napisáchomsja, zápovidi tvojejá ne poslúšavše, krestóm tvojím osudísja: prirazísja bo tí jáko smértnu: otpadé že vlásti tvojejá deržávoju, i nemoščnýj obličísja."), ("", "", "Izbáviteľ róda čelovíčeskaho, i netľínnomu životú načáľnik v mír prišél jesí: voskresénijem bo tvojím razdrál jesí smértnyja pelený, jéže slavoslóvim vsí: slávno bo proslávisja."), ("Bohoródičen", "", "Prevýšši javílasja jesí čístaja prisnoďívo, vsjákija nevídimyja že i vídimyja tvári: ziždíteľa bo rodilá jesí, jáko blahovolí voplotítisja vo utróbi tvojéj, jehóže so derznovénijem molí, spastí dúšy náša."), ), "2": ( ("", "", "Netrénu, neobýčnu, nemókrenno morskúju šéstvovav stezjú, izbránnyj vopijáše Izráiľ: Hóspodevi poím, jáko proslávisja."), ("", "", "Síla nemoščných, voskresénije pádšich, i netľínije uméršich býl jesí Christé, plóti tvojejá strástiju: jáko proslávisja."), ("", "", "Uščédri pádšij óbraz, i voskresí sokrušénnyj, soďíteľ Bóh i obnovíteľ umerščvlén býv vsích oživí: jáko proslávisja."), ), "3": ( ("", "", "Netrénu, neobýčnu, nemókrenno morskúju šéstvovav stezjú, izbránnyj vopijáše Izráiľ: Hóspodevi poím, jáko proslávisja."), ("", "", "Neveščéstvennaja drévle ľístvica, i stránno oledeňívšij púť mórja, tvojé javľáše roždestvó čístaja, jéže pojém vsí: jáko proslávisja."), ("", "", "Síla výšňaho, ipostás soveršénnaja, Bóžija múdrosť, voplóščšisja prečístaja, iz tebé, k čelovíkom besídova jáko proslávisja."), ("", "", "Prójde skvozí dvér neprochódnuju, zakľučénnyja utróby tvojejá, právdy Sólnce čístaja, i mírovi vozsijá: jáko proslávisja."), ) ), "P3": ( "1": ( ("", "", "Procvilá jésť pustýňa, jáko krín, Hóspodi, jazýčeskaja neploďáščaja cérkov, prišéstvijem tvojím, v néjže utverdísja mojé sérdce."), ("", "", "Tvár v strásti tvojéj izmiňášesja, zrjášči ťá v niščétňi óbrazi ot bezzakónnych poruhájema, osnovávšaho vsjá božéstvennym manovénijem."), ("", "", "Ot pérsti po óbrazu mjá rukóju tvojéju sozdál jesí: i sokrušénna páki v pérsť smértnuju za hrích, Christé sošéd vo ád, sovoskresíl jesí."), ("Bohoródičen", "", "Číni udivíšasja ánheľstiji prečístaja, i čelovíčeskaja ustrašíšasja serdcá o roždeství tvojém: ťímže ťá Bohoródicu víroju čtím."), ), "2": ( ("", "", "Lúk sokrušísja síľnych deržávoju tvojéju Christé, i síloju nemoščstvújuščiji prepojásašasja."), ("", "", "Íže vsích výšši Christós, umálisja málym čím, strástiju plotskóju, ánheľskaho jestestvá."), ("", "", "Mértv so bezzakónnymi vminívsja, sijája ženám vincém slávy Christé, javílsja jesí ot voskrésnija."), ), "3": ( ("", "", "Lúk sokrušísja síľnych deržávoju tvojéju Christé, i síloju nemoščstvújuščiji prepojásašasja."), ("", "", "Íže vrémene prevýššij vsjákaho, jáko vrémenem tvoréc, iz tebé Ďívo vóleju mladénec sozdásja."), ("", "", "Črévo prostránňijšeje nebés vospojím, ímže Adám na nebesích rádujasja živét."), ) ), "P4": ( "1": ( ("", "", "Prišél jesí ot Ďívy, ne chodátaj, ni ánhel, no sám Hóspodi voplóščsja, i spásl jesí vsehó mja čelovíka. Ťím zovú ti: sláva síľi tvojéj Hóspodi."), ("", "", "Predstojíši sudíšču jáko sudím, Bóže mój, ne vopijá Vladýko, súd iznosjá jazýkom: ímže strástiju tvojéju Christé vselénňij soďílal jesí spasénije."), ("", "", "Strástiju tvojéju Christé, vrahú oskuďíša orúžija, protívnym že jéže vo ád schoždénijem tvojím, hrády razrušíšasja, i mučíteleva dérzosť nizložéna býsť."), ("Bohoródičen", "", "Ťá pristánišče spasénija, i sťínu nedvížimu, Bohoródice Vladýčice, vsí vírniji svímy: tý bo molítvami tvojími izbavľáješi ot bíd dúšy náša."), ), "2": ( ("", "", "Uslýšach Hóspodi, slávnoje tvojé smotrénije, i proslávich čelovikoľúbče, nepostižímuju tvojú sílu."), ("", "", "Víďivši na drévi ťá Christé prihvoždéna Ďíva, jáže neboľíznenno ťá róždšaja, Máterski boľízni preterpí."), ("", "", "Pobiždéna býsť smérť, mértv pľiňájet ádova vratá: vsejádcu bo razóršusja, jáže páče jestestvá vsjá mí darovášasja."), ), "3": ( ("", "", "Uslýšach Hóspodi, slávnoje tvojé smotrénije, i proslávich čelovikoľúbče, nepostižímuju tvojú sílu."), ("", "", "Sé prevoznesésja božéstvennaja horá dómu Hospódňa, prevýšše síl, Bohomáter jávstvenňijše."), ("", "", "Zakónov jestéstvennych kromí, jedína Ďívo róždši vladýčestvujuščaho tváriju, spodóbilasja jesí božéstvennaho zvánija."), ) ), "P5": ( "1": ( ("", "", "Chodátaj Bóhu i čelovíkom býl jesí Christé Bóže: tobóju bo Vladýko, k svitonačáľniku Otcú tvojemú, ot nóšči nevíďinija, privedénije ímamy."), ("", "", "Jáko kédry Christé, jazýkov šatánije sokrušíl jesí vóleju Vladýko: jáko izvólil jesí na kiparísi, i na pévki, i kédri, plótiju sovozvyšájem."), ("", "", "V róvi Christé preispódňim položíša ťá bezdychánna mértva: no tvojéju jázvoju zabvénnyja mértvyja, íže vo hrobích spjáščyja, ujázven s sobóju voskresíl jesí."), ("Bohoródičen", "", "Molí Sýna tvojehó i Hóspoda, Ďívo čístaja, na ťá upovájuščym mír darováti, pľinénnym izbavlénije, ot soprotívnych nastojánij."), ), "2": ( ("", "", "Úhľ Isáiji projavléjsja, sólnce iz ďívstvennyja utróby vozsijá, vo ťmí zablúždšym, Bohorazúmija prosviščénije dáruja."), ("", "", "Postíti otverhíjsja Adám, vkušájet smertonósnaho dréva pérvyj: no sehó hrích potrebľájet, raspnýjsja vtorýj."), ("", "", "Jestestvóm čelovíčeskim strásten že i smérten býl jesí, íže bezstrástnyj neveščéstvennym Božestvóm, obeztľívyj umerščvlénnyja Christé, ot preispódnich ádovych voskresíl jesí."), ), "3": ( ("", "", "Úhľ Isáiji projavléjsja, sólnce iz ďívstvennyja utróby vozsijá, vo ťmí zablúždšym, Bohorazúmija prosviščénije dáruja."), ("", "", "Óblacy vesélija sládosť kropíte súščym na zemlí: jáko otročá dadésja, íže sýj préžde vík, ot Ďívy voplóščsja Bóh náš."), ("", "", "Žitijú i plóti mojéj svít vozsijá, i drjáchlosť hrichá razruší: naposľídok ot Ďívy bez símene voplóščsja výšnij."), ) ), "P6": ( "1": ( ("", "", "V bézdňi hrichóvňij vaľájasja, neizsľídnuju milosérdija tvojehó prizyváju bézdnu: ot tlí Bóže mjá vozvedí."), ("", "", "Jáko zloďíj právednik osudísja i so bezzakónnymi na drévi prihvozdísja, povínnym ostavlénije svojéju dáruja króviju."), ("", "", "Jedíňim úbo čelovíkom, pérvym Adámom drévle v mír vníde smérť, i jedíňim voskresénije Sýnom Bóžijim javísja."), ("Bohoródičen", "", "Neiskusomúžno Ďívo rodilá jesí, i víčnuješi Ďíva, javľájušči ístinnaho Božestvá, Sýna i Bóha tvojehó óbrazy."), ), "2": ( ("", "", "Hlás hlahól molébnych ot boľíznennyja Vladýko, duší uslýšav, ot ľútych mjá izbávi: jedín bo jesí nášeho spasénija vinóven."), ("", "", "Bľustíteli položíl jesí pádšemu, Cheruvímy dréva živótnaho, no víďivše ťá, dvéri otverzóšasja: javílsja bo jesí putetvorjá razbójniku v ráj."), ("", "", "Púst ád i isprovéržen býsť smértiju jedínaho: jéže bo mnóhoje bohátstvo sokróviščestvova, jedín o vsích nás Christós istoščíl jésť."), ), "3": ( ("", "", "Hlás hlahól molébnych ot boľíznennyja Vladýko, duší uslýšav, ot ľútych mjá izbávi: jedín bo jesí nášeho spasénija vinóven."), ("", "", "Jestestvó čelovíčeskoje rabótajuščeje hrichú, Vladýčice čístaja, tobóju svobódu ulučí: tvój bo Sýn, jáko áhnec, za vsích zakalájetsja."), ("", "", "Vopijém tí vsí ístinňij Bohomáteri, prohňívavšija rabý izbávi: jedína bo derznovénije k Sýnu ímaši."), ) ), "K": ( ("", "", "Voskrésl jesí ot hróba vsesíľne Spáse, i ád víďiv čúdo, užasésja, i mértviji vostáša: tvár že víďašči srádujetsja tebí, i Adám sveselítsja, i mír Spáse mój vospivájet ťá prísno."), ("", "", "Tý jesí svít omračénnym, tý jesí voskresénije vsích, i živót čelovíkov, i vsích sovoskresíl jesí, smértnuju deržávu Spáse razór, i ádova vratá sokrušívyj Slóve: i mértviji víďivše čúdo čuďáchusja, i vsjáka tvár srádujetsja o voskreséniji tvojém čelovikoľúbče. Ťímže i vsí slávim i pojém tvojé snizchoždénije, i mír Spáse mój, vospivájet ťá prísno."), ), "P7": ( "1": ( ("", "", "Bohoprotívnoje veľínije bezzakónnujuščaho mučíteľa vysók plámeň voznesló jésť: Christós že prostré Bohočestívym otrokóm rósu duchóvnuju, sýj blahoslovén, i preproslávlen."), ("", "", "Ne terpíl jesí Vladýko, za blahoutróbije smértiju čelovíka zríti múčima, no prišél i spásl jesí tvojéju króviju, čelovík býv: sýj blahoslovén , i preproslávlen Bóh otéc nášich."), ("", "", "Víďivše ťá Christé, obolčéna vo odéždu otmščénija, užasóšasja vrátnicy ádovy: bezúmnaho bo mučíteľa rabá, Vladýko, prišél jesí ubíti: sýj blahoslovén i preprosláven Bóh otéc nášich."), ("Bohoródičen", "", "Svjatých svjaťíjšuju ťá razumíjem, jáko jedínu róždšuju Bóha nepremínnaho, Ďívo neskvérnaja, Máti beznevístnaja: vsím bo vírnym istočíla jesí netľínije, božéstvennym roždestvóm tvojím."), ), "2": ( ("", "", "Vitíji javíšasja ótrocy, ľubomúdrijšiji drévle: ot Bohoprijátnyja bo duší Bohoslóvjašče, ustnámi pojáchu: prebožéstvennyj otcév i náš Bóže blahoslovén jesí."), ("", "", "Osudí práotca drévle vo Jedémi preslušánije: no vóleju sudím býsť, prestúpľšemu razrišája prehrišénija, prebožéstvennyj otcév Bóh, i preproslávlen."), ("", "", "Spásl jesí ujázvennaho jazýkom, závistiju čelovikoubíjcy, vo Jedémi vóľnym uhryzénijem: vóľnoju bo strástiju iscilíl jesí, prebožéstvennyj otcév Bóh, i preproslávlen."), ("Bohoródičen", "", "Choďášča mjá v síni smértňij prizvál jesí k svítu, temnozráčnyj ád, blistánijem oblóž Božestvá, prebožéstvennyj otcév Bóh, i preproslávlen."), ), "3": ( ("", "", "Vitíji javíšasja ótrocy, ľubomúdrijšiji drévle: ot Bohoprijátnyja bo duší Bohoslóvjašče, ustnámi pojáchu: prebožéstvennyj otcév i náš Bóže blahoslovén jesí."), ("", "", "Zrjáše v noščí úbo Jákov, jáko v hadániji Bóha voploščénna, iz tebé že svítlostiju javísja pojúščym: prebožéstvennyj otcév Bóh, i preproslávlen."), ("", "", "Známenija jáže v tebí neizrečénnaho projavľája sňátija, so Jákovom bóretsja: ímže vóleju sojedinísja čelovíkom čístaja: prebožéstvennyj otcév Bóh, i preproslávlen."), ("", "", "Mérzok íže ne propovédujet ťá Ďívy Sýna, jedínaho ot prepétyja Tróicy nesumňínnoju víroju, i jazýkom vopijá: prebožéstvennyj otcév Bóh, i preproslávlen."), ) ), "P8": ( "1": ( ("", "", "Péšč inohdá óhnennaja v Vavilóňi ďíjstva razďiľáše, Bóžijim veľínijem chaldéji opaľájuščaja, vírnyja že orošájuščaja, pojúščyja: blahoslovíte vsjá ďilá Hospódňa Hóspoda."), ("", "", "Króviju tvojéju Christé, očervléno plóti tvojejá zrjášče oďijánije trépetom užasáchusja mnóhomu tvojemú dolhoterpíniju, ánheľstiji číni, zovúšče: blahoslovíte vsjá ďilá Hospódňa Hóspoda."), ("", "", "Tý mojé smértnoje oďíjal jesí ščédre, v bezsmértije vostánijem tvojím. Ťímže veseľáščesja blahodárstvenno vospivájut ťá izbránniji ľúdije Christé, zovúšče tebí: požérta býsť voístinnu smérť pobídoju."), ("Bohoródičen", "", "Tý íže Otcú nerazlúčnaho, vo utróbi Bohomúžno požívša bezsímenno začalá jesí, i neizrečénno rodilá jesí Bohorodíteľnice prečístaja: ťímže ťá spasénije vsích nás svímy."), ), "2": ( ("", "", "O podóbiji zláťi, nebréhše treblažénniji júnoši, neizmínnyj i živýj Bóžij óbraz víďivše, sredí ohňá vospiváchu: osuščestvovánnaja da pojét Hóspoda vsjá tvár, i prevoznósit vo vsjá víki."), ("", "", "Víďin býl jesí na kresťí prihvoždájem, íže bohátyj v mílosti, vóleju pohrébľsja jesí: i tridnévno voskrésl jesí, i izbávil jesí vsjá čelovíki čelovikoľúbče, víroju pojúščyja: da pojét Hóspoda vsjá tvár, i prevoznósit vo vsjá víki."), ("", "", "Izbáviti ot istľínija, sošéd v preispódňaja Slóve Bóžij, jehóže sozdál jesí Christé, síloju tvojéju božéstvennoju, i bez istľínija sotvór, slávy prisnosúščnyja tvojejá pričástnika soďílal jesí, da pojét, zovúšči, vsjá tvár, i prevoznósit Christá vo víki."), ), "3": ( ("", "", "O podóbiji zláťi, nebréhše treblažénniji júnoši, neizmínnyj i živýj Bóžij óbraz víďivše, sredí ohňá vospiváchu: osuščestvovánnaja da pojét Hóspoda vsjá tvár, i prevoznósit vo vsjá víki."), ("", "", "Víďin býsť na zemlí tobóju, i s čelovíki poživé, íže bláhostiju nesravnénnyj i síloju, jemúže pojúšče vsí vírniji zovém: osuščestvovánnaja da pojét Hóspoda vsjá tvár, i prevoznósit vo vsjá víki."), ("", "", "Voístinnu ťá čístuju propovídajušče slávim Bohoródicu: tý bo jedína rodilá jesí ot Tróicy voploščénna, jemúže so Otcém i Dúchom vsí pojém: da pojét Hóspoda vsjá tvár, i prevoznósit vo vsjá víki."), ) ), "P9": ( "1": ( ("", "", "Beznačáľna Rodíte<NAME>, Bóh i Hospóď, voplóščsja ot Ďívy nám javísja, omračénnaja prosvitíti, sobráti rastočénnaja: ťím vsepítuju Bohoródicu veličájem."), ("", "", "Jáko v rají nasaždéno na lóbňim Spáse, trebohátoje drévo tvojehó prečístaho krestá, króviju i vodóju božéstvennoju, jáko ot istóčnika božéstvennaho, rebrá tvojehó Christé, napojájemo, živót nám prozjabló jésť."), ("", "", "Nizložíl jesí síľnyja, raspnýjsja vsesíľne, i jéže nízu ležáščeje vo ádovi tverdýni, jestestvó čelovíčeskoje voznés, na Ótčem posadíl jesí prestóľi. S nímže tebí hrjadúšču poklaňájuščesja, veličájem."), ("Tróičen", "", "Jedínicu tričíslennuju, Tróicu jedinosúščnuju pravoslávno pojúšče vírniji, slávim: nepresikómo prebožéstvennoje jestestvó, trisvítluju, nevečérňuju zarjú, jedínu netľínnuju nám svít vozsijávšuju."), ), "2": ( ("", "", "Ot Bóha Bóha Slóva, neizrečénnoju múdrostiju prišédšaho obnovíti Adáma,jádiju v tľínije pádaho ľúťi: ot svjatýja Ďívy neizrečénno voplotívšahosja nás rádi,vírniji jedinomúdrenno písňmi veličájem."), ("", "", "Posreďí osuždénnych, jáko áhnec vozvýšen býl jesí Christé, na kresťí, na lóbňim kopijém v rebró probodájem, živót darovál jesí nám pérstnym jáko bláh, víroju čtúščym božéstvennoje tvojé voskresénije."), ("", "", "Íže svojéju smértiju, smérti deržávu síloju uprazdnívšemu Bóhu vsí vírniji poklonímsja, jáko íže ot víka mértvyja sovoskresí, i vsím podajét živót i voskresénije."), ), "3": ( ("", "", "Vés jesí želánije, vés sládosť, Slóve Bóžij, Ďívy Sýne, Bóže bohóv, Hóspodi, svjatých presvjatýj. Ťím ťá vsí s róždšeju veličájem."), ("", "", "Žézl kríposti dadésja jestestvú tľínnomu, Slóvo Bóžije vo utróbi tvojéj čístaja: i sijé voskresí, do áda popólzšejesja. Ťímže ťá vsečístaja, jáko Bohoródicu veličájem."), ("", "", "Júže izvólil jesí Vladýko, prijimí mílostivno molítvennicu, Máter tvojú o nás, i tvojejá bláhosti vsjáčeskaja ispólňatsja: da ťá vsí jáko blahoďíteľa veličájem."), ) ), ), "CH": ( ("", "", "Vsjákoje dychánije i vsjá tvár, ťá slávit Hóspodi, jáko krestóm smérť uprazdníl jesí, da pokážeši ľúdem, jéže iz mértvych tvojé voskresénije, jáko jedín čelovikoľúbec."), ("", "", "Da rekút Judée, káko vójini pohubíša strehúščiji carjá? Počtó bo kámeň ne sochraní kámene žízni? Ilí pohrebénnaho da daďát, ilí voskrésšemu da poklóňatsja, hlahóľušče s námi: sláva mnóžestvu ščedrót tvojích, Spáse náš, sláva tebí."), ("", "", "Rádujtesja ľúdije i veselítesja, ánhel siďáj na kámeni hróbňim, tój nám blahovistí, rék: Christós voskrése iz mértvych, Spás míra, i ispólni vsjáčeskaja blahouchánija: rádujtesja ľúdije i veselítesja."), ("", "", "Ánhel úbo jéže rádujsja, préžde tvojehó začátija Hóspodi, blahodátňij prinesé: ánhel že kámeň slávnaho tvojehó hróba v tvojé voskresénije otvalí: óv úbo v pečáli místo, vesélija óbrazy vozviščája: séj že v smérti místo, Vladýku žiznodávca propovíduja nám, ťímže vopijém tí: blahoďíteľu vsích, Hóspodi sláva tebí."), ("", "", "Vozlijáša míra so slezámi na hrób tvój žený, i ispólnišasja rádosti ustá ích, vnehdá hlahólati: voskrése Hospóď."), ("", "", "Da pochváľat jazýcy i ľúdije Christá Bóha nášeho, vóleju nás rádi krest preterpívšaho, i vo áďi tridnévnovavšaho: i da poklóňatsja jehó iz mértvych voskreséniju, ímže prosvitíšasja vsehó míra koncý."), ("", "", "Ráspjat i pohrebén býl jesí Christé, jákože izvólil jesí, isprovérhl jesí smérť, i voskrésl jesí vo slávi, jáko Bóh i Vladýka, dáruja mírovi žízň víčnuju i véliju mílosť."), ("", "", "O voístinnu bezzakónniji, pečátavše kámeň, bóľšich nás čudés spodóbiste! Ímut rázum strážije, dnés prójde iz hróba, i hlahólachu: rcýte, jáko nám spjáščym, prijidóša učenicý, i ukradóša jehó. I któ krádet mertvecá, páče že i náha? Sám voskrése samovlástno jáko Bóh, ostávľ vo hróbi i pohrebáteľnaja svojá: prijidíte vídite judéje, káko ne rastórže pečáti, smérť poprávyj i ródu čelovíčeskomu bezkonéčnuju žízň dárujaj, i véliju mílosť."), ), ) #let L = ( "B": ( ("", "", "Hlás tí prinósim razbójnič, i mólimsja: pomjaní nás Spáse, vo cárstviji tvojém."), ("", "", "Krest tebí prinósim v proščénije prehrišénij: jehóže nás rádi prijál jesí čelovikoľúbče."), ("", "", "Poklaňájemsja tvojemú Vladýko pohrebéniju, i vostániju: ímiže ot tľínija izbávil jesí mír čelovikoľúbče."), ("", "", "Smértiju tvojéju Hóspodi, požérta býsť smérť: i voskresénijem tvojím Spáse, mír spásl jesí."), ("", "", "Mironósicy srítil jesí, voskrés ot hróba, i učenikóm vozvistíl jesí, reščí tvojé vostánije."), ("", "", "Íže vo ťmí spjáščiji ťá svít víďivše, v preispódňijšich ádovych Christé voskrésóša."), ("", "", "Otcá proslávim, Sýnu poklonímsja vsí, i svjatómu Dúchu vírno vospojím."), ("Bohoródičen", "", "Rádujsja prestóle ohnezráčnyj. Rádujsja, nevísta nenevístnaja. Rádujsja, jáže Bóha čelovíkom Ďívo róždšaja."), ), "TKB": ( ("", "", "Jehdá snizšél jesí k smérti, životé bezsmértnyj, tohdá ád umertvíl jesí blistánijem božestvá. Jehdá že i uméršyja ot preispódnich voskresíl jesí, vsjá síly nebésnyja vzyváchu: žiznodávče Christé Bóže náš, sláva tebí."), ("", "", "Voskrésl jesí ot hróba vsesíľne Spáse, i ád víďiv čúdo, užasésja, i mértviji vostáša: tvár že víďašči srádujetsja tebí, i Adám sveselítsja, i mír Spáse mój vospivájet ťá prísno."), ("Bohoródičen", "", "Vsjá páče smýsla, vsjá preslávnaja tvojá Bohoródice, tájinstva, čistoťí zapečátannoj, i ďívstvu chranímu Máti poználasja jesí nelóžna, Bóha róždši ístinnaho: tohó molí spastísja dušám nášym."), ), "P": ( ("", "", "Kríposť mojá i pínije mojé Hospóď, i býsť mňí vo spasénije."), ("", "", "Nakazúja nakazá mja Hospóď, smérti že ne predadé mja."), ("", "", "Uslýšit ťá Hospóď v déň pečáli, zaščítit ťá ímja Bóha Jákovľa."), ("", "", "Hóspodi spasí carjá, i uslýši ný, vóňže ášče déň prizovém ťá."), ) )
https://github.com/dyc3/senior-design
https://raw.githubusercontent.com/dyc3/senior-design/main/use-cases.typ
typst
#import "lib/use-cases.typ": usecase = Use Cases <Chapter::UseCases> #usecase( [Deploy to Fly], description: [ In this use case, the maintainer of OTT is hosting the official website, OpenTogetherTube.com. The website needs to remain deployable to Fly.io, and the deployment pipelines need to continue to be functional. Deployment diagrams for with and without the load balancer can be found in @Figure::deployment-current and @Figure::deployment-new, respectively. ], diagram: [@Figure::use-case-maint], basic_flow: ("Maintainer attempts deployment to Fly.io", "Deployment to Fly.io succeeds"), alt_flows: (("Maintainer attempts deployment to Fly.io", "Deployment to Fly.io fails", "Maintainer troubleshoots deployment failure"),) ) <UseCase::maintaining> #usecase( [Access Diagnostics], description: [ In this use case, the maintainer of OTT is hosting the official website, OpenTogetherTube.com. The system needs to allow the maintainer to access diagnostics for the system to troubleshoot issues. This includes logs, stack traces, and metrics. ], diagram: [@Figure::use-case-maint], prereq: ( "Maintainer has access to Fly", "OTT is already deployed to Fly", ), basic_flow: ( "Maintainer runs `fly log`", "Maintainer reads logs, stack traces in real time" ), alt_flows: ( ( "Maintainer configures Fly app to collect metrics", "Maintainer browses to Fly hosted grafana dashboard", "Maintainer views metrics, creates dashboards, or creates alerts", ), ( "Maintainer configures on-premises prometheus instance to collect metrics", "Maintainer browses to on-premises hosted grafana", "Maintainer views metrics, creates dashboards, or creates alerts", ), ) ) <UseCase::troubleshoot> #figure( image("figures/use-cases/use-case-maint.svg"), caption: [Use Case diagram for @UseCase::maintaining and @UseCase::troubleshoot], ) <Figure::use-case-maint> #pagebreak() #usecase( [Deploy OTT], description: [ In this use case, a user is hosting an instance of OTT on their own server. The user may or may not be using Docker to deploy their instance. It should remain possible to deploy an instance of OTT without starting additional services (other than what's currently required). Current deployments must continue to work when the user updates their instance of OTT. Deployment diagrams for with and without the load balancer can be found in @Figure::deployment-current and @Figure::deployment-new, respectively. ], diagram: [@Figure::use-case-self-host], prereq: ( [User can clone a git repository], [User has a computer with Docker installed], [User has a computer with docker-compose installed], ), basic_flow: ( [User clones OTT repository], [User runs `docker-compose up`], [User waits for containers to start], [User navigates to `localhost:8080` in browser], [User can utilize self-hosted version of OTT as end user], ), alt_flows: ( ( [User writes configuration file for Monolith], [User configures reverse proxy to point to OTT's configured port], [User configures DNS for a custom domain to point to their reverse proxy], [User runs `docker-compose up` (does *not* include Balancer)], [User waits for containers to start], [User navigates to custom domain in browser], [User can utilize self-hosted version of OTT as end user], ), ( [User writes configuration file for Monolith], [User writes configuration file for Balancer], [User configures reverse proxy to point to Balancer port], [User configures DNS for a custom domain to point to their reverse proxy], [User runs `docker-compose up` (includes Balancer)], [User waits for containers to start], [User navigates to custom domain in browser], [User can utilize self-hosted version of OTT as end user], ), ) ) <UseCase::self-host> #figure( image("figures/use-cases/use-case-self-host.svg"), caption: [Use Case diagram for @UseCase::self-host], ) <Figure::use-case-self-host> #pagebreak() #usecase( [Using OTT as an end user], description: [In this use case, an end user is using the website to watch videos. The end user must not see any difference between the current version of OTT and the new version of OTT with the load balancer. This implies that no changes to the client must be necessary.], diagram: [@Figure::use-case-enduser], basic_flow: ( "User connects to OTT website", "User creates permanent or temporary room", "User shares link to room", "Any number of people join the room", "User watches adds videos to queue", "User watches videos in queue" ), alt_flows: ( ( "User connects to OTT website", "User creates permanent or temporary room", "User tweaks room settings or permissions", "User shares link to room", "Any number of people join the room", "User watches adds videos to queue", "User watches videos in queue" ), ( "Users connects to OTT website", "OTT automatically loads a permanent room", "Any number of people join the room", "User watches adds videos to queue", "User watches videos in queue" ), ) ) <UseCase::end-user> #figure( image("figures/use-cases/use-case-enduser.svg", width: 30%), caption: [Activity diagram for @UseCase::end-user], ) <Figure::use-case-enduser> #pagebreak() #usecase( [Interface with Visualization], description: [In this use case, a vistor comes up to our booth on the day of the innovation expo and interacts with the visualization for the load balancer. The visualization must be a completely separate system that the load balancer interacts with.], basic_flow: ( "Visitor approaches booth", "Visitor adds or removes any number of monoliths", "Monoliths appear/dissappear from the screen appropriately", "Visitor connects through the balancer to OTT", "Visitor adds and joins room", "Room appears on screen tethered to the appropriate monolith", "Client appears on screen tethered to the appropriate room", "Client disconnects", "Client disappears from visualization screen", "Visitor walks away" ), alt_flows: ( ( "Visitor approaches booth", "Visitor adds or removes any number of monoliths", "Monoliths appear/dissappear from the screen appropriately", "Visitor connects through the balancer to OTT", "Visitor adds and joins room", "Room appears on screen tethered to the appropriate monolith", "Client appears on screen tethered to the appropriate room", "Visitor removes the monolith the client is currently connected to", "Client is forcibly disconnected", "Client disappears from visualization screen", "Room is retethered to appropriate monolith", "Client reconnects through the balancer to OTT", "Client rejoins the room they created", "Client reappears on visualization screen", "Client disconnects", "Client disappears from visualization screen", "Visitor walks away" ), ( "Visitor approaches booth", "Visitor connects through the balancer to OTT", "Visitor joins an already existing room", "Client appears on screen tethered to the appropriate room", "Client disconnects", "Client disappears from visualization screen", "Visitor walks away" ), ( "Visitor approaches booth", "Visitor is uninterested", "Visitor walks away" ) ) ) <UseCase::visualization-interface> #figure( image("figures/use-cases/use-case-visualization-interface.svg"), caption: [Use Case Diagram for @UseCase::visualization-interface] )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/rich-counters/0.1.0/example.typ
typst
Apache License 2.0
#import "@preview/rich-counters:0.1.0": * #set heading(numbering: "1.1") #let mycounter = richcounter(identifier: "mycounter", inherited_levels: 1) // DOCUMENT Displaying `mycounter` here: #context (mycounter.display)("1.1") = First level heading Displaying `mycounter` here: #context (mycounter.display)("1.1") Stepping `mycounter` here. #(mycounter.step)() Displaying `mycounter` here: #context (mycounter.display)("1.1") = Another first level heading Displaying `mycounter` here: #context (mycounter.display)("1.1") Stepping `mycounter` here. #(mycounter.step)() Displaying `mycounter` here: #context (mycounter.display)("1.1") == Second level heading Displaying `mycounter` here: #context (mycounter.display)("1.1") Stepping `mycounter` here. #(mycounter.step)() Displaying `mycounter` here: #context (mycounter.display)("1.1") = Aaand another first level heading Displaying `mycounter` here: #context (mycounter.display)("1.1") Stepping `mycounter` here. #(mycounter.step)() Displaying `mycounter` here: #context (mycounter.display)("1.1")
https://github.com/atareao/fondos-productivos
https://raw.githubusercontent.com/atareao/fondos-productivos/master/src/gnome_shell.typ
typst
MIT License
//ref https://gist.github.com/rothgar/7079722 #set page( "presentation-16-9", fill: black, margin: 0.5cm) #set text(size: 11pt, fill: white) = GNOME Shell #columns(3, gutter: 12pt)[ == Navegación general #line(stroke: white, length: 100%) #table( columns: (1fr, 1.7fr), gutter: -4pt, `Super`+" o "+`Alt+F1`, "Actividades", `Alt+F2`, "Ventana de comando", `Super+A`, "Vista de aplicaciones", `Super+M`, "Bandeja de mensajes", `Super+N`, "Notificaciones", `Ctrl+Alt+Tab`, "Alterna el foco", `Alt+Esc`, "Alterna entre ventanas", `Ctrl+W`, "Cierra una ventana", `Ctrl+,`, "Configuración", `Ctrl+K Ctrl+S`, "Atajos de teclado", ) == Edición básica #table( columns: (1fr, 1.7fr), gutter: -4pt, `Ctrl+X`, "Corta una línea", `Ctrl+C`, "Copia una línea", `Alt+`+sym.arrow.t+`/`+sym.arrow.b, "Mueve una línea arriba o abajo", `Ctrl+Shift+K`, "Borra una línea", `Ctrl+Enter`, "Inserta una línea debajo", `Ctrl+Shift+Enter`, "Inserta una línea encima", `Ctrl+Shift+\`, "Inserta una línea encima", `Ctrl+Q`, "Vuelve a pintar en pantalla", ) == Moviendo el cursor #table( columns: (1fr, 1.7fr), gutter: -4pt, `Ctrl+A`, "Al inicio de la línea", `Ctrl+E`, "Al final de la línea", `Alt+B`, "A la izquierda de una palabra", `Ctrl+B`, "A la izquierda un carácter", `Alt+F`, "A la derecha una palabra", `Ctrl+F`, "A la derecha un carácter", `Ctrl+XX`, "Del principio al final y al revés", ) == Borrando texto #table( columns: (1fr, 5fr), gutter: -4pt, `Ctrl+D`, "Al inicio de la línea", `Alt+D`, "Al inicio de la línea", `Ctrl+H`, "Al final de la línea", `Ctrl+W`, "A la izquierda un carácter", `Alt+F`, "A la derecha una palabra", `Ctrl+F`, "A la derecha un carácter", `Ctrl+XX`, "Del principio al final y al revés", ) == Mayúsculas y minúsculas #table( columns: (1fr, 5fr), gutter: -4pt, `Alt+U`, "Mayúsculas hasta el final de la palabra", `Alt+L`, "Minúsculas hasta el final de la palabra", `Alt+C`, "Mayúsculas para el carácter", ) == Errores #table( columns: (1fr, 5fr), gutter: -4pt, `Alt+T`, "Intercambia la palabra con la anterior", `Ctrl+T`, "Intercambia dos caracteres", `Ctrl+_`, "Deshacer", ) == Autocompletado #table( columns: (1fr, 5fr), gutter: -4pt, `tab`, "Autocompleta", ) == Historial #table( columns: (1fr, 5fr), gutter: -4pt, `Ctrl+P`, "Comando anterior", `Ctrl+N`, "Comando siguiente", `Ctrl+R`, "Busca comandos anteriores", `Ctrl+O`, "Ejecuta el comando encontrado", `Ctrl+G`, "Abandona la búsqueda", `Alt+R`, "Revierte cambios editados", `!!`, "Repite el último comando", `!*`, "Repite solo los árgumentos", `history`, "Mueltra la historia", ) == Atajos de teclado #table( columns: (1fr, 4fr), gutter: -4pt, `bind -p`, "Muestra los atajos de teclado", ) == Copiar y pegar #table( columns: (1fr, 2fr), gutter: -5pt, `Ctrl+Shift+C`, "Copia la selección", `Ctrl+Shift+P`, "Pega", ) ]
https://github.com/giZoes/justsit-thesis-typst-template
https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/pages/bachelor-decl-page.typ
typst
MIT License
#import "../utils/indent.typ": indent #import "../utils/style.typ": 字号, 字体 #import "../../others/bachelor-assignment.typ":bachelor-assignment // 本科生声明页 #let bachelor-decl-page( // need-assignment: false, anonymous: false, twoside: false, fonts: (:), info: (:), ) = { // 0. 如果需要匿名则短路返回 if anonymous { return } // 1. 默认参数 fonts = 字体 + fonts info = ( title: ("基于 Typst 的", "苏理工学位论文"), ) + info // 2. 对参数进行处理 // 2.1 如果是字符串,则使用换行符将标题分隔为列表 if type(info.title) == str { info.title = info.title.split("\n") } // 3. 正式渲染 pagebreak(weak: true, to: if twoside { "odd" }) v(48pt) align( center, text( font: fonts.宋体, size: 字号.小二, weight: "semibold", "江苏科技大学苏州理工学院学位论文原创性声明", ), ) v(32pt) block[ #set text(font: fonts.宋体, size: 字号.四号) #set par(justify: true, first-line-indent: 2em, leading: 1.28em) #indent 本人郑重声明:所呈交的学位论文,是本人在导师的指导下,独立进行研究工作所取得的成果。除文中已经注明引用的内容外,本论文不包含任何其他个人或集体已经发表或撰写过的作品成果。对本文的研究做出重要贡献的个人和集体,均已在文中以明确方式标明。本人完全意识到本声明的法律结果由本人承担。 ] v(100pt) grid( columns: (100pt, 260pt), [], align(left)[ #set text(font: fonts.宋体, size: 字号.四号, ) 学位论文作者签名(手签) #v(1cm)           年  月  日 ] ) //使用授权书 pagebreak(weak: true, to: if twoside { "odd" }) v(52pt) align( center, text( font: fonts.宋体, size: 字号.小二, weight: "semibold", "江苏科技大学苏州理工学院学位论文版权使用授权书", ), ) v(32pt) block[ #set text(font: fonts.宋体, size: 字号.四号) #set par(justify: true, first-line-indent: 2em, leading: 1.28em) #indent 本学位论文作者完全了解学校有关保留、使用学位论文的规定,同意学校保留并向国家有关部门或机构送交论文的复印件和电子版,允许论文被查阅和借阅。本人授权江苏科技大学可以将本学位论文的全部或部分内容编入有关数据库进行检索,可以采用影印、缩印或扫描等复制手段保存和汇编本学位论文。 ] v(32pt) block[ #set text(font: fonts.宋体, size: 字号.四号) #set par(justify: true, first-line-indent: 2em, leading: 1.28em) #indent 本学位论文属于: 1、保密 □,在#h(3em)年解密后适用本授权书。 2、不保密 □ 。 ] v(7cm) grid( columns: (50fr,50fr), align(center)[ #set text(font: fonts.宋体, size: 字号.四号, ) 学位论文作者签名(手签): #v(1cm) 年  月  日 ], align(center)[ #set text(font: fonts.宋体, size: 字号.四号, ) 指导教师签名(手签): #v(1cm) 年  月  日 ] ) //任务书 pagebreak(weak: true, to: if twoside { "odd" }) // if need-assignment { // bachelor-assignment() // }else{ text(font: fonts.宋体, size: 字号.四号, fill: red,)[#align(center)[任务书添加至此处]] // } }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/flow-2_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(height: 60pt) #v(19pt) #block[ But, soft! what light through yonder window breaks? It is the east, and Juliet is the sun. ]
https://github.com/HeZeBang/shtthesis-typst
https://raw.githubusercontent.com/HeZeBang/shtthesis-typst/main/template.typ
typst
MIT License
// Font Declaration #let oldfont = ( heiti : ("Heiti SC", "Heiti TC", "SimHei", "PT Sans"), heitibf : ("Heiti SC", "Heiti TC", "SimHeiBold", "SimHei"), songti : ("Times New Roman", "Songti SC", "Songti TC", "SimSun"), songtibf : ("Times New Roman", "Songti SC", "Songti TC", "SimSunBold", "SimSun"), zhongsong : ("Times New Roman", "STZhongsong", "SimSun") ) #let fontfamily = ( heiti : ( regular : ("Heiti SC", "Heiti TC", "SimHei", "PT Sans"), bold : ("Heiti SC", "Heiti TC", "SimHeiBold", "SimHei")), songti : ( regular : ("Times New Roman", "Songti SC", "Songti TC", "SimSun"), bold : ("Times New Roman", "Songti SC", "Songti TC", "STZhongsong", "SimSunBold", "SimSun"), ), zhongsong : ( regular : ("Times New Roman", "STZhongsong", "SimSun"), ) ) #let size2pt = ( chuhao: 42pt, xiaochu: 36pt, yihao: 26pt, xiaoyi: 24pt, erhao: 22pt, xiaoer: 18pt, sanhao: 16pt, xiaosan: 15pt, sihao: 14pt, xiaosi: 12pt, wuhao: 10.5pt, xiaowu: 9pt, liuhao: 7.5pt, xiaoliu: 6.5pt, qihao: 5.5pt, bahao: 5pt, ) #let Font_Constructor(font: fontfamily.songti.regular, fontsize : size2pt.wuhao, it) = { if(type(it) == "dictionary" and it.at("children", default: false) != false) { for i in it.children { if (i.func()==strong) { text( size:fontsize, font: font.regular, weight: "bold", i) } else { text( size:fontsize, font: font.regular, weight: "regular", i) } } } else if (type(it) == "function" and it.func() == strong) { text( size:fontsize, font: font.at("bold", default: font.regular), weight: "regular", it) } else { text( size:fontsize, font: font.regular, weight: "regular", it) } } #let heiti(fontsize, it) = Font_Constructor( font: fontfamily.heiti, fontsize: fontsize, it ) #let songti(fontsize, it) = Font_Constructor( font: fontfamily.songti, fontsize: fontsize, it) #let project( title: ("标题","TITLE"), abstract: ([],[]), authors: ((),()), ids: (), enroll: "20XX", institution: ("",""), major: ("",""), advisor: ("",""), year: 2023, month: 12, logo: "./logo_red.svg", keywords: (), body, ) = { set document(author: authors.at(0), title: title.at(0)) set page( margin: (left: 25mm, right: 25mm, top: 31mm, bottom: 31mm), ) set text(/*font: "Linux Libertine", */lang: "zh") // 中文封面 { align(left)[#image(logo, height:1.45cm)] v(1.75cm) align(center)[ #songti(size2pt.erhao)[*本科毕业论文(设计)*] ] v(4.1cm) let juststr(body_str, target) = { let sliced = body_str.split("") let space = " " let str_len = sliced.len() - 2 let s = calc.max(0, calc.round((target - str_len) / (str_len - 1))) [#sliced.slice(1,str_len + 1).join(space*int(s))] } let infovalue(data) = { rect( stroke: (bottom: 1pt + black), width:100%, songti(size2pt.sihao, data) ) } let infokey(data) = { songti(size2pt.sihao)[#juststr(data,4):] } align(center)[#table( columns: (auto, 9cm), align: horizon, stroke: none, infokey("题目"), infovalue(title.at(0)), infokey("学生姓名"), infovalue(authors.at(0).join(", ")), infokey("学号"), infovalue(ids.join(", ")), infokey("入学年份"), infovalue(enroll), infokey("所在学院"), infovalue(institution.at(0)), infokey("攻读专业"), infovalue(major.at(0)), infokey("指导教师"), infovalue(advisor.at(0)), )] align(bottom + center)[ #songti(size2pt.xiaosi)[上海科技大学 \ #year#[年]#month#[月]] ] } pagebreak() // 英文封面 { align(left)[#image(logo, height:1.45cm)] v(1.75cm) align(center)[ #heiti(size2pt.erhao)[*THESIS*] ] v(4.1cm) let infovalue(data) = { rect( stroke: (bottom: 1pt + black), width:100%, songti(size2pt.sihao, data) ) } let infokey(data) = { align(left)[#songti(size2pt.sihao)[#data: ]] } align(center)[#table( columns: (auto, 9cm), align: horizon, stroke: none, infokey("Subject"), infovalue(title.at(1)), infokey("Student Name"), infovalue(authors.at(1).join(", ")), infokey("Student ID"), infovalue(ids.join(", ")), infokey("Year of Entrance"), infovalue(enroll), infokey("School"), infovalue(institution.at(1)), infokey("Major"), infovalue(major.at(1)), infokey("Advisor"), infovalue(advisor.at(1)), )] align(bottom + center)[ #songti(size2pt.xiaosi)[ShanghaiTech University \ Date: #year / #month] ] } pagebreak() //本科毕业论文诚信声明、版权使用授权书 { set text( size: 14pt, font: fontfamily.songti.regular, ) v(2.2cm) align(center)[ #heiti(size2pt.xiaoer)[ #set par(justify: false, leading: 1.15em, first-line-indent: 2em) *上海科技大学 \ 毕业论文(设计)学术诚信声明* ] ] v(1.1cm) [ #set par(justify: false, leading: 1.5em, first-line-indent: 2em) 本人郑重声明:所呈交的毕业论文(设计),是本人在导师的指导下,独立进行研究工作所取得的成果。除文中已经注明引用的内容外,本论文不包含任何其他个人或集体已经发表或撰写过的作品成果。对本文的研究做出重要贡献的个人和集体,均已在文中以明确方式标明。本人完全意识到本声明的法律结果由本人承担。] v(7em) align(right)[ 作者签名:#h(14em) 日#h(2em)期:#h(2em)年#h(1em)月#h(1em)日#h(7em) ] pagebreak() v(2.2cm) align(center)[ #heiti(size2pt.xiaoer)[ #set par(justify: false, leading: 1.15em) *上海科技大学 \ 毕业论文(设计)版权使用授权书* ] ] v(1.1cm) [ #set par(justify: false, leading: 1.5em, first-line-indent: 2em) 本毕业论文(设计)作者同意学校保留并向国家有关部门或机构送交论文的复印件和电子版,允许论文被查阅和借阅。本人授权上海科技大学可以将本毕业论文(设计)的全部或部分内容编入有关数据库进行检索,可以采用影印、缩印或扫描等复制手段保存和汇编本毕业论文(设计)。 #h(7em)*保#h(1em)密* #text(size:20pt,math.square),在#("_"*4)年年解密后适用本授权书。 本论文属于 #h(7em)*不保密* #text(size:20pt,math.square)。 (请在以上方框内打“√”) ] v(3em) grid( columns:(1fr, 1fr), [ #align(left)[ 作者签名: 日#h(2em)期:#h(2em)年#h(1em)月#h(1em)日 ]],[ #align(left)[ 指导教师签名: 日#h(2em)期:#h(2em)年#h(1em)月#h(1em)日 ] ] ) } counter(page).update(0) pagebreak() // 含页眉页尾页面 { set page(header: [ #rect( stroke: (bottom: black + 1pt), grid( columns: (auto, 1fr), [#image(logo, height: 1.16cm)], [#align(right)[#songti(size2pt.xiaowu,title.at(0))]]) ) ],) set page( numbering: "I", number-align: center, ) // 中文摘要 { align(center)[ #heiti(size2pt.sanhao)[ #v(1em) *#title.at(0)* #v(2em) ] #heading( outlined: false, numbering: none, heiti(size2pt.sihao)[ 摘要 #v(3em) ] ) ] set par(justify: true, leading: 0.77em, first-line-indent: 2em) set text(size: size2pt.wuhao, font: fontfamily.songti.regular) [ #h(2em)#abstract.at(0) ] v(2em) [ #heiti(size2pt.xiaosi)[关键词:] #songti(size2pt.wuhao)[#keywords.at(0)] ] } pagebreak() // 英文摘要 { align(center)[ #songti(size2pt.sanhao)[ #v(1em) *#upper(title.at(1))* #v(2em) ] #heading( outlined: false, numbering: none, songti(size2pt.sanhao)[ *ABSTRACT* #v(3em) ] ) ] set par(justify: true, leading: 0.77em, first-line-indent: 2em) set text(size: size2pt.wuhao, font: fontfamily.songti.regular) [ #h(2em)#abstract.at(1) ] v(2em) [ #songti(size2pt.xiaosi)[*Key words: *] #songti(size2pt.wuhao)[#keywords.at(1)] ] } pagebreak() // 目录和编号 align(center, text(size: size2pt.sanhao, font:fontfamily.heiti.bold)[ #v(1em) 目录 #v(1em) ]) set heading(numbering: "1") let number-until-with(max-level, schema) = (..numbers) => { if numbers.pos().len() <= max-level { numbering(schema, ..numbers) } } set heading(numbering: number-until-with(3, "1.1.1")) show outline.entry: it => { text(size: size2pt.wuhao, font: fontfamily.songti.regular)[ #let bdy = it.body #link(it.element.location(), bdy) #box(width: 1fr, repeat(".")) #it.page.text.match(regex("第(.*?)页")).captures.at(0) ] } { set par(leading: 1em) outline(depth: 3, indent: true, title:{}) } pagebreak() set page( numbering: "第 1 页 共 1 页", number-align: center, ) counter(page).update(1) // 正文版式 { set heading( numbering: (..numbers) => if numbers.pos().len() == 1 { return numbering("第一章", ..numbers) } else { return numbering("1.1", ..numbers) } ) show heading.where( level: 1 ): it => block(width: 100%)[ #set align(center) #set text(size2pt.sanhao, weight: "bold", font: fontfamily.heiti.regular) #v(1em) #it #v(1em) ] set text(size: size2pt.wuhao, font: fontfamily.songti.regular) set par(justify: true, leading: 1.24em, first-line-indent: 2em) show par: set block(spacing: 1.24em) show heading: it => { set text(weight: "bold", font: fontfamily.heiti.regular, size: size2pt.sanhao) set block(above: 1.5em, below: 1.5em) it } + v(-1em) + box() body } } }
https://github.com/mvuorre/quarto-apaish
https://raw.githubusercontent.com/mvuorre/quarto-apaish/main/_extensions/apaish/typst-template.typ
typst
Creative Commons Zero v1.0 Universal
// document mode #let doc( title: none, running-head: none, authors: none, affiliations: none, authornote: none, abstract: none, keywords: none, margin: (x: 2.5cm, y: 2.5cm), paper: "us-letter", font: ("New Computer Modern"), fontsize: 11pt, leading: 0.55em, spacing: 0.55em, first-line-indent: 1.25cm, toc: false, cols: 1, doc, ) = { set page( paper: paper, margin: margin, header-ascent: 50%, header: locate( loc => if [#loc.page()] == [1] { [] } else { grid( columns: (1fr, 1fr), align(left)[#running-head], align(right)[#counter(page).display()] ) } ), ) set par( justify: true, leading: leading, first-line-indent: first-line-indent ) // Also "leading" space between paragraphs show par: set block(spacing: spacing) set text( font: font, size: fontsize ) if title != none { align(center)[ #v(6em)#block(below: leading*4)[ #text(size: fontsize*1.4)[#title] ] ] } if authornote != none { footnote(numbering: "*", authornote) counter(footnote).update(0) } if authors != none { align(center)[ #block(below: leading*2)[ #set text(size: fontsize*1.15) // Formatting depends on N authors 1, 2, or 2+ #if authors.len() > 2 { for a in authors [ #a.name#super[#a.affiliations]#if a!=authors.at(authors.len()-1) [#if a==authors.at(authors.len()-2) [, and] else [,]] ] } #if authors.len() == 2 { for a in authors [ #a.name#super[#a.affiliations]#if a!=authors.at(authors.len()-1) [and] ] } #if authors.len() == 1 { for a in authors [ #a.name#super[#a.affiliations] ] } ] ] } if affiliations != none { align(center)[ #block(below: leading*2)[ #for a in affiliations [ #super[#a.id]#a.name \ ] ] ] } if abstract != none { block(inset: (x: 10%, y: 0%), below: 3em)[ #align(center, text("Abstract")) #set par(first-line-indent: 0pt, leading: leading) #abstract #if keywords != none {[ #v(1em)#text(weight: "regular", style: "italic")[Keywords:] #h(0.25em) #keywords ]} ] } /* Redefine headings up to level 5 */ show heading.where( level: 1 ): it => block(width: 100%, below: leading*2, above: leading*2)[ #set align(center) #set text(size: fontsize) #it.body ] show heading.where( level: 2 ): it => block(width: 100%, below: leading*2, above: leading*2)[ #set align(left) #set text(size: fontsize) #it.body ] show heading.where( level: 3 ): it => block(width: 100%, below: leading*2, above: leading*2)[ #set align(left) #set text(size: fontsize, style: "italic") #it.body ] show heading.where( level: 4 ): it => text( size: 1em, weight: "bold", it.body + [.] ) show heading.where( level: 5 ): it => text( size: 1em, weight: "bold", style: "italic", it.body + [.] ) if cols == 1 { doc } else { columns(cols, gutter: 4%, doc) } } // Manuscript mode #let man( title: none, running-head: none, authors: none, affiliations: none, authornote: none, abstract: none, keywords: none, margin: (x: 2.5cm, y: 2.5cm), paper: "us-letter", font: ("Times New Roman"), fontsize: 12pt, leading: 2em, spacing: 2em, first-line-indent: 1.25cm, toc: false, cols: 1, doc, ) = { set page( paper: paper, margin: margin, header-ascent: 50%, header: grid( columns: (1fr, 1fr), align(left)[#running-head], align(right)[#counter(page).display()] ) ) set par( justify: false, leading: leading, first-line-indent: first-line-indent ) // Also "leading" space between paragraphs show par: set block(spacing: spacing) set text( font: font, size: fontsize ) if title != none { align(center)[ #v(8em)#block(below: leading*2)[ #text(weight: "bold", size: fontsize)[#title] ] ] } if authornote != none { footnote(numbering: "*", authornote) counter(footnote).update(0) } if authors != none { align(center)[ #block(above: leading, below: leading)[ // Formatting depends on N authors 1, 2, or 2+ #if authors.len() > 2 { for a in authors [ #a.name#super[#a.affiliations]#if a!=authors.at(authors.len()-1) [#if a==authors.at(authors.len()-2) [, and] else [,]] ] } #if authors.len() == 2 { for a in authors [ #a.name#super[#a.affiliations]#if a!=authors.at(authors.len()-1) [and] ] } #if authors.len() == 1 { for a in authors [ #a.name#super[#a.affiliations] ] } ] #counter(footnote).update(0) ] } if affiliations != none { align(center)[ #block(above: leading, below: leading)[ #for a in affiliations [ #super[#a.id]#a.name \ ] ] ] } pagebreak() if abstract != none { block(above: 0em, below: 2em)[ #align(center, text(weight: "bold", "Abstract")) #set par(first-line-indent: 0pt, leading: leading) #abstract #if keywords != none {[ #text(weight: "regular", style: "italic")[Keywords:] #h(0.25em) #keywords ]} ] } pagebreak() /* Redefine headings up to level 5 */ show heading.where( level: 1 ): it => block(width: 100%, below: leading, above: leading)[ #set align(center) #set text(size: fontsize) #it.body ] show heading.where( level: 2 ): it => block(width: 100%, below: leading, above: leading)[ #set align(left) #set text(size: fontsize) #it.body ] show heading.where( level: 3 ): it => block(width: 100%, below: leading, above: leading)[ #set align(left) #set text(size: fontsize, style: "italic") #it.body ] show heading.where( level: 4 ): it => text( size: 1em, weight: "bold", it.body + [.] ) show heading.where( level: 5 ): it => text( size: 1em, weight: "bold", style: "italic", it.body + [.] ) if cols == 1 { doc } else { columns(cols, gutter: 4%, doc) } } // Journal mode #let jou( title: none, running-head: none, authors: none, affiliations: none, authornote: none, abstract: none, keywords: none, margin: (x: 2.5cm, y: 2.5cm), paper: "us-letter", font: ("Times New Roman"), fontsize: 10pt, leading: 0.5em, // Space between lines spacing: 0.5em, // Space between paragraphs first-line-indent: 0cm, toc: false, cols: 2, mode: none, doc, ) = { set page( paper: paper, margin: margin, header-ascent: 50%, header: locate( loc => if [#loc.page()] == [1] { [] } else { grid( columns: (1fr, 1fr), align(left)[#running-head], align(right)[#counter(page).display()] ) } ), ) set par( justify: true, leading: leading, first-line-indent: first-line-indent ) // Also "leading" space between paragraphs show par: set block(spacing: spacing) set text( font: font, size: fontsize ) if title != none { align(center)[ #v(3em)#block(below: leading*4)[ #text(size: fontsize*1.8)[#title] ] ] } if authornote != none { footnote(numbering: "*", authornote) counter(footnote).update(0) } if authors != none { align(center)[ #block(below: leading*2)[ #set text(size: fontsize*1.3) // Formatting depends on N authors 1, 2, or 2+ #if authors.len() > 2 { for a in authors [ #a.name#super[#a.affiliations]#if a!=authors.at(authors.len()-1) [#if a==authors.at(authors.len()-2) [, and] else [,]] ] } #if authors.len() == 2 { for a in authors [ #a.name#super[#a.affiliations]#if a!=authors.at(authors.len()-1) [and] ] } #if authors.len() == 1 { for a in authors [ #a.name#super[#a.affiliations] ] } ] #counter(footnote).update(0) ] } if affiliations != none { align(center)[ #block(below: leading*2)[ #for a in affiliations [ #super[#a.id]#a.name \ ] ] ] } if abstract != none { block(inset: (x: 15%, y: 0%), below: 3em)[ #set text(size: 9pt) #set par(first-line-indent: 0pt, leading: leading) #abstract #if keywords != none {[ #v(1em)#text(weight: "regular", style: "italic")[Keywords:] #h(0.25em) #keywords ]} ] } /* Redefine headings up to level 5 */ show heading.where( level: 1 ): it => block(width: 100%, below: leading*2, above: leading*2)[ #set align(center) #set text(size: fontsize) #it.body ] show heading.where( level: 2 ): it => block(width: 100%, below: leading*2, above: leading*2)[ #set align(left) #set text(size: fontsize) #it.body ] show heading.where( level: 3 ): it => block(width: 100%, below: leading*2, above: leading*2)[ #set align(left) #set text(size: fontsize, style: "italic") #it.body ] show heading.where( level: 4 ): it => text( size: 1em, weight: "bold", it.body + [.] ) show heading.where( level: 5 ): it => text( size: 1em, weight: "bold", style: "italic", it.body + [.] ) if cols == 1 { doc } else { columns(cols, gutter: 4%, doc) } }