repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/Skimmeroni/Appunti | https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Metodi%20Algebrici/Metodi_defs.typ | typst | Creative Commons Zero v1.0 Universal | #import "@preview/ctheorems:1.1.2": *
#let example = thmbox("example", "Esempio", fill: rgb("#e9eef7"))
#let theorem = thmbox("theorem", "Teorema", fill: rgb("#e7f7e6"))
#let principle = thmbox("principle", "Principio", fill: rgb("#e7f7e6"))
#let lemma = thmbox("lemma", "Lemma", fill: rgb("#f7ebf4"))
#let corollary = thmbox("corollary", "Corollario", fill: rgb("#f7ebf4"))
#let proof = thmproof("proof", "Dimostrazione")
|
https://github.com/0x6e66/hbrs-typst | https://raw.githubusercontent.com/0x6e66/hbrs-typst/main/modules_en/01_fundamentals.typ | typst | = Fundamentals
#lorem(500)
== Sub-Fundamentals
#lorem(500) |
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/docs/tinymist/feature/cli.typ | typst | Apache License 2.0 | #import "mod.typ": *
#show: book-page.with(title: "Tinymist Command Line Interface (CLI)")
== Starting a LSP Server
To start a language server following the #link("https://microsoft.github.io/language-server-protocol/")[Language Server Protocol].
```
tinymist lsp
```
== Starting a Preview Server
To start a preview server, you can use the following command:
```
tinymist preview path/to/main.typ
```
See #link("https://enter-tainer.github.io/typst-preview/standalone.html")[Arguments].
|
https://github.com/CreakZ/mirea-algorithms | https://raw.githubusercontent.com/CreakZ/mirea-algorithms/master/reports/work_8/work_8.typ | typst | #import "../title_page_template.typ": title_page
#import "../layouts.typ": *
#set text(font: "New Computer Modern", size: 14pt)
#set page(margin: 2cm, paper: "a4")
#set heading(numbering: "1.")
#set figure(supplement: [Рисунок])
#set figure.caption(separator: [ -- ])
#title_page(8, [Стек и очередь])
#un_heading([Оглавление])
#outline(
title: none
)
#set par(justify: true, first-line-indent: 1.25cm)
#pagebreak()
#set page(numbering: "1")
#head1([= Условие задачи])
#par(
[
#indent Требуется выполнить два задания.
]
)
#par(
[
Первое задание не требует разработки кода, его цель в изучении АТД алгоритмов применения стека и очереди в задачах преобразования выражений из одной формы в другую.
Требуется решить три задачи.
]
)
#par(
[
Приведены образцы оформления решения каждой задачи.
Теоретический материал по алгоритмам преобразования арифметического выражения, представленного в строковом формате, из инфиксной формы в польскую постфиксную или префиксную.
]
)
#par(
[
Во втором задании требуется разработать программу вычисления значения арифметического выражения, представленного в одной из трех форм.
]
)
#head1([= Постановка задачи])
#par(
[#indent Задания моего персонального варианта (№22):]
)
#par(
[*Задание 1.* Выполнить четыре задачи, определенные вариантом задания 1.
Варианты задач представлены в таблице 18.]
)
#par(
[*Задание 2.* Дано арифметическое выражение в нотации, указанной в варианте, представленное в строковом формате.
Разработать программу выполнения задачи варианта. Структура представления стека или очереди определена вариантом.]
)
#pagebreak()
#head1([= Задание 1])
#head2([== Подзадание 1])
#par(
[
#indent Выполнить преобразование инфиксной записи выражения в постфиксную нотацию, расписывая процесс по шагам.
]
)
#par(
[
_Исходное выражение (согласно варианту, 22 строка 1 столбца таблицы 18):_
$ S = "z^(y+x)/m/n*(k-p)" $
]
)
#par(
[
#indent Приведем решение задачи в виде последовательности выкладок. Результат выкладок будем записывать в строку $S_1$, а операторы -- в стек $W$.
]
)
#let state(s1, w) = {
text([$S_1$: #s1 \ $W$: #w])
}
#par(
enum(
[Добавим операнд z в строку $S_1$ \ #state([z], [])],
[Добавим оператор ^ в стек $W$ \ #state([z], [^])],
[Добавим открывающую скобку в стек $W$ \ #state([z], [^(])],
[Добавим операнд y в строку $S_1$ \ #state([zy], [^(])],
[Добавим оператор + в стек $W$ \ #state([zy], [^(+])],
[Добавим операнд x в строку $S_1$ \ #state([zyx], [^(+])],
[Текущий символ равен закрывающей скобке, значит извлекаем все операторы из стека $W$ до открывающей скобки и помещаем в строку $S_1$ \ #state([zyx+], [^])],
[Извлечем оператор ^ из стека $W$ и добавим в строку $S_1$ \ #state([zyx+^], [])],
[Добавим оператор / в стек $W$ \ #state([zyx+^], [/])],
[Добавим операнд m в строку $S_1$ \ #state([zyx+^m], [/])],
[Добавим оператор / в стек $W$ \ #state([zyx+^m], [\//])],
[Извлечем из стека $W$ оператор / и добавим его в строку $S_1$ \ #state([zyx+^m/], [/])],
[Добавим операнд n в строку $S_1$ \ #state([zyx+^m/n], [/])],
[Извлечем оператор / из стека $W$ и добавим в строку $S_1$ \ #state([zyx+^m/n/], [])],
[Добавим оператор \* в cтек $W$ \ #state([zyx+^m/n/], [\*])],
[Добавим открывающую скобку в стек $W$ \ #state([zyx+^m/n/], [\*(])],
[Добавим операнд k в строку $S_1$ \ #state([zyx+^m/n/k], [\*(])],
[Добавим оператор - в стек $W$ \ #state([zyx+^m/n/k], [\*(-])],
[Добавим операнд p в строку $S_1$ \ #state([zyx+^m/n/kp], [\*(])],
[Текущий символ равен закрывающей скобке, значит извлекаем все операторы из стека $W$ до открывающей скобки и помещаем в строку $S_1$ \ #state([zyx+^m/n/kp-], [\*])],
[Извлечем из стека $W$ оператор \* и добавим его в строку $S_1$ \ #state([zyx+^m/n/kp-\*], [])]
)
)
#par(
[
#indent Преобразование завершено, поскольку стек $W$ пуст. Полученная строка $S_1 = "zyx+^m/n/kp-*"$ представляет собой постфиксную форму записи исходного инфиксного выражения.
]
)
#head2([== Подзадание 2])
#par(
[
#indent Представить инфиксную нотацию выражения с расстановкой скобок, расписывая процесс по шагам.
]
)
#par(
[
_Исходное выражение (согласно варианту, 22 строка 2 столбца таблицы 18):_
$ S = "afbc*-zx-/y++" $
]
)
#par(
[
#indent Приведем решение задачи в виде таблицы (см. табл. 1). Результат решения запишем в строку $S_1$.
]
)
#par(
first-line-indent: 0cm,
[
Таблица 1 -- Решение позадания 2
]
)
#figure(
table(
columns: 2,
align: (left, center),
table.header(
[Стек операндов],
[Операция (операнд) исходного выражения]
),
[a], [a],
[af], [f],
[afb], [b],
[afbc], [c],
[af(b*c)], [\*],
[a(f-b*c)], [-],
[a(f-b*c)z], [z],
[a(f-b*c)zx], [x],
[a(f-b*c)(z-x)], [-],
[a(f-b*c)/(z-x)], [/],
[a(f-b*c)/(z-x)y], [y],
[a((f-b*c)/(z-x))+y], [+],
[a+(((f-b*c)/(z-x))+y)], [+]
)
)
#par(
[
#indent Преобразование завершено. Полученная строка $S_1 = "a+(((f-b*c)/(z-x))+y)"$ представляет собой инфиксную форму записи исходного постфиксного выражения.
]
)
#pagebreak()
#head2([== Подзадание 3])
#par(
[
#indent Представить префиксную нотацию выражения, полученного в результате выполнения задачи 2, расписывая процесс по шагам.
]
)
#par(
[
Приведем решение позадания в виде последовательности выкладок.
]
)
#enum(
[Преобразуем самое вложенное выражение в префиксную форму: f-b*c = -f*bc.
Подставим полученное выражение обратно в исходную строку: a+(((-f*bc)/(z-x))+y).],
[Аналогично преобразуем z-x: -zx. Подставим полученное в исходную строку: a+(((-f*bc)/-zx)+y).],
[Аналогично преобразуем выражение (-f*bc)/-zx = /-f*bc-zx. Подставим полученное в исходную строку: a + ((/-f*bc-zx) + y).],
[Аналогично преобразуем выражение (/-f*bc-zx) + y = +/-f*bc-zxy. Подставим результат в исходную строку: a+(+/-f*bc-zxy).],
[Аналогично преобразуем выражение: +a+/-f*bc-zxy.]
)
#par(
[
#indent Полученное выражение +a+/-f*bc-zxy является префиксной формой записи инфиксного выражения, полученного в подзадании 2.
]
)
#head2([== Подзадание 4])
#par(
[
#indent Вычислить значение выражения.
]
)
#par(
[
_Исходное выражение (согласно варианту, 22 строка 3 столбца таблицы 18):_
$ S = "-+3+5,1/*2,4^1+2,6" $
]
)
#par(
[
#indent Приведем решение подзадания 4 в виде последовательности выкладок. Начнем с самого внешнего оператора и будем двигаться внутрь
]
)
#par(
enum(
[Самый внешний оператор --- -.],
[Разберем выражение +3+5,1. Поскольку все операторы являются плюсами, просто найдем сумму всех чисел: $3+5+1=9$.],
[Далее разберем оставшееся выражение /\*2,4^1+2,6.
Самая вложенная операция --- +2,6 = $2+6=8$.
Далее по вложенности следует операция ^1,8 (8 -- результат сложения на предыдущем шаге).
^1,8 = $1 ^ 8 = 1$.
Затем следует операция \*2,4 = $2 dot 4 = 8$.
Последняя операция -- частное (/) результатов, полученных на последнем и предпоследнем шагах соответственно: /8,1 = $8 div 1 = 8$],
[Остается последняя операция --- разность результатов, полученных после выполнения шагов 2 и 3 соответственно: -9,8 = $9 - 8 = 1$.]
)
)
#par(
[#indent В результате вычислений получим ответ: 1.]
)
#pagebreak()
#head1([= Задание 2])
#par(
[
#indent Дано арифметическое выражение в постфиксной нотации, представленное в строковом формате.
Разработать программу выполнения задачи варианта.
В качестве структуры данных использовать стек, реализованный на основе линейного списка.
]
)
#head2([== АТД задачи])
#head2([== #raw("Stack")])
#let tab(theme) = {
set par(first-line-indent: 1.25cm, hanging-indent: 1.25cm)
text([#theme #linebreak()])
}
#let method(num, head, pre, post, header) = {
par(hanging-indent: 1.25cm, first-line-indent: 1.25cm, [
#num #head #linebreak()
Предусловие: #pre #linebreak()
Постусловие: #post #linebreak()
Заголовок: #header #linebreak()
])
}
#par(
[
АТД Stack \ { \
#tab([_Данные_ (описание свойств структуры данных задачи)])
#tab([top -- указатель на вершину стека])
#tab([_Операции_ (объявления операций)])
#method(
[1.],
[Метод, создающий пустой стек],
[нет],
[пустой стек],
[#raw("Stack()")]
)
#method(
[2.],
[Метод, осуществляющий добавление элемента на вершину стека],
[value -- значение нового элемента],
[обновленный стек],
[#raw("void push(int value)")]
)
#method(
[3.],
[Метод, осуществляющий удаление элемента с вершины стека],
[исходный стек],
[обновленный стек],
[#raw("void pop()")]
)
#method(
[4.],
[Метод, осуществляющий считывание значения элемента, находящегося на вершине стека],
[исходный стек],
[значение элемента, находящегося на вершине стека],
[#raw("int peek()")]
)
#method(
[5.],
[Метод, осуществляющий проверку стека на пустоту],
[исходный стек],
[#raw("true"), если стек пуст, иначе #raw("false")],
[#raw("bool empty()")]
) \
}
]
)
#head2([== #raw("Element")])
#par(
[
АТД Element \ { \
#tab([_Данные_ (описание свойств структуры данных задачи)])
#tab([value -- значение текущего элемента стека])
#tab([next -- указатель на следующий элемент стека])
#tab([_Операции_ (объявления операций)])
#method(
[1.],
[Метод, создающий элемент стека],
[value -- значение элемента стека],
[элемент стека],
[#raw("Element(int value)")]
) \
}
]
)
#head2([== Код реализации АТД])
#par([1. Код файла #raw("stack.h")])
#let stack_h = read("../../src/work_8/headers/stack.h")
#raw(stack_h, lang: "cpp")
#par([2. Код файла #raw("stack.cpp")])
#let stack_cpp = read("../../src/work_8/source/stack.cpp")
#raw(stack_cpp, lang: "cpp")
#par([3. Код файла #raw("element.h")])
#let element_h = read("../../src/work_8/headers/element.h")
#raw(element_h, lang: "cpp")
#par([4. Код файла #raw("element.cpp")])
#let element_cpp = read("../../src/work_8/source/element.cpp")
#raw(element_cpp, lang: "cpp")
#head2([== Код основной программы])
#par([1. Код файла #raw("main.cpp")])
#let main = read("../../src/work_8/main.cpp")
#raw(main, lang: "cpp")
#par([2. Код файла #raw("operations.cpp")])
#let operations = read("../../src/work_8/source/operations.cpp")
#raw(operations, lang: "cpp")
#head2([== Тестирование])
#par(
[
#indent *Тест №1.* Входная строка: 8,2,5\*+4,3,2\*-4-/. Ожидаемые выходные данные: "Ответ: -3"
]
)
#figure(
image(
"image/test1.png",
width: 60%
),
caption: [Результаты теста №1]
)
#pagebreak()
#par(
[
#indent *Тест №2.* Входная строка: 4,8,2\*-5+. Ожидаемые выходные данные: "Ответ: -7"
]
)
#figure(
image(
"image/test2.png",
width: 60%
),
caption: [Результаты теста №1]
)
#par(
[
#indent *Тест №3.* Входная строка: 2,2,1+^4/2/9,6-\*. Ожидаемые выходные данные: "Ответ: 3"
]
)
#figure(
image(
"image/test3.png",
width: 60%
),
caption: [Результаты теста №3]
)
#pagebreak()
#head1([= Выводы])
#par(
[
#indent В результате выполнения работы были получены знания и навыки по реализации структуры стек и очередь,
выполнению операций управления стеком и очередью,
практическому применению стека и очереди при вычислении значения арифметического выражения и преобразования арифметических выражений из инфиксной нотации в польскую нотацию.
]
)
|
|
https://github.com/RemiSaurel/miage-rapide-tp | https://raw.githubusercontent.com/RemiSaurel/miage-rapide-tp/main/0.1.0/lib.typ | typst | #let conf(
subtitle: none,
authors: (),
years: (2024, 2025),
toc: true,
lang: "fr",
font: "Satoshi",
date: none,
image: "../assets/miage.png",
title,
doc,
) = {
set text(lang: lang, font: font)
v(32pt)
figure(
image(image, width: 50%),
)
v(32pt)
let count = authors.len()
let ncols = 1
if count > 3 {
ncols = 2
}
v(32pt)
align(center)[
#line(length: 100%)
#v(16pt)
#text(32pt, title, weight: "semibold")\
#v(16pt)
#if (subtitle != none) {
line(length: 10%)
text(24pt, subtitle, weight: "medium")
}
#line(length: 100%)
#v(64pt)
#text(20pt)[Années universitaires: ]
#text(20pt, years.map(year => str(year)).join("-"))
#align(bottom)[
#grid(
columns: (0.5fr,) * ncols,
row-gutter: 12pt,
..authors.map(author => [
#text(16pt, author.name) \
]
),
)]
]
pagebreak()
set align(left)
show heading.where(level: 1): it => [
#pad(
top: 6pt,
text(22pt ,it.body)
)
]
show outline.entry.where(
level: 1
): it => {
v(12pt, weak: true)
strong(it)
}
if toc {
outline(indent: 2em, depth: 1)
pagebreak()
}
set page(
margin: (top: 42pt),
header: [
#set text(8pt)
#smallcaps[#title]
#if (date != none) {
h(1fr) + text(date)
}
#line(length: 100%)
],
)
doc
}
#let c = counter("question")
#let question(title, counter: true) = {
v(8pt)
if (counter) {
c.step()
heading(level: 2, c.display() + ") " + title)
} else {
heading(level: 2, title)
}
v(4pt)
}
#let code-block(code, language, title: none) = {
v(6pt)
if (title != none) {
text(10pt, style: "italic", title)
linebreak()
}
raw(code, lang: language)
v(6pt)
}
#let remarque(content, bg-color: silver, text-color: black) = {
v(4pt)
block(
fill: bg-color,
width: 100%,
inset: 8pt,
radius: 4pt,
text(10pt, content, fill: text-color)
)
}
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/036%20-%20Guilds%20of%20Ravnica/015_The%20Gathering%20Storm%3A%20Chapter%2010.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Gathering Storm: Chapter 10",
set_name: "Guilds of Ravnica",
story_date: datetime(day: 14, month: 08, year: 2019),
author: "<NAME>",
doc
)
The rain came down as though it had a grudge against the city, rattling roof tiles and slamming against windows. Even with his magic splitting the torrent above his head, Ral walked through a mist of ricocheting drops, and his coat was wet through by the time he arrived at New Prahv.
The Azorius guildhall was crawling with soldiers. Isperia had called out every reserve to provide security for the summit, and to hold back the crowds of curious citizens who had gathered in spite of the foul weather. That something important was happening had become an open secret in the city, and the square around the great triple tower was packed with a mass of humanity. White-armored Azorius soldiers struggled to keep a narrow lane open, through which the delegates could arrive.
Ral kept a wary eye on the mob. They seemed interested, rather than furious, at least so far, and he caught a wave of excited shouts as the Simic delegation arrived in a living carriage that pulled itself along with great purple tentacles. Ral himself slipped in behind them, acknowledged by the soldiers at the gate but ignored by the onlookers.
A nervous young woman guided him into one of the towers, and they ascended a polished marble staircase. Eventually she led him to a grand pair of double doors, inlaid with gold and silver filigree depicting the Azorius crest, so heavy a pair of burly servants had to push them open. Inside was one of the Senate’s own debating chambers, a circular room with a raised marble bench running all the way around the perimeter. There was a dais at the far end for a speaker, in front of a massive, multi-paned window, which was streaked with rain. In the distance, lightning flashed among the clouds, and Ral felt his own power resonate in sympathy with every bolt.
He was not the first to arrive. Isperia occupied the dais, with <NAME> at her side, both absorbed in reading something. Hekara, who had left that morning to get final instructions from her superiors, sat on the marble bench, waving frantically to Ral.
More surprising was the cyclops sitting cross-legged behind the bench, head bent, only inches from grazing the ceiling. This had to be Borborygmos, the Gruul guildmaster. He had a bestial look, with a wild mane of red hair and two twisting horns, wearing only a few scraps of leather armor. In the polished serenity of the Azorius guildhall, the giant looked completely out of place.
#emph[But he’s here.] Niv-Mizzet had promised he would be, but Ral had to admit for once he’d doubted the Firemind. #emph[I wonder what kind of favors he pulled in to make ] that#emph[ happen?]
Borborygmos paid no attention Ral, but he looked up with a snort as the doors opened again, admitting the angelic form of Aurelia. She was trailed by several high-ranking Boros officers, including the female minotaur Ral had seen last time. The sight of their uniforms seemed to rile the cyclops, who made a low growling sound punctuated by a few angry barks.
"Ahem." The speaker was a small, green-skinned humanoid standing near Borborygmos’s feet. The frog-faced creature wore a well-tailored dark suit and spoke with an erudite accent. "Guildmaster Borborygmos wishes to know how much longer he will be kept waiting with the running dogs of order."
The cyclops’s single eye was fixed on Aurelia. Most of the guilds were rivals to one degree or another, but the animosity between the anarchic Gruul Clans and the Boros Legion was legendary. The angel glanced at the cyclops, then politely took her seat, but her minotaur companion growled back, "You should be grateful to even have a seat at this table."
Borborygmos boomed a laugh. His translator said, "The guildmaster wishes you to understand that he is only here in deference to long-standing obligations to the Firemind. He offers no respect to any lesser creature."
"Lesser creatures," the minotaur said. "He—"
"Please," Isperia said, with quiet authority. "Let’s not have this meeting dissolve before it begins. The other delegations are arriving as we speak."
"I, for one, am eager to hear what Niv-Mizzet has to say." This was a new voice, made harsh and anonymous by a strange buzz, as though heard on the other side of thick wall. Ral looked across the room and saw a blurred, shifting figure, its humanoid shape covered in a cloak of illusion, so that it showed an every-changing arrangement of clothes and features. Ral had no idea when it had arrived.
"Lazav," Aurelia said with distaste. "You refuse to show yourself, even here?"
"Especially here, I should think." Lazav leaned back on the bench, dropping his blurred feet up on the rail.
"The Senate welcomes the Dimir guildmaster," Isperia said. Then, as the big doors opened again, she added, "And also the delegations from Simic and Selesnya."
Selesnya was represented by Emmara, in company with several other elves Ral didn’t know. A party of four purple-robed magi from Simic were just behind them. Their leader was an older man with hard, pebbly skin and bulging, fishy eyes, and his companions were a similar mix of humanoid and ichthyoid. #emph[Biomancers] , Ral thought, with an edge of distaste, as they bowed to Isperia and took their seats. He’d never been fully comfortable with the Simic’s strange ideas about improving themselves.
Orzhov was next to arrive. Kaya and Teysa came in together, followed by several priests in black and gold robes. #emph[I’m going to have to get the full story from them at some point.] Last of all came the new queen of the Golgari, unaccompanied. Vraska wore a spectacular suit of scaled armor, gleaming with the iridescent colors of beetle scales, and the tendrils on her head lay flat and quiescent. Only when she saw Isperia did they shift, rising a fraction before she mastered herself and gave a shallow bow.
"Representatives and guildmasters," Isperia said, rising to her haunches. The sphinx’s voice grew effortlessly louder until it dominated the room. "I thank you for coming. We face an unprecedented threat to Ravnica itself, and I am heartened by this evidence that the guilds can draw together in a crisis."
"Evidence is something we haven’t seen much of," one of the Simic snapped in a nasal voice. "Zarek has proposed some wild theories about many worlds and interplanar threats. How do we know that any of this is real?"
"I believe him," Lazav said. "Nothing else fits the facts we have, limited as they are."
The Boros minotaur snorted. "Yes, let us rely on the word of a spy who’s busy tearing apart his own guild."
"I found my guild in need of . . . cleansing," Lazav said. "And I will tell you now that I am not the one in this chamber you should mistrust." He turned to face Ral, and even through the illusion cloak Ral felt his gaze.
Slowly, Ral ran a hand through his hair, a tiny crackle restoring its customary frizz. He got to his feet, holding up his hands for silence.
"Honored representatives," he said, looking around the room. "I’m aware that simply being here, together, is nearly unprecedented. But if we are going to defend Ravnica, we are going to have to go much further than that. <NAME> is real, and he is coming. None of us can stop him."
"So you assume," said the minotaur. "You underestimate the Legion."
Borborygmos grunted, and his translator said, "We welcome this Bolas, if he will test his might against the Gruul."
"Don’t be a fool," Vraska snapped. "None of you know Bolas the way Ral and I do. He does not believe in half-measures. If he is coming to Ravnica, it is #emph[because] we cannot stop him."
"That’s certainly his reputation," Kaya said. Everyone looked at her, and she seemed almost embarrassed to have spoken. "Look. I’m not from around here, you all know that. But I’ve dealt with plenty of people who’ve gotten in Bolas’s way, and they’ve all regretted it. Take that for what it’s worth."
"His agents have already caused a great deal of harm," Emmara said. "The coup attempt at Selesnya was his doing, and it was nearly successful."
"Whether it was his doing is unclear," one of the elves near her said. "We shouldn’t jump to conclusions."
"Precisely," the Simic leader said. "Who benefits from this cooperation? Obviously the Azorius, with their laws and committees. We sit in their very hall! Could it not be that they have manufactured this supposed crisis for their own advantage?"
"I have no love for the Senate," Vraska grated, "but that is simply idiocy."
"I apologize if the subtleties are too much for a sub-sentient mind to comprehend," the fish-eyed representative sneered.
"You should all listen to Ral," Hekara burst out, unexpectedly. When, again, everyone paused to look, she flushed slightly. "He’s usually right, is all," she said. "And he’s my mate. So you should pay attention."
The Simic representative’s eyes rolled. "If we’re #emph[quite] finished hearing from—"
An enormous shadow darkened the hall.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The great glass windows folded themselves delicately, moving as though of their own accord, in the grips of an unstoppable magical force. The roar of the rain redoubled, layered over with distant thunder. Some drops spattered on the polished marble, but most were blocked by the huge, scaled shape that now blocked the opening, claws gripping the outside of the building, wings spread wide for balance.
Niv-Mizzet had arrived.
His head just about fit into the chamber, like some enormous snake, with its brightly-colored fins spread wide. Isperia stepped back slightly, giving the dragon center stage. When the Firemind spoke, his voice echoed inside the skull of everyone present.
"Vraska is right," Niv-Mizzet said. "You do not understand what is coming for you. But I do." His huge head shifted, staring at each representative in turn. "I am the #emph[parun] of my guild. I have lived on Ravnica for more than fifteen thousand years, and I have defeated more challengers than any of you can possibly imagine. I have knowledge that no one else living possesses, sorceries that are otherwise gone to time, weapons whose making is lost. And I am telling you that #emph[<NAME> is more powerful than I] ."
There was a long silence.
"If his power is so irresistible," Aurelia said eventually, "then why gather us here at all?"
"It is not irresistible. I have been working on a way to stop him." The Firemind’s fins flexed. "It is a most dangerous and all-consuming ritual, but I believe it will grant me the power I need."
"But that would violate the Guildpact," Lazav said, in the tone of someone finally understanding. "So you want to use the fail-safe."
The elves with Emmara looked at one another in confusion. Emmara cleared her throat. "What fail-safe?"
"I imagine Trostani keeps that to herself," Lazav said.
"When Azor, in his wisdom, created the Guildpact," Isperia said, "he created a means by which it could be amended. It merely requires the agreement of all ten guilds."
"It was not supposed to be necessary," Niv-Mizzet said, "because the Living Guildpact could perform the same function. But <NAME> is still missing, and may never return. We can no longer afford to wait."
"In other words," the Simic representative said, "you want us to grant you permission to become practically all powerful?" He snorted. "How is that not simply an invitation to Izzet hegemony?"
"I have led the Izzet for ten thousand years," the Firemind said. "But I will leave them for this, and <NAME> will take my place. The new strictures of the Guildpact will still bind me, even with my new power. I will become a guardian of Ravnica itself, above the concerns of guild politics."
"Is that even possible?" Kaya said.
Ral spoke up. "Niv-Mizzet has a deeper understanding of the Guildpact than anyone living." He thought he saw Vraska roll her eyes, but she said nothing.
"Convenient," said the Simic representative. "So we must simply take his word for it."
"The Firemind may be the expert," Isperia said, "but every guild has its own lawmages. I suggest we take a recess, to allow the representatives to consult them and get a better understanding of what Niv-Mizzet is asking. This conference will reconvene tomorrow morning, and we will make our decision then."#linebreak
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Following proper diplomatic protocol, the Azorius stewards had scheduled Ravnica’s most awkward reception to take place after the meeting. Vraska took one look at the room, full of suspicious stares and cucumber sandwiches, and walked away. They’d all been assigned quarters somewhere in the tower, and she resolved to find them.
#emph[The tower.] Being here, in the center of Azorius power, grated more than she thought it would. All these people—thousands of scribes, bookkeepers, legislators—just going about their daily routines, scribbling words on a page. #emph[They have no idea what it costs.] What their decisions meant to people out in the rest of the city. #emph[The scratch of a pen sends someone to prison. A tick mark is a death sentence.] It made her want to scream.
"Vraska."
She turned, reluctantly, to find Ral coming up behind her. Vraska put her hands on her hips, her tendrils shifting uneasily.
"What do you want, Zarek?"
"I . . ." He pulled up short, taking in her expression. "Is everything all right?"
"Fine," Vraska spat. She straightened up, making an effort not to let her inner turmoil show on her face. "What is it?"
"I just wanted to thank you for your help. I’m not sure I got the chance, after we left the cathedral."
Vraska waved a hand. "Your friend was bleeding to death. I imagine that was distracting."
Ral paused, as though he’d realized something, then went on. "And I know coming here can’t be easy for you."
#emph[You have no idea.] Vraska suppressed a snarl, and gave a curt nod. "I only hope it’s not for nothing."
"They’ll come together," Ral said. "We’ve got them this far."
#emph[We.] He trusted her, Vraska realized. She wanted to laugh, or possibly cry. Instead, she went to turn away, then hesitated.
"Can I ask you something?"
"Of course," Ral said.
"What Niv-Mizzet said, about Jace. That he might be dead. Does he—do you think he knows something we don’t?"
Ral frowned. "It’s hard to say, with him. He doesn’t confide in me more than he has to."
"Do #emph[you] believe he’s coming back?"
"Beleren? Probably." Ral shrugged. "He’s too annoying to stay gone."
"I can agree with that," Vraska said, forcing a smile. "I should go. There are things I need to attend to."
"Of course." Ral bowed. "Tomorrow, then."
#emph[Tomorrow.]
She found her quarters, a bland but comfortable apartment, and shooed away the liveried stewards who tried to make her more comfortable. Everything here was so #emph[sterile] , locked away inside a giant column of stone and steel. In her own domain, she slept on a bed of living moss, surrounded by the subtlety beautiful scents of decay. And before that, she’d grown used to the #emph[Belligerent] , its ever-present sway and the salt smell of the sea. Lying on the bed here felt like trying to sleep in a tomb.
Not that sleep was a real possibility. She felt her mind racing like a small animal caught in a trap, searching for a way out. #emph[Damn Ral and his trust. Damn Jace, for not being here when I need him. Damn, damn, damn . . .]
Slowly, ever so slowly, the sun went down. Vraska lay in the cool darkness, staring at nothing, trying not to think.
There was a rustle from the front door of her room. She rolled out of bed at once, heart slamming in her chest, tendrils wild and writhing. For a few moments, there was only silence.
Something was visible by the door. A folded piece of paper, shoved underneath. Vraska padded across the room and picked it up. In a neat copperplate hand, the note said only,
#emph[The conference chamber, now. No guards.]
There was a long silence. Slowly, Vraska crushed the paper into a ball.#linebreak
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#linebreak The door to the conference chamber stood half-open. Vraska slipped through, her boots clicking softly on the marble. The big windows were closed, and rain drummed against them in a steady rhythm. Beyond, the city was mostly dark, the downpour having driven all but the most dedicated from the streets. Only a few lights burned, echoed in the sky by distant flashes of lightning. As the note had promised, no guards waited by the door.
Isperia sat where she had during the conference, propped on her leonine haunches. She was reading something and making notes, her big paws handling paper and pen with surprising delicacy. She tipped her head as Vraska entered, making note of the gorgon’s presence, but didn’t look up until Vraska cleared her throat.
"Guildmaster," Isperia said. "I would have thought you’d be asleep by now."
"Just feeling restless," Vraska said, walking across the room. She was calm, her tendrils flat and placid. "You?"
"I require little sleep," Isperia said. "And my duties never cease. Even in the midst of such great events, the business of the Senate continues."
"Yes," Vraska said. "It does, doesn’t it?"
Isperia reached the end of a page and carefully set down her pen. She looked up, her pale eyes knowing.
"There is something you wish to say," the sphinx said.
"How much do you know about me?" Vraska said.
"Enough," Isperia said. "You were an assassin for the Golgari. Given recent revelations, it is safe to assume that you are a Planeswalker."
"Do you want to know how I found out I was a Planeswalker?"
"I admit to some curiosity on anything concerning the subject."
"I was born here on Ravnica." Vraska started pacing back and forth, Isperia’s placid eyes following her. "In the depths, of course, but I was never a member of the Golgari. I wasn’t . . . political, and they would have wanted me to be their tool." She touched her tendrils, gently. "I just wanted to be true to my nature. To hunt, alone and free.
"I was seventeen when the Senate decided that the Golgari had grown too powerful, too numerous. They needed to be pushed out of certain areas they’d claimed. The other guilds stood by as Azorius soldiers descended into the depths and rounded up peaceful rot farmers, kraul, whoever they could find. They didn’t care whether we were guild members or not. They took me because of what I was, not what I believed, and tossed me in prison with the rest.
"And what a prison it was." Vraska turned sharply to face Isperia. "Your scribes are good at laws and principles, but not so talented when it comes to basic logistics, are they? We were packed in five, six, seven to a cell. It was bound to boil over, and when it did the crackdown was vicious. They started hauling us away to improvised cells across the city. I was stuck in some dirty basement with half a hundred others.
"They kept us there for hours. Days. No one in the Senate knew what to do. We were starving, filthy with our own waste, and all the guards could tell us was that we had to wait until they got new instructions. Eventually someone snapped. The guards hit back.
"I wasn’t even fighting." Vraska looked down at her hands. "I hadn’t dealt with surface-dwellers much, then, but I knew they were waiting for an excuse. A gorgon is dangerous. We can’t #emph[help] but be dangerous, can we? If I fought, or talked back, they would have had every reason to kill me. So I stayed in the corner, with my hands over my eyes." She took a deep breath. "And when it was finished, they dragged me over and beat me anyway. I remember the moment I realized they weren’t going to stop, that I was going to die in this stinking basement, for no damned reason at all. I couldn’t stand that. So I just . . . left."
"You planeswalked," Isperia said.
"That’s one way of putting it," Vraska agreed. "Another way is saying I woke up in a swamp, with half my ribs broken and no idea where I was."
"According to the information Niv-Mizzet has shared," Isperia said, "traumatic experiences are a common trigger for the ignition of a Planeswalker’s spark."
"So I understand," Vraska murmured. She stopped walking, directly in front of the sphinx. "I suppose I have you to thank, then, for mine." Her tendrils shifted. "Not the Azorius. You. It was your name on the arrest order."
"I know," Isperia said. "I was supreme judge at the time. I remember the riots you describe."
"Regrettable, I’m sure," Vraska said. "That’s how the Azorius described them. ‘Regrettable.'"
"Yes."
Vraska took a step forward. "#emph[Do] you regret it? Signing the order?"
"No," Isperia said mildly. "Mistakes were made in the execution, but the principle was sound. The Golgari #emph[had] grown dangerous, and the balance was threatened. The Senate has to act in the best interests of Ravnica."
"You’d do it again."
"If necessary."
"I thought so." Vraska sighed. "Jace told me #emph[I] should act in the best interests of Ravnica. For a while, I thought he was right. Aboard my ship, with my own crew, I could believe it." She shook her head. "Coming back here, though . . ."
"And yet you came to this council," Isperia said. "You put Ravnica’s interest first."
"I did."
#emph[I’m sorry, Jace.] It had all seemed so simple, aboard the #emph[Belligerent] . #emph[You were wrong about me.]
Vraska looked up, and her eyes filled with golden light.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#linebreak This time, the delegates arrived in a mass, milling outside the double doors. Ral watched the Simic representatives talking in a tight huddle, as Emmara argued with her fellow elves and Borborygmos, hunched over in the corridor, gave an exasperated grunt. <NAME> talked quietly with the two Azorius soldiers outside the door, until a steward hurried over, bearing a long iron key.
"Apologies," Dovin said. "Apparently the door was locked last night, for some reason."
He turned the key, and the soldiers pushed the doors wide. Ral took a step forward, then froze.
The conference room looked much as it had the previous day. The great window was open, and rain had sprayed across the marble and darkened the pure white curtains. Sitting at the head of the conference circle, where she had been the previous night, was Isperia. She was in the act of rearing up, her back paws flat on the floor, her calm face caught in an expression of frozen surprise. And, from nose to tail, she was nothing but gray stone, like an exquisitely detailed statue.
It took Ral a moment to process what he was seeing, and another moment to draw breath. Before he could speak, the hallway erupted into pandemonium.
"Assassination!" bellowed the minotaur, stepping in front of Aurelia.
"The gorgon!" one of the elves snapped. "Where is she?"
Ral realized that Vraska was not among the crowd of ambassadors at the same time everyone else did, and the babble of voices rose to a higher pitch.
"It’s a trap!" rasped the fish-eyed Simic representative. "She’s lured us to the slaughter!"
Only <NAME> seemed able to retain his calm. He stepped into the room, staring at the petrified guildleader, then turned back to the Azorius soldiers in the corridor.
"Establish a perimeter, Captain. I want this building searched at once. Extra security here, on the double."
"I will coordinate my forces to assist," Aurelia said. Her wings snapped open as she sprinted across the room and hurled herself out the open window.
"Everyone, remain calm," Dovin said, turning around. "You are all under our protection—"
"We see what your protection is worth!" the Simic representative snapped. "I for one am leaving at once."
The argument among the elves reached a crescendo as the purple-robed Simic magi stalked toward the exit. The others who’d come with Emmara turned to follow them, and Emmara herself gave Ral a helpless look and shook her head before hurrying to catch up.
Ral looked at Dovin desperately. "Perhaps if we went somewhere to wait—"
"Fish-face is right," Kaya said. "We should get out of here until we know it’s safe. If Vraska has turned on us, there’s no telling what else she’s got planned."
"But—"
"Sorry." Kaya tapped Teysa on the shoulder, got a nod, and the two of them walked away.
With that, a consensus seemed to have been reached. Hekara drifted to Ral’s side as the other delegates fled, leaving apologies in their wake. Ral stared after them, still stunned, not quite able to believe how quickly things had changed.
#emph[We were so close.] He felt the old anger boiling up inside him. #emph[So ] damned#emph[ close. And Vraska . . .] #emph[] #linebreak "Now what?" Hekara said, hesitantly.
Borborygmos gave an angry roar before turning to shuffle awkwardly down the corridor. His frog-like translator gave Ral a bow.
"The guildmaster instructs me to say that he sacrificed much to be here, at Niv-Mizzet’s behest. Much respect and honor amongst his people. Now he will face challenges, for certain. He wishes you to know that you have his animus."
"What’s animus?" Hekara said, as the translator bowed again and turned to leave.
"A polite why to say he’s going to pull my head off the next time he sees me," Ral muttered. He turned to find Lazav at his shoulder, wrapped in his flickering cloak of illusion. "You’re leaving too, I suppose?"
"Only for the moment," Lazav said. "The Dimir remain at your disposal, should you find a way to proceed. But I would like to take this moment to remind you of my warning."
"Which warning was that?"
"That #emph[I] was not the one you should mistrust." Lazav gave a blurred, flickering bow and melted away.
#emph[That’s it.] Ral felt like he’d been hollowed out. #emph[It’s over.] #emph[] #linebreak He’d thought this time would be different. He’d put his trust in Hekara, in Kaya. In #emph[Vraska] . #emph[Why on Ravnica did I think that was going to work out well?] #emph[] #linebreak #emph[And now . . .] #emph[] #linebreak He closed his eyes. Behind his eyelids, he could see the maps of the Implicit Maze he’d compiled for Niv-Mizzet, back before the contest that had produced the Living Guildpact. The paths led through every guild’s territory, the complex network of magic that maintained the basic underpinnings of Ravnica. To change it required the consent of every guild, because the magic touched every guild.
#emph[Unless . . .] #emph[] #linebreak He felt something bubbling up at the back of his mind. Plans and blueprints, a machine that would stretch across the Tenth District.
#emph[A way forward.] #emph[] #linebreak His eyes opened.
"Ral?" Hekara said.
"We’re #emph[not] finished." Ral ran a hand through his hair, an electric crackle returning it to its frizzy peak. "Not yet."
|
|
https://github.com/ludwig-austermann/modpattern | https://raw.githubusercontent.com/ludwig-austermann/modpattern/main/README.md | markdown | MIT License | # modpattern
This package provides exactly one function: `modpattern`
It's primary goal is to create make this:

## modpattern function
The function with the signature
`modpattern(size, body, dx: 0pt, dy: 0pt, background: none)`
has the following parameters:
- `size` is as size for patterns
- `body` is the inside/body/content of the pattern
- `dx`, `dy` allow for translations
- `background` allows any type allowed in the box fill argument. It gets applied first
Notice that, in contrast to typst patterns, size is a positional argument.
Take a look at the example directory, to understand how to use this and to see the reasoning behind the `background` argument. |
https://github.com/pluttan/os | https://raw.githubusercontent.com/pluttan/os/main/lab1/dz1.typ | typst | #import "@docs/bmstu:1.0.0":*
#import "@preview/tablex:0.0.8": tablex, rowspanx, colspanx, cellx
#show: student_work.with(
caf_name: "Компьютерные системы и сети",
faculty_name: "Информатика и системы управления",
work_type: "домашнему заданию",
study_field: "09.03.01 Информатика и вычислительная техника",
discipline_name: "Дискретная математика",
theme: "Поток в транспортной сети. Алгоритм Форда-Фалкерсона",
author: (group: "ИУ6-42Б", nwa: "<NAME>"),
date: "13.05.24",
adviser: (nwa: "<NAME>"),
city: "Москва",
table_of_contents: false,
)
= Задание, теоретические сведения, построение графа, определение источника и стока
== Задание
Сеть в виде взвешенного орграфа задана матрицей Ω пропускных способностей
ориентированных ребер. При помощи алгоритма Форда – Фалкерсона определить максимальный
поток $𝜑_max$, доставляемый от источника $s = x_1$ к стоку $s = x_12$ и указать минимальный разрез, отделяющий $t$ от $s$.
Оптимизационную часть алгоритма реализовать в виде коррекции потока хотя бы на одном
увеличивающем маршруте.
Матрица пропускных способностей (вариант 19):
#align(center)[
#tablex(
columns: 13,
inset: 10pt,
align: center + horizon,
[],[$x_1$],[$x_2$],[$x_3$],[$x_4$],[$x_5$],[$x_6$],[$x_7$],[$x_8$],[$x_9$],[$x_10$],[$x_11$],[$x_12$],
[$x_1$], [ ],[13],[ ],[46],[26],[ ],[ ],[ ],[ ],[ ],[ ],[ ],
[$x_2$], [ ],[ ],[ ],[ ],[ ],[ ],[20],[ ],[ ],[ ],[ ],[ ],
[$x_3$], [ ],[ ],[ ],[ ],[ ],[12],[ ],[ ],[ ],[ ],[ ],[ ],
[$x_4$], [ ],[ ],[ ],[ ],[ ],[21],[ ],[ ],[ ],[ ],[24],[ ],
[$x_5$], [ ],[ ],[27],[ ],[ ],[ ],[15],[14],[ ],[ ],[ ],[ ],
[$x_6$], [ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[16],[ ],[ ],[ ],
[$x_7$], [ ],[ ],[ ],[ ],[ ],[ ],[ ],[8 ],[ ],[13],[ ],[31],
[$x_8$], [ ],[ ],[33],[ ],[ ],[ ],[ ],[ ],[ ],[22],[ ],[ ],
[$x_9$], [ ],[ ],[ ],[ ],[ ],[ ],[ ],[4 ],[ ],[10],[ ],[18],
[$x_10$],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[17],[50],
[$x_11$],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[22],[ ],[ ],[7],
[$x_12$],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],
)]
#pagebreak()
== Теоретические сведения для решения задания
=== Теорема 1
Если $(s, …, x_i, …, x_j, …, t)$ – путь от $s$ к $t$ и все ребра этого пути ненасыщенные, то поток на этом пути (а следовательно, и во всей сети) можно увеличить на величину $delta^∗ = min {delta (x_i, x_j)}$ по всем ребрам пути.
При применении теоремы 1 хотя бы одно ребро становится насыщенным. При итерационном применении теорема 1 появляется ситуация, когда нет ни одного пути от источника к стоку, на котором все ребра были бы ненасыщенными. Эта ситуация говорит о полном потоке.
=== Теорема 2
Рассмотрим маршрут из источника к стоку. Пусть на этом маршруте прямые рёбра строго ненасыщенные, а поток на обратных рёбрах строго положителен. Тогда, если $(s, …, x_i, …, x_j, …, t)$ – маршрут из $s$ к $t$, удовлетворяющий указанным условиям, то величину потока на этом маршруте (следовательно, и во всей сети) можно увеличить на величину $ε* = min{δ*, φ*}$, где $δ^*$ – минимальная остаточная пропускная способность по всем прямым ребрах маршрута, а $φ^*$ – минимальная величина потоков по всем обратным ребрам маршрута. На всех прямых ребрах маршрута потоки увеличиваются на $ε^*$, на обратных – уменьшаются на $ε^*$. Такой маршрут называется увеличивающим.
=== Теорема 3
Поток в сети достигает максимального значения тогда и только тогда, когда в сети более невозможно построить увеличивающий маршрут.
=== Теорема 4 (Теорема Форда – Фалкерсона)
Для любой сети с одним источником и одним стоком величина максимального потока $phi_max$, доставляемого от источника к стоку, равна пропускной способности минимального разреза.
=== Алгоритм Форда – Фалкерсона
- Задать начальный поток.
- Итерационно применяя теорему 1, получить полный поток.
- Итерационно применять теорему 2. При возникновении ситуации невозможности построить более увеличивающий маршрут на основании теоремы 3 достигаем максимальный поток.
- Определить разрез, по которому проходит максимальный поток.
#pagebreak()
== Построенный граф, его источник и сток
Построим взвешенный ориентированный граф по матрице Ω пропускных способностей ориентированных ребер (рис. 1).
#img(image("1.png", width:90%), [Построенный граф])
Источником будет вершина $x_1 = s$, стоком -- вершина $x_2 = t$. Поток $phi = 0$.
= Получение полного потока
Определим, итерационно применяя теорему 1, полный поток $phi_n$.
== Путь $(x_1, x_2, x_7, x_8, x_10, x_11, x_12)$
Рассмотрим путь $(x_1, x_2, x_7, x_8, x_10, x_11, x_12)$.
#img(image("2.png", width:90%), [Путь $(x_1, x_2, x_7, x_8, x_10, x_11, x_12)$, отмеченный на графе])
Рассчитаем остаточную пропускную способность пути:
#let fd(x1,x2) = {$space c(x_#x1, x_#x2) - phi(x_#x1, x_#x2)$}
$ delta^* = min{fd(1,2),fd(2,7),\ fd(7,8), fd(8,10),\ fd(10,11), fd(11,12)} = \
= min{13 - 0, 20 - 0, 8 - 0, 22 - 0, 17 - 0, 7 - 0}=\ = min{13, 20, 8, 22, 17, 7} = 7\ c(x_i, x_j) "- пропускная способность ребра с вершинами" x_i space и space x_j \ phi(x_i, x_j) "- поток ребра с вершинами" x_i space и space x_j $
#h(35pt) Добавим к потоку всех ребер, входящих в путь, остаточную пропускную способность пути. Ребра, пропускная способность которых будет равна потоку через ниx, станут насыщенными.
#pagebreak()
#img(image("3.png", width:80%), [Граф с добавленными потоками через ребра пути])
В данном случае ребро $(x_11, x_12)$ стало насыщенным.
Таким образом общий поток $phi_n = phi_n + delta^* = 0 + delta^* = 7$.
В результате, после выполнения всех действий получаем граф:
#img(image("4.png", width:80%), [Граф с текущими потоками])
== Путь $(x_1, x_2, x_7, x_10, x_11, x_9, x_12)$
Рассмотрим путь $(x_1, x_2, x_7, x_10, x_11, x_9, x_12)$.
#img(image("5.png", width:90%), [Путь $(x_1, x_2, x_7, x_10, x_11, x_9, x_12)$])
Рассчитаем остаточную пропускную способность пути:
$ delta^* = min{fd(1,2),fd(2,7),\ fd(7,10), fd(10,11),\ fd(11, 9), fd(9,12)} = \
= min{13 - 7, 20 - 7, 13 - 0, 17 - 7, 22 - 0, 18 - 0}=\ = min{6,13,13,10,22,18} = 6\ c(x_i, x_j) "- пропускная способность ребра с вершинами" x_i space и space x_j \ phi(x_i, x_j) "- поток ребра с вершинами" x_i space и space x_j $
#h(35pt) Добавим к потоку всех ребер, входящих в путь, остаточную пропускную способность пути. Ребра, пропускная способность которых будет равна потоку через ниx, станут насыщенными.
#img(image("6.png", width:80%), [Граф с добавленными потоками через ребра пути])
В данном случае ребро $(x_1, x_2)$ стало насыщенным.
Таким образом общий поток $phi_n = phi_n + delta^* = 7 + delta^* = 13$.
В результате, после выполнения всех действий получаем граф:
#img(image("7.png", width:80%), [Граф с текущими потоками])
== Путь $(x_1, x_5, x_7, x_12)$
Рассмотрим путь $(x_1, x_5, x_7, x_12)$.
#img(image("8.png", width:90%), [Путь $(x_1, x_5, x_7, x_12)$])
Рассчитаем остаточную пропускную способность пути:
$ delta^* = min{fd(1,5),fd(5,7),\ fd(7,12)} = min{26 - 0, 15 - 0, 31 - 0}=\ = min{26, 15, 31}
= 15\ c(x_i, x_j) "- пропускная способность ребра с вершинами" x_i space и space x_j \ phi(x_i, x_j) "- поток ребра с вершинами" x_i space и space x_j $
#h(35pt) Добавим к потоку всех ребер, входящих в путь, остаточную пропускную способность пути. Ребра, пропускная способность которых будет равна потоку через ниx, станут насыщенными.
#img(image("9.png", width:80%), [Граф с добавленными потоками через ребра пути])
В данном случае ребро $(x_5, x_7)$ стало насыщенным.
Таким образом общий поток $phi_n = phi_n + delta^* = 13 + delta^* = 28$.
В результате, после выполнения всех действий получаем граф:
#img(image("10.png", width:80%), [Граф с текущими потоками])
== Путь $(x_1, x_5, x_8, x_10, x_11, x_9, x_12)$
Рассмотрим путь $(x_1, x_5, x_8, x_10, x_11, x_9, x_12)$.
#img(image("11.png", width:90%), [Путь $(x_1, x_5, x_8, x_10, x_11, x_9, x_12)$])
Рассчитаем остаточную пропускную способность пути:
$ delta^* = min{fd(1, 5), fd(5, 8),\ fd(8, 10), fd(10, 11),\ fd(11,9), fd(9,12)}\ = min{26 - 15, 14 - 0, 22 - 7, 17 - 13, 22 - 6, 18 - 6}\ = min{11, 14, 15, 4, 16, 12} = 4\ c(x_i, x_j) "- пропускная способность ребра с вершинами" x_i space и space x_j \ phi(x_i, x_j) "- поток ребра с вершинами" x_i space и space x_j $
#h(35pt) Добавим к потоку всех ребер, входящих в путь, остаточную пропускную способность пути. Ребра, пропускная способность которых будет равна потоку через ниx, станут насыщенными.
#img(image("12.png", width:80%), [Граф с добавленными потоками через ребра пути])
В данном случае ребро $(x_10, x_11)$ стало насыщенным.
Таким образом общий поток $phi_n = phi_n + delta^* = 28 + delta^* = 32$.
В результате, после выполнения всех действий получаем граф:
#img(image("13.png", width:80%), [Граф с текущими потоками])
#pagebreak()
== Путь $(x_1, x_5, x_8, x_10, x_12)$
Рассмотрим путь $(x_1, x_5, x_8, x_10, x_12)$.
#img(image("14.png", width:90%), [Путь $(x_1, x_5, x_8, x_10, x_12)$])
Рассчитаем остаточную пропускную способность пути:
$ delta^* = min{fd(1, 5), fd(5, 8),\ fd(8, 10), fd(10,12)}\ = min{26 - 19, 14 - 4, 22 - 11, 50 - 0}\ = min{7, 10, 11, 50} = 7\ c(x_i, x_j) "- пропускная способность ребра с вершинами" x_i space и space x_j \ phi(x_i, x_j) "- поток ребра с вершинами" x_i space и space x_j $
#h(35pt) Добавим к потоку всех ребер, входящих в путь, остаточную пропускную способность пути. Ребра, пропускная способность которых будет равна потоку через ниx, станут насыщенными.
#img(image("15.png", width:80%), [Граф с добавленными потоками через ребра пути])
В данном случае ребро $(x_1, x_5)$ стало насыщенным.
Таким образом общий поток $phi_n = phi_n + delta^* = 32 + delta^* = 39$.
В результате, после выполнения всех действий получаем граф:
#img(image("16.png", width:80%), [Граф с текущими потоками])
== Путь $(x_1, x_4, x_6, x_9, x_8, x_10, x_12)$
Рассмотрим путь $(x_1, x_4, x_6, x_9, x_8, x_10, x_12)$.
#img(image("17.png", width:90%), [Путь $(x_1, x_4, x_6, x_9, x_8, x_10, x_12)$])
Рассчитаем остаточную пропускную способность пути:
$ delta^* = min{fd(1, 4), fd(4, 6),\ fd(6, 9), fd(9, 8),\ fd(8, 10), fd(10,12)}\ = min{46 - 0, 21 - 0, 16 - 0, 4 - 0, 22 - 18, 50 - 7} = \ = min{46, 21, 16, 4, 4, 43} = 4\ c(x_i, x_j) "- пропускная способность ребра с вершинами" x_i space и space x_j \ phi(x_i, x_j) "- поток ребра с вершинами" x_i space и space x_j $
#h(35pt) Добавим к потоку всех ребер, входящих в путь, остаточную пропускную способность пути. Ребра, пропускная способность которых будет равна потоку через ниx, станут насыщенными.
#img(image("18.png", width:80%), [Граф с добавленными потоками через ребра пути])
В данном случае ребра $(x_9, x_8)$ и $(x_8, x_10)$ стали насыщенными.
Таким образом общий поток $phi_n = phi_n + delta^* = 39 + delta^* = 43$.
В результате, после выполнения всех действий получаем граф:
#img(image("19.png", width:80%), [Граф с текущими потоками])
#pagebreak()
== Путь $(x_1, x_4, x_6, x_9, x_10, x_12)$
Рассмотрим путь $(x_1, x_4, x_6, x_9, x_10, x_12)$.
#img(image("20.png", width:90%), [Путь $(x_1, x_4, x_6, x_9, x_10, x_12)$])
Рассчитаем остаточную пропускную способность пути:
$ delta^* = min{fd(1, 4), fd(4, 6),\ fd(6, 9), fd(9, 10)\ fd(10,12)}\ = min{46 - 4, 21 - 4, 16 - 4, 10 - 0, 50 - 11} = \ = min{42, 17, 12, 10, 39} = 10\ c(x_i, x_j) "- пропускная способность ребра с вершинами" x_i space и space x_j \ phi(x_i, x_j) "- поток ребра с вершинами" x_i space и space x_j $
#h(35pt) Добавим к потоку всех ребер, входящих в путь, остаточную пропускную способность пути. Ребра, пропускная способность которых будет равна потоку через ниx, станут насыщенными.
#img(image("21.png", width:80%), [Граф с добавленными потоками через ребра пути])
В данном случае ребро $(x_9, x_10)$ стало насыщенным.
Таким образом общий поток $phi_n = phi_n + delta^* = 43 + delta^* = 53$.
В результате, после выполнения всех действий получаем граф:
#img(image("22.png", width:80%), [Граф с текущими потоками])
== Путь $(x_1, x_4, x_6, x_9, x_12)$
Рассмотрим путь $(x_1, x_4, x_6, x_9, x_12)$.
#img(image("23.png", width:90%), [Путь $(x_1, x_4, x_6, x_9, x_12)$])
Рассчитаем остаточную пропускную способность пути:
$ delta^* = min{fd(1, 4), fd(4, 6),\ fd(6, 9), fd(9,12)}\ = min{46 - 14, 21 - 14, 16 - 14, 18 - 10} = \ = min{32, 7, 2, 8} = 2\ c(x_i, x_j) "- пропускная способность ребра с вершинами" x_i space и space x_j \ phi(x_i, x_j) "- поток ребра с вершинами" x_i space и space x_j $
#h(35pt) Добавим к потоку всех ребер, входящих в путь, остаточную пропускную способность пути. Ребра, пропускная способность которых будет равна потоку через ниx, станут насыщенными.
#img(image("24.png", width:80%), [Граф с добавленными потоками через ребра пути])
В данном случае ребро $(x_6, x_9)$ стало насыщенным.
Таким образом общий поток $phi_n = phi_n + delta^* = 53 + delta^* = 55$.
В результате, после выполнения всех действий получаем граф:
#img(image("25.png", width:80%), [Граф с текущими потоками])
#pagebreak()
== Путь $(x_1, x_4, x_11, x_9, x_12)$
Рассмотрим путь $(x_1, x_4, x_11, x_9, x_12)$.
#img(image("26.png", width:90%), [Путь $(x_1, x_4, x_11, x_9, x_12)$])
Рассчитаем остаточную пропускную способность пути:
$ delta^* = min{fd(1, 4), fd(4, 11),\ fd(11, 9), fd(9,12)}\ = min{46 - 16, 24 - 0, 22 - 10, 18 - 12} = \ = min{30, 24, 12, 6} = 6\ c(x_i, x_j) "- пропускная способность ребра с вершинами" x_i space и space x_j \ phi(x_i, x_j) "- поток ребра с вершинами" x_i space и space x_j $
#h(35pt) Добавим к потоку всех ребер, входящих в путь, остаточную пропускную способность пути. Ребра, пропускная способность которых будет равна потоку через ниx, станут насыщенными.
#img(image("27.png", width:80%), [Граф с добавленными потоками через ребра пути])
В данном случае ребро $(x_9, x_12)$ стало насыщенным.
Таким образом общий поток $phi_n = phi_n + delta^* = 55 + delta^* = 61$.
В результате, после выполнения всех действий получаем граф:
#img(image("28.png", width:80%), [Граф с текущими потоками])
== Почему больше нет путей от источника к стоку?
В процессе выполнения данного пункта мы строим пути, проходящие только через ненасыщенные ребра, таким образом из источника можно начать строить путь только через ребро $(x_1, x_4)$. Из вершины $x_4$ ведут 2 ребра. Данные ребра ненасыщенны, поэтому можно продолжить построение пути по ним. Одно из ребер ведет в вершину $x_6$, из которой исходит только одно ребро, но оно насыщенно, поэтому по данному ребру из $x_4$ построить путь невозможно. Второе ребро ведет в вершину $x_11$, оно ненасыщенно. Из $x_11$ исходят 2 ребра, но одно из них насыщенно, поэтому из вершины $x_11$ путь может проходить только в вершину $x_9$. Из данной вершины исходят только насыщенные ребра, поэтому дальнейшее построение пути до стока невозможно.
== Полученный граф и полный поток
После применения теоремы 1 получили граф с насыщенными ребрами (выделены цветом на рис. 29).
#img(image("29.png", width:80%), [Граф с текущими потоками])
Полный поток получился равным $phi_n = 61$.
== Проверки
Посчитаем сумму потоков ребер, исходящих из вершины $x_1$.
$ phi_x_1 = phi(x_1, x_2) + phi(x_1, x_4) + phi(x_1, x_5) = 13 + 26 + 22 = 61 = phi_n $
#h(35pt)Посчитаем сумму потоков ребер, приходящих в вершину $x_12$.
$ phi_x_12 = phi(x_7, x_12) + phi(x_9, x_12) + phi(x_10, x_12) + phi(x_11, x_12) =\ = 15 + 21 + 18 + 7 = 61 = phi_x_1 = phi_n $
#h(35pt)Значения исходящего из истока, входящего в сток и общего потока совпали.
Построим матрицу потоков ребер.
#align(center)[
#tablex(
columns: 13,
inset: 10pt,
align: center + horizon,
[],[$x_1$],[$x_2$],[$x_3$],[$x_4$],[$x_5$],[$x_6$],[$x_7$],[$x_8$],[$x_9$],[$x_10$],[$x_11$],[$x_12$],
[$x_1$], [ ],[13],[ ],[22],[26],[ ],[ ],[ ],[ ],[ ],[ ],[ ],
[$x_2$], [ ],[ ],[ ],[ ],[ ],[ ],[13],[ ],[ ],[ ],[ ],[ ],
[$x_3$], [ ],[ ],[ ],[ ],[ ],[0 ],[ ],[ ],[ ],[ ],[ ],[ ],
[$x_4$], [ ],[ ],[ ],[ ],[ ],[16],[ ],[ ],[ ],[ ],[ 6],[ ],
[$x_5$], [ ],[ ],[ 0],[ ],[ ],[ ],[15],[11],[ ],[ ],[ ],[ ],
[$x_6$], [ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[16],[ ],[ ],[ ],
[$x_7$], [ ],[ ],[ ],[ ],[ ],[ ],[ ],[7 ],[ ],[ 6],[ ],[15],
[$x_8$], [ ],[ ],[ 0],[ ],[ ],[ ],[ ],[ ],[ ],[22],[ ],[ ],
[$x_9$], [ ],[ ],[ ],[ ],[ ],[ ],[ ],[4 ],[ ],[10],[ ],[18],
[$x_10$],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[17],[21],
[$x_11$],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[16],[ ],[ ],[7],
[$x_12$],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],
)]
#h(35pt)По данной таблице можно посчитать сумму входящего потока и исходящего для любой вершины. Эти потоки будут равны (за исключением вершин источника и стока). Для подсчета входящего потока вершины $x_n$ суммируем все значения столбца $x_n$ таблицы, для подсчета исходящего потока суммируем все значения строки.
#align(center)[
#tablex(
columns: 3,
inset: 10pt,
align: center + horizon,
[Вершина],[Входящий\ поток],[Исходящий\ поток],
[$x_1$], [ ],[61],
[$x_2$], [13],[13],
[$x_3$], [0],[0],
[$x_4$], [22],[22],
[$x_5$], [26],[26],
[$x_6$], [16],[16],
[$x_7$], [28],[28],
[$x_8$], [22],[22],
[$x_9$], [32],[32],
[$x_10$],[38],[38],
[$x_11$],[23],[23],
[$x_12$],[61],[ ],
)]
= Оптимизация
Итерационно используя теорему 2, увеличиваем полный поток.
== Увеличивающий маршрут $(x_1, x_4, x_11, x_10, x_12)$
Выполним разметку вершин, необходимо пометить вершину стока.
Для начала пометим знаком + источник $x_1$.
Каждую следующую вершину помечаем номером предыдущей со знаком + или -:
- Со знаком +, если ребро направлено из предыдущей вершины (последней помеченной) в помечаемую и оно строго ненасыщенно (в данном случае ребро называется прямым),
- Со знаком -, если ребро противоположно направлено и его поток не равен 0 (само ребро называется обратным).
Таким образом получилось отметить 5 вершин
#align(center)[
#tablex(
columns: 2,
inset: 10pt,
align: center + horizon,
[Вершина],[Пометка],
[$x_1$], [+],
[$x_4$], [+1],
[$x_11$], [+4],
[$x_10$], [-11],
[$x_12$], [+10],
)]
#img(image("30.png", width:80%), [Граф с метками])
Ребра, которые направлены на вершины с метками + (прямые ребра) обозначим синим, а те, которые противоположно направлены на вершины с метками - (обратные ребра) обозначим оранжевым.
Рассчитаем остаточную пропускную способность синих (прямых) ребер.
$ delta^* = min{fd(1, 4), fd(4, 11), fd(10,12)}=\ = min{46 - 22, 24 - 6, 50 - 21} = min{24, 18, 29} = 18\ c(x_i, x_j) "- пропускная способность ребра с вершинами" x_i space и space x_j \ phi(x_i, x_j) "- поток ребра с вершинами" x_i space и space x_j $
#h(35pt)Найдем минимальный поток оранжевых (обратных) ребер.
$ phi^* = min{phi(10,11)} = min{17} = 17 $
$ epsilon^* = min{delta^*, phi^*} = min{18, 17} = 17 $
#h(35pt)Поток в сети можно увеличить на 17 единиц ($phi_max = phi_n +17 = 78$) за счет данного увеличивающего маршрута. Увеличим поток на синих (прямых) ребрах на $epsilon^*$ и уменьшим на оранжевых (обратных) на то же значение.
#img(image("31.png", width:80%), [Граф с оптимизированным распределением потоков])
Так как на оранжевом (обратном) ребре поток уменьшился можно сделать вывод, что ребро $(x_10, x_11)$ перестало быть насыщенным.
В результате, после выполнения всех действий получаем граф:
#img(image("32.png", width:80%), [Граф с текущими потоками])
== Почему больше нет увеличивающих маршрутов?
Попробуем пометить еще один увеличивающий маршрут.
Пометим $x_1$ знаком +. Из $x_1$ можно попасть только в вершину $x_4$, так как $x_1$ не является концом ребра, ни одну вершину мы не можем пометить знаком -, а знаком + можем пометить, только ту, ребро которой не является насыщенным.
Таким образом помечаем $x_4$ как +1. Вершина $x_4$ является концом ребра, начало которого в $x_1$, таким образом вершина $x_1$ может быть помечена как -4, но так как из $x_1$ можно пометить только $x_4$ помечать $x_1$ второй раз не целесообразно.
Вершина $x_4$ является началом 2 ненасыщенных ребер, это означает, что мы можем пометить одну из двух вершин меткой +4. Если мы пометим вершину $x_6$, то будет невозможно пометить $x_9$, так как ребро насыщенно, и $x_3$, так как поток, проходящий через ребро равен 0. Таким образом из вершины $x_6$ можно пометить только вершину -- $x_4$.
Попробуем вернуться на пару шагов назад и пометить $x_11$ вместо $x_6$. Так как больше ничего пометить мы не можем (остальные маршруты не могут привести к стоку) далее будем рассматривать все относительно вершины $x_11$. Помечать $x_4$ нет смысла. Поэтому дальше пометить мы можем только $x_9$.
Меткой -9 можно пометить $x_11$, но помечать данную вершину нет смысла. Меткой +9 мы не можем пометить ни одну из вершин, так как все ребра, началом которых является $x_9$, насыщены. Остается рассмотреть только возможность пометки вершины $x_6$ меткой -9: из нее мы можем попасть только в вершину $x_4$ и далее вести рассуждения так же, как и во втором абзаце.
Таким образом любые попытки пометить сток приводят нас к циклу, в котором мы помечаем одни и те же вершины разными метками, но при этом сток пометить не удается, поэтому можно утверждать, что больше нет увеличивающих маршрутов.
Поэтому по теореме 3 можно утверждать, что полный поток равен максимальному.
#pagebreak()
== Полученный граф и общий поток
Получили граф с максимальным общим потоком.
#img(image("32.png", width:80%), [Граф с максимальным общим потоком])
Максимальный общий поток получился равным $phi_max = 78$.
#pagebreak()
== Проверки
Посчитаем сумму потоков ребер, исходящих из вершины $x_1$.
$ phi_x_1 = phi(x_1, x_2) + phi(x_1, x_4) + phi(x_1, x_5) = 13 + 26 + 38 = 78 = phi_max $
#h(35pt)Посчитаем сумму потоков ребер, приходящих в вершину $x_12$.
$ phi_x_12 = phi(x_7, x_12) + phi(x_9, x_12) + phi(x_10, x_12) + phi(x_11, x_12) =\ = 15 + 38 + 18 + 7 = 78 = phi_x_1 = phi_max $
#h(35pt)Значения исходящего из истока, входящего в сток и общего потока совпали.
Построим матрицу потоков ребер.
#align(center)[
#tablex(
columns: 13,
inset: 10pt,
align: center + horizon,
[],[$x_1$],[$x_2$],[$x_3$],[$x_4$],[$x_5$],[$x_6$],[$x_7$],[$x_8$],[$x_9$],[$x_10$],[$x_11$],[$x_12$],
[$x_1$], [ ],[13],[ ],[39],[26],[ ],[ ],[ ],[ ],[ ],[ ],[ ],
[$x_2$], [ ],[ ],[ ],[ ],[ ],[ ],[13],[ ],[ ],[ ],[ ],[ ],
[$x_3$], [ ],[ ],[ ],[ ],[ ],[0 ],[ ],[ ],[ ],[ ],[ ],[ ],
[$x_4$], [ ],[ ],[ ],[ ],[ ],[16],[ ],[ ],[ ],[ ],[23],[ ],
[$x_5$], [ ],[ ],[ 0],[ ],[ ],[ ],[15],[11],[ ],[ ],[ ],[ ],
[$x_6$], [ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[16],[ ],[ ],[ ],
[$x_7$], [ ],[ ],[ ],[ ],[ ],[ ],[ ],[7 ],[ ],[ 6],[ ],[15],
[$x_8$], [ ],[ ],[ 0],[ ],[ ],[ ],[ ],[ ],[ ],[22],[ ],[ ],
[$x_9$], [ ],[ ],[ ],[ ],[ ],[ ],[ ],[4 ],[ ],[10],[ ],[18],
[$x_10$],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ 0],[38],
[$x_11$],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[16],[ ],[ ],[7],
[$x_12$],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],[ ],
)]
#h(35pt)По данной таблице можно посчитать сумму входящего потока и исходящего для любой вершины. Эти потоки будут равны (за исключением вершин источника и стока). Для подсчета входящего потока вершины $x_n$ суммируем все значения столбца $x_n$ таблицы, для подсчета исходящего потока суммируем все значения строки.
#align(center)[
#tablex(
columns: 3,
inset: 10pt,
align: center + horizon,
[Вершина],[Входящий\ поток],[Исходящий\ поток],
[$x_1$], [ ],[78],
[$x_2$], [13],[13],
[$x_3$], [0],[0],
[$x_4$], [39],[39],
[$x_5$], [26],[26],
[$x_6$], [16],[16],
[$x_7$], [28],[28],
[$x_8$], [22],[22],
[$x_9$], [32],[32],
[$x_10$],[38],[38],
[$x_11$],[23],[23],
[$x_12$],[78],[ ],
)]
#h(35pt)Напишем код, который считает максимальный поток по входной матрице пропускных способностей. Результатом работы кода тоже является число 78.
#img(image("34.png", width:40%), [Вывод кода])
#let code = (read("code.cpp"))
#set text(10.5pt)
#raw(code, lang:"cpp")
#set text(14pt)
= Построение минимального разреза
Для любой сети с одним источником и одним стоком величина максимального потока, доставляемая от источника к стоку равна пропускной способности минимального разреза.
// Если из сети исключить прямые и насыщенные ребра, а так же обратные, поток которых равен 0, то сеть разбивается на 2 компонента связности, причем источник и сток оказываются в разных компонентах.
Пусть подмножество вершин, оставшихся непомеченными при попытке построить увеличивающий маршрут будет $A = {x_2, x_3, x_5, x_7, x_8, x_10, x_12}$, тогда
$ phi_t = sum phi(U_i) - sum phi(U_j) $
$ U_i in U_A^+ - "подмножество ребер, заходящих в вершины подмножества A" $
$ U_j in U_A^- - "подмножество ребер, исходящих из вершин подмножества A" $
#h(35pt) В случае максимального потока $sum phi(U_j) = 0$, тогда:
$ phi_t = sum phi(U_i) $
#h(35pt)Все ребра из $U_A^+$ являются насыщенными и $sum phi(U_i) = phi_max$ сумма пропускных способностей дает максимальный поток. Именно эти ребра образуют минимальный разрез.
Насыщенные ребра имеют свойства: начальная вершина $in X$ ($X = {x_1, x_4, x_6, x_9, x_11}$ - вершины, которые удалось пометить), конечная в подмножестве A. Таким образом получаем, что разрез будет проходить между теми вершинами, которые удалось пометить и теми, которые пометить не удалось. Получаем разрез $(X arrow A)$:
#img(image("33.png", width:80%), [Разрез $(X arrow A)$])
Минимальный разрез в данной сети составляют ребра
$ (X arrow A) = {(x_1, x_2), (x_1, x_5), (x_9, x_8), (x_9, x_10), (x_9, x_12), (x_11, x_12)} $
#h(35pt)Рассчитаем пропускную способность минимального разреза
$ C(X arrow A) = C(x_1, x_2) + C(x_1, x_5) + C(x_9, x_8) + C(x_9, x_10) +\ + C(x_9, x_12) + C(x_11, x_12) = 13 + 26 + 4 + 10 + 18 + 7 = 78 $
#h(35pt)Пропускная способность минимального разреза совпала с максимальным потоком сети.
= Вывод
- Для определения полного потока было исследовано 9 путей, был достигнут полный поток $phi_n = 61$. Был проверен баланс.
- В оптимизационной части алгоритма был построен 1 увеличивающий маршрут, который увеличил полный поток, полученный в предыдущем пункте на 17 единиц, полный поток стал равен максимальному. Был проверен баланс и написан код по поиску максимального потока в сети, вывод программы совпал с максимальным потоком $phi_max = 78$.
- В минимальном разрезе 6 ребер оказались насыщенными, пропускная способность минимального разреза совпала с максимальным потоком. Условие теоремы Форда-Фалкерсона не нарушено, максимальный поток найден верно.
#img(image("32.png", width:80%), [Получившийся граф])
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/let-11.typ | typst | Other | // Ref: false
// Destructuring with an empty sink and empty array.
#let (..a) = ()
#test(a, ())
|
https://github.com/Charging1948/quarto-typst-dhbw | https://raw.githubusercontent.com/Charging1948/quarto-typst-dhbw/main/README.md | markdown | # DHBW Mosbach Bachelor Thesis Format
Initially based upon [Project-Report-Typst (by aurghya-0)](https://github.com/aurghya-0/Project-Report-Typst)
## Installing
```bash
quarto use template Charging1948/quarto-dhbw-typst
```
This will install the format extension and create an example qmd file
that you can use as a starting place for your document.
## Using
_TODO_
|
|
https://github.com/TheWebDev27/Calc-II-Honors-Project | https://raw.githubusercontent.com/TheWebDev27/Calc-II-Honors-Project/main/references.typ | typst | #set text(
font: "New Computer Modern",
size: 10pt
)
#set align(center)
= References
\
<NAME>. (1976). _Foundations of Infinitesimal Calculus_, <NAME> & Schmidt.
\
<NAME>. (1996). _Calculus With Analytic Geometry_ (2nd ed.), Mcgraw-Hill Education.
\
<NAME>. (2012). _A Brief Introduction to Infinitesimal Calculus_, can be found at \ https://homepage.math.uiowa.edu/~stroyan/InfsmlCalculus/Lecture1/Lect1.pdf. |
|
https://github.com/naps62/presentation-rust | https://raw.githubusercontent.com/naps62/presentation-rust/main/main.typ | typst | #import "./theme.typ": *
#set page(paper: "presentation-16-9")
#set text(size: 25pt)
#show: simple-theme.with(
foreground: dark,
background: light
)
#title-slide[
= Rust
=== A brief intro
#figure(
image("assets/ferris.png", width: 10%)
)
<NAME> (\@naps62) / Subvisual
]
#slide[
#set align(center)
#side-by-side[
== Tauri
#figure(
image("assets/tauri.png", width: 100%)
)
][
== Typst
#figure(
image("assets/typst.png", width: 100%)
)
]
]
#slide[
#set align(center)
#side-by-side[
== Delta
#figure(
image("assets/delta.png", width: 100%)
)
][
== Just
#figure(
image("assets/just.png", width: 100%)
)
]
]
#centered-slide[
#figure(
image("assets/dhh.png", width: 80%)
)
]
#slide[
== We went from this
```
unresolved external symbol "void __cdecl importStoredClients(class
std::basic_fstream<char,struct std::char_traits<char> > const &,class
std::vector<class Client,class std::allocator<class Client> > &)" (?
importStoredClients@@YAXABV?$basic_fstream@DU?$char_traits@D@std@@@std@@AAV?
$vector@VClient@@V?$allocator@VClient@@@std@@@2@@Z)
```
]
#slide[
== ... to this
== ```js 1 + "2" == "12" ```
== `Undefined is not a function`
]
#focus-slide[
= Types of Types
]
#slide[
== Structural Typing (Typescript, OCaml, ...)
#set text(size: 22pt)
#image("assets/ts.png", width: 20pt)
```typescript
type Foo = { x: number, y: string };
type Bar = { x: number };
let x: Foo = { x: 1, y: "hello" };
```
]
#slide[
== Nominal Typing (Rust, C/C++, ...)
#set text(size: 22pt)
#image("assets/ferris.png", width: 30pt)
```rust
struct Foo { x: i32, y: String };
struct Bar { x: i32 };
fn main() {
let x: Foo = Foo { x: 1, y: "hello".to_string() };
// this would not compile
// let y: Bar = x;
}
```
]
#focus-slide[
= What makes Rust good?
]
#focus-slide[
= 1. Type inference
]
#slide[
== This is the same code
#set align(horizon)
```rust
let list: Vec<u32> =
vec![1u32, 2u32, 3u32].iter().map(|v: &u32| v + 1).collect::<Vec<u32>>()
```
#v(2em)
```rust
let list =
vec![1, 2, 3].iter().map(|v| v + 1).collect()
```
]
#slide[
#set align(horizon)
Type inference eliminates most noise.
Exceptions: function headers; ambiguity.
```rust
fn increment_and_dedup(v: Vec<u32>) -> HashSet<u32> {
v.iter().map(|v| v + 1).collect()
}
```
]
#focus-slide[
= 2. Memory Safety
=== even in multi-threaded code
]
#slide[
= This fails to compile
#set align(horizon)
```rust
fn main() {
let x = 1;
let r1 = &x;
let r2 = &mut x;
println!("{} {}", r1, r2);
}
```
]
#slide[
= Multi-threading type-safety
#set align(horizon)
#table(
columns: (1fr, 3fr),
stroke: none,
[```rust trait Send```], [safe to *send* to another thread],
[```rust trait Sync```], [safe to *share* between threads],
)
]
#focus-slide[
= 3. Compiler
]
#slide[
== Zero-cost abstractions
#v(2em)
The ability to use high-level features without runtime cost.
Trade-off: compile-time complexity
]
#slide[
== "If it compiles, it works"
#v(2em)
not to be taken literally
it's how strongly typed programming *feels*
]
#slide[
== Making illegal states unrepresentable
#only(1)[
#v(2em)
Aim for compile-time safety, not runtime validations
- Type-drive development;
- Abuse ```rust Option```, ```rust Result```, and ```rust enum```;
- Typestate pattern. (https://cliffle.com/blog/rust-typestate/)
]
#only(2)[
```rust
enum AccountState {
Active { email: Email, active_at: DateTime },
Inactive { email: Email },
Banned { reason: String },
}
/// Newtype pattern
/// email regex can be enforced on constructor
/// runtime size is the same as String
type Email(String)
```
]
]
#focus-slide[
= 4. Tooling
]
#centered-slide[
```sh
cargo build
cargo run --package serve
cargo +nightly clippy
cargo fmt
cargo test
cargo build --target wasm32-unknown-unknown
cargo audit
bacon
```
]
#focus-slide[
= Tips to get started
]
#slide[
== Don't get too Rust'y right away
- if you're writing ```rust Foo<'a>```, you're gonna have a bad time;
- Abuse ```rust clone()``` instead of fighting the borrow checker;
- get v1 working, only then optimize.
- tooling will teach you along the way
]
#focus-slide[
= Why NOT Rust?
#v(1em)
#set text(size: 24pt)
bonus slides if I got here before the 20m mark
]
#slide[
== Compilation times?
- Incremental compilation is great(ish)
- Not quite instant-reload, but rather close
- Release builds are more painful
- You should `cargo check` instead of `cargo build`
]
#slide[
== Refactoring is a slog?
#figure(image("assets/rust-refactoring.png", height: 75%))
]
#title-slide[
= Rust
=== A brief intro
#figure(
image("assets/ferris.png", width: 10%)
)
<NAME> (\@naps62) / Subvisual
]
|
|
https://github.com/rabotaem-incorporated/algebra-conspect-1course | https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/03-polynomials/01-polys-power-series.typ | typst | Other | #import "../../utils/core.typ": *
== Многочлены и формальные степенные ряды
#def[
Последовательность _финитная_ $<==> exists N: forall n >= N: a_n = 0$.
]
#def[
Многочленом над $R$ (от одной переменной) называется финитная последовательность $(a_i), space a_i in RR, space i=0,1,2,...$.
]
#def[
$R$ --- коммутативное кольцо с 1, тогда:
$R[x] = \{(a_i) divides a_i in R, space i = 0, 1, ...; a_i = 0$ при $i -> oo \}$ --- _кольцо многочленов_ над $R$.
]
#pr[
Операции в $R[x]$:
"Сложение":
$(a_i) + (b_i) = (a_i + b_i)$
"Умножение":
$(a_i) dot (b_i) = (p_i)$, где $p_k = limits(sum)_(i=0)^k a_i b_(k-i)$
]
#pr(name: [Переход к стандартной записи])[
Пусть $a in R, space [a] = (a, 0, 0, ...)$ --- многочлен, равный $a$.
$[a] + [b] = [a + b]$
$[a] dot [b o b a] = (a b o b a, 0, 0, ...) = [a b o b a]$
Отождествим $[a]$ с $a$.
$[a] dot (b_0, b_1, ...) = (a b_0, a b_1, ...)$
$(a_0, a_1, ..., a_n, 0, 0, ...) = (a_0, 0, 0, ...) + (0, a_1, 0, 0, ...) + ... + (0, 0, ..., a_n, 0, 0, ...) =$
$a_0 dot underbrace((1, 0, 0, ...), x_0) + a_1 dot underbrace((0, 1, 0, ...), x_1) + ... + a_n dot underbrace((0, 0, ..., 1, 0, 0, ...), x_n) = a_0 + a_1 dot x_1 + ... + a_n dot x_n$
$x_j dot x_1 = (0, ..., 1, 0, 0, ...) dot (0, 1, 0, 0, ...) = (0, ..., 0, 1, 0, 0, ...) = x_(j+1) ==> forall m in NN: x_m = x_1^m$
$x_1 = x ==> x_m = x_1^m = x^m$
Значит получили стандартную запись многочленов $(a_0 + a_1 x + a_2 x^2 + ... + a_n x^n)$
]
#def[
Пусть $f in R[x], space f eq.not 0$ (то есть не $(0)$)
Тогда степенью $f$ называется максимальное $j$ такое что $a_j eq.not 0$
Обозначим $deg f = j$.
Если $f = 0$, то $deg f in \{-1, -oo\}$ (по разному обозначают).
]
#def[
$d = deg f ==> a_d$ называется старшим коэффициентом $f$.
]
#def[
Константой называется множество $f$ такое что $deg f <= 0$.
]
#def[
Мономом называется множество вида $a x^j$.
]
#pr[
$R[x]$ --- коммутативное ассоциативное кольцо с 1.
]
#proof[\
1-4. Аксиомы относящиеся к сложению очевидны.
5. Коммутативность умножения очевидна.
6. Ассоциативность умножения:
$f, g, h in R[x], space (f g)h = f(g h)$
$f = limits(sum)_(i=0)^k f_i X_i$, где $f_i in R$
$g = limits(sum)_(i=0)^l g_i X_i$, где $g_i in R$
$h = limits(sum)_(i=0)^n h_i X_i$, где $h_i in R$
Ассоциативность мономов $(f dot g) dot h = f dot (g dot h)$ --- сводится к сложению, $f, g, h$ --- мономы.
$(f g)h = (sum f_i X^i dot sum g_j X^j) dot sum h_k X^k = sum (f_i X^i dot g_j X^j) dot sum h_k X^k limits(=)^("ассоц. мономов")$
$sum f_i X^i dot sum (g_j X^j dot h_k X^k) = f(g h)$
7. Нейтральный элемент по умножению --- $1 = (1, 0, 0, ...)$.
8. Дистрибутивность:
$display(cases(
(a X^i dot b X^j) dot c X^k = a b X^(i+j) dot c X^k = a b c dot X^(i+j+k),
a X^i dot (b X^j dot c X^k) = a X^i dot b c X^(j + k) = a b c dot X^(i+j+k)
))$
]
#def[
$R[[x]] = \{ (a_i) divides a_i in R, i = 0, 1, ... \}$ --- множество формальных степенных рядов над $R$.
]
$(a_i) = limits(sum)_(i = 0)^(oo) a_i X^i$
#exercise[
$R[[x]]$ --- коммутативное ассоциативное кольцо с 1.
] |
https://github.com/Akida31/anki-typst | https://raw.githubusercontent.com/Akida31/anki-typst/main/typst/doc/doc.typ | typst | #import "@preview/tidy:0.3.0"
#import "../src/lib.typ" as anki
#set heading(numbering: (..num) => if num.pos().len() < 3 {
numbering("1.1.", ..num)
})
#show heading.where(level: 1, outlined: true): inner => [
#{
set text(size: 24pt)
inner
}
// #set text(size: 13pt)
// Items:
]
#set document(title: "anki documentation")
#show link: it => underline(text(fill: blue, it))
#let version = [v#toml("../typst.toml").package.version]
#align(center + horizon)[
#set text(size: 20pt)
#block(text(weight: 700, size: 40pt, "anki-typst"))
Create anki cards from typst.
#v(40pt)
#version
#h(40pt)
#datetime.today().display()
// TODO
// #link("https://repolink")
]
#pagebreak(weak: true)
#set page(numbering: "1/1")
#outline(indent: true, depth: 2)
#set page(numbering: "1/1", header: grid(columns: (auto, 1fr, auto),
align(left, version),
[],
align(right)[anki-typst],
))
#pagebreak(weak: true)
#let module(name, path, private: false, do_pagebreak: true) = {
let docs = tidy.parse-module(
read(path),
name: name,
scope: (anki: anki),
preamble: "import anki: *;",
require-all-parameters: not private,
)
if do_pagebreak {
pagebreak(weak: true)
}
tidy.show-module(
docs,
omit-private-definitions: true,
first-heading-level: 2,
show-outline: false,
)
}
= Examples
#let example(name) = {
let file_content = read(name).split("\n").slice(3).join("\n")
tidy.show-example.show-example(raw(file_content), scale-preview: 100%, mode: "markup", scope: (anki: anki))
}
*Via theorem environment:*
#example("example1.typ")
*Via raw function:*
#example("example2.typ")
#pagebreak(weak: true)
= Function reference
#module("lib", "../src/lib.typ", do_pagebreak: false)
#module("raw", "../src/raw.typ")
#module("theorems", "../src/theorems.typ")
// #module("Private: config", "../src/config.typ", private: true)
// #module("Private: utils", "../src/utils.typ", private: true)
|
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/186.%20useful.html.typ | typst | useful.html
How to Write Usefully
February 2020What should an essay be? Many people would say persuasive. That's
what a lot of us were taught essays should be. But I think we can
aim for something more ambitious: that an essay should be useful.To start with, that means it should be correct. But it's not enough
merely to be correct. It's easy to make a statement correct by
making it vague. That's a common flaw in academic writing, for
example. If you know nothing at all about an issue, you can't go
wrong by saying that the issue is a complex one, that there are
many factors to be considered, that it's a mistake to take too
simplistic a view of it, and so on.Though no doubt correct, such statements tell the reader nothing.
Useful writing makes claims that are as strong as they can be made
without becoming false.For example, it's more useful to say that Pike's Peak is near the
middle of Colorado than merely somewhere in Colorado. But if I say
it's in the exact middle of Colorado, I've now gone too far, because
it's a bit east of the middle.Precision and correctness are like opposing forces. It's easy to
satisfy one if you ignore the other. The converse of vaporous
academic writing is the bold, but false, rhetoric of demagogues.
Useful writing is bold, but true.It's also two other things: it tells people something important,
and that at least some of them didn't already know.Telling people something they didn't know doesn't always mean
surprising them. Sometimes it means telling them something they
knew unconsciously but had never put into words. In fact those may
be the more valuable insights, because they tend to be more
fundamental.Let's put them all together. Useful writing tells people something
true and important that they didn't already know, and tells them
as unequivocally as possible.Notice these are all a matter of degree. For example, you can't
expect an idea to be novel to everyone. Any insight that you have
will probably have already been had by at least one of the world's
7 billion people. But it's sufficient if an idea is novel to a lot
of readers.Ditto for correctness, importance, and strength. In effect the four
components are like numbers you can multiply together to get a score
for usefulness. Which I realize is almost awkwardly reductive, but
nonetheless true._____
How can you ensure that the things you say are true and novel and
important? Believe it or not, there is a trick for doing this. I
learned it from my friend <NAME>, who has a horror of saying
anything dumb. His trick is not to say anything unless he's sure
it's worth hearing. This makes it hard to get opinions out of him,
but when you do, they're usually right.Translated into essay writing, what this means is that if you write
a bad sentence, you don't publish it. You delete it and try again.
Often you abandon whole branches of four or five paragraphs. Sometimes
a whole essay.You can't ensure that every idea you have is good, but you can
ensure that every one you publish is, by simply not publishing the
ones that aren't.In the sciences, this is called publication bias, and is considered
bad. When some hypothesis you're exploring gets inconclusive results,
you're supposed to tell people about that too. But with essay
writing, publication bias is the way to go.My strategy is loose, then tight. I write the first draft of an
essay fast, trying out all kinds of ideas. Then I spend days rewriting
it very carefully.I've never tried to count how many times I proofread essays, but
I'm sure there are sentences I've read 100 times before publishing
them. When I proofread an essay, there are usually passages that
stick out in an annoying way, sometimes because they're clumsily
written, and sometimes because I'm not sure they're true. The
annoyance starts out unconscious, but after the tenth reading or
so I'm saying "Ugh, that part" each time I hit it. They become like
briars that catch your sleeve as you walk past. Usually I won't
publish an essay till they're all gone � till I can read through
the whole thing without the feeling of anything catching.I'll sometimes let through a sentence that seems clumsy, if I can't
think of a way to rephrase it, but I will never knowingly let through
one that doesn't seem correct. You never have to. If a sentence
doesn't seem right, all you have to do is ask why it doesn't, and
you've usually got the replacement right there in your head.This is where essayists have an advantage over journalists. You
don't have a deadline. You can work for as long on an essay as you
need to get it right. You don't have to publish the essay at all,
if you can't get it right. Mistakes seem to lose courage in the
face of an enemy with unlimited resources. Or that's what it feels
like. What's really going on is that you have different expectations
for yourself. You're like a parent saying to a child "we can sit
here all night till you eat your vegetables." Except you're the
child too.I'm not saying no mistake gets through. For example, I added condition
(c) in "A Way to Detect Bias"
after readers pointed out that I'd
omitted it. But in practice you can catch nearly all of them.There's a trick for getting importance too. It's like the trick I
suggest to young founders for getting startup ideas: to make something
you yourself want. You can use yourself as a proxy for the reader.
The reader is not completely unlike you, so if you write about
topics that seem important to you, they'll probably seem important
to a significant number of readers as well.Importance has two factors. It's the number of people something
matters to, times how much it matters to them. Which means of course
that it's not a rectangle, but a sort of ragged comb, like a Riemann
sum.The way to get novelty is to write about topics you've thought about
a lot. Then you can use yourself as a proxy for the reader in this
department too. Anything you notice that surprises you, who've
thought about the topic a lot, will probably also surprise a
significant number of readers. And here, as with correctness and
importance, you can use the Morris technique to ensure that you
will. If you don't learn anything from writing an essay, don't
publish it.You need humility to measure novelty, because acknowledging the
novelty of an idea means acknowledging your previous ignorance of
it. Confidence and humility are often seen as opposites, but in
this case, as in many others, confidence helps you to be humble.
If you know you're an expert on some topic, you can freely admit
when you learn something you didn't know, because you can be confident
that most other people wouldn't know it either.The fourth component of useful writing, strength, comes from two
things: thinking well, and the skillful use of qualification. These
two counterbalance each other, like the accelerator and clutch in
a car with a manual transmission. As you try to refine the expression
of an idea, you adjust the qualification accordingly. Something
you're sure of, you can state baldly with no qualification at all,
as I did the four components of useful writing. Whereas points that
seem dubious have to be held at arm's length with perhapses.As you refine an idea, you're pushing in the direction of less
qualification. But you can rarely get it down to zero. Sometimes
you don't even want to, if it's a side point and a fully refined
version would be too long.Some say that qualifications weaken writing. For example, that you
should never begin a sentence in an essay with "I think," because
if you're saying it, then of course you think it. And it's true
that "I think x" is a weaker statement than simply "x." Which is
exactly why you need "I think." You need it to express your degree
of certainty.But qualifications are not scalars. They're not just experimental
error. There must be 50 things they can express: how broadly something
applies, how you know it, how happy you are it's so, even how it
could be falsified. I'm not going to try to explore the structure
of qualification here. It's probably more complex than the whole
topic of writing usefully. Instead I'll just give you a practical
tip: Don't underestimate qualification. It's an important skill in
its own right, not just a sort of tax you have to pay in order to
avoid saying things that are false. So learn and use its full range.
It may not be fully half of having good ideas, but it's part of
having them.There's one other quality I aim for in essays: to say things as
simply as possible. But I don't think this is a component of
usefulness. It's more a matter of consideration for the reader. And
it's a practical aid in getting things right; a mistake is more
obvious when expressed in simple language. But I'll admit that the
main reason I write simply is not for the reader's sake or because
it helps get things right, but because it bothers me to use more
or fancier words than I need to. It seems inelegant, like a program
that's too long.I realize florid writing works for some people. But unless you're
sure you're one of them, the best advice is to write as simply as
you can._____
I believe the formula I've given you, importance + novelty +
correctness + strength, is the recipe for a good essay. But I should
warn you that it's also a recipe for making people mad.The root of the problem is novelty. When you tell people something
they didn't know, they don't always thank you for it. Sometimes the
reason people don't know something is because they don't want to
know it. Usually because it contradicts some cherished belief. And
indeed, if you're looking for novel ideas, popular but mistaken
beliefs are a good place to find them. Every popular mistaken belief
creates a dead zone of ideas around
it that are relatively unexplored because they contradict it.The strength component just makes things worse. If there's anything
that annoys people more than having their cherished assumptions
contradicted, it's having them flatly contradicted.Plus if you've used the Morris technique, your writing will seem
quite confident. Perhaps offensively confident, to people who
disagree with you. The reason you'll seem confident is that you are
confident: you've cheated, by only publishing the things you're
sure of. It will seem to people who try to disagree with you that
you never admit you're wrong. In fact you constantly admit you're
wrong. You just do it before publishing instead of after.And if your writing is as simple as possible, that just makes things
worse. Brevity is the diction of command. If you watch someone
delivering unwelcome news from a position of inferiority, you'll
notice they tend to use lots of words, to soften the blow. Whereas
to be short with someone is more or less to be rude to them.It can sometimes work to deliberately phrase statements more weakly
than you mean. To put "perhaps" in front of something you're actually
quite sure of. But you'll notice that when writers do this, they
usually do it with a wink.I don't like to do this too much. It's cheesy to adopt an ironic
tone for a whole essay. I think we just have to face the fact that
elegance and curtness are two names for the same thing.You might think that if you work sufficiently hard to ensure that
an essay is correct, it will be invulnerable to attack. That's sort
of true. It will be invulnerable to valid attacks. But in practice
that's little consolation.In fact, the strength component of useful writing will make you
particularly vulnerable to misrepresentation. If you've stated an
idea as strongly as you could without making it false, all anyone
has to do is to exaggerate slightly what you said, and now it is
false.Much of the time they're not even doing it deliberately. One of the
most surprising things you'll discover, if you start writing essays,
is that people who disagree with you rarely disagree with what
you've actually written. Instead they make up something you said
and disagree with that.For what it's worth, the countermove is to ask someone who does
this to quote a specific sentence or passage you wrote that they
believe is false, and explain why. I say "for what it's worth"
because they never do. So although it might seem that this could
get a broken discussion back on track, the truth is that it was
never on track in the first place.Should you explicitly forestall likely misinterpretations? Yes, if
they're misinterpretations a reasonably smart and well-intentioned
person might make. In fact it's sometimes better to say something
slightly misleading and then add the correction than to try to get
an idea right in one shot. That can be more efficient, and can also
model the way such an idea would be discovered.But I don't think you should explicitly forestall intentional
misinterpretations in the body of an essay. An essay is a place to
meet honest readers. You don't want to spoil your house by putting
bars on the windows to protect against dishonest ones. The place
to protect against intentional misinterpretations is in end-notes.
But don't think you can predict them all. People are as ingenious
at misrepresenting you when you say something they don't want to
hear as they are at coming up with rationalizations for things they
want to do but know they shouldn't. I suspect it's the same skill._____
As with most other things, the way to get better at writing essays
is to practice. But how do you start? Now that we've examined the
structure of useful writing, we can rephrase that question more
precisely. Which constraint do you relax initially? The answer is,
the first component of importance: the number of people who care
about what you write.If you narrow the topic sufficiently, you can probably find something
you're an expert on. Write about that to start with. If you only
have ten readers who care, that's fine. You're helping them, and
you're writing. Later you can expand the breadth of topics you write
about.The other constraint you can relax is a little surprising: publication.
Writing essays doesn't have to mean publishing them. That may seem
strange now that the trend is to publish every random thought, but
it worked for me. I wrote what amounted to essays in notebooks for
about 15 years. I never published any of them and never expected
to. I wrote them as a way of figuring things out. But when the web
came along I'd had a lot of practice.Incidentally,
Steve
Wozniak did the same thing. In high school he
designed computers on paper for fun. He couldn't build them because
he couldn't afford the components. But when Intel launched 4K DRAMs
in 1975, he was ready._____
How many essays are there left to write though? The answer to that
question is probably the most exciting thing I've learned about
essay writing. Nearly all of them are left to write.Although the essay
is an old form, it hasn't been assiduously
cultivated. In the print era, publication was expensive, and there
wasn't enough demand for essays to publish that many. You could
publish essays if you were already well known for writing something
else, like novels. Or you could write book reviews that you took
over to express your own ideas. But there was not really a direct
path to becoming an essayist. Which meant few essays got written,
and those that did tended to be about a narrow range of subjects.Now, thanks to the internet, there's a path. Anyone can publish
essays online. You start in obscurity, perhaps, but at least you
can start. You don't need anyone's permission.It sometimes happens that an area of knowledge sits quietly for
years, till some change makes it explode. Cryptography did this to
number theory. The internet is doing it to the essay.The exciting thing is not that there's a lot left to write, but
that there's a lot left to discover. There's a certain kind of idea
that's best discovered by writing essays. If most essays are still
unwritten, most such ideas are still undiscovered.Notes[1] Put railings on the balconies, but don't put bars on the windows.[2] Even now I sometimes write essays that are not meant for
publication. I wrote several to figure out what Y Combinator should
do, and they were really helpful.Thanks to <NAME>, <NAME>, <NAME>, and
<NAME> for reading drafts of this.Spanish TranslationJapanese Translation
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/chronos/0.1.0/gallery/readme/boilerplate.typ | typst | Apache License 2.0 | #import "/src/lib.typ" as chronos
#set page(
width: auto,
height: auto,
margin: 0.5cm
)
#chronos.diagram({
import chronos: *
_par("Alice")
_par("Bob")
}) |
https://github.com/fsr/rust-lessons | https://raw.githubusercontent.com/fsr/rust-lessons/master/src/lesson8.typ | typst | #import "slides.typ": *
#show: slides.with(
authors: ("<NAME>", "<NAME>"), short-authors: "H&A",
title: "Wer rastet, der rostet",
short-title: "Rust-Kurs Lesson 7",
subtitle: "Ein Rust-Kurs für Anfänger",
date: "Sommersemester 2023",
)
#show "theref": $arrow.double$
#show link: underline
#new-section("Lifetimes")
#slide(title: "Let's pretend we're the compiler")[
```rust
fn biggest(x: &i32, y: &i32) -> &i32 {
if *x > *y {
x
} else {
y
}
}
```
#begin(2)[
```rust
fn main() {
let i1 = 7;
let result;
{
let i2 = 8;
result = biggest(&i1, &i2);
}
println!("The bigger value is {}", result);
}
```
]
]
#slide(title: "What makes up the type of a reference?")[
#begin(1)[
- the underlying type, `i32`
]
#begin(2)[
- the mutability, `&` vs `&mut`
]
#begin(3)[
- the lifetime, how long does the underlying value live?
]
]
#slide(title: "Terminology")[
*lexical scope:*
Section of code where a _variable_ is valid.
Starts with `{` and ends with `}`
*liveness scope:*
Section of code where the _value_ of a variable is valid.
Starts where the value is created and ends where the value is dropped.
*lifetime:*
Section of code where the _reference_ to a value is valid.
Starts at creation of reference.
Is _at most_ as long as the liveness scope of the underlying value.
]
#slide(title: "Lifetime annotation syntax")[
```rust
&i32 // a reference
&'a i32 // a reference with an explicit lifetime
&'a mut i32 // a mutable reference with an explicit lifetime
&'this_can_be_anything i32 // a reference with a long lifetime identifier
```
]
#slide(title: "A dangling reference")[
#one-by-one[
how does the compiler know this shouldn't compile?
][
- `x` has a liveness scope, it ends with the inner lexical scope
][
- `ref_to_x` has lifetime `'b`, which is _at most_ as long as the liveness scope of `x`
]
```rust
fn main() {
let r;
{
let x = 5;
let ref_to_x /* &'b i32 */= &x; // -+-- 'b
r = ref_to_x; // |
} // -+ `x` is dropped theref lifetime 'b ends here
println!("r: {}", r);
}
```
]
#slide(title: "Fixing the biggest function")[
#set text(15pt)
- by annotating lifetimes
#alternatives[
```rust
fn biggest(x: &i32, y: &i32) -> &i32 {
if *x > *y {
x
} else {
y
}
}
fn main() {
let i1 = 7;
let result;
{
let i2 = 8;
result = biggest(&i1, &i2);
}
println!("The bigger value is {}", result);
}
```
][
```rust
fn biggest<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
if *x > *y {
x
} else {
y
}
}
fn main() {
let i1 = 7;
let result;
{
let i2 = 8;
result = biggest(&i1, &i2);
} // i2 is dropped
println!("The bigger value is {}", result);
}
```
]
#begin(2)[
- `biggest` is generic over lifetime `'a`
- the returned `&'a i32` is assigned to result
theref `'a` must be _at least_ as long as liveness scope of result
- "`i2` does not live long enough"
]
]
#slide(title: "Using references in structs")[
- needs lifetime annotations
```rust
struct Person<'a> {
name: &'a str,
age: u8,
}
```
]
#slide(title: "Lifetime elision")[
#begin(2)[
1. compiler assigns a different lifetime to every reference missing an annotation
]
#begin(3)[
2. one input lifetime parameter theref this lifetime is assigned to all output parameters
]
#begin(4)[
3. more than one input lifetime parameter && there is `&self` theref lifetime of `&self` is assigned to all output parameters
]
#alternatives[
```rust
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
```
][
```rust
fn first_word<'a>(s: &'a str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
```
][
```rust
fn first_word<'a>(s: &'a str) -> &'a str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
```
][
rule 3 does not apply here:
```rust
fn first_word<'a>(s: &'a str) -> &'a str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
```
]
]
#slide(title: "Lifetime annotations in method definitions")[
```rust
impl<'a> Person<'a> {
fn age(&self) -> i32 {
*self.age
}
fn name(&self) -> &'a str {
self.name
}
}
```
#begin(2)[
- without the explicit annotation `'a` the returned `&str` would have the same lifetime as `&self`
- in some cases `'a` can be longer than liveness scope of self
]
]
#slide(title: "The static lifetime")[
- special lifetime `'static` is valid over the length of the whole program
```rust
let s: &'static str = "I have a static lifetime.";
```
- string slices are embedded in programs binary theref is always available
]
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/codelst/1.0.0/codelst.typ | typst | Apache License 2.0 |
#let codelst-counter = counter("@codelst-line-numbers")
#let codelst-count-blanks( line, char:"\t" ) = {
let m = line.match(regex("^" + char + "+"))
if m != none {
return m.end
} else {
return 0
}
}
#let codelst-add-blanks( line, spaces:4, gobble:0 ) = {
if gobble in (none, false) { gobble = 0 }
if line.len() > 0 {
line = line.slice(gobble)
}
return line.replace(regex("^\t+"), (m) => " " * (m.end * spaces))
}
#let codelst-numbering = numbering
#let code-frame(
fill: luma(250),
stroke: .6pt + luma(200),
inset: (x: .45em, y: .65em),
radius: 3pt,
code
) = block(
fill: fill,
stroke: stroke,
inset: inset,
radius: radius,
breakable: true,
width: 100%,
code
)
#let codelst-lno( lno ) = {
v(0.08em)
if type(lno) != "string" {
lno.counter.display((lno, ..x) => align(right, text(.8em, luma(160), raw(str(lno)))))
} else {
align(right, text(.8em, luma(160), raw(lno)))
}
}
#let sourcecode(
lang: auto,
numbering: "1",
numbers-start: auto,
numbers-side: left,
numbers-width: auto,
numbers-style: codelst-lno,
numbers-first: 1,
numbers-step: 1,
continue-numbering: false,
gutter: 10pt,
tab-indent: 2,
gobble: auto,
highlighted: (),
highlight-color: rgb(234, 234,189),
label-regex: regex("// <([a-z-]{3,})>$"),
highlight-labels: false,
showrange: none,
showlines: false,
frame: code-frame,
code
) = {
// Find first raw element in body
if code.func() != raw {
code = code.children.find((c) => c.func() == raw)
}
assert.ne(code, none, message: "Missing raw content.")
let line-numbers = numbering != none
let numbers-format = numbering
let code-lang = lang
if lang == auto {
if code.has("lang") {
code-lang = code.lang
} else {
code-lang = "plain"
}
}
let code-lines = code.text.split("\n")
let line-count = code-lines.len()
// Reduce lines to range
if showrange != none {
assert.eq(showrange.len(), 2)
showrange = (
calc.clamp(calc.min(..showrange), 1, line-count) - 1,
calc.clamp(calc.max(..showrange), 1, line-count)
)
code-lines = code-lines.slice(..showrange)
line-count = code-lines.len()
if numbers-start == auto {
numbers-start = showrange.first() + 1
}
}
// TODO: Should this happen before showrange?
if not showlines {
let trim-start = code-lines.position((line) => line.trim() != "")
let trim-end = code-lines.rev().position((line) => line.trim() != "")
code-lines = code-lines.slice(trim-start, line-count - trim-end)
line-count = code-lines.len()
}
// Starting line number
if numbers-start == auto {
numbers-start = 1
}
// Get the amount of whitespace to gobble
if gobble == auto {
gobble = 9223372036854775807
let _c = none
for line in code-lines {
if line.len() == 0 { continue }
if not line.at(0) in (" ", "\t") {
gobble = 0
} else {
if _c == none { _c = line.at(0) }
gobble = calc.min(gobble, codelst-count-blanks(line, char:_c))
}
if gobble == 0 { break }
}
}
// Convert tabs to spaces and remove unecessary whitespace
code-lines = code-lines.map((line) => codelst-add-blanks(line, spaces:tab-indent, gobble:gobble))
// Parse labels
let labels = (:)
if label-regex != none {
for (i, line) in code-lines.enumerate() {
let m = line.match(label-regex)
if m != none {
labels.insert(str(i), m.captures.at(0))
code-lines.at(i) = line.replace(label-regex, "")
if highlight-labels {
highlighted.push(i + numbers-start)
}
}
}
}
// Add a blank raw element, to allow use in figure
raw("", lang:code-lang)
// Does this make sense to pass full code to show rules?
// #block(height:0pt, clip:true, code)
if frame == none {
frame = (b) => b
}
frame(layout(size => style(styles => {
let m1 = measure(raw("0"), styles)
let m2 = measure(raw("0\n0"), styles)
let letter-height = m1.height
let descender = 1em - letter-height
let line-gap = m2.height - 2*letter-height - descender
// Measure the maximum width of the line numbers
// We need to measure every line, since the numbers
// are styled and could have unexpected formatting
// (e.g. line 10 is extra big)
let numbers-width = numbers-width
if numbering != none and numbers-width == auto {
numbers-width = calc.max(
..range(numbers-first - 1, line-count, step:numbers-step).map((lno) => measure(
numbers-style(codelst-numbering(numbering, lno + numbers-start)),
styles
).width)
) + .1em
} else if numbering == none {
numbers-width = 0pt
}
let code-width = size.width - numbers-width - gutter
// Create line numbers and
// highlight / labels columns
let highlight-column = ()
let numbers-column = ()
for i in range(line-count) {
// Measure actual code line height
// (including with potential line breaks)
let m = measure(
block(
width: code-width,
spacing:0pt,
raw(code-lines.at(i))
),
styles
)
let line-height = calc.max(letter-height, m.height)
numbers-column.push(block(
width: 100%,
// clip: true,
// breakable: true,
height: line-height,
// spacing: 0pt,
below: if i == line-count - 1 {
0pt
} else {
descender + line-gap
},
{
codelst-counter.step()
if i + numbers-start >= numbers-first and calc.rem(i + numbers-start - numbers-first, numbers-step) == 0 [
#numbers-style(codelst-counter.display((lno, ..x) => [
#codelst-numbering(numbering, lno)<line-number>
]))
#if str(i) in labels { label(labels.at(str(i))) }
]
}
))
highlight-column.push({
// move(dy:-.5 * (line-gap + descender),
block(
breakable: true,
width: size.width,
fill: if i + numbers-start in highlighted {
highlight-color
} else {
none
},
spacing: 0pt,
height: line-height + line-gap + descender
// height: line-height
)
// )
// Prevent some empty space at the bottom due
// to line highlights
if i == line-count -1 and i + numbers-start not in highlighted {
v(-1 * (line-gap + descender))
}
})
}
numbers-column = {
if not continue-numbering {
codelst-counter.update(numbers-start - 1)
}
//stack(dir: ttb, ..numbers-column)
v(.5 * (line-gap + descender))
numbers-column.join()
}
highlight-column = {
set align(left)
stack(dir:ttb,
// spacing: -.5 * (line-gap + descender),
..highlight-column
)
// highlight-column.join()
}
// Create final code block
// (might have changed due to range option and trimming)
let code-column = {
set align(left)
set par(justify:false)
v(.5 * (line-gap + descender))
raw(lang:code-lang, code-lines.join("\n"))
}
grid(
columns: if numbering == none {
(-gutter, 1fr)
} else if numbers-side != right {
(-gutter, numbers-width, 1fr)
} else {
(-gutter, 1fr, numbers-width)
},
column-gutter: gutter,
..if numbering == none {
(highlight-column, code-column)
} else if numbers-side != right {
(highlight-column, numbers-column, code-column)
} else {
(highlight-column, code-column, numbers-column)
}
)
})) // end style + layout
) // end frame
}
#let sourcefile( code, file:none, lang:auto, ..args ) = {
if file != none and lang == auto {
let m = file.match(regex("\.([a-z0-9]+)$"))
if m != none {
lang = m.captures.first()
}
} else if lang == auto {
lang = "plain"
}
sourcecode( ..args, raw(code, lang:lang, block:true))
}
#let lineref( label, supplement:"line" ) = locate(loc => {
let lines = query(selector(label), loc)
assert.ne(lines, (), message: "Label <" + str(label) + "> does not exists.")
[#supplement #numbering("1", ..codelst-counter.at(lines.first().location()))]
})
#let codelst-styles( body ) = {
show figure.where(kind: raw): set block(breakable: true)
body
}
#let codelst(
tag: "codelst",
reversed: false,
..args
) = {
if not reversed {
return (body) => {
show raw.where(lang: tag): (code) => {
let code-lines = code.text.split("\n")
let lang = code-lines.remove(0).trim().slice(1)
sourcecode(..args, raw(lang:lang, code-lines.join("\n")))
}
body
}
} else {
return (body) => {
show raw: (code) => {
if code.text.starts-with(":" + tag) {
sourcecode(..args, raw(lang: code.lang, code.text.slice(tag.len() + 1)))
} else {
code
}
}
body
}
}
}
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/chained-call.typ | typst | Apache License 2.0 | #{
a.bbbbbbbbbbbbb().c().ddddddddddddddddddddddd
}
#{
a.bbbbbbbbbbbbbb()[c][d].eeeeeeeeee().f()
}
#{
a.bbbbbbbbbbbbbb()[c][d].eeeeeeeeee().f(123)[444][ccc]
}
#{
let (title, _) = query(heading.where(level: 1)).map(e => (e.body, e.location().page())).rev().find(((_, v)) => v <= page)
}
#a.b()[c][d].eeeeeeeeeeeeeee().fffffffff()
#{
(1,).rev().map(((n, c)) =>
f(n,c,1))
}
|
https://github.com/mismorgano/UG-PartialDifferentialEquations-23 | https://raw.githubusercontent.com/mismorgano/UG-PartialDifferentialEquations-23/main/tareas/tarea-01/tarea-01.typ | typst |
#set text(font: "New Computer Modern", size: 12pt)
#set enum(numbering: "(a)")
#let inf = $infinity$
#let e = counter("exercise")
#let exercise(label, body, number: none) = {
if number != none {
e.update(number)
} else {
e.step()
}
box(width: 100%,stroke: 1pt, inset: 5pt, [#text(size: 1.6em)[*Problema #e.display() #label*] \ #body],)
}
#align(center, text(17pt)[
*Ecuaciones Diferenciales Parciales*\
*Tarea 1*
])
#align(center)[<NAME>
#link("mailto:<EMAIL>")]
#exercise()[11.1][
Supongamos que $f$ es $T$-periódica y sea $F$ una antiderivada de $f$; por ejemplo
$ F(x) = integral_0^x f(x) d x, quad -inf <x<inf. $
Muestra que $F$ es $T$-periódica si y solo si la integral de $f$ sobre cualquier intervalo de longitud $T$ es cero.]
*Demostración:*
Sea $F$ una antiderivada de $f$, entonces se cumple que $F'(x) = f(x)$ para todo $x in RR$. Por el Teorema Fundamental del Calculo tenemos
$ F(T + x) - F(x) = integral_(x)^(T+x) f(x) d x. $
De lo anterior tenemos que $F$ es $T$-periódica si y solo $F(T+x) - F(x) = 0$ lo cual sucede si y solo si
$ integral_(x)^(T+x) f(x) d x = 0, $
es decir, la integral sobre todo intervalo de longitud $T$ es cero.
#exercise()[11.4][
Muestra que $e^x$ es suma de una función par y una función impar.]
*Demostración:*
Supongamos que $e^x$ es suma de una función par $f$ y una función impar $g$, es decir,
$ e^x = f(x) + g(x)$. Dado que $f(x) = f(-x)$ para todo $x in RR$ y que $g(-x) = -g(x)$ para todo $x in RR$, entonces
$ e^(-x) = f(-x) + g(-x) = f(x) - g(x). $
Lo anterior implica que $e^x + e^(-x) = 2f(x)$, por lo cual $ f(x) = (e^x + e^(-x))/2$, de manera similar tenemos que
$e^x - e^(-x) = 2g(x)$ y por tanto $g(x) = (e^x - e^(-x))/2.$
Por ultimo notemos que
$ f(x) + g(x) = (e^x + e^(-x))/2 + (e^x - e^(-x))/2 = e^x, $
mas aún, $f$ y $g$ son únicas.
#exercise()[11.17][
Considera la integral $ integral_0^1 (d x)/(1+x^2) $
+ Evalúa la integral de manera explicita.
+ Usa la serie de Taylor de $1/(1+x^2)$ (una serie geométrica) para obtener una serie infinita para la integral.
+ Iguala la parte a) y la b) para derivar una formula para $pi$.]
*Demostración:*
+ Notemos que $(arctan x)' = 1/(1+x^2)$, por lo cual, el Teorema Fundamental del Calculo nos dice que
$ integral_0^1 (d x)/(1+x^2) = arctan(1) - arctan(0) = pi/4 - 0 = pi/4. $
+ Nosotros sabemos que para $abs(u)<1$ se cumple $ 1/(1-u) = sum_(k=0)^(infinity) u^k, $ por lo cual si consideramos $u = -x^2$ tenemos que
$ 1/(1+x^2) = sum_(k=0)^(infinity) (-x^2)^k = sum_(k=0)^(infinity) (-1)^k x^(2k), $
para $abs(-x^2) = abs(x^2)<1.$ Más aún la convergencia anterior es uniforme en su radio de convergencia, que es 1,
por lo cual se cumple que
$ integral 1/(1+x^2) d x = integral sum_(k=0)^(infinity) (-1)^k x^(2k) d x = sum_(k=0)^(infinity) (-1)^k integral x^(2k) d x = sum_(k=0)^(infinity) (-1)^k x^(2k+1)/(2k +1). $
+ De lo anterior tenemos que
$ pi/4 = integral_0^1 (d x)/(1+x^2) = sum_(k=0)^(infinity) (-1)^k integral_0^1 x^(2k) d x = sum_(k=0)^(infinity) (-1)^k 1/(2k +1), $
por lo cual
$ pi = sum_(k=0)^(infinity) (-1)^k 4/(2k +1). $
#exercise()[13.1][
Para cada una de los siguientes problemas de valores iniciales en la frontera, determina si existe o no una distribución de temperatura
y encuentra los valores de $beta$ para los cuales una solución de equilibrio existe.
+ $ (diff u)/(diff t) = (diff^2 u) /(diff x^2) +1, quad (diff u)/(diff x)(0, t) = 1, quad (diff u)/(diff x)(a, t) = beta, $
+ $ (diff u)/(diff t) = (diff^2 u) /(diff x^2), quad (diff u)/(diff x)(0, t) = 1, quad (diff u)/(diff x)(a, t) = beta, $
+ $ (diff u)/(diff t) = (diff^2 u) /(diff x^2) + x -beta, quad (diff u)/(diff x)(0, t) = 0, quad (diff u)/(diff x)(a, t) = 0. $]
*Solución:*
Supongamos que existe una solución de equilibrio, entonces tenemos que existe $phi$ (que no depende del tiempo) tal que
$u(x, t) = phi(t)$.
+ De lo anterior tenemos que la ecuación la podemos escribir en términos de $phi$ como $ phi''(x) = -1, $
al integrar obtenemos que
$ phi'(x) = -x + C quad "y que " phi(x) = -x^2/2 + C x + D. $
Por lo cual $u_x (x, t) = -x + C$ y $u(x, t) = -x^2/2 + C x + D$ para todo $x, t$, usando las condiciones iniciales vemos que
$u_x(0, t) = C = 1$, entonces $u_x (x, t) = -x + 1$, se sigue que $u_x(a, t) = -a + 1= beta$.
De lo anterior, existe una solución de equilibrio si y solo si $beta = 1-a$ y la solución es:
$ u(x,t) = -x^2/2 + x + D "para" 0<x<a #footnote[Pues es un problema de frontera.], $
donde $D$ es constante.
+ De manera similar tenemos que $phi''(x) = 0$, lo cual implica que $ phi'(x) = C quad"y que "quad phi(x) = C x + D, $
usando las condiciones iniciales tenemos que $u_x (0, 1) = 1 = C$, por tanto $u_x (x,t) = 1$, por otro lado
también se debe cumplir que $u_x (a, t) = 1 = beta$. De lo anterior vemos que existe _solución de equilibrio_
dada por $ u(x, t) = x + D quad "para" 0<x<a, $
donde $D$ es constante.
+ En este caso se debe cumplir que $phi''(x) = - (x-beta)$ al integrar#footnote[Usando ideas de *EDO*.] obtenemos que
$phi'(x) = -(x-beta)^2/2 + C$ y que $phi(x) = -(x-beta)^3/6 + C x + D$.
Por las condiciones iniciales tenemos que $u_x (0, t) = -beta^2/2 + C = 0$ y que $u_x (a, t) = -(a-beta)^2/2 + C = 0$,
lo cual implica que $C=beta^2/2$ y que $ beta^2/2 = (a-beta)^2/2 => beta^2 = a^2 - 2a beta +beta^2 => 0 = a(a-2beta). $
Como es un problema de frontera podemos suponer que $a!= 0$ y por tanto se debe cumplir que $a - 2beta = 0$,
entonces existe _solución de equilibrio_ si y solo si $beta = a/2$ y $C = a^2/8$, la solución esta dada por
$ u(x, t) = -(x-a/2)^3/6 + a^2/8 x +D, "para" 0<x<a $
donde $ D$ es constante.
#exercise[14.11][
Usando la ecuación de onda en una dimensión que gobierna el pequeño desplazamiento de una
cuerda que vibra uniformemente:
$ (diff^2 u)/(diff t^2) = c^2 (diff^2 u)/(diff x^2), quad 0< x<L, quad t>0, $
deriva la ecuación de la energía para una cuerda que vibra,
$ (d E)/ (d t) = rho c^2 (diff u)/(diff x) (diff u)/(diff t) limits(bar.v)_0^L, $
donde la energía Total $E$ es la suma de la energía cinética y la energía potencial, y $rho$
es la densidad lineal, esto es, la masa por unidad de longitud de la cuerda (suponiendo constante),
$ E(t) = rho/2 integral_0^L ( (diff u) / (diff t) )^2 d x + (rho c^2 )/ 2 integral_0^L ((diff u)/(diff x)^2) d x. $]
*Solución:*
Supongamos que $u$ satisface $ (diff^2 u)/(diff t^2) = c^2 (diff^2 u)/(diff x^2), quad 0< x<L, quad t>0, $ entonces
por la formula de integración de Leibniz se cumple que
$ (d E)/(d t) &= rho/2 d/(d t)(integral_0^L u_t^2 d x)+ (rho c^2 )/ 2 d/(d t) (integral_0^L u_x^2 d x) \
&= rho/2 integral_0^L diff/(diff t) u_t^2 d x + (rho c^2 )/ 2 integral_0^L diff/(diff t) u_x^2 d x, $
luego, por regla de la cadena se cumple que
$ (d E)/(d t) = rho/2 integral_0^L 2u_t u_(t t) d x + (rho c^2 )/ 2 integral_0^L 2u_x u_(x t) d x, $
por hipótesis tenemos que $u_(t t) = c^2 u_(x x)$ y ademas se cumple que $u_(x t) = u_(t x)$ pues $u in C^2$, por lo cual
$ (d E)/(d t) &= rho c^2 integral_0^L u_t u_(x x) d x + rho c^2 integral_0^L u_x u_(x t) d x\
&= rho c^2 integral_0^L (u_t u_(x x) + u_x u_(t x)) d x \
&= rho c^2 integral_0^L diff/(diff x) (u_t u_x) d x, \ $
se sigue por el Teorema Fundamental del Calculo que
$ (d E)/(d t) = rho c^2 (u_t u_x)limits(bar.v)_0^L, $
como queremos.
#exercise()[15.1][
Muestra que la función $ u = 1/(sqrt(x^2 +y^2+z^2)), $
es armonica, es decir, es una solución a la ecuación de Laplace en tres dimensiones, $Delta u = 0$.]
*Demostración:*
Queremos que $u_(x x) + u_(y y) + u_(z z) = 0$. Primero, por regla de la cadena, notemos que
$ u_x = -1/2 1/(root(3/2, x^2 +y^2 +z^2))(2x) = -(x^2 +y^2 +z^2)^(-3/2)(x), $
luego,
$ u_(x x) &= -(-3/2)(x^2 +y^2 +z^2)^(-5/2)(2x)(x) - (x^2 +y^2 +z^2)^(-3/2)\
&= (3x^2)/(x^2 +y^2 +z^2)^(5/2) - 1/(x^2 +y^2 +z^2)^(3/2) $
De manera similar, por simetría, tenemos que
$ u_(y y) = (3y^2)/(x^2 +y^2 +z^2)^(5/2) - 1/(x^2 +y^2 +z^2)^(3/2), $
$ u_(z z) = (3z^2)/(x^2 +y^2 +z^2)^(5/2) - 1/(x^2 +y^2 +z^2)^(3/2). $
De lo anterior vemos que
$ u_(x x) + u_(y y) + u_(z z) &= 3(x^2+y^2+z^2)/(x^2 +y^2 +z^2)^(5/2) - 3/(x^2 +y^2 +z^2)^(3/2) \
&= (3(x^2+y^2+z^2) - 3(x^2+y^2+z^2))/(x^2 +y^2 +z^2)^(5/2)\
&= 0, $
como queremos
#exercise()[19.2][
La ecuación diferencial de Hermite se lee como
$ y'' -2x y' + lambda y = 0, quad -infinity < x < infinity, $
+ Multiplica por $e^(-x^2)$ y devuelve la ecuación diferencial en forma de Sturm-Liuville.
Determina si el problema de Sturm-Liouville resultante es regular o singular.
+ Muestra que los polinomios de Hermite
$ H_0(x) = 1, quad H_1(x) = 2x, quad H_2(x)= 4x^2-2, quad H_3(x) = 8x^3-12x $
son funciones propias del problema de Sturm-Liouville y encuentra los valores propios correspondientes.
+ Usa una función de peso apropiada y muestra que $H_1$ y $H_2$ son ortogonales en el intervalo $(-infinity, infinity)$
con respecto a esta función de peso.]
*Solución*
+ Recordemos primero que un problema de Sturm-Liouville tiene la forma
$ (p(x)phi'(x))' + [q(x) + lambda sigma(x)]phi(x) = 0, quad a<x<b, $
donde $p', q$ y $sigma$ son continuas en $[a, b]$ y $p, sigma$ son positivas.
Desarrollando un poco notemos que un problema de Sturm-Liouville también tiene la forma
$ p(x)'phi'(x) + p(x)phi''(x) + [q(x) + lambda sigma(x)]phi(x) = 0, quad a<x<b, $
Luego, tenemos que
$ 0 = (y'' -2x y' + lambda y)e^(-x^2) = e^(-x^2)y'' -2x e^(-x^2) y' + lambda e^(-x^2) y, $
comparando coeficientes podemos notar que $p(x) = e^(-x^2)$, $q(x) = 0$ y $sigma(x) =e^(-x^2)$ las cuales son continuas y positivas en todo $RR$.
Entonces la forma de Sturm-Liouville de la ecuación de Hermite es:
$ (e^(-x^2)y')' + lambda e^(-x^2) y = 0, $
dado que el intervalo es infinito el sistema es singular.
+
- Para $y = H_0(x)=1$, entonces $y' = 0$ y el sistema se convierte en $ + lambda e^(-x^2) = 0, $ dado que la exponencial es positiva se sigue que $lambda=0.$
- Suponiendo $y = H_1(x)=2x$ tenemos que $y'=2$ y por tanto el sistema se ve como
$ (e^(-x^2)2)' + lambda e^(-x^2) 2x = -4x e^(-x^2) + lambda e^(-x^2)2x = 0 => (lambda - 2)e^(-x^2)x = 0, $
$x!=0$ implica que $lambda = 2$.
- Si $y = H_2(x) = 4x^2 -2$ entonces $y' = 8x$, el sistema queda como
$ (e^(-x^2)8x)' + lambda e^(-x^2) (4x^2 - 2) = 0, $
de hecho se debe cumplir que
$ 0 = (y'' -2x y' + lambda y)e^(-x^2), $
como $e^(-x^2)$ es positiva entonces se debe cumplir que $0 = y'' -2x y' + lambda y$, como $y'' = 8$, se debe cumplir que
$8 - 16x^2 + lambda(4x^2 -2) = 0 => (4lambda - 16)x^2 + (8-2lambda) = 0, $
lo cual implica que $4lambda - 16 =0$ y $8-2lambda = 0$ y por tanto $lambda = 4$.
- Suponiendo $y = H_3(x) = 8x^3 -12x$, tenemos que $y' = 24x^2 -12$ y $y'' = 48x$, por tanto se debe cumplir que
$ 48x - 2x(24x^2 -12) + lambda(8x^3 -12x) = 0 => (8lambda - 48)x^3 + (72 -12lambda)x = 0, $
es decir $8lambda - 48 = 0$ y $72 -12lambda=0$ lo cual implica $lambda = 6$.
+ Para checar que $H_1$, $H_2$ son ortogonales consideremos $sigma(x) = e^(-x^2)$, entonces tenemos que
$ angle.l H_1, H_2 angle.r = integral_(-inf)^inf 2x e^(-x^2) d x, $
como $2x e^(-x^2)$ es una función impar y los limites de integración son simétricos tenemos que la integral vale cero,
como queremos.
#exercise()[19.3][
Encuentra todas las funciones $phi$ para las cuales $u(x, t) = phi(x-c t)$ es una solución a la ecuación del calor
$ (diff^2 u)/(diff x^2) = 1/k (diff u)/(diff t), quad -infinity<x<infinity, $
donde $k$ y $c$ son constantes.]
*Solución:*
Supongamos $u(x, t) = phi(x-c t)$ es solución y sea $s=x-c t$ entonces por regla de la cadena tenemos que
$ u_(x x) = phi''(s)quad "y que"quad u_(t) = -c phi'(s), $
por lo cual se debe cumplir que
$ phi''(s) =-c/k phi'(s) => phi''(s) + c/k phi'(s) = 0, $
cuyo polinomio característico es $lambda^2 + c/k lambda = 0$, sus ceros son $lambda = 0$ y $lambda=-c/k$, por lo cual
la solución general esta dada por:
$ phi(s) = A + B e^(-c/k s), $
se sigue entonces que
$ u(x, t) = phi(x -c t) = A + B e^(-c/k (x - c t)), $
donde $A, B$ son constantes.
#exercise()[19.12][
Encuentra todas las funciones $phi$ para las cuales $u(x, t) = phi(x+c t)$ es una solución a la ecuación del calor
$ (diff^2 u)/(diff x^2) = 1/k (diff u) / (diff t), $
donde $k$ y $c$ son constantes.]
*SoLución:*
Sea $s = x + c t$, la regla de la cadena implica que
$ u_(x x) = phi''(s)quad "y que"quad u_(t) = c phi'(s), $
entonces de debe cumplir que
$ phi''(s) =c/k phi'(s) => phi''(s) - c/k phi'(s) = 0, $
su polinomio característico es $lambda^2 - c/k lambda = 0$ cuyas raíces son $lambda = 0$ y $lambda=c/k$, entonces la solución
general es:
$ phi(s) = A + B e^(c/k s), $
y por tanto
$ u(x, t) = phi(x -c t) = A + B e^(c/k (x - c t)), $
con $A, B$ constantes.
#exercise()[19.15][
Ademas de las ecuaciones lineales, algunos ecuaciones no lineales también pueden resultar en _soluciones de onda viajera_ de la forma
$ u(x, t) = phi(x- c t). $
La _Ecuación de Fisher,_ la cual modela la propagación de un gen ventajoso en una población, donde $u(x, t)$ es la densidad del gen
en la población al tiempo $t$ y posición $x$, es dada por
$ (diff u)/(diff t) = (diff^2 u)/(diff x^2) +u(1-u). $
Muestra que la ecuación de Fisher tiene solución de esta forma si $phi$ satisface la ecuación diferencial ordinaria no lineal
$ phi'' + c phi' + phi(1-phi) =0. $]
*Solución:*
Supongamos que $ u(x, t) = phi(x -c t)$ cumple que $phi'' + c phi' + phi(1-phi) =0$, por regla de la cadena notemos que $u_t = -c phi'$
y que
$ u_(x x) = phi'', $
por hipótesis $phi'' + c phi' + phi(1-phi) =0$ lo cual implica que $-c phi' = phi'' + phi(1-phi),$ sustituyendo lo anterior notemos que
$ u_t = u_(x x) + u(1-u), $
es decir, $u$ satisface la ecuación de Fisher, como queremos.
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/fletcher/0.1.1/src/all.typ | typst | Apache License 2.0 | #import "@preview/cetz:0.1.2" as cetz
#import "utils.typ": *
#import "marks.typ": *
#import "draw.typ": *
#import "layout.typ": * |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10860.typ | typst | Apache License 2.0 | #let data = (
("PALMYRENE LETTER ALEPH", "Lo", 0),
("PALMYRENE LETTER BETH", "Lo", 0),
("PALMYRENE LETTER GIMEL", "Lo", 0),
("PALMYRENE LETTER DALETH", "Lo", 0),
("PALMYRENE LETTER HE", "Lo", 0),
("PALMYRENE LETTER WAW", "Lo", 0),
("PALMYRENE LETTER ZAYIN", "Lo", 0),
("PALMYRENE LETTER HETH", "Lo", 0),
("PALMYRENE LETTER TETH", "Lo", 0),
("PALMYRENE LETTER YODH", "Lo", 0),
("PALMYRENE LETTER KAPH", "Lo", 0),
("PALMYRENE LETTER LAMEDH", "Lo", 0),
("PALMYRENE LETTER MEM", "Lo", 0),
("PALMYRENE LETTER FINAL NUN", "Lo", 0),
("PALMYRENE LETTER NUN", "Lo", 0),
("PALMYRENE LETTER SAMEKH", "Lo", 0),
("PALMYRENE LETTER AYIN", "Lo", 0),
("PALMYRENE LETTER PE", "Lo", 0),
("PALMYRENE LETTER SADHE", "Lo", 0),
("PALMYRENE LETTER QOPH", "Lo", 0),
("PALMYRENE LETTER RESH", "Lo", 0),
("PALMYRENE LETTER SHIN", "Lo", 0),
("PALMYRENE LETTER TAW", "Lo", 0),
("PALMYRENE LEFT-POINTING FLEURON", "So", 0),
("PALMYRENE RIGHT-POINTING FLEURON", "So", 0),
("PALMYRENE NUMBER ONE", "No", 0),
("PALMYRENE NUMBER TWO", "No", 0),
("PALMYRENE NUMBER THREE", "No", 0),
("PALMYRENE NUMBER FOUR", "No", 0),
("PALMYRENE NUMBER FIVE", "No", 0),
("PALMYRENE NUMBER TEN", "No", 0),
("PALMYRENE NUMBER TWENTY", "No", 0),
)
|
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Templates/question.typ | typst | #let question_heading(doc) = {
show heading.where(level: 2) : set text(weight: "medium", style: "italic")
show heading.where(level: 3) : set text(weight: "medium")
doc
} |
|
https://github.com/InternetFreedomFoundation/ghost-typst | https://raw.githubusercontent.com/InternetFreedomFoundation/ghost-typst/main/main.typ | typst | #set page(
numbering: "1",
number-align: center,
)
#set heading(numbering: "1.")
#set par(justify: true)
#set text(
font: "Helvetica",
)
#show "__GHOST_URL__": "https://internetfreedom.in"
#show "GHOST_URL/": "https://internetfreedom.in"
#align(center, text(18pt)[
*Internet Freedom Foundation* \
New Delhi, India
])
#align(center+horizon,[
#image("logo.png", width: 50%)
])
#align(bottom+center)[
#set par(justify: false)
*Last Update at: Sun Jun 2 19:53:33 EEST 2024 * \
This document is an attempt to create a print-friendly archive of the entirety of content publically available at \ https://internetfreedom.in.
]
#pagebreak()
#outline()
#pagebreak()
#let p(post) = [
== #post.title
#v(2pt)
*published on* = #post.published_at
#post.plaintext
#pagebreak()
]
#let ghostToPDF(db) = [
= Posts
#for (post) in (db.db.at(0).data.posts) {
if (post.visibility == "public" and post.type == "post" and post.status != "draft") {
p(post)
}
}
= Pages
#for (post) in (db.db.at(0).data.posts) {
if (post.visibility == "public" and post.type == "page" and post.status != "draft") {
p(post)
}
}
]
#ghostToPDF(json("iff.json"))
|
|
https://github.com/rabotaem-incorporated/algebra-conspect-1course | https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/04-linear-algebra/09-basis.typ | typst | Other | #import "../../utils/core.typ": *
== Базис и размерность
#ticket[Равносильные определения базиса. Размерность]
#def[
Набор векторов $sq(e) in V$ называется _базисом_, если $ forall v in V space.quad exists! alpha_1, ..., alpha_n in K: space.quad v = alpha_1 e_1 + ... + alpha_n e_n $
]
#pr(name: "Эквивалентные определения базиса")[
Пусть $e_1, ..., e_n in V$. Тогда следующие утверждения эквиваленты:
+ $sq(e)$ --- базис $V$
+ $sq(e)$ --- ЛНС и $Lin(sq(e)) = V$.
+ $sq(e)$ --- Максимальная по включению ЛНС (то есть она не является собственным подмножеством к какой-либо другой ЛНС).
+ $sq(e)$ --- Минимальная по включению порождающая система (то есть она перестает быть таковой при удалении любого вектора).
]
#proof[
- "$1 => 2$": Пусть есть нетривиальная линейная комбинация: $alpha_1 e_1 + ... + alpha_n e_n = 0 = 0 dot e_1 + ... + 0 dot e_n$ --- противоречие с определением базиса. $Lin(sq(v)) = V$ --- из определения базиса.
- "$2 => 1$": Пусть $alpha_1 e_1 + ... + alpha_n e_n = beta_1 e_1 + ... + beta_n e_n$. Тогда $(alpha_1 - beta_1) e_1 + ... = 0$. $sq(e)$ --- ЛНС, значит $alpha_i - beta_i = 0 ==> alpha_i = beta_i$.
- "$2 => 3$": Предположим это не так. Тогда $exists v in V space.quad sq(e), v$ --- ЛНС, но $v in V = Lin(sq(e))$, что несовместимо с линейной независимостью. Противоречие.
- "$3 => 2$": Пусть $v in.not Lin(sq(e)) ==> sq(e), v$ --- ЛНС. Противоречие с максимальностью.
- "$2 => 4$": Предположим $sq(e, n - 1)$ --- порождающая система (не умаляя общности). Тогда $e_n in Lin(sq(e, n - 1))$ и $sq(e)$ --- ЛЗС. Противоречие с условием 2.
- "$4 => 2$": Пусть $sq(e)$ --- ЛЗС. Тогда в ней найдется вектор, который выражается через предыдущие: $e_j in Lin(sq(e, j - 1)) ==> Lin(e_1, ..., e_j, ..., e_n) = Lin(e_1, ..., hat(e_j), ..., e_n)$. Значит и без $e_j$ система порождающая. Противоречие с минимальностью.
]
#pr[
Пусть $V = Lin(sq(v))$. Тогда из набора $sq(v)$ можно выбрать базис.
]
#proof[
Если какой-то вектор выражается через остальные --- будем удалять его, иначе --- оставлять. Повторяем пока не останется ЛНС.
]
#follow[
В любом конечномерном пространстве существует базис.
]
#notice[
В бесконечномерном пространстве тоже есть базис, но линейные комбинации берутся финитные.
]
#pr[
Любые базисы содержат одинаковое число векторов.
Пусть $e_1, ..., e_m$ и $f_1, ..., f_n$ --- базисы $V$. Тогда $m = n$.
]
#proof[
$f_1, ..., f_n in Lin(e_1, ..., e_m) = V$. $f_1, ..., f_n$ --- ЛНС. Значит $n <= m$. Аналогично, $n >= m$.
]
#def[
_Размерностью_ $V$ называется число векторов в базисе $V$. Обозначается $Dim V$
]
#example[
$Dim M_(m, n)(K) = m n$
]
#ticket[Свойства пространств заданной размерности. Размерность подпространства]
#pr[
Пусть $Dim V = n$.
+ Если $sq(v, m)$ --- ЛНС в $V$, то $m <= n$.
+ Если $Lin(sq(v, m)) = V$, то $m >= n$.
+ Если $sq(v)$ --- ЛНС, то это базис.
+ Если $Lin(sq(v)) = V$, то это базис.
]
#proof[
+ $sq(v, m) in Lin(sq(e)) ==> m <= n$, по теореме о линейной зависимости линейных комбинаций.
+ Из порождающего семейства можно выбрать базис.
+ Если $sq(v)$ --- не базис, найдется $v$ такой, что $sq(v), v$ --- ЛНС. Противоречие с 1.
+ Из $sq(v)$ можно выбрать базис, а так как векторов здесь $n$, это и есть базис.
]
#pr[
Пусть $Dim V = n$, $W < V$. Тогда
+ $Dim W <= n$.
+ $Dim W = n$ если и только если $W = V$.
]
#proof[
+ $W < V$ --- подпространство, значит $W = Lin(sq(w, m))$. $sq(w, m)$ --- ЛНС в $V$. $m <= n$.
+ Если $W = V$, то $W = Lin(sq(w))$. $sq(w)$ --- ЛНС. $n = n$.
]
|
https://github.com/ist199211-ist199311/continuous-ifc-devops | https://raw.githubusercontent.com/ist199211-ist199311/continuous-ifc-devops/master/go-theme.typ | typst | // This theme contains ideas from the former "bristol" theme, contributed by
// https://github.com/MarkBlyth
#import "@preview/polylux:0.3.1": *
#let clean-footer = state("clean-footer", [])
#let clean-short-title = state("clean-short-title", none)
#let clean-color = state("clean-color", teal)
#let clean-logo = state("clean-logo", none)
// go-lang colors
#let go-gopher-blue = rgb("#00add8")
#let go-light-blue = rgb("#5dc9e2")
#let go-fuchsia = rgb("#ce3262")
#let go-aqua = rgb("#00a29c")
#let go-black = rgb("#000000")
#let go-yellow = rgb("#fddd00")
#let go-gradient = dir => gradient.linear(go-gopher-blue, go-aqua, dir: dir)
#let cloud-secondary = white.mix(go-gopher-blue)
#let clouds = [
#place(bottom, dx: 270pt, dy: -20pt, circle(radius: 35pt, fill: cloud-secondary))
#place(bottom, dx: 370pt, dy: -40pt, circle(radius: 35pt, fill: cloud-secondary))
#place(bottom, dx: 420pt, dy: -15pt, circle(radius: 30pt, fill: cloud-secondary))
#place(bottom, dx: 530pt, dy: 30pt, circle(radius: 40pt, fill: cloud-secondary))
#place(bottom, dx: 770pt, dy: -10pt, circle(radius: 40pt, fill: cloud-secondary))
#place(bottom, dx: -30pt, circle(radius: 55pt, fill: white))
#place(bottom, dx: 40pt, circle(radius: 45pt, fill: white))
#place(bottom, dx: 110pt, circle(radius: 45pt, fill: white))
#place(bottom, dx: 160pt, dy: -10pt, circle(radius: 55pt, fill: white))
#place(bottom, dx: 200pt, dy: 20pt, circle(radius: 55pt, fill: white))
#place(bottom, dx: 290pt, dy: 15pt, circle(radius: 55pt, fill: white))
#place(bottom, dx: 350pt, dy: 60pt, circle(radius: 55pt, fill: white))
#place(bottom, dx: 420pt, dy: 50pt, circle(radius: 55pt, fill: white))
#place(bottom, dx: 600pt, dy: 50pt, circle(radius: 55pt, fill: white))
#place(bottom, dx: 650pt, dy: 30pt, circle(radius: 55pt, fill: white))
#place(bottom, dx: 700pt, dy: 55pt, circle(radius: 55pt, fill: white))
]
#let clean-theme(
aspect-ratio: "16-9",
footer: [],
short-title: none,
logo: none,
color: teal,
body
) = {
set page(
paper: "presentation-" + aspect-ratio,
margin: 0em,
header: none,
footer: none,
)
set text(size: 25pt, font: "Noto Sans")
show footnote.entry: set text(size: .6em)
clean-footer.update(footer)
clean-color.update(color)
clean-short-title.update(short-title)
clean-logo.update(logo)
body
}
#let title-slide(
title: none,
subtitle: none,
authors: (),
date: none,
watermark: none,
secondlogo: none,
) = {
let content = locate( loc => {
let color = go-yellow
let logo = clean-logo.at(loc)
let authors = if type(authors) in ("string", "content") {
( authors, )
} else {
authors
}
set text(white)
place(top + left, box(fill: go-gradient(direction.btt), height: 100%, width: 100%))
place(bottom, dy: 30pt, clouds)
if watermark != none {
set image(width: 100%)
place(watermark)
}
[
#set image(height: 2.2em)
#place(bottom + left, dx: 0.5em, dy: -0.5em, logo)
]
v(-15%)
align(center + horizon)[
#block(
inset: 1em,
breakable: false,
[
#text(2.5em)[*#title*] \
#{
if subtitle != none {
parbreak()
text(.9em)[#subtitle]
}
}
]
)
#v(-5%)
#set text(size: .8em)
#grid(
columns: (1fr,) * calc.min(authors.len(), 3),
column-gutter: 1em,
row-gutter: 1em,
..authors
)
#v(1em)
#date
]
})
logic.polylux-slide(content)
}
#let slide(title: none, body) = {
let header = align(top, locate( loc => {
let color = go-gopher-blue
let logo = none
let short-title = clean-short-title.at(loc)
show: block.with(stroke: (bottom: 1mm + color), width: 100%, inset: (y: .3em))
set text(size: .5em)
grid(
columns: (1fr, 1fr),
if logo != none {
set align(left)
set image(height: 4em)
logo
} else { box(height: 4em) },
if short-title != none {
align(horizon + right, grid(
columns: 1, rows: 1em, gutter: .5em,
short-title,
utils.current-section
))
} else {
align(horizon + right, utils.current-section)
}
)
}))
let footer = locate( loc => {
let color = go-gopher-blue
block(
stroke: ( top: 1mm + color ), width: 100%, inset: ( y: .3em ),
text(.5em, {
clean-footer.display()
h(1fr)
logic.logical-slide.display()
})
)
})
set page(
margin: ( top: 4em, bottom: 2em, x: 1em ),
header: header,
footer: footer,
footer-descent: 1em,
header-ascent: 1.5em,
)
let body = pad(x: .0em, y: .5em, body)
let content = {
show heading: it => text(go-gopher-blue, it)
if title != none {
heading(level: 2, title)
}
body
}
logic.polylux-slide(content)
}
#let outline-slide(title: none, body) = {
set page(
margin: ( top: 4em, bottom: 2em, x: 1em ),
footer-descent: 1em,
header-ascent: 1.5em,
fill: go-gradient(direction.ttb),
)
set text(white)
let body = pad(x: .0em, y: .5em, body)
let content = {
v(10%)
if title != none {
show heading: it => underline(stroke: 3pt + go-yellow, it)
heading(level: 2, title)
}
place(top, dy: -130pt, dx: 100%, rotate(180deg, clouds))
body
}
logic.polylux-slide(content)
}
#let focus-slide(background: teal, foreground: white, body) = {
set page(fill: background, margin: 2em)
set text(fill: foreground, size: 1.5em)
let content = { v(.1fr); body; v(.1fr) }
// logic.polylux-slide(align(horizon, body))
logic.polylux-slide(content)
}
#let new-section-slide(name) = {
set page(margin: 2em, fill: go-gradient(direction.ltr))
let content = locate( loc => {
let color = go-yellow
set align(center + horizon)
show: block.with(stroke: ( bottom: 1mm + color ), inset: 1em,)
set text(size: 1.5em, white)
strong(name)
utils.register-section(name)
})
logic.polylux-slide(content)
} |
|
https://github.com/Blezz-tech/math-typst | https://raw.githubusercontent.com/Blezz-tech/math-typst/main/test/test.typ | typst | #outline(indent: 12pt)
= 1. tikz
#import "@preview/cetz:0.1.2"
#show math.equation: block.with(fill: white, inset: 1pt)
#cetz.canvas(length: 4cm, {
import cetz.draw: *
set-style(
mark: (fill: black),
stroke: (thickness: 0.4pt, cap: "round"),
angle: (
radius: 0.3,
label-radius: .22,
fill: green.lighten(80%),
stroke: (paint: green.darken(50%))
),
content: (padding: 1pt)
)
grid((-1.5, -1.5), (1.4, 1.4), step: 0.5, stroke: gray + 0.2pt)
circle((0,0), radius: 1)
line((-1.5, 0), (1.5, 0), mark: (end: ">"))
content((), $ x $, anchor: "left")
line((0, -1.5), (0, 1.5), mark: (end: ">"))
content((), $ y $, anchor: "bottom")
for (x, ct) in ((-1, $ -1 $), (-0.5, $ -1/2 $), (1, $ 1 $)) {
line((x, 3pt), (x, -3pt))
content((), anchor: "above", ct)
}
for (y, ct) in ((-1, $ -1 $), (-0.5, $ -1/2 $), (0.5, $ 1/2 $), (1, $ 1 $)) {
line((3pt, y), (-3pt, y))
content((), anchor: "right", ct)
}
// Draw the green angle
cetz.angle.angle((0,0), (1,0), (1, calc.tan(30deg)),
label: text(green, [#sym.alpha]))
line((0,0), (1, calc.tan(30deg)))
set-style(stroke: (thickness: 1.2pt))
line((30deg, 1), ((), "|-", (0,0)), stroke: (paint: red), name: "sin")
content("sin", text(red)[$ sin alpha $], anchor: "right")
line("sin.end", (0,0), stroke: (paint: blue), name: "cos")
content("cos", text(blue)[$ cos alpha $], anchor: "top")
line((1, 0), (1, calc.tan(30deg)), name: "tan", stroke: (paint: orange))
content("tan", $ text(#orange, tan alpha) = text(#red, sin alpha) / text(#blue, cos alpha) $, anchor: "left")
})
= 2. Code
#import "@preview/codelst:1.0.0": sourcecode
#sourcecode[```hs
main :: IO
main = putStreLn "Hello world!"
```]
= 3. Таблицы истинности
#import "@preview/truthfy:0.2.0": generate-table, generate-empty
#generate-table($A and B$, $B or A$, $A => B$, $(A => B) <=> A$, $ A xor B$)
#generate-table($p => q$, $not p => (q => p)$, $p or q$, $not p or q$)
= 4. gviz
#import "@preview/gviz:0.1.0": *
#show raw.where(lang: "dot-render"): it => render-image(it.text)
```dot-render
digraph mygraph {
node [shape=box];
A -> B;
B -> C;
B -> D;
C -> E;
D -> E;
E -> F;
A -> F [label="one"];
A -> F [label="two"];
A -> F [label="three"];
A -> F [label="four"];
A -> F [label="five"];
}```
#let my-graph = "digraph {A -> B}"
= 5. easy-pinyin
#set text(font: "Noto Sans CJK SC")
#import "@preview/easy-pinyin:0.1.0": pinyin, zhuyin
汉(#pinyin[ha4n])语(#pinyin[yu3])拼(#pinyin[pi1n])音(#pinyin[yi1n])。
#let per-char(f) = [#f(delimiter: "|")[汉|语|拼|音][ha4n|yu3|pi1n|yi1n]]
#let per-word(f) = [#f(delimiter: "|")[汉语|拼音][ha4nyu3|pi1nyi1n]]
#let all-in-one(f) = [#f[汉语拼音][ha4nyu3pi1nyi1n]]
#let example(f) = (per-char(f), per-word(f), all-in-one(f))
// argument of scale and spacing
#let arguments = ((0.5, none), (0.7, none), (0.7, 0.1em), (1.0, none), (1.0, 0.2em))
#table(
columns: (auto, auto, auto, auto),
align: (center + horizon, center, center, center),
[arguments], [per char], [per word], [all in one],
..arguments.map(((scale, spacing)) => (
text(size: 0.7em)[#scale,#repr(spacing)],
..example(zhuyin.with(scale: scale, spacing: spacing))
)).flatten(),
)
= 6. IMBA
#import "@preview/bob-draw:0.1.0": *
#show raw.where(lang: "bob"): it => render(it)
#let svg = bob2svg("<--->")
#render("<--->")
#render(
```
0 3
*-------*
1 /| 2 /|
*-+-----* |
| |4 | |7
| *-----|-*
|/ |/
*-------*
5 6
```,
width: 25%,
)
```bob
"cats:"
/\_/\ /\_/\ /\_/\ /\_/\
( o.o )( o.o )( o.o )( o.o )
```
```bob
/\_/\ /\_/\ /\_/\ /\_/\
( o.o )( o.o )( o.o )( o.o )
```
= 7. Collout
#import "@preview/babble-bubbles:0.1.0": *
// #info[This is information]
// #success[I'm making a note here: huge success]
// #check[This is checked!]
// #warning[First warning...]
// #note[My incredibly useful note]
// #question[Question?]
// #example[An example make things interesting]
// #quote[To be or not to be]
= 8. math
$
a &=b & quad c&=d \
e &=f & g&=h
$
= 9. |
|
https://github.com/mitex-rs/mitex | https://raw.githubusercontent.com/mitex-rs/mitex/main/packages/mitex/specs/prelude.typ | typst | Apache License 2.0 | /// Define a normal symbol, as no-argument commands like \alpha
///
/// Arguments:
/// - s (str): Alias command for typst handler.
/// For example, alias `\prod` to typst's `product`.
/// - sym (content): The specific content, as the value of alias in mitex-scope.
/// For example, there is no direct alias for \negthinspace symbol in typst,
/// but we can add `h(-(3/18) * 1em)` ourselves
///
/// Return: A spec item and a scope item (none for no scope item)
#let define-sym(s, sym: none) = {
(
(kind: "alias-sym", alias: s),
if sym != none {
(alias: s, handle: sym)
} else {
none
},
)
}
/// Define a greedy command, like \displaystyle
///
/// Arguments:
/// - s (str): Alias command for typst handler.
/// For example, alias `\displaystyle` to typst's `mitexdisplay`, as the key in mitex-scope.
/// - handle (function): The handler function, as the value of alias in mitex-scope.
/// It receives a content argument as all greedy matches to the content
/// For example, we define `mitexdisplay` to `math.display`
///
/// Return: A spec item and a scope item (none for no scope item)
#let define-greedy-cmd(s, handle: none) = {
(
(kind: "greedy-cmd", alias: s),
if handle != none {
(alias: s, handle: handle)
} else {
none
},
)
}
/// Define an infix command, like \over
///
/// Arguments:
/// - s (str): Alias command for typst handler.
/// For example, alias `\over` to typst's `frac`, as the key in mitex-scope.
/// - handle (function): The handler function, as the value of alias in mitex-scope.
/// It receives two content arguments, as (prev, after) arguments.
/// For example, we define `\over` to `frac: (num, den) => $(num)/(den)$`
///
/// Return: A spec item and a scope item (none for no scope item)
#let define-infix-cmd(s, handle: none) = {
(
(kind: "infix-cmd", alias: s),
if handle != none {
(alias: s, handle: handle)
} else {
none
},
)
}
/// Define a glob (Global Wildcard) match command with a specified pattern for matching args
/// Kind of item to match:
/// - Bracket/b: []
/// - Parenthesis/p: ()
/// - Term/t: any rest of terms, typically {} or single char
///
/// Arguments:
/// - pat (pattern): The pattern for glob-cmd
/// For example, `{,b}t` for `\sqrt` to support `\sqrt{2}` and `\sqrt[3]{2}`
/// - s (str): Alias command for typst handler.
/// For example, alias `\sqrt` to typst's `mitexsqrt`, as the key in mitex-scope.
/// - handle (function): The handler function, as the value of alias in mitex-scope.
/// It receives variable length arguments, for example `(2,)` or `([3], 2)` for sqrt.
/// Therefore you need to use `(.. arg) = > {..}` to receive them.
///
/// Return: A spec item and a scope item (none for no scope item)
#let define-glob-cmd(pat, s, handle: none) = {
(
(kind: "glob-cmd", pattern: pat, alias: s),
if handle != none {
(alias: s, handle: handle)
} else {
none
},
)
}
/// Define a command with a fixed number of arguments, like \hat{x} and \frac{1}{2}
///
/// Arguments:
/// - num (int): The number of arguments for the command.
/// - alias (str): Alias command for typst handler.
/// For example, alias `\frac` to typst's `frac`, as the key in mitex-scope.
/// - handle (function): The handler function, as the value of alias in mitex-scope.
/// It receives fixed number of arguments, for example `frac(1, 2)` for `\frac{1}{2}`.
///
/// Return: A spec item and a scope item (none for no scope item)
#let define-cmd(num, alias: none, handle: none) = {
(
(
kind: "cmd",
args: ("kind": "right", "pattern": (kind: "fixed-len", len: num)),
alias: alias,
),
if handle != none {
(alias: alias, handle: handle)
} else {
none
},
)
}
/// Define an environment with a fixed number of arguments, like \begin{alignedat}{2}
///
/// Arguments:
/// - num (int): The number of arguments as environment options for the environment.
/// - alias (str): Alias command for typst handler.
/// For example, alias `\begin{alignedat}{2}` to typst's `alignedat`,
/// and alias `\begin{aligned}` to typst's `aligned`, as the key in mitex-scope.
/// - kind (str): environment kind, it could be "is-math", "is-cases", "is-matrix",
/// "is-itemize", "is-enumerate"
/// - handle (function): The handler function, as the value of alias in mitex-scope.
/// It receives fixed number of named arguments as environment options,
/// for example `alignedat(arg0: ..)` or `alignedat(arg0: .., arg1: ..)`.
/// And it receives variable length arguments as environment body,
/// Therefore you need to use `(.. arg) = > {..}` to receive them.
///
/// Return: A spec item and a scope item (none for no scope item)
#let define-env(num, kind: "none", alias: none, handle: none) = {
(
(
kind: "env",
args: if num != none {
(kind: "fixed-len", len: num)
} else {
(kind: "none")
},
ctx_feature: (kind: kind),
alias: alias,
),
if handle != none {
(alias: alias, handle: handle)
} else {
none
},
)
}
#let define-glob-env(pat, kind: "none", alias: none, handle: none) = {
(
(
kind: "glob-env",
pattern: pat,
ctx_feature: (kind: kind),
alias: alias,
),
if handle != none {
(alias: alias, handle: handle)
} else {
none
},
)
}
/// Define a symbol without alias and without handler function, like \alpha => alpha
///
/// Return: A spec item and no scope item (none for no scope item)
#let sym = ((kind: "sym"), none)
/// Define a symbol without alias and with handler function,
/// like \negthinspace => h(-(3/18) * 1em)
///
/// Arguments:
/// - handle (function): The handler function, as the value of alias in mitex-scope.
/// For example, define `negthinspace` to handle `h(-(3/18) * 1em)` in mitex-scope
///
/// Return: A symbol spec and a scope item
#let of-sym(handle) = ((kind: "sym"), (handle: handle))
/// Define a left1-op command without handler, like `\limits` for `\sum\limits`
///
/// Arguments:
/// - alias (str): Alias command for typst handler.
/// For example, alias `\limits` to typst's `limits`
/// and alias `\nolimits` to typst's `scripts`
///
/// Return: A cmd spec and no scope item (none for no scope item)
#let left1-op(alias) = ((kind: "cmd", args: (kind: "left1"), alias: alias), none)
/// Define a cmd1 command like \hat{x} => hat(x)
///
/// Return: A cmd1 spec and a scope item (none for no scope item)
#let cmd1 = ((kind: "cmd1"), none)
/// Define a cmd2 command like \binom{1}{2} => binom(1, 2)
///
/// Return: A cmd2 spec and a scope item (none for no scope item)
#let cmd2 = ((kind: "cmd2"), none)
/// Define a matrix environment without handler
///
/// Return: A matrix-env spec and a scope item (none for no scope item)
#let matrix-env = ((kind: "matrix-env"), none)
/// Receives a list of definitions composed of the above functions, and processes them to return a dictionary containing spec and scope.
#let process-spec(definitions) = {
let spec = (:)
let scope = (:)
for (key, value) in definitions.pairs() {
let spec-item = value.at(0)
let scope-item = value.at(1)
spec.insert(key, spec-item)
if scope-item != none {
if "alias" in scope-item and type(scope-item.alias) == str {
let key = if scope-item.alias.starts-with("#") {
scope-item.alias.slice(1)
} else {
scope-item.alias
}
scope.insert(key, scope-item.handle)
} else {
scope.insert(key, scope-item.handle)
}
}
}
(spec: spec, scope: scope)
}
|
https://github.com/hitszosa/universal-hit-thesis | https://raw.githubusercontent.com/hitszosa/universal-hit-thesis/main/lib.typ | typst | MIT License | #import "harbin/bachelor/lib.typ" as harbin-bachelor
#import "harbin/bachelor/lib.typ" as weihai-bachelor
#import "harbin/bachelor/lib.typ" as shenzhen-bachelor
#import "harbin/bachelor/lib.typ" as universal-bachelor
|
https://github.com/Cheng0Xin/typst-libs | https://raw.githubusercontent.com/Cheng0Xin/typst-libs/master/semantics/semantics.typ | typst | #let vspace-between-formula = 5pt
#let hspace-between-formula = 20pt
#let cons-obj(obj, styles) = if type(obj) == content {
let c-content = align(start+bottom)[#obj]
return (
text: c-content,
length: measure(c-content, styles).width,
)
} else if type(obj) == dictionary {
let up-content = cons-obj(obj.up, styles)
let down-content = cons-obj(obj.down, styles)
let label-size = if obj.keys().contains("label") {
measure(obj.label, styles).width
} else {
15pt
}
// let line-size = calc.max(up-content.length, down-content.length) + hspace-between-formula
let line-size = calc.max(up-content.length, down-content.length)
return (
label: if obj.keys().contains("label") {obj.label} else {[]},
up: up-content,
down: down-content,
line-length: line-size,
length: line-size + label-size
)
} else if type(obj) == array {
let result = obj.map((x) => cons-obj(x, styles))
let sum_result = result.fold(0pt, (acc, x) => { return acc + x.length })
return (
array: result,
length: sum_result + (result.len() - 1) * hspace-between-formula,
)
}
#let linewithlabel(length, name, style) = {
let xdir = measure(name, style).width + 2pt
line(length: length)
place(
dy: -5pt,
dx: -xdir,
align(right+horizon, text(name))
)
}
#let generate(obj, style) = {
if obj.keys().contains("text") {
obj.text
} else if obj.keys().contains("array") {
stack(dir:ltr, spacing: hspace-between-formula, ..obj.array.map((x)=> generate(x, style)))
} else if obj.keys().contains("up") {
stack(dir:ttb, spacing: vspace-between-formula,
align(center+bottom, generate(obj.up, style)),
v(vspace-between-formula),
linewithlabel(obj.line-length, obj.label, style),
v(vspace-between-formula),
align(center+bottom, generate(obj.down, style)),
)
}
}
#let rule(obj) = style(s => {
let c-obj = cons-obj(obj, s)
block(
breakable: false,
generate(c-obj, s)
)
})
|
|
https://github.com/Ttajika/class | https://raw.githubusercontent.com/Ttajika/class/main/microecon/main.typ | typst | #import "quiz_bank.typ":*
#show heading: set text(font: "<NAME>", fill: gradient.linear(..color.map.crest))
#set heading(numbering: "1.")
#set page(numbering: "1")
#set text(font: "<NAME>", lang:"ja")
#set par(leading: 1em, first-line-indent: 1em)
#show math.equation: set text(font: "TeX Gyre Pagella Math")
#show strong: set text(fill:maroon.darken(30%))
#show strong: set text(font: "<NAME>")
#let kuran_count = counter("kuran_counter")
//問題自体は[quiz_bank.typ]に格納する.
#align(center)[ #text(size:18pt,font: "<NAME>", weight: "bold", fill: gradient.linear(..color.map.crest))[基礎ミクロ経済学 問題集]\
多鹿 智哉 \@ 日本大学 経済学部
]
//問題の具体的なsourceはquiz_bank.typを参照すること
= 意思決定と市場均衡
#tests_gen(Quiz,style:"Q", numbering-style: "number", subgroups:("Q11", "Q3"), categories:("Term1",), mode:"cat", question-style: test-question-style, answer-style: test-answer-style)
= 消費者の理論
#tests_gen(Quiz,style:"Q", numbering-style: "number", subgroups:("Q11", "Q3"), categories:("Term2",), mode:"cat", question-style: test-question-style, answer-style: test-answer-style)
= 生産者の理論
#tests_gen(Quiz,style:"Q", numbering-style: "number", subgroups:("Q11", "Q3"), categories:("Term3",), mode:"cat", question-style: test-question-style, answer-style: test-answer-style)
= 一般均衡理論
#tests_gen(Quiz,style:"Q", numbering-style: "number", subgroups:("Q11", "Q3"), categories:("Term4",), mode:"cat", question-style: test-question-style, answer-style: test-answer-style)
// \
// #tests_gen(Quiz,style:"Q", numbering-style: "number", subgroups:("Q11", "Q3"), categories:(), mode:"sub", question-style: test-question-style, answer-style: test-answer-style)
// それぞれの変数の説明
// - Quiz: quiz_bank.typでつくった問題のリスト. 形式に従った問題のリストであればなんでも良い.形式については[quiz_bank.typ]を参照のこと
// - style: str型をとる. "Q" or "A" or "both" or "Q-A"
// - numbering-style: "number" or "id"
// - subgroups: idのリストを指定して, modeを"sub"に指定するとリストにあるidに対応する問題を出力する.
// - categories: categoryのリストを指定して, modeを"cat"に指定するとカテゴリーが指定したものに対応する問題を出力する
// - mode: デフォルトは""で,これは全ての問題を出力する. "sub"でsubgoupsで指定したidリスト,"cat"でカテゴリーで指定したものに限定して出力する.
// - question-style: 問題の出力のスタイル. いまのところ default-quiz-styleとtest-question-style, および test-question-style-no-spaceの3種類
// - answer-style: 解答の出力のスタイル. いまのところ default-answer-styleとtest-answer-styleの2種類
// = ランダムテスト
// \
// #let seed = datetime.today().year() * datetime.today().month() * datetime.today().day()
// //seedには適当な数字を入れる.現状は日付を利用する
// #random_test(Quiz,style:"Q", size:3, numbering-style: "number", subgroups:(), categories:(), mode:"", question-style: test-question-style-no-space, answer-style: test-answer-style, seed:seed)
// ランダムに問題を出力する
// 基本はtests_genと同じ
// - size: 出力する問題の数を指定する
// - seed:問題を選ぶための乱数のシード.デフォルトは今日の日付(ymd)の積(y*m*d). シードが同じなら乱数も同じ.
// //#pagebreak()
// = 解答欄も作ることができる.
// #import "answer_box.typ":*
// #ansbox(1,2,3)
// #ansbox(3,2,2, daimon:none, shomon:"問1.", shomon_width:4em, shomon_start:7, content:([],[],[],[],[],[#image("img/patterns.png",width:100%)],[文字の大きさ]), box_width:(2cm,1fr,auto), height:(1cm,2cm,auto), hideanswer:true)
// #counter(figure.where(kind:"answerbox")).update(13)
// #ansbox(3, daimon:"問1.", daimon_width:4em)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/paddling-tongji-thesis/0.1.1/init-files/sections/acknowledgments.typ | typst | Apache License 2.0 | #import "@preview/paddling-tongji-thesis:0.1.1": *
#heading("谢辞", numbering: none)
#empty-par()
本节通常用于感谢在研究过程中给予帮助和支持的人们,例如指导老师、实验室同学、朋友和家人等。
在谢辞中,需要真诚地表达感谢之情,回顾一下在研究过程中所受到的帮助和支持,并提到他们的具体贡献和重要性。同时,也可以简要说明一下自己在研究过程中的收获和体会,表达对他们的感激之情和祝福。
最后,需要注意不要出现太多的感情用词,语言简洁明了,表达真诚和诚恳即可。
谢谢支持本项目的所有朋友们。并且希望选用该模板的朋友们都能顺利通过查重与答辩。
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/string-18.typ | typst | Other | // Test the `trim` method.
#let str = "Typst, LaTeX, Word, InDesign"
#let array = ("Typst", "LaTeX", "Word", "InDesign")
#test(str.split(",").map(s => s.trim()), array)
#test("".trim(), "")
#test(" abc ".trim(at: start), "abc ")
#test(" abc ".trim(at: end, repeat: true), " abc")
#test(" abc".trim(at: start, repeat: false), "abc")
#test("aabcaa".trim("a", repeat: false), "abca")
#test("aabca".trim("a", at: start), "bca")
#test("aabcaa".trim("a", at: end, repeat: false), "aabca")
#test("".trim(regex(".")), "")
#test("123abc456".trim(regex("\d")), "abc")
#test("123abc456".trim(regex("\d"), repeat: false), "23abc45")
#test("123a4b5c678".trim(regex("\d"), repeat: true), "a4b5c")
#test("123a4b5c678".trim(regex("\d"), repeat: false), "23a4b5c67")
#test("123abc456".trim(regex("\d"), at: start), "abc456")
#test("123abc456".trim(regex("\d"), at: end), "123abc")
#test("123abc456".trim(regex("\d+"), at: end, repeat: false), "123abc")
#test("123abc456".trim(regex("\d{1,2}$"), repeat: false), "123abc4")
#test("hello world".trim(regex(".")), "")
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.0/src/complex.typ | typst | Apache License 2.0 | // Real and imaginary part
#let re(V) = V.at(0)
#let im(V) = V.at(1)
// Complex multiplication
#let mul(V,W) = (re(V)*re(W) - im(V)*im(W),im(V)*re(W) + re(V)*im(W))
// Complex conjugate
#let conj(V) = (re(V),-im(V))
// Dot product of V and W as vectors in R^2
#let dot(V,W) = re(mul(V,conj(W)))
// Norm and norm-squared
#let normsq(V) = dot(V,V)
#let norm(V) = calc.sqrt(normsq(V))
// V*t
#let scale(V,t) = mul(V,(t,0))
// Unit vector in the direction of V
#let unit(V) = scale(V, 1/norm(V))
// V^(-1) as a complex number
#let inv(V) = scale(conj(V), 1/normsq(V))
// V / W
#let div(V,W) = mul(V,inv(W))
// V + W and V - W
#let add(V,W) = (re(V) + re(W),im(V) + im(W))
#let sub(V,W) = (re(V) - re(W),im(V) - im(W))
// Argument
#let arg(V) = calc.atan2(..V) / 1rad
// Signed angle from V to W
#let ang(V,W) = arg(div(W,V))
// exp(i*a)
#let expi(a) = (calc.cos(a),calc.sin(a))
// Rotate by angle a
#let rot(v,a) = mul(v,expi(a))
|
https://github.com/SavaGlavan/homework_template | https://raw.githubusercontent.com/SavaGlavan/homework_template/main/template.typ | typst | MIT License | #let apply-template(body, name: "", class: "", term: "", title: "") = {
set page(
paper: "us-letter",
header: [
#text(class)
#h(1fr)
#text(term)\
#text(title)
#h(1fr)
#text(name)
#line(length: 100%)
],
margin: (
left: 1cm,
right: 1cm,
),
numbering: "1",
)
set enum(full: true, numbering: (..n) => {
let a = n.pos().len()
while a > 3{
a -= 3
}
let format = if a > 2 {"i)"} else if a > 1 {"a."} else {"1."}
numbering(format, n.pos().last())
})
body
}
|
https://github.com/Gekkio/gb-ctr | https://raw.githubusercontent.com/Gekkio/gb-ctr/main/timing.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "common.typ": cetz, monotext, hex
#let clock = (len, ..args) => (type: "C", len: len, ..args.named())
#let data = (len, label, ..args) => (type: "D", len: len, label: label, ..args.named())
#let either = (len, ..args) => (type: "E", len: len, ..args.named())
#let high = (len, ..args) => (type: "H", len: len, ..args.named())
#let low = (len, ..args) => (type: "L", len: len, ..args.named())
#let unknown = (len, ..args) => (type: "U", len: len, ..args.named())
#let undefined = (len, ..args) => (type: "X", len: len, ..args.named())
#let high_impedance = (len, ..args) => (type: "Z", len: len, ..args.named())
#let diagram = (..args, w_scale: 1.0, y_scale: 1.0, grid: false, fg: () => none) => {
cetz.canvas(length: 0.7em, {
import cetz.draw
let x_slope = 0.15 * w_scale;
let y_step = 2 * y_scale
let y_level = (H: 1.0 * y_scale, L: 0.0 * y_scale, M: 0.5 * y_scale)
draw.set-style(stroke: (thickness: 0.07em))
let resolve_level = (prev_state, event) => if event.type == "C" {
if prev_state.level == "L" { "H" } else { "L" }
} else if ("L", "H", "E").contains(event.type) {
event.type
} else if ("Z", "X", "D", "U").contains(event.type) {
"M"
}
let invert_level = (level) => if level == "L" { "H" }
else if level == "H" { "L" }
else { level }
let draw_event = (prev_state, event, next_type) => {
let opacity = 100% - (if "opacity" in event { event.opacity } else { 100% })
let fg_paint = (if event.type == "X" { red }
else if event.type == "Z" { blue }
else { black }
).lighten(opacity)
let fg_opts = (stroke: if "stroke" in event { event.stroke } else { (paint: fg_paint) })
let x_start = if ("D", "U").contains(prev_state.type) { x_slope } else { 0.0 }
let x_end = event.len * w_scale
if event.type == "L" or event.type == "H" {
let y = y_level.at(event.type)
let y_invert = y_level.at(invert_level(event.type))
if prev_state.level == event.type or prev_state.level == "" {
draw.line((x_start, y), (x_end, y), ..fg_opts)
} else if prev_state.level == "E" {
draw.line((x_start, y_invert), (x_start + x_slope, y), ..fg_opts)
draw.line((x_start, y), (x_end, y), ..fg_opts)
} else if prev_state.level == "M" {
draw.line((x_start, y_level.M), (x_start + x_slope, y), (x_end, y), ..fg_opts)
} else if prev_state.level == invert_level(event.type) {
draw.line((x_start, y_invert), (x_start + x_slope, y), (x_end, y), ..fg_opts)
}
} else if event.type == "C" {
if prev_state.level == "L" or prev_state.level == "H" {
let prev_y = y_level.at(prev_state.level)
let y = y_level.at(invert_level(prev_state.level))
draw.line((x_start, prev_y), (x_start, y), (x_end, y), ..fg_opts)
} else if prev_state.level == "E" {
draw.line((x_start, y_level.H), (x_start + x_slope, y_level.L), ..fg_opts)
draw.line((x_start, y_level.L), (x_end, y_level.L), ..fg_opts)
} else if prev_state.level == "M" {
draw.line((x_start, y_level.M), (x_start + x_slope, y_level.L), (x_end, y_level.L), ..fg_opts)
} else if prev_state.level == "" {
draw.line((x_start, y_level.L), (x_end, y_level.L), ..fg_opts)
}
} else if event.type == "E" {
if prev_state.level == "L" or prev_state.level == "M" {
let y = y_level.at(prev_state.level)
draw.line((x_start, y), (x_start + x_slope, y_level.H), (x_end, y_level.H), ..fg_opts)
} else {
draw.line((x_start, y_level.H), (x_end, y_level.H), ..fg_opts)
}
if prev_state.level == "H" or prev_state.level == "M" {
let y = y_level.at(prev_state.level)
draw.line((x_start, y), (x_start + x_slope, y_level.L), (x_end, y_level.L), ..fg_opts)
} else {
draw.line((x_start, y_level.L), (x_end, y_level.L), ..fg_opts)
}
} else if event.type == "X" or event.type == "Z" {
if prev_state.level == "L" or prev_state.level == "H" {
let y = y_level.at(prev_state.level)
draw.line((x_start, y), (x_start + x_slope, y_level.M), (x_end, y_level.M), ..fg_opts)
} else if prev_state.level == "M" or prev_state.level == "" {
draw.line((x_start, y_level.M), (x_end, y_level.M), ..fg_opts)
} else if prev_state.level == "E" {
draw.line((x_start, y_level.H), (x_start + x_slope, y_level.M))
draw.line((x_start, y_level.L), (x_start + x_slope, y_level.M))
draw.line((x_start + x_slope, y_level.M), (x_end, y_level.M), ..fg_opts)
}
} else if event.type == "D" or event.type == "U" {
let x_start = if ("X", "Z", "").contains(prev_state.type) { 0.0 } else { x_slope }
let x_end = event.len * w_scale + x_slope
let fill = if event.type == "U" { gray } else if "fill" in event { event.fill.lighten(opacity) } else { none }
let left-open = prev_state.level == ""
let right-open = next_type == ""
if left-open and right-open {
if fill != none {
draw.rect((x_start, y_level.L), (x_end, y_level.H), stroke: none, fill: fill)
}
draw.line((x_start, y_level.H), (x_end, y_level.H), ..fg_opts)
draw.line((x_start, y_level.L), (x_end, y_level.L), ..fg_opts)
} else {
if prev_state.level == "H" or prev_state.level == "E" {
draw.line((0.0, y_level.H), (x_slope, y_level.M), ..fg_opts)
}
if prev_state.level == "L" or prev_state.level == "E" {
draw.line((0.0, y_level.L), (x_slope, y_level.M), ..fg_opts)
}
let points = ()
if left-open {
points.push((x_start, y_level.H))
points.push((x_end - x_slope, y_level.H))
points.push((x_end, y_level.M))
points.push((x_end - x_slope, y_level.L))
points.push((x_start, y_level.L))
} else if right-open {
points.push((x_end, y_level.H))
points.push((x_start + x_slope, y_level.H))
points.push((x_start, y_level.M))
points.push((x_start + x_slope, y_level.L))
points.push((x_end, y_level.L))
} else {
points.push((x_start, y_level.M))
points.push((x_start + x_slope, y_level.H))
points.push((x_end - x_slope, y_level.H))
points.push((x_end, y_level.M))
points.push((x_end - x_slope, y_level.L))
points.push((x_start + x_slope, y_level.L))
points.push((x_start, y_level.M))
}
draw.line(..points, ..fg_opts, fill: fill)
}
}
draw.anchor("center", ((x_end - x_start) / 2.0 + x_start, y_level.M))
if "label" in event {
draw.content("center", text(0.5em, fill: black.lighten(opacity), event.label))
}
draw.translate((event.len * w_scale, 0))
}
let lanes = args.pos().rev()
draw.group(name: "labels", {
for i in range(0, lanes.len()) {
let lane = lanes.at(i)
draw.content((0, i * y_step + 0.5 * y_scale), anchor: "east", lane.label)
}
})
draw.group(name: "diagram", ctx => {
let (ctx, east) = cetz.coordinate.resolve(ctx, "labels.east")
let (x, _, _) = east;
draw.translate((x + 1, 0))
draw.group(ctx => {
for i in range(0, lanes.len()) {
let lane = lanes.at(i)
draw.group(ctx => {
draw.anchor("west", (0.0, y_level.L))
let prev_state = (level: "", type: "")
for i in range(lane.wave.len()) {
let event = lane.wave.at(i)
let next_type = if i + 1 < lane.wave.len() { lane.wave.at(i + 1).type } else { "" }
draw_event(prev_state, event, next_type)
prev_state.level = resolve_level(prev_state, event)
prev_state.type = event.type
}
draw.anchor("east", (0.0, y_level.H))
if grid {
draw.on-layer(-1, {
draw.grid("west", "east", step: (x: 0.5 * w_scale, y: 0.5 * y_scale), stroke: (paint: gray.lighten(60%), thickness: 0.01em))
})
}
})
draw.translate((0, y_step))
}
})
fg()
})
})
}
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/single-elem-destruct.typ | typst | Apache License 2.0 | #let (num,) = (1,)
#num
#let (((num,),),) = (((1,),),)
#num
#let (_,) = (((1,),),)
#let ((num),) = (1,)
#num
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/utils.typ | typst | #let section(name) = {
align(center, [#heading(numbering: "1.1.1.", level: 1, name)])
line(length: 100%)
}
#let subsection(name) = {
align(center, [#heading(numbering: "1.1.1.", level: 2, name)])
line(length: 100%)
}
#let subsubsection(name) = {
align(center, [#heading(numbering: "1.1.1.", level: 3, name)])
line(length: 100%)
}
#let subsubsubsection(name) = {
align(center, [#heading(numbering: "1.1.1.", level: 4, name)])
line(length: 100%)
}
|
|
https://github.com/dark-flames/resume | https://raw.githubusercontent.com/dark-flames/resume/main/main-cv.typ | typst | MIT License | #import "resume.typ": *
#resume((
x-lang: "en",
x-version: "cv"
)) |
https://github.com/Lelidle/Q12-cs-scripts | https://raw.githubusercontent.com/Lelidle/Q12-cs-scripts/main/languages.typ | typst | #import "template.typ": *
#show: setup
#set enum(numbering: (..args) => strong(numbering("1.", ..args))) // in Aufzählungen Zahlen fett
#set heading (
numbering: "1."
)
#v(1fr)
#align(center)[#text(32pt)[Formale Sprachen \ #align(center)[#image("images/chomsky.png", width: 80%)]]]
#v(1fr)
#pagebreak()
#set page(
header: align(right)[
Formale Sprachen Skript 2inf1 \
],
numbering: "1"
)
#show outline.entry.where(
level: 1
): it => {
v(12pt, weak: true)
strong(it)
}
#outline(title: "Inhaltsverzeichnis", indent: auto)
#pagebreak()
= Sprachen
== Einleitung
Auf den ersten Blick erscheint es etwas rätselhaft, warum sich die Informatik mit der Sprachlehre beschäftigen sollte. Auf den zweiten Blick wird dies aber schon klarer, da es nicht umsonst um *Programmiersprachen* genannt wird.
Jede Sprache hat ihre eigene *Syntax* und es steckt eine gewisse *Semantik* hinter den Begriffen, beide Begriffe werden im Folgenden noch ausführlich besprochen.
Die formalen Sprachen sind ein wichtiges Teilgebiet der *theoretischen Informatik*, d.h. in diesem Schuljahr stehen weniger die praktischen Dinge im Vordergrund, sondern der theoretische Unterbau.
Die Sprachentheorie kommt in vielen Bereichen der Informatik zum Einsatz, insbesondere aber in einem der zentralsten Bereiche, dem *Compilerbau*. Einer Programmiersprache liegt eine sogenannte *Grammatik* zugrunde, die letztendlich festlegt was ein "gültiges Programm" (d.h. syntaktisch korrekt!) darstellt. Der Compiler muss also einerseits diese Struktur überprüfen, andererseits dann eine Übersetzung in Maschinensprache oder eine andere Programmiersprache vornehmen.
Ein (sehr grober) Überblick über die Funktionsweise eines Compilers wäre also:
1. *Syntaxanalyse*: Der Compiler nutzt die formalen Regeln der Sprache, um den Quellcode syntaktisch zu analysieren, d.h. es wird geklärt: "Handelt es sich um ein korrektes Programm".
2. *Semantische Analyse*: Es existieren in der Regel auch weitere formale Regeln, die die *Bedeutung* (Semantik) des Programms überprüfen sollen. Das geht natürlich nicht vollständig, aber beispielsweise können die zulässigen Bereiche von Variablen oder die korrekte Verwendung von Typen ("starke Typisierung von Java" z.B.!) überprüft werden.
3. *Übersetzung und Optimierung*: Viele Compiler optimieren den geschriebenen Code und erstellen eine _Zwischendarstellung_, um die Performance zu steigern.
4. *Codegenerierung*: Zuletzt muss die optimierte Darstellung noch in den tatsächlich von der Maschine ausführbaren Code überführt werden. (oder alternativ in die Darstellung der Ziel-Programmiersprache)
#hinweis[
Da es sich bei diesem Thema um ein sehr schwieriges handelt - es gibt mehrere Vorlesungen, die sich ausschließlich damit im Studium beschäftigen - können wir in der Schule nur eine sehr abgespeckte Variante dieser Theorien behandeln, die sich in der Regel nicht auf Programmiersprachen, sondern auf andere Ausdrücke bezieht, die nach bestimmten Regeln aufgebaut werden, z.B. Email-Adressen, ISBN-Nummern, Autokennzeichen, etc.]
Das folgende Unterkapitel klärt zunächst grundlegende Begriffe etwas genauer.
#pagebreak()
== Grundlagen
Zunächst muss definiert werden, was eine formale Sprache eigentlich sein soll:
#definition[Eine formale Sprache $L$ besteht aus einer Menge von *Zeichenketten (Wörtern)* eines *Alphabets $Sigma$*, das alle benutzbaren *Zeichen (Token)* beinhaltet.
Kurz: $L subset.eq Sigma^*$]
Der Ausdruck *$Sigma^*$* ist eine Kurzschreibweise für alle möglichen Wörter, die aus einem Alphabet gebildet werden können. Besteht das Alphabet z.B. nur aus einem einzigen Buchstaben $Sigma = {a}$, so könnten die folgenden Wörter damit gebildet werden:
$ Sigma^* = {epsilon, a, a\a, a\a\a, dots.down} $
Dabei steht *$epsilon$* für das "leere Wort" (kein Leerzeichen, sondern einfach "kein Wort", so wie in Java "" einem leeren String entspricht - es ist offiziell zwar eine Zeichenkette, enthält aber kein Zeichen!). in $Sigma^*$ stecken also *alle* möglichen Wörter. Unsere formale Sprache muss aber nicht alle enthalten. Wir könnten z.B. die Sprache definieren, die nur eine geradzahlige Anzahl an $a$'s enthält, also:
$ L = {epsilon, a\a, a\a\a\a, dots.down} $
Und offensichtlich gilt $L subset.eq Sigma^*$
*Weitere Beispiele*:
1. *Natürliche Sprachen*: Am Beispiel Deutsch. Unser Alphabet besteht aus den folgenden Zeichen: $ Sigma = {"a"; dots.down; "z"; "A"; dots.down; "Z"; "ä";"Ä";"ö";"Ö";"ü";"Ü";"ß";"!";"\";\"";",";".";":";"Leerzeichen"} $ $Sigma^*$ ist dann die Menge aller möglichen Zeichenketten, allerdings gehören nicht alle zu unserer Sprache! #grid(columns:(50%, 50%),
rows:(auto),
gutter: 5pt,
[#align(center)[#text(green)[*Gehören zur Sprache*]
Informatik
Pizza
Das ist ein deutscher Satz!]],
[#align(center)[#text(red)[*Gehören nicht zur Sprache*]
Infom
Pazzizo
sjg aksjdfkajs aksjkkii!]]
) Die Analyse natürlicher Sprachen beschäftigt Linguisten schon lange, bisher entziehen sich diese aber einer strengen formalen Klassifikation - d.h. die Regeln für die Bildung deutscher, englischer, französischer und anderer Sprachen sind nicht eindeutig bzw. nicht vollständig bekannt (wenig überraschend!). Wir werden uns mit schöneren (d.h. eindeutigeren) *künstlichen* Sprachen beschäftigen.
2. *ISBN-Nummern*: Buchnummern bestehen aus fünf-Zahlengruppen, z.B.: $ 978-3-86680-192-9 $ Dabei gibt es natürlich auch gewisse Regeln, die dritte fünfstellige Nummer bezeichnet den Verlag, d.h. nicht jede fünfstellige Zahl existiert als Verlagsnummer.
#merke[An diesem Beispiel lässt sich der Unterschied zwischen *syntaktisch* und *semantisch* gut herausarbeiten:
1. Das "Wort" $999$ ist nicht Teil der Sprache, weil es *syntaktisch* falsch ist, es ist keine dreizehnstellige Zahl.
2. Das Wort $978-3-99999-192-9$ ist nicht Teil der Sprache, weil es die entsprechende Verlagsnummer nicht gibt. Es erfüllt *semantisch* nicht die Voraussetzungen, d.h. aufgrund der *Bedeutung*.]
3. *Autokennzeichen*: z.B.: NM-AB 34. Offensichtlich ist nicht jede Zeichenkette auch ein existierendes (oder mögliches) Autokennzeichen.#hinweis[Ersteres ist natürlich wieder nichts, was man einfach formalisieren kann. Die Behandlung von syntaktischen Fehlern ist natürlich wesentlich einfacher als die Behandlung von semantischen Fehlern - anders gesagt: es ist vergleichsweise einfach zu entscheiden, ob ein Programm korrekt geschrieben ist (Syntax), aber weniger leicht zu entscheiden, ob es tut was es soll (Semantik).
*Für Profis*: Streng genommen können beide Probleme natürlich nicht entscheidbar sein, siehe letztes Kapitel dieses Schuljahr und #link("https://de.wikipedia.org/wiki/Satz_von_Rice")[Satz von Rice].]
4. *Mathematische Terme*: Selbsterklärend, Terme werden in der 7. Klasse im Wesentlichen sogar als "sinnvolle Aneinanderreihung von Zahlen, Variablen und Operationen" definiert. D.h. $ 2x + 3 +7$ gehört zur Sprache, 2+++5 dagegen nicht.
5. *Viele weitere Beispiele*: Chemische Reaktionsgleichungen, Adressen, Nuklidschreibweise, Notation von Schachbewegungen, Geografische Koordinaten, Chat-Ausdrücke/Smileys, Barcodes, Steno, Raumnummern, Musiknoten, Telefonnummern, IP-Adressen, Morsecode, Militärische Handzeichen, Programmiersprachen etc.
Im Folgenden beschäftigen wir uns mit der Systematik, wie die *Regeln* für Sprachen beschrieben werden können, d.h.: wie können wir beschreiben, welche Wörter zu einer Sprache gehören und welche nicht - und das führt direkt zum Begriff der *Grammatik*.
#pagebreak()
= Grammatiken
== Grundlagen
Auch bei natürlichen Sprachen werden die Regeln zur Bildung von Sätzen durch Grammatiken festgelegt. Bei "künstlichen" Sprachen ist dies ähnlich, jedoch etwas systematischer als die "gewachsenen" natürlichen Sprachen.
Ein offensichtliches Problem der Beschreibung von allgemeinen Sprachen ist, dass eine Sprache unendlich viele korrekte Zeichenketten haben kann, trotz eines endlichen Alphabets (z.B. die Sprache aller Zeichenketten, die nur eine geradzahlige Anzahl an a's haben!).
Die Lösung sind *(endlich) viele Produktionsregeln*, die die Bildung dieser möglichen Worte beschrieben. Die Produktionsregeln zusammen mit dem Alphabet bilden dann die *Grammatik* einer Sprache.
*Das zu einfache Beispiel*:
Wir wollen die Sprache aller einstelligen Zahlen, sprich die Sprache der Ziffern definieren. Das zugrunde liegende Alphabet ist also $Sigma = {0, 1, dots.down, 9}$. Die zugehörige Produktionsregel wird wie folgt notiert:
#let ziffer = [#text(red)[Ziffer]]
#let ersteZiffer = [#text(blue)[ErsteZiffer]]
#let ziffern = [$"'1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' "$]
#let ziffern0 = [$"'0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' "$]
#let E = [#text(orange)[E]]
#let Z = [#text(red)[Z]]
#let N = [#text(blue)[N]]
#prodRules(
content: (
[#ziffer], [#ziffern0]
)
)
Diese Regel besteht aus:
1. einer *linken Seite*, hier steht ein *Nichtterminalsymbol*, d.h. ein Symbol, das nicht zum Alphabet gehört, sondern nur eine "Beschreibung" darstellt (das wird beim nächsten Beispiel deutlicher).
2. Zeichen des Alphabets (sogenannte *Terminalsymbole*) in Apostrophen - das sind die Zeichen des Alphabets, die wir mit dieser Regel "*produzieren*" können.
3. senkrechten Strichen $|$, die ein "oder" darstellen.
Die obige Regel kann also so interpretiert werden:
Das Nichtterminal "#ziffer" kann mit irgendeiner Ziffer von 0 bis 9 ersetzt werden.
Das sieht bisher noch nicht besonders nützlich aus, deswegen:
*Ein etwas komplexeres Beispiel*:
Als nächstes sollen alle dreistelligen Zahlen gebildet werden können. Man kann also eine ähnliche Regel wie oben benutzen, muss aber sicherstellen, dass die erste Ziffer keine $0$ ist, da es sonst keine dreistellige Zahl wäre:
#prodRules(
content:(
[#text(green)[Zahl]], [#text(blue)[ErsteZiffer] #ziffer #ziffer ],
[#ersteZiffer], [#ziffern],
[#ziffer], [#ersteZiffer | '0' ]
)
)
Die erste Zeile besteht dieses Mal nur aus Nichtterminalsymbolen und beschreibt die Struktur der Zahlen komplett, die übrigen Zeilen legen dann fest, welche Terminale, sprich welche Ziffern, in den einzelnen Schritten ersetzt werden dürfen.
In der dritten Regel greifen wir dabei wieder auf die zweite Regel zurück, um Schreibarbeit zu sparen.
#hinweis[Insbesondere in schriftlichen Prüfungen muss eindeutig sein, ob eine Zeichenkette *ein* oder *zwei* Nichtterminale darstellt. Im späteren Verlauf ist es üblich die Nichtterminalsymbole abzukürzen, man würde hier z.B. *E* für die ErsteZiffer nehmen und *Z* für die Ziffer. Der Ausdruck *EZ* und *E Z* kann dann aber durchaus unterschiedliche Bedeutung haben, wenn es noch eine weitere Regel mit *$\E\Z -> dots.c$* gibt.
*Quintessenz*: leserlich und eindeutig schreiben, deutliche Leerzeichen einbauen!
]
*Das noch komplexere Beispiel*:
#let zahl = [#text(green)[Zahl]]
#let gerade = [#text(purple)[gerade]]
#let ungerade = [#text(orange)[ungerade]]
Als letztes soll die Sprache aller dreistelligen Zahlen gebildet werden, die mit einer geraden Zahl starten und mit einer ungeraden Zahl enden, das zugehörige Alphabet sind wieder die Ziffern. Das können wir beispielsweise mit folgenden Regeln darstellen:
#prodRules(
content: (
[#zahl], [#gerade #ziffer #ungerade],
[#gerade], [$"'2' | '4' | '6' | '8'" $],
[#ungerade], [$"''1 | '3' | '5' | '7' | '9'" $],
[#ziffer], [#gerade | #ungerade]
)
)
Für ein bestimmtes Wort der Sprache können wir eine *Ableitung* (hat nichts mit der mathematischen Funktion zu tun!) angeben, d.h. eine Folge an Produktionsregeln, die aus dem Startsymbol (hier #zahl) das gesuchte Wort durch Ersetzungen bildet, z.B. wird die Zahl 211 wie folgt gebildet:
$ #zahl &->^((1)) #gerade #ziffer #ungerade ->^((2)) 2 #ziffer #ungerade\ &->^((4)) 2 #ungerade #ungerade
->^((3)) 2 1 #ungerade ->^((3)) 2 1 1 $
Ist eine Zeichenfolge, bzw. hier Zahl nicht in der Sprache, so können wir keine entsprechende Reihenfolge finden.
Eine alternative Darstellung ist der sogenannte *Ableitungsbaum* (oder auch *Syntaxbaum*, für das obige Beispiel:
#align(center)[
#figure(
image("images/syntaxbaum.png", width: 60%),
caption: [Erstellt mit #link("https://flaci.com/")[Flaci]]
)
]
Die Wurzel des Baums ist das *Startsymbol*. Die jeweiligen Kinder des Knotens ergeben sich durch Anwendung einer Regel.
Es gilt außerdem:
- jedes Blatt muss ein *Terminalsymbol* sein.
- jeder innere Knoten muss ein *Nichtterminalsymbol* sein.
Zusammengefasst:
#definition[Eine *Grammatik* einer formalen Sprache wird definiert durch vier verschiende Eigenschaften bzw. Objekte:
1. *Vokabular V*: endliche Menge von Nichtterminalsymbolen.
2. *Alphabet $Sigma$*: eine Menge von Zeichen/Terminalsymbolen.
3. *Startsymbol S*: das Startsymbol der Ableitung.
4. *Produktionsregeln P*: Regeln der Form: $ "<Nr.>: " <"Nichtterminal"> -> <"wird ersetzt durch"> $
Kurz: G = (V, $Sigma$, P, S)]
#hinweis(customTitle: "Hinweise")[1. Unsere Notation der Produktionsregeln orientiert sich an dem, was oft in Schulbüchern angegeben ist. Eine alternative ist die sogenannte erweiterte Backus-Naur-Form, kurz *EBNF*, siehe z.B. #link("https://de.wikipedia.org/wiki/Erweiterte_Backus-Naur-Form")[hier]. Dazu später mehr.
2. Streng genommen können mit der angegebenen Form an Produktionsregeln nicht alle formalen Sprachen angegeben werden, dazu mehr im Exkurs zu #link(<ChomskyHierarchie>)[Chomsky].]
Das noch komplexere Beispiel von oben würde also vollständig so angegeben werden:
$ G &=( {#zahl, #text(green)[gerade], #text(blue)[Ziffer], #text(orange)[ungerade]} \
&{0,1,2,3,4,5,6,7,8,9}, \
#prodRules(
content: (
[#zahl], [#gerade #ziffer #ungerade],
[#gerade], [$"'0' | '2' | '4' | '6' | '8'" $],
[#ungerade], [$"''1 | '3' | '5' | '7' | '9'" $],
[#ziffer], [#gerade | #ungerade]
)
)
\
& #zahl)
$
In aller Regel werden bei Aufgaben zu Grammatiken nur die Produktionsregeln verlangt, da die übrigen Mengen bzw. das Startsymbol aus diesen oder dem Kontext ersichtlich werden. Ist eine *vollständige* Beschreibung der Grammatik explizit gefragt, so muss dennoch die obige Form angegeben werden, siehe Aufgabe 3 auf der nächsten Seite.
<AufgabeGrammatik1>
#task(customTitle: [_Aufgaben_])[
#set enum(numbering: (..args) => strong(numbering("1.", ..args)))
1. Definieren Sie die Produktionsregeln einer Grammatik, die die folgenden umgangssprachlichen Ausdrücke erzeugt. Geben Sie außerdem jeweils einen Ableitungsbaum für die Worte in Klammern an:
- Alle zweistelligen natürlichen Zahlen. (57)
- Alle zweistelligen ganzen Zahlen. (-17)
- Alle höchstens zweistelligen ganzen Zahlen. (-3)
- Alle natürlichen Zahlen. (1111)
- Alle Wörter mit 4 Buchstaben, die mit "e" beginnen und mit "a" enden (enta) #hinweis[Als Alphabet sind nur die Kleinbuchstaben zugelassen, es müssen keine "sinnvollen" Wörter im Sinne einer natürlichen Sprache sein.]
#link(<LösungGrammatik1>)[Zur Lösung]
2. Beschreiben Sie die Wörter der Sprache, die durch folgende Produktionsregeln erzeugt werden, umgangssprachlich: $ &(1) "Zahl" -> "'5'" "Ziffer" "Ende" | #h(2pt)epsilon \
&(2) "Ziffer" -> "'"0"'"|"'"1"'"|"'"2"'"|"'"3"'"|"'"4"'"|"'"5"'"|"'"6"'"|"'"7"'"|"'"8"'"|"'"9"'" \
&(3) "Ende" -> "'12' | '22'" $
#link(<LösungGrammatik2>)[Zur Lösung]
3. Geben Sie eine *vollständige* Grammatik für die folgenden Sprachen an: #hinweis[Sie können #link("https://flaci.com")[Flaci] zur Überprüfung nutzen]
- Symmetrische a-b-Ketten nach folgendem Muster: #align(center)[aba, aabaa, aaabaaa, aaaabaaaa, $dots.c$]
- Geradzahlige Zahlen in Binärdarstellung: $ 0, 10, 100, 110, 1000, 1010, 1100, 1110, dots.c$
- Natürliche Zahlen mit Tausenderpunkten: $ 1, 50, 375, 1.451, 100.105, 205.111.305 dots.c $
#link(<LösungGrammatik3>)[Zur Lösung]
]
#pagebreak()
*Lösungen*:
<LösungGrammatik1>
*Zweistellige natürliche Zahlen*:
#prodRules(
content:(
[#text(yellow.darken(17%))[NatZwei]], [#ersteZiffer #ziffer],
[#ersteZiffer], [#ziffern],
[#ziffer], [$"'0' | "$ #ersteZiffer]
)
)
*Zweistellige ganze Zahlen*:
#prodRules(
content: (
[#text(yellow.darken(17%))[GanzZwei]], [#ersteZiffer #ziffer | $"'"-"'"$ #ersteZiffer #ziffer],
[#ersteZiffer], [#ziffern],
[#ziffer], [$"'0' | "$ #ersteZiffer]
)
)
*Höchstens zweistellige natürliche Zahlen*:
#prodRules(
content: (
[#text(yellow.darken(17%))[NatHöchstensZwei]], [#ersteZiffer | #ersteZiffer #ziffer],
[#ersteZiffer], [#ziffern],
[#ziffer], [$"'0' | "$ #ersteZiffer]
)
)
oder auch:
#prodRules(
content: (
[#text(yellow.darken(17%))[NatHöchstensZwei]], [#ersteZiffer #ziffer],
[#ersteZiffer], [#ziffern],
[#ziffer], [$"'0'" " | " #ersteZiffer " | " epsilon $]
)
)
*Natürliche Zahlen*:
1. Variante (Aufbau der Zeichenkette von vorne)
#let kette = [#text(green.darken(20%))[kette]]
#prodRules(
content: (
[#text(yellow.darken(17%))[Nat]], [#ersteZiffer | #ersteZiffer #kette],
[#kette], [#ziffer #kette | #ziffer (Selbstreferenz!)],
[#ersteZiffer], [#ziffern],
[#ziffer], [$"'0' |" #ersteZiffer
$]
)
)
2. Variante (Aufbau der Zeichenkette von hinten)
#prodRules(
content: (
[#text(yellow.darken(17%))[Nat]], [#ersteZiffer | #text(yellow.darken(17%))[Nat] #ziffer (Selbstreferenz!)],
[#ersteZiffer], [#ziffern],
[#ziffer], [$"'0' |" #ersteZiffer $]
)
)
Die sich selbst referenzierenden Regeln machen es möglich, dass unendlich viele Zeichen entstehen können. (Natürlich wäre es z.B. auch möglich, dass sich zwei Regeln gegenseitig referenzieren und so unendlich viele Zeichen ermöglichen)
*Alle Wörter mit 4 Buchstaben, die mit "e" beginnen und mit "a" enden*:
#let buchstabe = [#text(blue)[Buchstabe]]
#prodRules(
content: (
[#text(red)[Wort]],[$"'e'" #buchstabe #buchstabe "'a'"$],
[#buchstabe], [$"'a' | 'b' | " dots.down " | 'z'"$]
)
)
#link(<AufgabeGrammatik1>)[Zurück zur Aufgabe]
<LösungGrammatik2>
*Beschreibungeder Sprache*:
Alle vierstelligen Zahlen, die mit 5 beginnen und auf 12 oder 22 enden *oder* keine Zahl, also das leere Wort!
#link(<AufgabeGrammatik1>)[Zurück zur Aufgabe]
<LösungGrammatik3>
*Symmetrische a-b-Ketten*:
$ G_1 = {
{#text(red)[Anzahl]},
{a,b},\
{(1) #text(red)[Anzahl] -> "'a' 'b' 'a' | 'a' " #zahl "'a'"}, \
#text(red)[Anzahl]
} $
#merke[Wir müssen hier in einer Regel symmetrisch vor und hinter unserem Vervielfacher arbeiten, da ansonsten eine ungleiche Anzahl an a's möglich wäre! Also eine Regel der Form $ "Wort" -> "X 'b' X" $ (X bildet beliebig viele a's) ist nicht möglich ]
*Geradzahlige Zahlen in Binärdarstellung*
Zuerst muss man die Regelmäßigkeit erkennen:
Es handelt sich um alle Ketten von Nullen und Einsen, die auf eine 0 enden und mit einer 1 beginnen. Einzige Ausnahme hier ist die 0, da diese ebenfalls schon geradzahlig ist.
#let X = [#text(blue)[X]]
#prodRules(
content: (
[#zahl],[$ "'0' | '1' " #X "'0'"$],
[#X], [$#X #X " | '1' | '0' | " epsilon$]
)
)
*Natürliche Zahlen mit Tausenderpunkten*
Wir müssen sicherstellen, dass am Anfang keine Null steht und das alle drei Zahlen ein Punkt folgt.
$ &(1) #zahl -> #text(red)[Präfix] " | " #zahl \
&(2) #text(red)[Präfix] -> #E " | " #E #Z " | " #E #Z #Z \
&(3) #text(red)[Dreier] -> "'.'" #Z #Z #Z \
&(4) #h(2pt)#E -> #ziffern \
&(5) #h(2pt)#Z -> #E " | '0'"
$
Die erste Regel stellt dabei sicher, dass zu einer bestimmten Anzahl an Dreierpaketen an Zahlen (die dann mit Punkten versehen werden) genau ein Präfix hinzukommt, dass aus einer bis drei Zahlen bestehen kann (insbesondere auch notwendig, um ein- bis dreistellige Zahlen zu basteln!)
#link(<AufgabeGrammatik1>)[Zurück zur Aufgabe]
#pagebreak()
== Grammatik einer Programmiersprache
Ziel dieses kurzen Kapitels ist es, die Grammatik der einfachen Programmiersprache von "Robot Karol" aufzustellen. (Falls sich jemand an dieser Stelle fragt, warum wir keine andere Sprache nehmen, der sei z.B. auf die #link("https://docs.python.org/3/reference/grammar.html")[Python-Dokumentation] hingewiesen :)
Es gab in Robot Karol (Ursprungsversion, verkürzter Befehlssatz) die folgenden Möglichkeiten:
1. *Befehle*: Schritt, LinksDrehen, RechtsDrehen, Hinlegen, Aufheben
2. *Bedingungen*: IstWand, NichtIstWand, IstZiegel, NichtIstZiegel
3. *Kontrollstrukturen*:
- wiederhole n mal <code> \*wiederhole
- wiederhole solange <Bedingung><code> \*wiederhole
- wenn <Bedingung> dann <code> \*wenn
- wenn <Bedingung> dann <code> \*wenn
#task[Entwickeln Sie die Produktionsregeln einer Grammatik für die obenstehend beschriebene Programmiersprache. Testen Sie Ihre Grammatik mit #link("https://flaci.com")[Flaci] und lassen Sie sich den entsprechenden Ableitungsbaum anzeigen. ]
Die Lösung folgt direkt auf der nächsten Seite!
#pagebreak()
Die Produktionsregeln der Grammatik von Robot Karol
#let programm = [#text(red)[Programm]]
#let bedingung = [#text(red)[Bedingung]]
$ &(1) #programm -> #text(red)[A] | #text(red)[A] #programm \
&(2) #h(2pt)#text(red)[A] -> #text(red)[Befehl] " | " #text(red)[Wiederholung] " | " #text(red)[Entscheidung] \
&(3) #text(red)[Befehl] -> "'Schritt' | 'LinksDrehen' | 'Rechtsdrehen' | 'Hinlegen' | 'Aufheben' " \
&(4) #text(red)[Entscheidung] -> "'wenn' " #bedingung " 'dann' " #programm "'"^*"wenn' | " \
&#h(100pt)"'wenn' " #bedingung " 'dann' " #programm " 'sonst' " #programm "'"^*"wenn'" \
&(5) #text(red)[Wiederholung] -> "'wiederhole" #N " 'mal' " #programm " '"^*"wiederhole' |" \
&#h(102pt)"'wiederhole solange" #bedingung #programm " '"^*"wiederhole'" \
&(6) #bedingung -> "'IstWand' | 'NichtIstWand' | 'IstZiegel' | 'NichtIstZiegel' " \
&(7) #h(2pt) #N -> #E " | " #E #text(red)[Rest] \
&(8) #text(red)[Rest] -> #Z " | " #Z #text(red)[Rest] \
&(9) #h(2pt)#E -> #ziffern \
&(10) #h(2pt) #Z -> #E " | '0'"
$
An dieser Stelle empfiehlt sich wirklich die Eingabe der Grammatik in Flaci und die Überprüfung eines klassischen Programms:
#align(center)[
```
wiederhole 4 mal
Schritt
*wiederhole
wenn IstZiegel
dann Aufheben
wiederhole 4 mal
RechtsDrehen
*wiederhole
*wenn
```
]
Es ergibt sich der folgende Ableitungsbaum (reinzoomen nötig!):
#align(center)[
#image("images/AbleitungKarol.png")
]
#pagebreak()
== Grammatik von E-Mail-Adressen
Für Emails gelten bei uns die folgenden (vereinfachten) Regeln:
1. Eine *Email-Adresse* besteht aus einer Benutzerkennung, dem \@-Zeichen und dem Namen einer Domäne.
2. Für die *Benutzerkennung* dürfen Kleinbuchstaben und Ziffern verwendet werden. Sie darf beliebig, mindestens jedoch ein zeichen lang sein.
3. Die *Domäne* setzt sich zusammen aus einer oder mehrerer Unterdomänen, gefolgt von einer Hauptdomäne (Top-Level-Domain). Die Bestandteile der Domäne sind jeweils durch einen Punkt getrennt.
4. Die *Top-Level-Domain* darf nur aus Kleinbuchstaben zusammengesetzt sein und ist entweder zwei oder drei Zeichen lang.
5. Jede *Unterdomäne* darf Kleinbuchstaben und Zahlen enthalten. Sie darf beliebig, mindestens jedoch zwei Zeichen lang sein.
#task[Entwickeln Sie die Produktionsregeln einer Grammatik für die oben beschriebenen Regeln für Email-Adressen. Testen Sie Ihre Grammatik mit #link("https://flaci.com")[Flaci] und lassen Sie sich den entsprechenden Ableitungsbaum anzeigen.]
Die Lösung findet sich auf der nächsten Seite!
#pagebreak()
In der folgenden Lösung steht #N für die Nutzerkennung (auch verwendet als beliebig lange Zeichenkette, aber mindestens ein Zeichen lang), #text(red)[U] für eine Unterdomäne und #text(red)[T] für eine Top-Level-Domain:
$ &(1) #text(red)[Email] -> #N " '@' " #text(red)[U] #text(red)[T]\
&(2) #h(2pt) #N -> #text(red)[B] " | " #Z " | " #N #N \
&(3) #h(2pt) #text(red)[B] -> "'a' | " dots.c " | 'z'" \
&(4) #h(2pt) #Z -> "'0' | " dots.c " | '9'" \
&(5) #h(2pt) #text(red)[U] -> #N #N "'.' | " #text(red)[U] #text(red)[U] \
&(6) #h(2pt) #text(red)[T] -> #text(red)[B] #text(red)[B] " | " #text(red)[B] #text(red)[B] #text(red)[B]
$
Damit Flaci nicht allzuviel zu tun hat verwenden wir zum Testen nur die Emailadresse "<EMAIL>". Es ergibt sich der folgende Ableitungsbaum (wieder reinzoomen nötig!):
#align(center)[
#image("images/AbleitungEmail.png")
]
#pagebreak()
== EBNF
Wie bereits in einem Hinweis erwähnt gibt es eine weitere übliche Notationsform, die *erweiterte Backus-Naur-Form*. Es gelten die folgenden Regeln (Auszug der für uns Wichtigsten):
1. Alle Regeln haben die Form #text(red)[*$<$Nichtterminal$> = dots.down$ ;*]
2. Aneinanderreihungen mit #text(red)[,] (kann weggelassen werden)
3. Oder-Symbol #text(red)[$|$]
4. Terminalsymbole werden in Anführungszeichen oder Apostrophe gesetzt.
5. *Optionen* werden in eckige Klammern gesetzt #text(red)[$[dots.down]$]
6. *Gruppierung von Elementen*: #text(red)[(dots.down)]
7. *Wiederholung* (auch Null mal): #text(red)[${dots.down}$]
8. *Mehrfachausführung*: #text(red)[$3^*X$]
9. *Ausschluss*: #text(red)[$dots.down - X$]
Die Apostrophe bei Zeichen sind insbesondere deswegen wichtig, um Zeichen der EBNF-Notation von der Verwendung innerhalb der Zeichenkette zu unterscheiden, so hat das "="-Zeichen untenstehend zwei verschiedene Bedeutungen - der Beginn der Regel und die Verwendung als tatsächliches Zeichen
#text(red)[Beispiel] = #text(red)[Anfang] '+' #text(red)[Mitte] '=' #text(red)[Ende] ;
#hinweis[Nimmt man die EBNF-Regeln ernst, müstte z.B. nach Anfang ein , stehen. Diese Kommata dürfen aber weggelassen werden (siehe oben)]
Im Folgenden finden sich einige Beispiele, um die EBNF-Regeln zu veranschaulichen:
#v(0.25cm)
#let var = [#text(red)[Var]]
#grid(
columns: (50%, 50%),
rows: (auto, auto, auto, auto, auto, auto),
gutter: 10pt,
[*Regel*], [*Möglicher Output*],
[#text(red)[Anfang] $ = [$'A' $|$ 'B'$]$ 'C';], [*AC* oder *BC* oder *C*],
[#text(red)[Mitte] $=$ 'A' $($ 'X' $|$ 'Y' | #var$)$;], [*AX* oder *AY* oder *A#var*],
[#text(red)[Ende]= $3^*$ #text(red)[Baum] 'Z';], [*#text(red)[Baum Baum Baum] Z*],
[#var $=$ 'A'${$'B' 'C' $}$ 'D';], [*AD* oder *ABCD* oder *ABCBCD* oder dots.down],
[#text(red)[Text] $=$ 'X' ${$#var$} -$ #var ;], [*X* oder *X #var #var* oder *X #var #var #var*]
)
#v(0.25cm)
#task(customTitle: [_Aufgaben_])[Schreiben Sie die Produktionsregeln in EBNF- Form für die folgenden umgangssprachlich beschriebenen Zeichenketten (jeweils ggf. mit den bisher gemachten Vereinfachungen)
1. Natürliche Zahlen
2. alle Vielfachen von 5 (also 5,10,15, $dots.down$)
3. Ganze Zahlen
4. Dezimalzahlen
5. geradzahlige Binärzahlen
6. Die Sprache, die nur die Wörter *x*, *xz* und *xyz* enthält (ohne "Oder"-Zeichen)
7. Natürliche Zahlen mit Tausenderpunkten
8. Emails
9. "Korrekte" Summen und Differenzen, also z.B.: $(15+(-3))-500+((33+11)-(-5))$]
Die Lösungen finden sich ab der nächsten Seite.
#pagebreak()
*Natürliche Zahlen*:
$ &(1) #text(red)[Nat] = #Z { #Z " | '0'"};\
&(2) #h(2pt)#Z = "'1'| " dots.down " |'9'";
$
*Alle Vielfachen von 5*:
$ &(1) #zahl = "'5'" | #Z " "{#Z "| '0'"} " "("'0'|'5'");\
&(2) #h(2pt)#Z = "'1'| " dots.down " |'9'";
$
*Ganze Zahlen*:
$ &(1) #text(red)[Ganz]= "'0' | ['-']" #Z " "{#Z" | '0'"};\
&(2) #h(2pt)#Z = "'1'| " dots.down " |'9'";
$
*Dezimalzahlen*:
$ &(1) #text(red)[Dezi]= "['-'] ('0'|" #Z{ #Z"|'0'"})"','"{#Z"|'0'"} #Z ";" \
&(2) #h(2pt)#Z = "'1'| " dots.down " |'9'";
$
*Geradzahlige Binärzahlen*:
$ &(1) #zahl= "'0'|'1' {'0'|'1'} '0';" $
oder
$ &(1) #zahl =" [ '1' {'0'|'1'}] '0';" $
*Die Sprache, die nur die Wörter x, xz und xyz enthält*
$ &(1) #text(red)[Wort]= " 'x'[['y']'z'];" $
*Natürliche Zahlen mit Tausenderpunkten*
$ &(1) #zahl = #E [#Z] [#Z] {"'.'"3^* #Z}";" \
&(2) #h(2pt)#E = "'1'| " dots.down " |'9';" \
&(3) #h(2pt)#Z = #Z "|'0';"
$
*Email-Adressen*:
$ &(1) #text(red)[Adresse] = #text(red)[Benutzer] "'@'" #text(red)[Domäne] ; \
&(2) #text(red)[Benutzer] = ( #Z "|" #text(red)[B] )" " { #Z "|" #text(red)[B]}; \
&(3) #text(red)[Domäne] = #text(red)[Unterdomäne] { #text(red)[Unterdomäne]} #text(red)[TLD] ; \
&(4) #text(red)[TLD] = #text(red)[B] #text(red)[B] [#text(red)[B]]; \
&(5) #text(red)[Unterdomäne]= 2^* ( #Z | #text(red)[B]) " " {#Z | #text(red)[B]}"'.'"; \
&(6) #h(2pt)#Z "'0'| " dots.down " |'9';" \
&(7) #h(2pt)#text(red)[B] "'a'| " dots.down " | 'z';"
$
#pagebreak()
*Terme*
$ &(1) #text(red)[Term] = #text(red)[Summand] ("'+'|'-'") #text(red)[Summand]{("'+'|'-'") #text(red)[Summand]}";"\
&(2) #text(red)[Summand]= #zahl "| '('" #text(red)[Term] "')';" \
&(3) #zahl = #text(red)[Nat] "| '0' | '(' '-'" #text(red)[Nat]"')';" \
&(4) #text(red)[Nat] = #ziffer -"'0'" {#ziffer}";" \
&(5) #ziffer = "'0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9';"
$
#v(0.5cm)
== Syntaxdiagramme für EBNF
Statt eine Grammatik anzugeben, kann die EBNF-Notation auch in Diagrammform in sogenannten *Syntaxdiagrammen* dargestellt werden. Dabei gibt es für jede Produktionsregel ein eigenes Syntaxdiagramm.
#align(center)[
#image("images/syntaxEinführung.png")
]
#task[Zeichnen Sie für die folgenden Regeln jeweils Syntaxdiagramme:
1. #text(red)[Nat] = #Z {#Z | '0'};
2. #text(red)[Ganz] = ['-'] #text(red)[Nat] | '0';
3. #text(red)[Dez] = ['-'] ('0' | #text(red)[Nat]) ',' {#Z|'0'} #Z ;
4. #text(red)[Wort] = 'X' {'x' | #text(red)[B A]} ;
5. #text(red)[Wort2] = [#text(red)[B] [#text(red)[C]] ('x' | 'y' | 'z')] ;
6. #text(red)[Zahl] = '5' | #Z { #Z | '0' } ( '0' | '5');
7. #text(red)[ZahlT] = #E [ #Z ] [ #Z ] { '.' $3^*$ #Z };
]
Die Lösungen finden sich wieder ab der nächsten Seite:
#pagebreak()
#grid(columns: (50%, 50%), rows: (auto), [*Natürliche Zahlen*:
#align(center)[#image("images/syntaxA1.png")]
], [*Ganze zahlen*
#align(center)[#image("images/syntaxA2.png")]
])
*Dezimalzahlen*:
#align(center)[#image("images/syntaxA3.png")]
#grid(columns: (50%, 50%), rows: (auto), [*Wort*:
#align(center)[#image("images/syntaxA4.png")]
], [*Wort 2*
#align(center)[#image("images/syntaxA5.png")]
])
*Vielfache von 5*:
#align(center)[#image("images/syntaxA6.png", width: 90%)]
#pagebreak(
)
*Natürliche Zahlen mit Tausenderpunkten*:
#align(center)[#image("images/syntaxA7.png")]
#v(0.5cm)
#task[Geben Sie die Produktionsregeln in EBNF-Form an, die zu den folgenden Syntaxdiagrammen gehören:
#align(center)[#image("images/syntaxA8.png")]
]
#pagebreak()
== Exkurs: Sprachklassen nach Chomsky
<ChomskyHierarchie>
Bisher haben wir nur an der Oberfläche der Sprachlehre gekratzt. Die bereits eingeführten künstlichen Sprachen können sich noch in *Klassen* einteilen lassen. Die Produktionsregeln der einzelnen Klassen unterliegen dabei verschiedenen Einschränkungen, d.h. manche Sprachen sind "*spezieller*".
Dabei gibt es einen direkten Zusammenhang zwischen den Eigenschaften der Produktionsregeln der *Grammatik* und den Eigenschaften der von ihr erzeugten Sprache *L(G)*.
Der amerikanische Sprachwissenschaftler Noam Chomsky hat ein Klassifikationssystem entwickelt, das vier Arten von formalen Grammatiken und damit von formalen Sprachen definiert (#cite(<hoffmann>) S. 169).
#align(center)[#image("images/chomsky.png", width: 70%)]
Um die Unterschiede der Sprachen besser beleuchten zu können, ist eine allgemeinere Definition einer Grammatik notwendig, als die, die wir bisher verwendet haben.
#definition[Eine *Grammatik* einer formalen Sprache ist ein Viertupel $(V, Sigma, P, S)$ und besteht aus
1. der endlichen _Variablenmenge V (Nonterminale)_,
2. dem endlichen _Terminalalphabet_ $Sigma$ mit $V sect Sigma = emptyset $
3. der endlichen Menge _P_ von _Produktionen (Regeln)_ und
4. der _Startvariablen S_ mit $ S in V$.
Jede Produktion aus _P_ hat die Form $l -> r$ mit $l in (V union Sigma)^+$ und $r in (V union Sigma)^*$ (#cite(<hoffmann>), S. 164).
]
Der Wesentliche Unterschied liegt - neben der noch mathematischeren Notation - in den erlaubten Produktionsregeln. Die linke Seite einer Regel kann im Allgemeinen nicht nur ein Nichtterminalsymbol enthalten, sondern mindestens ein Terminal oder Nichtterminalsymbol. Das erweitert unsere Möglichkeiten beträchtlich!
#pagebreak()
Damit lässt sich die Klassifikation mit Leben füllen (#cite(<hoffmann>), S. 169):
1. *Phrasenstrukturgrammatiken (Typ-0-Grammatiken)* \ Jede Grammatik, die die obere Definition erfüllt ist automatisch eine Typ-0-Grammatik. Es gibt insbesondere keine weiteren Einschränkungen für die Produktionsregeln.
2. *Kontextsensitive Grammatiken (Typ-1-Grammatiken)* \ Bei kontextsensitiven Grammatiken muss $|r| >= |l|$ gelten, d.h. die rechte Seite muss mindestens so lang sein, wie die linke Seite der Produktionsregel (einzige Ausnahme: $S -> epsilon$, dann darf $S$ aber in keiner rechten Seite vorkommen!)
3. *Kontextfreie Grammatiken (Typ-2-Grammatiken)* \ Zusätzlich zu der vorherigen Einschränkung darf jetzt auf der linken Seite nur noch ein einziges Nonterminal stehen (d.h. unsere Grammatikdefinition entspricht kontextfreien Sprachen).
4. *Reguläre Grammatiken (Typ-3-Grammatiken)* \ Die speziellsten Grammatiken, sie sind kontextfrei und besitzen zusätzlich die Eigenschaft, dass die rechte Seite einer Regel entweder $epsilon$ ist oder ein Terminalsymbol gefolgt von einem Nichtterminalsymbol.
*Beispiele* (#cite(<hoffmann>), S. 169ff.)
1. $L_3 := {(\a\b)^n | n in NN^+}$ ist eine *reguläre Sprache*. #hinweis[Der Exponent steht hier für eine Wiederholung, d.h. hier betrachten wir Wörter wie $\a\b, \a\b\a\b, dots.down$] Mögliche Produktionsregeln sind: $ &(1) #h(2pt) S -> \a\B \ &(2)#h(2pt) B -> \b \ &(3) #h(2pt) B -> \bC \ &(4) #h(2pt)C -> \a\B $ \ Ableitung von $\a\b\a\b$: $ S ->^((1)) \aB ->^((3)) \a\b\C ->^((4)) \a\b\a\B ->^((2)) \a\b\a\b $ Das Wort wird also von links nach rechts "aufgebaut". Man spricht deswegen auch von einer "*rechts-linearen Grammatik*".
2. $L_2 := {a^n b^n | n in NN^+}$ ist eine *kontextfreie Sprache*, aber nicht regulär. Die Sprache ist nicht mehr regulär, da wir in irgendeiner Form "zählen" müssten, wie viele a's es gibt, bevor die b's beginnen. Das ist mit den Regeln für reguläre Grammatiken nicht möglich. \ Eine mögliche Produktionsregel ist: $ &(1) #h(2pt) S -> \a\S\b | \a\b $
3. $L_1 := {a^n b^n c^n | n in NN^+}$ ist eine *kontextsensitive Sprache*, aber nicht kontextfrei. Der Unterschied liegt darin, dass wir auch Terminalsymbole auf die linke Seite der Produktionsregeln packen können. Dadurch können wir die Regel abhängig von der *Umgebung* (also dem Kontext) des Nichtterminalsymbols machen, die Grammatik wird etwas länglich: $ &(1) #h(2pt) S -> \S\A\BC | \a\b\c \ &(2) #h(2pt) \C\A -> \AC \ &(3) #h(2pt) \C\B -> \B\C \ &(4) #h(2pt) \BA -> \AB \ &(5) #h(2pt) \cA -> \Ac \ &(6) \cB -> \Bc \ &(7) #h(2pt) \bA -> \Ab \ &(8) #h(2pt) \aA -> \aa \ &(9) #h(2pt) \bB -> \bb \ &(10)#h(2pt) \cC -> \cc $ Eine Ableitung des Wortes $\a\a\a\b\b\b\c\c\c$ ist dem geneigten Lesy zur Übung überlassen :).
4. $L_0 := {omega | omega " codiert eine terminierende Turing-Maschine"}$ ist eine *Typ-0-Sprache*, aber keine *kontextsensitive Sprache*. Eine explizite Grammatik für diese Sprache anzugeben ist schwer, deswegen wird an dieser Stelle darauf verzichtet.
#pagebreak()
= Endliche Automaten
== Deterministische endliche Automaten
Die Überprüfung, ob ein bestimmtes Wort in einer Sprache liegt haben wir bisher über die direkte Anwendung der Regeln selbst händisch ausprobiert, bzw. anhand der Struktur der Wörter direkt erkannt.
Dieses Vorgehen ist im Allgemeinen - insbesondere bei komplexen Grammatiken bzw. Sprachen - natürlich fehleranfällig und sehr zeitintensiv. Es braucht also eine Möglichkeit das Ganze zu automatisieren. Das Werkzeug der Wahl ist dabei ein sogenannter *deterministischer endlicher Automat (DEA)*. Er prüft, ob eine eingegebene Zeichenkette ein Wort der entsprechenden Sprache ist.
Ein DEA wird häufig über ein sogenanntes *Zustandsdiagramm* visualisiert:
#align(center)[#image("images/ab.png", width: 50%)]
Dieser Automat akzeptiert alle Wörter der Sprache $L_3 := {(\a\b)^n | n in NN^+}$, der Zustand *$q_0$* ist der *Startzustand*, der Zustand *$q_2$* ein Endzustand. Der Zustand *$q_3$* wird häufig auch *Fallenzsutand* genannt, da der Automat von dort nicht wieder wegkommt, dazu später mehr.
Formal definiert sich ein Automat wie folgt:
#definition[Ein deterministischer endlicher Automat wird durch die folgenden Angaben festgelegt:
1. *Q*: eine endliche Menge von *Zuständen*
2. *$Sigma$*: eine endliche Menge von Eingabesymbolen (unser *Alphabet*!)
3. *$delta$* eine *Zustandsübergangsfunktion*, die angibt, in welchen Folgezustand $q' in Q$ der Automat übergeht, wenn im aktuellen zustand $q in Q$ das Symbol x aus $Sigma$ eingelesen wird, also $delta(q,x) = q'.$
4. *$q_0$*: ein *Anfangszustand*.
5. *F*: eine Menge von *Endzuständen* (final states)
Kurz: DEA = (Q, $Sigma$, $delta$, $q_0$, F)]
#pagebreak(
)
*Beispiel $L_3 := {(\a\b)^n | n in NN^+}$*:
*Q* $ = {q_0; q_1; q_2; q_3}$
*$Sigma$* $ = {a;b}$
*$delta$*: siehe unten
*$q_0$*
*F* $= {q_2}$
Die Zustandsübergangsfunktion wird entweder als Diagramm (wie oben) dargestellt, oder in einer Tabelle, in der für jedes Paar aus Zustand $q$ und Alphabetzeichen $x$ der neue Zustand steht.
#align(center)[
#table(
columns:(25pt, 25pt, 25pt),
rows: (25pt,25pt,25pt,25pt,25pt),
[*$delta$*], [*$a$*], [*$b$*],
[*$q_0$*], [$q_1$], [$q_3$],
[*$q_1$*], [$q_3$], [$q_2$],
[*$q_2$*], [$q_1$], [$q_3$],
[*$q_3$*], [$q_3$], [$q_3$]
)
]
*Überprüfung einer Zeichenkette*:
Möchte man nun überprüfen, ob eine bestimmte Zeichenkette ein Wort der Sprache ist, so beginnt man im Startzustand. Danach werden alle Symbole der Zeichenkette nacheinander eingelesen. Nach jedem Symbol $x$ geht der Automat gemäß der Übergangstabelle vom aktuellen $q$ in den neuen Zustand $q'$ über $delta(q,x) = q'$.
Für das Wort $\a\b\ab$ ergibt sich die folgende Reihenfolge an Zuständen:
$ q_0 ->^(a) q_1 ->^(b) q_2 ->^(a) q_1 ->^(b) q_2 $
#hinweis[Mit #link("https://flaci.com") kann diese Überprüfung auch automatisiert erfolgen!]
Nach Abarbeitung der Zeichenkette gibt es drei Möglichkeiten:
1. Der Automat stoppt in einem Endzustand - daraus folgt, dass die Zeichenkette #text(green)[zur Sprache]gehört.
2. Der Automat stoppt in einem Nicht-Endzustand - daraus folgt, dass die Zeichenkette #text(red)[nicht zur Sprache] gehört.
3. Der Automat stoppt, da die Zeichenkette nicht komplett abgearbeitet werden kann, da es zu einer Kombination aus Zustand $q$ und Symbol $x$ keinen Folgezustand gibt - daraus folgt, dass die Zeichenkette #text(red)[nicht zur Sprache] gehört.
Der dritte Fall kann nur auftreten, wenn der Automat *nicht vollständig* ist. Den obigen Automaten könnte man alternativ auch so darstellen:
#grid(columns:(50%, 50%), rows:(auto), [#align(center)[#image("images/ab_2.png")]], [#align(center)[
#table(
columns:(25pt, 25pt, 25pt),
rows: (25pt,25pt,25pt,25pt),
[*$delta$*], [*$a$*], [*$b$*],
[*$q_0$*], [$q_1$], [],
[*$q_1$*], [], [$q_2$],
[*$q_2$*], [$q_1$], [],
)
]
])
In der ersten Variante diente der Zustand $q_3$ nur dazu, die "losen Enden" aufzusammeln, d.h. alle Eingaben, die zu einer garantiert ungültigen Kombination führen (wenn beispielsweise zwi $a$ direkt nacheinander kommen). Wird so ein *Fallenzustand* benutzt und damit jede mögliche Kombination $(q,x)$ kodiert, so spricht man von einem *vollständigen* Automaten.
Jeder nicht vollständige Automat kann also leicht zu einem vollständigen Automaten gemacht werden. Der Übersichtlichkeit halber ist aber häufig eine nicht vollständige Angabe zu bevorzugen.
#hinweis[Ein DEA, der die Worte einer bestimmten Sprache akzeptiert, kann nur gefunden werden, wenn es sich um eine reguläre Sprache handelt!]
#v(0.5cm)
== Exkurs: Nichtdeterministische endliche Automaten
Der obige Automatentyp war unter Anderen dadurch gekennzeichnet, dass es für jeden Zustand und eine Eingabe immer genau einen Folgezustand gibt. Das muss nicht notwendigerweise so sein. Lässt man mehrere ausgehende Kanten für eine Eingabe aus einem Zustand zu, so spricht man von einem *nichtdeterministischen endlichen Automaten* (NEA), da es nicht mehr exakt festgelegt (determiniert) ist, welcher Zustand als nächstes kommt. In der Übergangstabelle kann es also auch *Mehrfacheinträge* geben.
Ein Wort wird dann akzeptiert, wenn es *einen möglichen Weg* gibt, der zu einem Endzustand führt.
Überraschenderweise ist dieser Ansatz nicht "*mächtiger*" als die deterministischen Automaten, d.h. auch mit NEA's können nur reguläre Sprachen erkannt werden.
*Beispiel*: die Sprache, die mindestens ein $a$, dann mindestens ein $b$ und am Ende beliebig viele $c$'s enthält, kann mit folgenden Automaten beschrieben werden.
#align(center)[#image("images/nea.png", width: 75%)]
#pagebreak()
== Übungen und Beispiele
#task[Geben Sie jeweils einen endlichen (nicht notwendigerweise vollständigen) Automaten an (Zustandsübergangsdiagramm), der die Wörter der Sprache erkennt:
1. Natürliche Zahlen
2. Ganze Zahlen
3. Natürliche, durch 10 teilbare Zahlen (als NEA und als DEA!)
4. a-b-Ketten, die
- mit mindestens zwei "b" enden.
- mit genau zwei "b" enden.
- mindestens einmal "aaa" oder "bbb" enthalten.
#hinweis[Eine a-b-Kette kann auch 0 a's oder 0 b's enthalten!]
5. Natürliche Zahlen mit Tausenderpunkten
]
Wie immer beginnen die Lösungen auf der nächsten Seite
#pagebreak()
#grid(
columns: (50%, 50%),
rows: (auto, auto, auto),
gutter:5pt,
[*4b)* #image("images/automatA4_b.png")], [*2)* #image("images/automatA2.png")], [*3-DEA*#image("images/automatA3_1.png")], [*3-NEA* #image("images/automatA3_2.png")],
[*4a)* #image("images/automatA4_a.png")], [*1)* #image("images/automatA1.png")],
)
*5)*
#align(center)[#image("images/automatA5.png")]
#pagebreak()
*4c)*
#align(center)[#image("images/automatA4_c.png", width: 90%)]
#task[Beschreiben Sie umgangssprachlich, welche Zeichenketten der folgende Automat erkennt: #align(center)[#image("images/automatA6.png")]]
#pagebreak()
*Lösung*: Der Automat akzeptiert alle durch drei teilbaren natürlichen Zahlen!
#task[Geben Sie jeweils einen (nicht notwendigerweise vollständigen) endlichen Automaten an, der die folgende Form hat:
#align(center)[\<kette\>\#\<prüf\>]
wobei:
1. \< kette\> eine beliebig lange, aber nicht leere a-b-Kette ist und \<prüf\> eine 1, falls zuvor ungeradzahlig viele a's enthalten waren. Andernfalls eine $0$.
2. \< kette\> eine beliebig lange, aber nicht leere a-b-Kette ist und \<prüf\> das Format $00, 01, 10$ oder $11$ hat, wobei das zweite Zeichen von der Anzahl der b's abhängt (wiederum 1, falls ungeradzahlig).
]
Die Lösung wie immer auf der nächsten Seite!
#pagebreak()
#align(center)[#image("images/automatA7.png")]
#align(center)[#image("images/automatA8.png")]
*Abschlussaufgabe*
#task[Zeichnen Sie das Zustandsdiagramm eines Automaten, der Datumsangaben der Form TT.MM.JJJJ erkennt, mit folgenden Einschränkungen:
1. Es sollen nur die *Jahreszahlen voon 1900 bis 2099* gültig sein und zudem sollen *alle Monate 31 Tage* haben.
2. Zusätzlich sollen jetzt die Tage den *Monaten angepasst* werden, jedoch hat der Februar immer *29 Tage*.
3. Zusätzlich soll der Februar jetzt *nur* 29 Tage in allen Jahren haben, die Vielfach von 4 sind.
4. Zusätzlich soll nun beachtet werden, dass *1900 kein Schaltjahr* ist!]
#pagebreak()
== Implementierung eines DEA
Ein Automat kann natürlich nicht nur gezeichnet werden, sondern auch implementiert werden. Wie auch in der 11. Jahrgangsstufe beginnen wir die Implementierung eher "naiv" und arbeiten uns dann voran.
#hinweis[Da der Anteil der Programmierung im 11.-Klassteil des Abiturs bereits recht hoch ist, sind konkrete Fragen zur Implementierung eines DEA nicht häufig, aber dennoch möglich. ]
=== Eine erste Implementierung
Grundsätzlich muss die Repräsentation des Automaten seinen aktuellen *Zustand speichern* und in irgendeiner Form die *Zustandsübergangstabelle* kennen und seinen *Zustand ändern* können, wenn ein Wort überprüft wird. Neben dem Konstruktor bieten sich also folgende Methoden an:
#align(center)[```Java
boolean testWord(String input)
void switchState(char c)
```]
Um an einem konkreten Beispiel zu arbeiten verwenden wir den Automaten *4b)*, der *a-b-Ketten* erkennt, die mit genau $2$ *b* enden. Zur Erinnerung:
#align(center)[#image("images/automatA4_b.png", width: 60%)]
Wir beginnen mit dem Grundgerüst:
#align(center)[```Java
public class DEA {
//Der Zustand kann der Einfachheit halber als Integer codiert werden:
private int state;
//In unserem Fall ist der Startzustand 0
public DEA() {
state = 0;
}
}
```]
#pagebreak()
Für die testWord()-Methode können wir die forEach-Struktur in Java verwenden:
#align(center)[```Java
public boolean testWord(String input) {
// Der String muss zunächst in ein Array aus Charactern umgewandelt werden
for(char c : input.toCharArray()) {
//Diese Methode muss noch implementiert werden!
switchState(c);
//Eine Ausgabe-Methode - nicht zwingend nötig, aber nützlich!
System.out.println("Zeichen " + c + " führt zu: " + state);
}
// Nach Abschluss wird überprüft, ob der Automat im Endzustand steht.
if(state == 2) {
//Falls ja wird er in den Anfangszustand versetzt...
state = 0;
//und zurückgegeben, dass das Wort in der Sprache enthalten ist
return true;
} else {
//andernfalls wird zurückgegeben, dass dem nicht so it.
state = 0;
return false;
}
}
```]
Die switchState()-Methode sorgt jetzt dafür, dass der Automat beim Lesen einer bestimmten Eingabe den Zustand (also das Attribut state) entsprechend des obigen Zustandsübergangsdiagramms wechselt. Die *Schwierigkeit* besteht dabei darin, dass die Änderung von zwei verschiedenen Parametern abhängt. Es gibt mehrere Ansätze, diesem Problem zu begegnen.
1. *Geschachtelte if-(else)-Bedingungen*: Beispielsweise kann zuerst abgefragt werden, in welchem Zustand sich der Automat befindet. Anschließend wird in jedem Zweig des if seperat ein weiteres if-else zur Abarbeitung des Zeichens.
2. *Geschachtelte switch-case-Strukturen*: Analog zu 1. kann statt einer if-else-Struktur auch die eingebaute switch-case-Syntax verwendet werden - insbesondere wenn es viele Zustände oder Zeichen gibt ist dies die bessere Variante.
3. *Mischung aus 1. und 2.*: Um beides zu veranschaulichen wird in der folgenden Methode für die Auswahl des Zustands switch-case verwendet und für die Entscheidung über das Zeichen if-else.
#align(center)[```Java
public void switchState(char c) {
//Die Variable nach der unterschieden werden soll wird ausgewählt - hier state
switch (state) {
//Die einzelnen "Fälle" (cases) werden nacheinander abgearbeitet.
case 0:
/*Hier genügt ein if-else, da nur zwischen a und b als Eingabe
unterschieden wird. Der Zustand verändert sich entsprechend.*/
if(c == 'a') {
state = 0;
} else {
state = 1;
}
/*break beendet die Ausführung - wird dies vergessen, so werden die
übrigen Fälle auch betrachtet - häufiger Fehler!*/
break;
//Die restlichen Zustände verlaufen analog
case 1:
if(c == 'b') {
state = 2;
} else {
state = 0;
}
break;
case 2:
if(c == 'a') {
state = 0;
} else {
state = 3;
}
break;
case 3:
if(c == 'a') {
state = 0;
} else {
state = 3;
}
break;
/*Sollte ein Zustand nicht definiert sein, wird dieser default-case
betreten. Hier kann beispielsweise eine Fehlerbehandlung erfolgen.*/
default:
break;
}
```]
Diese Implementierung reicht bereits aus! Ein kurzer Test zeigt, dass der Automat korrekte Ausgaben macht:
#align(center)[```Java
public static void main(String[] args) {
DEA dea = new DEA();
System.out.println( dea.testWord("aabb"));
System.out.println(dea.testWord("abba"));
System.out.println(dea.testWord("aaaabbbbcaa"));
}
```]
liefert "true, false, false" (mit den weiteren Ausgaben von oben dazwischen).
Diese Implementierung hat allerdings offensichtliche Schwächen, z.B.:
1. Wenn in einem Wort "unerlaubte Zeichen" auftreten (das c im dritten Test), so wird dieses einfach übergangen.
2. Es wird nur ein einziger Automat definiert. Um eine andere Sprache erkennen zu können, müsste alles noch einmal neu geschrieben werden.
Die Zustände und die Übergänge sollten idealerweise also "von außen" definiert werden können. Dazu ist die switch-case Struktur nicht geeignet, deswegen verwenden wir stattdessen eine *HashMap*.
#pagebreak()
=== Exkurs - Implementierung mit Hilfe einer HashMap
Das Folgende geht wieder weit über den Schulstoff hinaus und ist nur als Anregung zu verstehen.
Um die obigen Probleme lösen zu können, darf der Zustand nicht direkt über den Code geändert werden - die Informationen über den Zustandswechsel und der Quellcode müssen separiert werden.
Es gibt selbstverständlich viele Ansätze, wie dies gelingen kann, eine (bzw. zwei) bieten sich aber besonders an und orientieren sich an der mathematischen Definition der *Zustandsübergangsfunktion $delta$*, zur Erinnerung:
$ delta(q,c) = q' $
wobei $q$ und $q'$ Zustände sind und $c$ ein bestimmtes Zeichen (bei uns jetzt: char in Java!)
Es wird also eine Funktion genutzt, die *zwei* Eingabeparametern genau *ein* Ergebnis zuordnen. Es handelt sich hier allerdings um eine sogenannte *diskrete* Funktion (im Gegensatz zu den kontinuierlichen Funktionen, die üblicherweise in der Mathematik betrachtet werden, also z.B. $f: x |-> x^2$ mit $x in RR$, die keine "Lücken" haben).
Wir kennen bereits zwei Datenstrukturen, die eine solche Zuordnung möglich machen würden, beide sind vernünftig einsetzbar:
1. Ein *2D-Array*: besonders effizient, wenn es ein vollständiger Automat ist.
2. Eine *HashMap*: die bessere Wahl, wenn der Automat nicht vollständig ist. Wenn es vorher nicht bekannt ist also im Schnitt also besser.
In beiden Fällen haben wir noch ein Problem: Java erlaubt es nicht, dass ein Tupel von Objekten einen Schlüssel für z.B. die HashMap oder einen Eintrag für ein Array bilden (Python z.B. erlaubt das!).
Um die Zuordnung also nutzen zu können, müssen wir noch eine "Dummy-Klasse" schreiben, die die beiden Informationen verknüpft (und nicht vergessen equals() und die hashCode()-Methode zu überschreiben, um Vergleiche und das Hashen für die HashMap möglich zu machen.)
Um sicherzustellen, dass bei den Zuständen keine falschen Zeichenketten auftauchen, kann wieder ein Enum verwendet werden, z.B.:
#align(center)[```Java
public enum State {
Q0, Q1, Q2, Q3, Q4,
Q5, Q6, Q7, Q8, Q9,
Q10, Q11, Q12, Q13, Q14,
Q15, Q16, Q17, Q18, Q19
}
```]
Damit wird natürlich der Zustandsvorrat auf 20 Zustände limitiert, aber das ist aktuell eine nebensächliche Einschränkung. Zurück zur zweiten Hilfsklasse, Pair:
#align(center)[```Java
public class Pair {
public State state;
public char c;
//Sowohl die Information zum Zustand als auch zum Character werden gespeichert
public Pair(State state, Character c) {
this.state = state;
this.c = c;
}
//Die überschriebene equals-Methode wurde schon im Listenskript behandelt
@Override
public boolean equals(Object o) {
if(this == o) {
return true;
}
if(!(o instanceof Pair)) {
return false;
}
Pair p = (Pair) o;
if(p.state == this.state && p.c == this.c) {
return true;
}
return false;
}
/*Die hashCode-Funktion muss überschrieben werden, um unser Pair als
Schlüssel in der HashMap verwenden zu können. Wir verwenden einfach
die Java-interne Hash-Funktion dafür.*/
@Override
public int hashCode() {
return Objects.hash(state, c);
}
}
```]
Der Rohbau hat jetzt mehr Zustände, da sowohl der Startzustand, der aktuelle Zustand, die HashMap als auch die Endzustände gespeichert und gesetzt werden müssen:
#align(center)[```Java
public class DEA {
private State state;
private State[] finalStates;
private HashMap<Pair, State> stateMap = new HashMap<Pair, State>();
private State startState;
public void reset(State startState, HashMap<Pair, State> map, State[] finalStates) {
this.startState = startState;
state = startState;
stateMap = map;
this.finalStates = finalStates;
}
}
```]
Die _testWord()_-Methode sieht vom Grundaufbau her ähnlich aus, die _switchState()_-Methode entfällt jedoch, da dafür direkt die HashMap verwendet werden kann. Wir entnehmen mit der aktuellen Kombination aus Zustand und zu verarbeitendem Character den nächsten Zustand aus der HashMap und setzen damit den aktuellen Zustand neu.
Das Entnehmen liefert allerdings standardmäßig null zurück, sollte der Eintrag nicht in der HashMap sein, deswegen wird bei einem "falschen" Zeichen, das nicht im Alphabet enthalten ist, der aktuelle Zustand auf null gesetzt.
#pagebreak()
#align(center)[```Java
public boolean testWord(String input) {
//Hilfs-Ausgabemethode
System.out.println("Start bei Zustand " + state);
//Analog zur ersten Implementierung
for(char c : input.toCharArray()) {
/*Der Zustand wird neu gesetzt, mit "get" erhält man
den Eintrag in der HashMap*/
state = stateMap.get(new Pair(state, c));
//Falls das aktuelle Paar nicht bekannt ist, wird null zurückgegeben
if(state == null) {
return false;
}
System.out.println("Zeichen " + c + " führt zu: " + state);
}
if(Arrays.asList(finalStates).contains(state)) {
state = startState;
return true;
} else {
state = startState;
return false;
}
}
```]
Damit ist die Implementierung schon abgeschlossen! Der Nachteil ist natürlich, dass damit die "Arbeit" des Automaten-Erstellens auf den Nutzer abgeschoben wird, die Testmethode ist dementsprechend länger:
#align(center)[```Java
public static void main(String[] args) {
State startState = State.Q0;
State[] finalStates = {State.Q2};
HashMap<Pair,State> testMap = new HashMap<Pair, State>();
//Es müssen alle Einträge der Zustandsübergangstabelle angegeben werden!
testMap.put(new Pair(State.Q0, 'a'), State.Q0);
testMap.put(new Pair(State.Q0, 'b'), State.Q1);
testMap.put(new Pair(State.Q1, 'a'), State.Q0);
testMap.put(new Pair(State.Q1, 'b'), State.Q2);
testMap.put(new Pair(State.Q2, 'a'), State.Q0);
testMap.put(new Pair(State.Q2, 'b'), State.Q3);
testMap.put(new Pair(State.Q3, 'a'), State.Q0);
testMap.put(new Pair(State.Q3, 'b'), State.Q3);
System.out.println(testMap.get(new Pair(State.Q0, 'b')));
DEA dea = new DEA();
dea.reset(startState, testMap, finalStates);
System.out.println(dea.testWord("aabb"));
System.out.println(dea.testWord("aabba"));
System.out.println(dea.testWord("aabbcc"));
}
```]
Der logische nächste Schritt wäre nun also, ein Format zu finden, in dem der Automat schneller angegeben werden kann und dann einen Konverter zu schreiben, der diesen Prozess oben automatisiert - das überlasse ich aber dem geneigten Lesy zur Übung. Flaci z.B. kann in ein JSON-Format exportieren.
#pagebreak()
#bibliography("bib.yml")
|
|
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/labels/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 0pt)
#import "/src/quill.typ": *
#let labels-everywhere = (
(content: "lt", pos: left + top),
(content: "t", pos: top),
(content: "rt", pos: right + top),
(content: "l", pos: left),
(content: "c", pos: center),
(content: "r", pos: right),
(content: "lb", pos: left + bottom),
(content: "b", pos: bottom),
(content: "rb", pos: right + bottom),
)
#quantum-circuit(
gate(hide[H], label: labels-everywhere),
)
#pagebreak()
#quantum-circuit(
1, mqgate(hide[Gate], n: 2, label: labels-everywhere), 1, [\ ],
3,
)
#pagebreak()
#quantum-circuit(
gategroup(1, 2, label: labels-everywhere), gate($X$), gate($Y$),
)
#pagebreak()
#quantum-circuit(
1, ctrl(0, label: (content: "al", pos: right + top)), 1
)
#pagebreak()
#quantum-circuit(
1, slice(label: labels-everywhere), 1, [\ ],
2, [\ ],
2, [\ ],
2, [\ ],
2, [\ ],
2,
)
#pagebreak()
#quantum-circuit(
gate("H", label: ((content: "H", pos: left, dx: 0pt, dy: 0pt))),
)
#pagebreak()
#quantum-circuit(
gate("H", label: ((content: "H", pos: bottom, dx: 0pt, dy: 0pt)))
)
#pagebreak()
#quantum-circuit(
2, slice(label: (content: "E", pos: top)),
gategroup(1,2,padding: 1em, radius: 2em, label: (content: "E", pos: bottom)), gate($H$, label: (content: "E", pos: top, dx: 50% + 2em, dy: 50%)), 2,
)
#pagebreak()
#quantum-circuit(
1, $H$, 1, $H$,[H],$I$, $S$, "H", [\ ],
lstick($|0〉$, label: "System 1"), gate($H$, label: "a"), 1, midstick("mid", label: (content: "r", pos: bottom)), 1, rstick($F$, label: "a"), setwire(0)
) |
https://github.com/kdog3682/2024-typst | https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/sinker.typ | typst | #let master = (
inline-canvas: (
length: 1in,
)
)
#let get(key, sink) = {
let ref = master.at(key)
let kwargs = sink.named()
return merge-fresh(ref, kwargs)
}
// #panic(arguments(1, foo: "a").named())
// #get("aa", arguments())
// this is the sink object
// on the one hand, need to stay on your course
// on the other hand, do need to look around
Talent Show
Something has to happen in a story ... in order for it to be a story.
There has to be rising action.
There has to be falling action.
There has to be something that the characters want.
There has to be a resolution of the want.
Is it obtained?
Is it pushed further?
Every story is
The typography is fixed to a certain degree.
Colons are still a bit of a problem.
Periods also break as orphans onto new lines.
the ruler() function is pretty cool.
if the height changes from a single iteration,
in typst, you cannot mutate objects. you can only recreate objects.
i guess this is because tracking mutations is very buggy.
|
|
https://github.com/sthenic/technogram | https://raw.githubusercontent.com/sthenic/technogram/main/src/metadata.typ | typst | MIT License | /* We keep document metadata in a stateful dict so that the we (and the user)
can query these values at arbitrary locations in the document. */
/* The global metadata state. */
#let metadata = state("metadata", (
title: none,
subtitle: none,
document-name: none,
author: none,
classification: none,
revision: none,
document-id: none,
date: none,
url: none,
))
/* Convenience function to override any number of entries in the state. */
#let update-metadata(..args) = context {
metadata.update(metadata.get() + args.named())
}
/* Convenience function to avoid exporting the state variable directly. */
#let get-metadata() = metadata.get()
|
https://github.com/rabotaem-incorporated/algebra-conspect-1course | https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/04-linear-algebra/15-linear-operators.typ | typst | Other | #import "../../utils/core.typ": *
== Линейные операторы
#ticket[Линейные операторы, условия обратимости]
#th(name: "<NAME> для линейных отображений")[
Пусть $Aa in Hom(V, W)$, $dim V = dim W < oo$. Тогда инъективность $Aa$ равносильна тому, что $Aa$ сюръективно.
]
#proof[
Инъективность $Aa$ равносильна $Ker Aa = 0 <==> dim Ker Aa = 0 <==> dim Im Aa = n <==> Im Aa = W$ равносильно $Aa$ сюръективно.
]
#def[
_Линейным оператором_ на пространстве $V$ называется элемент $End V = Hom(V, V)$.
]
#pr[
$(End V, +, compose)$ --- ассоциативное кольцо с единицей.
+ Сложение определяется как $(Aa + cal(B))(v) = Aa v + cal(B) v$.
+ Нейтральный элемент по $+$: $Id_V = 0$.
+ Нейтральным элементом по $compose$ является $id_V = epsilon_V$.
]
#proof[
Это доказывается непосредственной проверкой аксиом.
#TODO[Проверить аксиомы]
]
#denote[
Пусть $dim V = n, Aa in End V,$ $E$ --- базис $V$. Матрица $Aa$ в базисе $E$ обозначается $[Aa]_E := [Aa]_(E, E)$
]
#pr[
Пусть $E$ --- базис $V$, $dim V = n$. Тогда отображение
$
lambda: End V &--> M_n (K) \
Aa &maps [Aa]_E
$
Является изоморфизмом колец.
]
#proof[
Знаем, что $lambda$ является биекцией, тогда проверим, что она сохраняет обе операции:
$ lambda(Aa + Bb) = [Aa + Bb] = ([(Aa + Bb)e_1]_E, ..., [(Aa + Bb)e_n]_E) = ([Aa e_1 + Bb e_1]_E, ..., [Aa e_n + Bb e_n]_E) = $
$ ([Aa e_1]_E + [Bb e_1]_E, ..., [Aa e_n]_E + [Bb e_n]_E) = [Aa]_E + [Bb]_E = lambda(Aa) + lambda(Bb) $
Тот факт, что $lambda$ сохраняет умножение был проверен в параграфе про линейные отображения в более общем случае.
]
#def[
Множество обратимых операторов над $V$ обоначается $GL(V)$.
]
#pr[
Пусть $Aa in End V$, $dim V = n < oo.$ Тогда следующие утверждения эквивалентны
+ $Aa in GL(V)$
+ $rk Aa = n$
+ $Aa$ --- инъективно ($dim Ker A = 0$)
+ $exists $ базис $E$ пространства $V: [Aa]_E in GL_n (K)$
+ $forall$ базиса $E$ пространства $V: [Aa]_E in GL_n (K)$
]
#proof[#sym.zws\
"$1 <==> 2 <==> 3$": по принципу Дирихле\
"$5 ==> 4$": базисы существуют\
"$4 ==> 1$": по предыдущему предложению\
"$1 ==> 5$": по предыдущему предложению
]
#pr[
Пусть $E, F$ --- базисы пространства $V$, $dim(V) = n < oo$, $C = M_(E arrow F)$. Тогда
$ [Aa]_F = C^(-1) mul [Aa]_E mul C $
]
#proof[
Из соответствующего предложения про линейные отображения.
]
#def[
Матрица $B$ называется _эквивалентной_ матрице $A$, если существует $C in GL_n (K): B = C^(-1) A C$.
]
|
https://github.com/EpicEricEE/typst-marge | https://raw.githubusercontent.com/EpicEricEE/typst-marge/main/tests/parameter/gap/test.typ | typst | MIT License | #import "/src/lib.typ": sidenote
#set par(justify: true)
#set page(width: 8cm, height: auto, margin: (outside: 4cm, rest: 5mm))
#let sidenote = sidenote.with(numbering: "1")
#lorem(3)
#sidenote[Normal gap.]
#lorem(3)
#sidenote[Normal gap.]
#lorem(3)
#sidenote(gap: 0pt)[Small gap.]
#lorem(3)
#sidenote(gap: 0pt)[Small gap.]
#lorem(3)
#sidenote(gap: 1.5em)[Large gap.]
#lorem(3)
#sidenote[Normal gap.]
#lorem(3)
#sidenote[Normal gap.]
#lorem(12)
#set page(height: 7cm)
#lorem(12)
#sidenote[Normal gap.]
#lorem(3)
#sidenote[Normal gap.]
#lorem(3)
#sidenote(gap: 0pt)[Small gap.]
#lorem(3)
#sidenote(gap: 0pt)[Small gap.]
#lorem(3)
#sidenote(gap: 1.5em)[Large gap.]
#lorem(3)
#sidenote[Normal gap.]
#lorem(3)
#sidenote[Normal gap.]
|
https://github.com/emsquid/projet-chiffres | https://raw.githubusercontent.com/emsquid/projet-chiffres/main/enonce.typ | typst | #let project(title: "", authors: (), body) = {
set document(author: authors, title: title)
set page(numbering: "1", number-align: center)
set text(font: "New Computer Modern", lang: "fr")
set par(justify: true)
show list: set block(below: 1%)
show math.equation: set text(weight: 400)
show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
align(center)[#block(text(weight: 700, 1.75em, title))]
linebreak()
body
}
#show: project.with(
title: "Reconnaissance de chiffres en Python",
authors: ("Emanuel", "David"),
)
== Objectif :
Le but des exercices de cette feuille est de réussir à créer un algorithme en Python
permettant de reconnaître un chiffre à travers une image. \
On implémentera ainsi différentes méthodes, plus ou moins simples,
pour ce qui est des images on pourra utiliser cette
#link("https://github.com/emsquid/projet-chiffres/blob/main/chiffres.tar.gz")[#text("archive", fill: blue)].
(Pour l'extraire : ```bash tar -xzf chiffres.tar.gz```) \
_Remarque_ : Les parties sont organisées de manière linéaire, il sera utile de réutiliser ce que vous aurez fait.
== Préparation :
Avant de reconnaître des chiffres on doit pouvoir lire et manipuler des images en Python.
Dans toute la feuille on considére une image de largeur *l* et de hauteur *h*.
+ Tout d'abord on aura besoin d'une fonction pour lire cette image depuis un fichier,
on pourra par exemple utiliser la classe ```python Image``` de la librairie ```python PIL```. \
(_Pour l'installer_ : ```bash pip3 install Pillow```)
+ Ensuite il faut une fonction pour passer de l'image à un objet plus simple à manipuler,
on pourra la représenter comme une *matrice* de pixels
de taille $1 times bold(l) dot.op bold(h)$, par exemple avec la librairie ```python numpy```.
On devra aussi transformer les couleurs en une valeur dans $[bold(0), bold(1)]$. \
(_Remarque_ : On fera attention à ce que notre matrice soit bien
en 2 dimensions pour pouvoir utiliser le produit matriciel correctement)
+ Enfin on pourra faire une fonction pour récupérer une liste contenant
tous les couples de référence `(image, chiffre)` depuis un répertoire. \
(_Remarque_ : pour lister tous les fichiers d'un répertoire on pourra utiliser
la fonction ```python listdir(repertoire)``` de la librairie ```python os```)
== Partie 1 : Les k plus proches voisins <partie1>
Dans cette première partie on va considérer une image comme un *point* ou un *vecteur*
de $[bold(0), bold(1)]^(bold(l) dot.op bold(h))$.
Ainsi en calculant la *distance* entre deux points ou le *produit scalaire* de deux vecteurs,
on peut obtenir une mesure de la ressemblance d'une image à une autre
et utiliser la méthode des
#link("https://fr.wikipedia.org/wiki/M%C3%A9thode_des_k_plus_proches_voisins")[#text("k plus proches voisins.", fill: blue)]
+ D'abord on crée une fonction pour calculer la *distance*
entre deux points de $[bold(0), bold(1)]^(bold(l) dot.op bold(h))$. \
On pourra appliquer la formule de la distance euclidienne
de la même manière que dans l'espace,
ou une autre si vous trouvez plus intéressant. \
(_Remarque_ : pour les performances on pourra enlever la racine carré dans
la formule de la distance euclidienne qui n'est pas nécessaire ici)
+ On fera aussi une fonction pour calculer le *produit scalaire*
de deux vecteurs de $[bold(0), bold(1)]^(bold(l) dot.op bold(h))$.
Encore une fois, la formule s'applique de la même manière que dans l'espace.
+ Enfin on peut créer une fonction pour reconnaître un chiffre depuis une image,
pour ça on peut trouver les *k* images parmi les références
dont les points sont les *moins distants*,
ou dont les vecteurs se *ressemblent le plus*,
et en déduire le chiffre. \
On pourra comparer la méthode avec la distance et celle avec le produit scalaire
pour voir laquelle fonctionne le mieux. \
== Partie 2 : Base d'un réseau neuronal <partie2>
Dans cette deuxième partie on va toujours utiliser l'image comme une matrice *m*,
et on va vouloir calculer à partir de celle-ci une *matrice* de taille $1 times 10$,
$bold(p) = mat(p_0, p_1, ..., p_8, p_9;)$,
où $p_n in [0, 1]$ représente la *probabilité* que $n$ soit le chiffre de l'image. \
Pour ça on va utiliser deux matrices paramètres,
une matrice de poids *W* de taille $bold(l) dot.op bold(h) times 10$
et une matrice de biais *b* de taille $1 times 10$. \
1. On commence par initialiser *W* et *b* avec des 0,
on pourrait aussi utiliser des distributions aléatoires,
à vous de voir ce qui fonctionne le mieux.
Vous pouvez remarquer qu'en utilisant l'application affine
$bold(p) = bold(m) dot.op bold(W) + bold(b)$
on peut obtenir la taille voulue pour *p*.
2. On fait donc une fonction pour calculer ce résultat,
on pensera à faire attention à bien utiliser le produit matriciel
et à la taille de la matrice de sortie.
Mais on a un problème, les valeurs de *p* ne sont pas dans l'intervalle $[0, 1]$
et ne s'apparentent pas à des probabilités.
3. On va utiliser la fonction
#link("https://fr.wikipedia.org/wiki/Sigmo%C3%AFde_(math%C3%A9matiques)")[#text("sigmoïde", fill: blue)]
dont l'expression est $sigma : x arrow.r.bar 1 / (1 + e^(-x)) in [0, 1]$
et l'appliquer à notre matrice *p* pour la rendre correcte.
De plus, dans ce calcul *W* et *b* ne nous apportent pour l'instant aucune information,
il va falloir que notre réseau apprenne de ses erreurs pour qu'ils prennent du sens.
Pour ça on va utiliser une
#link("https://fr.wikipedia.org/wiki/Fonction_objectif")[#text("fonction objectif", fill: blue)],
ce type de fonction permet d'évaluer la qualité de nos prédictions,
et on modifiera nos paramètres en se basant sur sa dérivée. \
(_Remarque_ : on s'intéresse à la dérivée car le but est de trouver un minimum,
ce qui revient à avoir fait une bonne prédiction)
4. Ici on va utiliser la fonction d'#link("https://fr.wikipedia.org/wiki/Erreur_quadratique_moyenne")[#text("erreur quadratique moyenne", fill: blue)],
pour faire simple sa dérivée est donnée par
$bold(p) arrow.r.bar bold(p) - mat(0, ..., 0, 1, 0, ..., 0;)$
avec le 1 à l'indice $n$, où $n$ est le chiffre à prédire.
Vous pourrez essayer d'en trouver une meilleure.
Après l'avoir implémenté, on veut propager le résultat
en retournant en arrière dans notre réseau neuronal.
5. Pour ça on multiplie le résultat précédent par
la dérivée de la fonction sigmoïde en $bold(p)$, terme à terme,
on appelle ce produit $Delta$. \
(_Remarque_ : si on voulait retourner plus en arrière
on pourrait continuer avec la dérivée de l'application affine
$bold(m) dot.op bold(W) + bold(b)$)
Tout en propageant le résultat, on veut aussi améliorer *W* et *b*,
on va pouvoir utiliser $Delta$ après l'avoir calculé.
6. On crée une fonction pour modifier nos deux paramètres :
- Le changement que reçoit *W* est $bold(W) arrow.r.bar bold(W) - alpha dot.op bold(m)^t dot.op Delta$
- Le changement que reçoit *b* est simplement $bold(b) arrow.r.bar bold(b) - alpha dot.op Delta$
Où $alpha in [0, 1]$ représente la *vitesse d'apprentissage*,
et $bold(m)^t$ est la transposée (pour que le produit matriciel soit possible).
7. Avec tout ça on peut faire une fonction intermédiaire pour s'entraîner sur une image,
on commence par calculer une prédiction $bold(p) = sigma(bold(m) dot.op bold(W) + bold(b))$,
puis on lui applique $Delta$ avant de retourner en arrière et d'ajuster nos paramètres.
En répétant cette opération pour plusieurs images
on améliore petit à petit nos paramètres et nos prédictions deviennent meilleures.
8. Pour terminer on peut donc faire une fonction qui s'entraîne sur un ensemble d'images,
on peut répéter plusieurs fois en *mélangeant* les images
et calculer le pourcentage de réussite pour chaque génération sur des images de test.
En fonction de l'ensemble de base utilisé on peut rapidement arriver entre 80% et 90% de prédictions réussites.
En bonus on peut essayer de sauvegarder nos paramètres *W* et *b* lorsque le pourcentage de réussite augmente.
== Partie 3 : Réseau neuronal séquentiel <partie3>
Dans cette troisième partie, nous allons construire un réseau neuronal séquentiel,
contrairement à la partie précédente où l'on avait une seule couche,
on aura plusieurs couches de tailles différentes ayant chacune leurs poids et leurs biais,
chaque couche aura un unique prédécesseur et un unique successeur. \
À la fin, on peut imaginer que notre système neuronal ressemblera à ça :
#figure(
image("exemple.png", width: 60%),
caption: [Un réseau neuronal à deux couches],
)
Par exemple, dans un réseau avec 3 couches, au lieu de faire directement $bold(p) = bold(m) dot.op bold(W) + bold(b)$,
on va calculer $bold(p) = ((bold(m) dot.op bold(W_1) + bold(b_1)) dot.op bold(W_2) + bold(b_2)) dot.op bold(W_3) + bold(b_3)$,
où $bold(W_n)$ et $bold(b_n)$ sont les matrices de poids et de biais de la couche n,
l'idée est d'avoir plusieurs étapes au lieu de passer directement de l'image à une prédiction. \
(_Exemple_ : $bold(m) = 1 times bold(784) arrow.r 1 times bold(392) arrow.r 1 times bold(196) arrow.r 1 times bold(10) = bold(p)$)
1. Créons d'abord une classe pour représenter une *couche*.
Une couche aura donc des données en entrée $bold(e)$ et en sortie $bold(s)$,
elle aura également un *prédécesseur* et un *successeur* (```python None``` si elle n'en a pas),
ainsi qu'une matrice de poids *W* et une matrice de biais *b*. \
(_Remarque_ : la tailles de *W* et *b* dépendra de la taille voulue pour l'entrée et la sortie)
Pour commencer on a besoin de calculer la sortie d'une couche à partir de son entrée.
2. On peut faire une méthode pour faire ce calcul à partir de *W* et *b*,
on peut se référer aux questions 2 et 3 de la #link(label("partie2"))[#text("partie 2", fill: blue)].
Pour la suite nos couches ont besoin de pouvoir s'échanger leurs résultats.
3. On a d'abord besoin d'une méthode permettant à une couche de se *connecter* à une autre,
cela permettra de récupérer les données venant de la suivante ou de la précédente.
4. Ensuite, pour faciliter les prochaines exécutions, on peut créé une méthode
pour récupérer les données en *entrée* d'une couche, c'est à dire la sortie de la couche précédente
(pensez à traiter le cas où la couche n'a pas de prédécesseur).
Maintenant que nos différentes couches peuvent interagir, on peut les utiliser dans un réseau neuronal.
5. Dans un premier temps, nous pouvons créer une classe pour représenter un *réseau neuronal*.
un réseau neuronal est simplement composée d'une liste de *couches*.
On ajoutera une méthode permettant d'ajouter une couche au réseau neuronal et de la connecter à la dernière.
Dans les prochaines questions nous allons nous concentrer sur l'apprentissage de notre réseau neuronal.
6. Nous pouvons implémenter une méthode entrainant notre système neuronal sur une image,
elle prendra comme paramètre notre *image*, le *chiffre* associé à l'image, et la vitesse d'apprentissage $bold(alpha)$.
Dans cette fonction, nous donnerons à notre première couche l'image comme entrée,
puis on transmettra le résultat à chaque couche l'une après l'autre, jusqu'à obtenir la prédiction $bold(p)$.
Une fois que l'image est passée par toutes nos couches, il va falloir évaluer le résultat et retourner en arrière.
7. Ainsi, on peut modifier nos *couches* pour qu'elles aient deux nouveaux attributs,
le delta d'entrée $Delta_e$ et le delta de sortie $Delta_s$,
les deltas nous indiquent les changements à appliquer à chaque couche.
8. Ensuite, pour faciliter les prochaines exécutions, on peut créé une méthode
pour récupérer le delta en *entrée* d'une couche, c'est à dire le delta en sortie de la couche suivante
(pensez à traiter le cas où la couche n'a pas de successeur).
Maintenant on peut utiliser ces deux attributs pour retourner en arrière et modifier nos paramètres pour chacune de nos couches.
9. On peut créer une méthode qui nous permet de faire ça en se basant sur le delta en entrée $Delta_e$ de notre couche.
On définit $Delta = sigma'(bold(e) dot.op bold(W) + bold(b)) times Delta_e$ (la multplication $times$ est faite terme à terme)
et les paramètres de chaque couche sont modifiées comme suit :
- Le changement que reçoit $bold(W)$ est $bold(W) arrow.r.bar bold(W) - alpha dot.op bold(m)^t dot.op Delta$
- Le changement que reçoit $bold(b)$ est simplement $bold(b) arrow.r.bar bold(b) - alpha dot.op Delta$
Enfin on définit le delta de sortie $Delta_s = Delta dot.op bold(W)^t$
10. Maintenant on peut changer notre méthode d'entrainement pour qu'elle retourne en arrière après avoir évalué une image, notre premier $Delta_e$ sera obtenu comme dans la question 4 de la #link(label("partie2"))[#text("partie 2", fill: blue)].
11. Pour suivre on peut faire une fonction qui s'entraîne sur un ensemble d'image comme dans la question 8 de la #link(label("partie2"))[#text("partie 2", fill: blue)].
12. Pour finir vous pouvez initialiser votre réseau neuronal, ajouter des neurones (attention aux dimensions d'entrée et de sortie), et l'entraîner sur le jeu de données fourni.
_Remarque_ : Si vous ajoutez un unique neurone, le résultat sera très similaire à la partie 2.
Cependant, ajouter plusieurs neurones prendra plus de temps au niveau de l'entraînement,
mais le changement des paramètres dans l'ensemble du réseau neuronal sera plus précis.
|
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/机器视觉实践/报告/3/3.typ | typst | The Unlicense | #import "../template.typ": *
#show: project.with(
title: "3",
authors: ("absolutex",),
)
= 机器视觉实践 三
== 实验目的
人脸图像祛痣
+ 去除人脸上的痣,使其恢复正常皮肤
+ 要求图像祛痣算法具有实时性
+ 要求实现图像局部祛痣,即在祛痣的同时保持无痣区域的颜色和对比度不变
+ 具体祛痣方法不限
+ 编程语言不限,可通过C++,Python或Matlab 实现
== 实验内容
一般祛痣广泛使用的有两种方法,一个是用 inpaint 计算出来,另一个是直接拿另一片区域的皮肤填补有痣区域的皮肤。这里把两个方法都实现了一遍。
当然下下策是使用单一色块填补,在人脸祛痣这种区域,如果使用单一色块直接覆盖,明显能看出p图痕迹。
=== inpaint
这里直接复用了第一次实验的 inpaint 代码,该代码使用一层用户手绘的蒙版作为 mask。inpaint 的调用在 ipt 函数里,这里不再赘述。
#include_code("../src/mole/inpaint.py")
=== 区域复制
这里是区域复制的不完整代码,ImageRegionFillApp 继承自另一个文件的 ImageTkApp,主要是一些底层代码,这里不放出。
代码使用两阶段绘制,第一个阶段是绘制一条直线到用户指定的区域,建立起区域与区域的映射关系,第二阶段是鼠标拖拽这条直线,将线段终点区域的色块(半径为 3 的圆形区域)复制到线段起点,也就是痣的区域。
鼠标右键可以从第二阶段回到第一阶段,以处理多个痣。
#include_code("../src/mole/move_region.py")
== 实验结果与心得体会
本次实验使用的素材是大模型生成的现实中不存在的人脸,痣是我自己用 GIMP 点上去的。
=== inpaint
#figure(
image("inpaint.jpg", width: 100%),
caption: [inpaint 去痣 效果图],
)
inpaint 效果主要取决于蒙版画的范围是否精确,越精确,边缘的色块突变越少。
本次实验 inpaint 的结果远看没有什么问题,近看的话还是能看出,去痣区域的内部颜色过于均匀,可以看出伪造痕迹。
=== 区域复制
#figure(
image("move_region.jpg", width: 100%),
caption: [区域复制去痣 效果图],
)
区域复制去痣更加考验手法。特别是这次的图像刚好有痣在脸部高光的分界处,如何选取色块来源可以让脸部的光线变化更加平缓,这是一个技术活。需要经过多次尝试,才能达成这样的效果。
|
https://github.com/Caellian/UNIRI_voxels_doc | https://raw.githubusercontent.com/Caellian/UNIRI_voxels_doc/trunk/main.typ | typst | #import "template.typ": config, figure-list
#show "TODO": box(fill: red, outset: 2pt, text(fill: white, weight: "black", "NEDOSTAJE SADRŽAJ"))
#show: config(
[Završni rad],
[Metode prikaza volumetrijskih struktura u računalnoj grafici],
[Tin Švagelj],
attributions: [
*Mentor:* doc. dr. sc., <NAME>
],
inserts: [
#include "problem.typ"
#include "summary.typ"
]
)
#include "./content/uvod.typ"
#include "./content/strukture.typ"
#include "./content/raytrace.typ"
#include "./content/prijevremeno.typ"
#include "./content/realno_vrijeme.typ"
#include "./content/generiranje.typ"
#include "./content/animacije.typ"
#include "./content/usporedba.typ"
#include "./content/zakljucak.typ"
#bibliography(
title: "Literatura",
"references.bib",
style: "ieee"
)
#figure-list()
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/math/vec.typ | typst | // Test vectors.
--- math-vec-gap ---
#set math.vec(gap: 1em)
$ vec(1, 2) $
--- math-vec-align ---
$ vec(-1, 1, -1, align: #left)
vec(-1, 1, -1, align: #center)
vec(-1, 1, -1, align: #right) $
--- math-vec-align-explicit-alternating ---
// Test alternating alignment in a vector.
$ vec(
"a" & "a a a" & "a a",
"a a" & "a a" & "a",
"a a a" & "a" & "a a a",
) $
--- math-vec-wide ---
// Test wide cell.
$ v = vec(1, 2+3, 4) $
--- math-vec-delim-set ---
// Test alternative delimiter.
#set math.vec(delim: "[")
$ vec(1, 2) $
--- math-vec-delim-empty-string ---
// Error: 22-24 expected exactly one character
#set math.vec(delim: "")
--- math-vec-delim-not-single-char ---
// Error: 22-39 expected exactly one character
#set math.vec(delim: "not a delimiter")
--- math-vec-delim-invalid-char ---
// Error: 22-25 invalid delimiter: "%"
#set math.vec(delim: "%")
--- math-vec-delim-invalid-symbol ---
// Error: 22-33 invalid delimiter: "%"
#set math.vec(delim: sym.percent)
--- math-vec-delim-invalid-opening ---
// Error: 22-33 invalid delimiter: "%"
#set math.vec(delim: ("%", none))
--- math-vec-delim-invalid-closing ---
// Error: 22-33 invalid delimiter: "%"
#set math.vec(delim: (none, "%"))
|
|
https://github.com/mitinarseny/invoice | https://raw.githubusercontent.com/mitinarseny/invoice/main/src/parties.typ | typst | #import "./utils.typ": mailto, tel
#let address(addr) = [
#if "street" in addr [
#addr.street, \
]
#if "city" in addr [
#addr.city,
]
#if "country" in addr [
#addr.country \
]
#if "postal_code" in addr [
#addr.postal_code
]
]
#let party(details) = align(horizon, table(
columns: 1,
stroke: none,
[*#details.name*],
[],
eval(details.at("info", default: ""), mode: "markup"),
[#if "address" in details [
_Address:_ \
#address(details.address)
]],
[],
[
#if "email" in details [
_e-mail:_: #mailto(details.email)
] \
#if "tel" in details [
_tel_: #tel(details.tel)
]
],
))
#let parties(contractor, billed_to) = table(
columns: (1fr, 1fr),
stroke: (x, y) => {
if x == 0 {(right: 1pt)} else {none} + if y == 0 {(bottom: 1pt)} else {none}
},
table.header(align(center)[== Contractor], align(center)[== Billed To]),
party(contractor), party(billed_to),
) |
|
https://github.com/txtxj/Formal-Methods-Typst | https://raw.githubusercontent.com/txtxj/Formal-Methods-Typst/main/sample.typ | typst | #import "template.typ": *
#import "formal_method_template.typ": proof
(1) #proof(
$(p and q) and r$, [p],
$s and t$, [p],
$p and q$, [$and e_1$ 1],
$q$, [$and e_2$ 3],
$s$, [$and e_1$ 2],
$q and s$, [$and i$ 4,5]
)
#line(length: 100%)
(2) #proof(
$q->r$, [p],
[+], 5,
$p->q$, [a],
[+], 3,
$p$, [a],
$q$, [$-> e$ 2,3],
$r$, [$-> e$ 1,4],
$p->r$, [$-> i$ 3-5],
$(p->q)->(p->r)$, [$-> i$ 2-6],
)
#line(length: 100%)
(3) #proof(
[+], 8,
$q$, [a],
[+], 6,
$p$, [a],
[+], 4,
$p$, [a],
[+], 2,
$q$, [a],
$p$, [Copy 3],
$q->p$, [$-> i$ 4-5],
$p->(q->p)$, [$-> i$ 3-6],
$p->(p->(q->p))$, [$-> i$ 2-7],
$q->(p->(p->(q->p)))$, [$-> i$ 1-8]
)
#pagebreak()
(4) #proof(
$p->q and r$, [p],
[+], 3,
$p$, [a],
$q and r$, [$-> e$ 1,2],
$q$, [$and e_1$ 3],
$p->q$, [$-> i$ 2-4],
[+], 3,
$p$, [a],
$q and r$, [$-> e$ 1,6],
$r$, [$and e_2$ 7],
$p->r$, [$-> i$ 6-8],
$(p->q) and (p->r)$, [$and i$ 5,9]
)
#line(length: 100%)
(5) #proof(
$p and not p$, [p],
$p$, [$and e_1$ 1],
$not p$, [$and e_2$ 1],
$bot$, [$not e$ 2,3],
$not(r -> q) and (r -> q)$, [$bot e$ 4]
)
#pagebreak()
(6) #proof(
$exists x(S->Q(x))$, [p],
[+], 5,
$S$, [a],
[+], 3,
$x_0$, [x],
$S->Q(x_0)$, [a],
$Q(x_0)$, [$-> e$ 3,2],
$exists x Q(x)$, [$exists x space i$ 4],
$exists x Q(x)$, [$exists x space e$ 1,3-5],
$S->exists x Q(x)$, [$-> i$ 2,6]
)
#pagebreak()
(7) #proof(
$forall x P(x) -> S$, [p],
[+], 24,
$not exists x(P(x) -> S)$, [a],
[+], 18,
$x_0$, [x],
$$, [],
[+], 3,
$P(x_0)->S$, [a],
$exists x (P(x)->S)$, [$exists x space i$ 4],
$bot$, [$not e $ 5,2],
$not (P(x_0)->S)$, [$not i$ 4-6],
[+], 5,
$S$, [a],
[+], 2,
$P(x_0)$, [a],
$S$, [Copy 8],
$P(x_0)->S$, [$-> i$ 9-10],
$bot$, [$not e$ 11,7],
$not S$, [$not i$ 8-12],
[+], 6,
$not P(x_0)$, [a],
[+], 3,
$P(x_0)$, [a],
$bot$, [$not e$ 15,14],
$S$, [$bot e$ 16],
$P(x_0)->S$, [$->i$ 15-17],
$bot$, [$not e $ 18,7],
$P(x_0)$, [PBC 14-19],
$forall x not S$, [$forall x space i$ 3-13],
$not S$, [$forall x space e$ 21],
$forall x P(x)$, [$forall x space i$ 3-20],
$S$, [$-> e$ 1,23],
$bot$, [$not e$ 24,22],
$exists x (P(x)->S)$, [PBC 2-25]
)
#pagebreak()
(8) #proof(
$forall x(P(x) and Q(x))$, [p],
[+], 2,
$x_0$, [x],
$P(x_0) and Q(x_0)$, [$forall x space e$ 1],
$P(x_0)$, [$and e_1$ 2],
$forall x P(x)$, [$forall x space i$ 2-3],
[+], 2,
$x_0$, [x],
$P(x_0) and Q(x_0)$, [$forall x space e$ 1],
$Q(x_0)$, [$and e_1$ 5],
$forall x Q(x)$, [$forall x space i$ 5-6],
$forall x P(x) and forall x Q(x)$, [$and i$ 4,7]
)
#line(length: 100%)
(9) #proof(
$not forall x not P(x)$, [p],
[+], 8,
$not exists x P(x)$, [a],
[+], 5,
$x_0$, [x],
$$,[],
[+], 3,
$P(x_0)$, [a],
$exists x P(x)$, [$exists x space i$ 4],
$bot$, [$not e$ 5, 2],
$not P(x_0)$, [$not space i$ 4-6],
$forall x not P(x)$, [$forall x space i$ 3-7],
$bot$, [$not e$ 8,1],
$exists x P(x)$, [PBC 2-9],
)
#line(length: 100%)
(10) #proof(
$forall x not P(x)$, [p],
[+], 5,
$exists x P(x)$, [a],
[+], 3,
$x_0$, [x],
$P(x_0)$,[a],
$not P(x_0)$, [$forall x space e$ 1],
$bot$, [$not e$ 3,4],
$bot$, [$exists e$ 2,3-5],
$not exists x P(x)$, [$not i$ 2-6]
) |
|
https://github.com/malramsay64/resume | https://raw.githubusercontent.com/malramsay64/resume/main/utils.typ | typst | // Helper Functions
#let monthname(n, display: "short") = {
n = int(n)
let month = ""
if n == 1 { month = "January" }
else if n == 3 { month = "March" }
else if n == 2 { month = "February" }
else if n == 4 { month = "April" }
else if n == 5 { month = "May" }
else if n == 6 { month = "June" }
else if n == 7 { month = "July" }
else if n == 8 { month = "August" }
else if n == 9 { month = "September" }
else if n == 10 { month = "October" }
else if n == 11 { month = "November" }
else if n == 12 { month = "December" }
else { result = none }
if month != none {
if display == "short" {
month = month.slice(0, 3)
} else {
month
}
}
month
}
#let strpdate(isodate) = {
let date = ""
if lower(isodate) != "present" {
date = datetime(
year: int(isodate.slice(0, 4)),
month: int(isodate.slice(5, 7)),
day: int(isodate.slice(8, 10))
)
date = date.display("[month repr:short]") + " " + date.display("[year repr:full]")
} else if lower(isodate) == "present" {
date = "Present"
}
return date
}
#let filter_visible(info, section) = {
if section in info and info.at(section) != none {
info.at(section).filter(i => i.at("display", default: true))
} else {
info.section = []
}
}
#let validate_work_instance(info) = {
assert("organization" in info, message: "Work instance: must include the key: organization" + info.keys().join(","))
let base_msg = "work instance: " + info.organization + "must include the key: "
if "positions" in info {
for position in info.positions {
let base_msg = "work.positions instance: " + info.organization + "must include the key: "
assert("position" in position, message: base_msg + "position")
assert("startDate" in position, message: base_msg + "startDate")
if "endDate" not in position {
position.endDate = "present"
}
if "summary" not in position {
position.summary = ""
}
if "highlights" not in position {
position.highlights = []
}
}
} else {
let position = (:)
assert("position" in info, message: base_msg + "position")
assert("startDate" in info, message: base_msg + "startDate")
position.position = info.remove("position")
position.startDate = info.remove("startDate")
position.endDate = info.remove("endDate", default: "present")
position.summary = info.remove("summary", default: "")
position.highlights = info.remove("highlights", default: [])
info.positions = (position, )
}
info
}
|
|
https://github.com/Servostar/dhbw-abb-typst-template | https://raw.githubusercontent.com/Servostar/dhbw-abb-typst-template/main/src/conf.typ | typst | MIT License |
// .--------------------------------------------------------------------------.
// | Configuration |
// '--------------------------------------------------------------------------'
// Author: <NAME>
// Edited: 27.06.2024
// License: MIT
#import "branding.typ": *
// default configuration
#let default-config = (
// language settings used to make decisions about hyphenation and others
lang: "en", // ISO 3166 language code of text: "de", "en"
region: "en", // region code
// mark this thesis as draft
// Adds preleminarry note page and watermark
draft: true,
// information about author(s)
author: (
name: "<NAME>",
semester: 4,
program: "Informationtechnology",
course: "TINF19IT1",
faculty: "Technik",
university: "DHBW Mannheim",
company: "ABB AG",
supervisor: "<NAME>",
matriculation-number: 123456789),
// information about thesis
thesis: (
title: "Unofficial ABB/DHBW Typst template",
subtitle: "for reports and thesises", // subtitle may be none
submission-date: "23rd march 2020",
timeframe: "1st january 2020 - 20th march 2020",
kind: "T2000",
// translated version of abstract, only used in case language is not english
summary: none,
abstract: none,
preface: none,
keywords: ( "IT", "other stuff" ),
bibliography: none /* bibliography("refs.bib") */,
glossary: none,
appendices: none),
style: (
header: (
content-padding: 1.5em,
underline-top-padding: 0pt,
logo-height: 3em),
footer: (
content-padding: 1.5em),
page: (
format: "a4",
margin: (
left: 3cm,
right: 2.5cm,
top: 2.5cm,
bottom: 2.5cm)),
text: (
size: 12pt,
font: "Fira Sans"),
heading: (
font: "Fira Sans"),
code: (
theme: "res/abb.tmTheme",
font: "FiraCode Nerd Font",
lines: false,
size: 10pt,
tab-size: 4),
link: (
color: ABB-GRAY-02)))
// Insert a dictionary `update` into `base` but only the entries of update that also exist in base
// Runs recursively on all sub dictionaries
#let deep-insert-checked(base, update) = {
if base == none {
panic("target dictionary is none")
}
if update == none {
return base
}
for (key, val) in base {
if key in update {
let update_val = update.at(key)
if type(val) == dictionary and type(update_val) == dictionary {
base.insert(key, deep-insert-checked(val, update_val))
} else if val == none or type(val) == type(update_val) {
base.insert(key, update_val)
} else {
panic("missmatched dictionary entry `" + key + "` type: expected `" + type(val) + "` got `" + type(update_val) + "`")
}
} else {
base.insert(key, val)
}
}
return base
}
#let validate-config(config) = {
return deep-insert-checked(default-config, config)
}
|
https://github.com/El-Naizin/cv | https://raw.githubusercontent.com/El-Naizin/cv/main/modules_en/projects.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Personnal Projects")
#cvEntry(
title: [Development of a rust profiler],
society: [Personnal UTC project], //todo: reformluler
date: [2023 - Present],
location: [],
description: list(
[Develeppoment in rust, of a *multi-architecture*, *multi-platform* application],
[Originated from the need for an open-source rust profiler, since most profilers target linux, with the perf library],
[Implementation of *conditionnal builds*],
[Reverse engineering of *MacOS PrivateFramework* kperf],
)
)
/*
#cvEntry(
title: [Solving Helltaker game with Logic Programming methods],
society: [School project],
date: [2022],
location: [],
description: list(
[Solved Helltaker levels with the Constraint programming method, using a *SAT solver*],
[Solved Helltaker levels with *Answer set programming*],
)
)
*/
#cvEntry(
title: [Implementation of Delaunay triangulation in $O(n log(n))$ complexity],
society: [Personnal project],
date: [2022],
location: [],
description: list(
[Read <NAME>as and Jorge Stolfi's 1985 paper],
[Implemented proposed method in *Rust*, with *nannou library* for rendering],
//[Efficient triangulation, but inefficient rendering],
//[Project coded to *learn Rust*],
)
)
#cvEntry(
title: [Coded an assembly SIMD image filter],
society: [School project],
date: [Autumn 2021],
location: [],
description: list(
[*SIMD* program was 4 times faster than *03* C program],
[Edge detection filter with the Kovalevsky method],
)
)
#cvEntry(
title: [Coded a 3D rendering engine in vulkan],
society: [Personnal project],
date: [Summer 2020],
location: [],
description: list(
[Learned how to use the *Vulkan API* and *OpenGL* in *C++* code],
[Learned pipeline systems for 3D rendering],
[*Toolchain* setup with premake *build tool* after using CMake],
)
)
/*
#cvEntry(
title: [Coded a game in Java with JavaFX],
society: [School project],
date: [2019],
location: [],
description: list(
[Coded a simple physics engine in Java],
[Managed a *Git* repository, I was in charge of *merging* branches],
[Used an Object-Oriented aproach, with an UML document produced],
)
)
*/
#cvEntry(
title: [Coded a Huffman compression algorithm in C],
society: [Personnal project],
date: [2018],
location: [],
description: list(
[To learn about *pointers*, and *data structures*],
[Learned how to properly use *Git* with this project],
)
)
/*
#cvEntry(
title: [],
society: [],
date: [],
location: [],
description: list(
[],
)
)
*/
|
https://github.com/mkhoatd/Typst-CV-Resume | https://raw.githubusercontent.com/mkhoatd/Typst-CV-Resume/main/CV/typstcv_single.typ | typst | MIT License | #let date_colour= rgb("#666666")
#let primary_colour= rgb("#2b2b2b")
#let headings_colour= rgb("#6A6A6A")
#let subheadings_colour= rgb("#333333")
#let recepient(date, department, university,address, postcode) = {
align(left,{
text(10pt,font: "Helvetica", fill: subheadings_colour,weight: "bold", )[#department]
h(1fr)
text(10pt,font: "Helvetica", fill: primary_colour,weight: "light", )[#date\ ]
text(10pt,font: "Helvetica", fill: subheadings_colour,weight: "bold", )[#university\ ]
text(10pt,font: "Helvetica", fill: headings_colour,weight: "light", )[#address\ ]
text(10pt,font: "Helvetica", fill: headings_colour,weight: "light", )[#postcode ]
}
)
}
// Section Headings (Education, Experience, etc)
#let section(title) = {
text(12pt,font: "Helvetica", fill: headings_colour,weight: "light", )[#upper[#title]\ ]
}
// Subsection Headings (University, Company, etc)
#let subsection(content) = {
text(11pt,font: "Helvetica", fill: subheadings_colour,weight: "bold", )[#upper[#content] ]
}
#let education(university, major, period, location, detail) = {
text(11pt,font: "Helvetica", fill: subheadings_colour,weight: "bold", )[#upper[#university] ]
h(1fr)
text(11pt,font: "Heiti TC", fill: headings_colour, weight: "medium", )[#period \ ]
text(11pt, font: "Heiti SC", fill: subheadings_colour,weight: "semibold",)[#major ]
h(1fr)
text(11pt,font: "Heiti TC", fill: headings_colour, weight: "medium", )[#location \ ]
if detail != [] or detail != "" {
text(11pt,font: "Helvetica", fill: primary_colour,weight: "light", )[#detail]
}
}
// Time period and location
#let term(period, location) = {
if location == [] or location == "" {
text(9pt,font: "Heiti TC", fill: headings_colour, weight: "medium", )[#period ]
} else {
text(9pt,font: "Heiti TC", fill: headings_colour, weight: "medium", )[#period | #location ]
}
}
// Projects
#let project(title, period, info) = {
text(11pt, font: "Heiti SC", fill: subheadings_colour,weight: "semibold",)[#title ]
if period != [] or period != "" {
h(1fr)
text(11pt,font: "Heiti TC", fill: headings_colour, weight: "medium", )[#period \ ]
} else {
[\ ]
}
if info != [] or info != "" {
text(11pt,font: "Helvetica", fill: primary_colour,weight: "light", )[#info ]
}
}
// Description of a job, degree, etc
#let descript(content) = {
text(11pt, font: "Heiti SC", fill: subheadings_colour,weight: "semibold",)[#content ]
}
// Job title
#let jobtitle(firm, title, period, location) = {
text(11pt,font: "Helvetica", fill: subheadings_colour,weight: "bold", )[#upper[#firm] ]
h(1fr)
text(11pt,font: "Heiti TC", fill: headings_colour, weight: "medium", )[#period \ ]
text(11pt, font: "Heiti SC", fill: subheadings_colour,weight: "semibold",)[#title]
h(1fr)
text(11pt,font: "Heiti TC", fill: headings_colour, weight: "medium", )[#location]
}
//job details
#let jobdetail(content) = {
text(11pt,font: "Helvetica", fill: primary_colour,weight: "light", baseline: 0em )[#set enum(tight:false,spacing:0em,indent: 0em, body-indent: 0em)
#content ]
}
// Details
#let info(content) = {
text(11pt,font: "Helvetica", fill: primary_colour,weight: "light", )[#content\ ]
}
#let sectionsep = {
line(length: 100%, stroke:0.1pt + primary_colour)
}
#let subsectionsep = {
[#v(0.5pt)]
}
#let awarddetail(award,organise,time) = {
text(11pt,font: "Helvetica", fill: primary_colour,weight: "light")[#award, #organise #h(1fr) #time\ ]
}
#let reference(name, department, firm, address, email) = {
align(left,{text(11pt, font: "Heiti SC", fill: subheadings_colour,weight: "semibold",)[#name\ ]
text(10pt,font: "Heiti TC", fill: headings_colour, weight: "medium", )[#department\ ]
text(10pt,font: "Heiti TC", fill: headings_colour, weight: "medium", )[#firm\ ]
text(10pt,font: "Heiti TC", fill: headings_colour, weight: "medium", )[#address\ ]
text(10pt,font: "Heiti TC", fill: headings_colour, weight: "medium", )[#email]})
}
#let teaching(position, university, detail) = {
text(11pt,font: "Helvetica", fill: subheadings_colour,weight: "bold", )[#upper[#university]]
text(11pt, font: "Heiti SC", fill: subheadings_colour,weight: "semibold",)[ | #position \ ]
if detail != [] or detail != "" {
text(11pt,font: "Helvetica", fill: primary_colour,weight: "light", )[#detail]
}
}
#let reference2(name, department, firm, email) = {
text(10pt, font: "Heiti SC", fill: subheadings_colour,weight: "semibold",)[#name | #email\ ]
text(10pt,font: "Heiti TC", fill: headings_colour, weight: "medium", )[#department, #firm\ ]
}
#let biblist(contents) = {
for ids in contents [
#id.title (#id.year)
]
}
#let keyword(content) = {
text(9pt, font: "Helvetica", fill: headings_colour,weight: "light",)[#content\ ]
}
// last update
#let lastupdate(lastupdated, date)= {
if lastupdated == "true" {
set text(8pt,font: "Helvetica", fill: primary_colour,weight: "light",)
[Last updated: #date]
}
}
#let main(
continue_header: "",
name: "",
address: "",
lastupdated: "",
pagecount: "",
date:"",
contacts: (),
bibfile: (),
mainbody,
) = {
// show contact details
let display(contacts) = {
set text(9pt,font:"Heiti TC",fill:headings_colour, weight: "medium",top-edge:"baseline",bottom-edge:"baseline",baseline: 2pt)
contacts.map(contact =>{
if contact.link == none [
contact.text
] else {
link(contact.link)[#{contact.text}]
}
}
).join(" | ")
}
set page(
footer: [
#lastupdate(lastupdated, date)
#h(1fr)
#if pagecount == "true" {
text(9pt,font: "Helvetica", fill: primary_colour,weight: "light",)[#counter(page).display("1 / 1", both: true,)]
}
],
)
if continue_header == "true" {
set page(
margin: (
left: 2cm,
right: 2cm,
top: 2.5cm,
bottom: 1.5cm,
),
header:{
// Head Name Section
text(20pt,font:"Helvetica Neue",fill:primary_colour, weight:"light",top-edge:"baseline",bottom-edge:"baseline",baseline: 11pt)[#align(center,[#name])]
v(2pt)
// text(9pt,font:"Heiti TC",fill:headings_colour, weight: "medium",top-edge:"baseline",bottom-edge:"baseline")[#align(center,[#address])]
align(center)[#display(contacts)]
line(length: 100%, stroke:0.5pt + primary_colour)
},
header-ascent: 1em,
)
mainbody
} else {
set page(
margin: (
left: 1.8cm,
right: 1.8cm,
top: 1cm,
bottom: 1cm,
),
)
text(20pt,font:"Helvetica Neue",fill:primary_colour, weight:"light",top-edge:"baseline",bottom-edge:"baseline",baseline: 11pt)[#align(center,[#name])]
v(2pt)
// text(9pt,font:"Heiti TC",fill:headings_colour, weight: "medium",top-edge:"baseline",bottom-edge:"baseline")[#align(center,[#address])]
align(center)[#display(contacts)]
line(length: 100%, stroke:0.5pt + primary_colour)
mainbody
}
//Main Body
}
// Chicago style
// <NAME>, <NAME>, <NAME>, and <NAME>. "Earnings, retained earnings, and book-to-market in the cross section of expected returns." Journal of Financial Economics 135, no. 1 (2020): 231-254.
// Sumiyana, Sumiyana. "Different characteristics of the aggregate of accounting earnings between developed and developing countries: Evidence for predicting future GDP." Journal of international studies 13, no. 1 (2020): 58-80.
#let chicago(contents) = {
set text(10pt,font: "Helvetica", fill: primary_colour,weight: "light", )
for (i, id) in contents.enumerate() {
grid(
columns: (auto,auto),
column-gutter: 0.4em,
{"["
str(i+1)
"]"},{
for author in id.author {
if author.len() == 1 [
#author.at("family"), #author.at("given").
] else {
if author.at("family") == id.author.first().at("family") [
#author.at("family"), #author.at("given")
] else if author.at("family") == id.author.last().at("family") [
and #author.at("given"), #author.at("family").
] else [
#author.at("given"), #author.at("family"),
]
}
}
[\" #id.title.\" #emph(id.container-title) ]
if "volume" in id [#id.volume, ]
if "issue" in id [no. #id.issue ]
[(#id.issued.date-parts.at(0).first())]
if "page" in id [: #id.page.] else[. ]
if "DOI" in id and "URL" in id {
[doi: ]
emph(link(id.DOI))
[\ ]
} else if "URL" in id {
[url: ]
emph(link(id.URL))
[\ ]
} else if "DOI" in id {
[doi: ]
emph(link(id.DOI))
[\ ]
}
}
)
}
}
// APA style
// <NAME>., <NAME>., <NAME>., & <NAME>. (2020). Earnings, retained earnings, and book-to-market in the cross section of expected returns. Journal of Financial Economics, 135(1), 231-254.
// <NAME>. (2020). Different characteristics of the aggregate of accounting earnings between developed and developing countries: Evidence for predicting future GDP. Journal of international studies, 13(1), 58-80.
#let apa(contents) = {
set text(10pt,font: "Helvetica", fill: primary_colour,weight: "light", )
for (i, id) in contents.enumerate() {
grid(
columns: (auto,auto),
column-gutter: 0.4em,
row-gutter: 0em,
{"["
str(i+1)
"]"},{
for author in id.author {
if author.len() == 1 [
#author.at("family"), #author.at("given").first().
] else {
if author.at("family") == id.author.first().at("family") [
#author.at("family"), #author.at("given").first().,
] else if author.at("family") == id.author.last().at("family") [
& #author.at("family"), #author.at("given").first().
] else [
#author.at("family"), #author.at("given").first().,
]
}
}
[(#id.issued.date-parts.at(0).first()). ]
[ #id.title. #emph(id.container-title)]
if "volume" in id [, #id.volume]
if "issue" in id [(#id.issue)]
if "page" in id [, #id.page.] else[. ]
if "DOI" in id and "URL" in id {
[ doi: ]
emph(link(id.DOI))
[\ ]
} else if "URL" in id {
[url: ]
emph(link(id.URL))
[\ ]
} else if "DOI" in id {
[doi: ]
emph(link(id.DOI))
[\ ]
}
}
)
}
} |
https://github.com/bigskysoftware/hypermedia-systems-book | https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/ch09-client-side-scripting.typ | typst | Other | #import "lib/definitions.typ": *
#import "lib/snippets.typ": fielding-rest-thesis
== Client Side Scripting
#blockquote(
attribution: fielding-rest-thesis,
)[
REST allows client functionality to be extended by downloading and executing
code in the form of applets or scripts. This simplifies clients by reducing the
number of features required to be pre-implemented.
]
Thus far we have (mostly) avoided writing any JavaScript (or \_hyperscript) in
Contact.app, mainly because the functionality we implemented has not required
it. In this chapter we are going to look at scripting and, in particular,
hypermedia-friendly scripting within the context of a Hypermedia-Driven
Application.
=== Is Scripting Allowed? <_is_scripting_allowed>
A common criticism of the web is that it’s being misused. There is a narrative
that WWW was created as a delivery system for "documents", and only came to be
used for "applications" by way of an accident or bizarre circumstances.
However, the concept of hypermedia challenges the split of document and
application. Hypermedia systems like HyperCard, which preceded the web, featured
rich capabilities for active and interactive experiences, including scripting.
HTML, as specified and implemented, does lack affordances needed to build highly
interactive applications. This doesn’t mean, however, that hypermedia’s _purpose_ is "documents"
over "applications."
Rather, while the theoretical foundation is there, the implementation is
underdeveloped. With JavaScript being the only extension point and hypermedia
controls not being well integrated to JavaScript (why can’t one click a link
without halting the program?), developers have not internalized hypermedia and
have instead used the web as a dumb pipe for apps that imitate "native" ones.
A goal of this book is to show that it is possible to build sophisticated web
applications using the original technology of the web, hypermedia, without the
application developer needing to reach for the abstractions provided by the
large, popular JavaScript frameworks.
Htmx itself is, of course, written in JavaScript, and one of its advantages is
that hypermedia interactions that go through htmx expose a rich interface to
JavaScript code with configuration, events, and htmx’s own extension support.
Htmx expands the expressiveness of HTML enough that it removes the need for
scripting in many situations. This makes htmx attractive to people who don’t
want to write JavaScript, and there are many of those sorts of developers, wary
of the complexity of Single Page Application frameworks.
However, dunking on JavaScript is not the aim of the htmx project. The goal of
htmx is not less JavaScript, but less code, more readable and
hypermedia-friendly code.
Scripting has been a massive force multiplier for the web. Using scripting, web
application developers are not only able to enhance their HTML websites, but
also create full-fledged client-side applications that can often compete with
native, thick client applications.
This JavaScript-centric approach to building web applications is a testament to
the power of the web and to the sophistication of web browsers in particular. It
has its place in web development: there are situations where the hypermedia
approach simply can’t provide the level of interaction that an SPA can.
However, in addition to this more JavaScript-centric style, we want to develop a
style of scripting more compatible and consistent with Hypermedia-Driven
Applications.
=== Scripting for Hypermedia
#index[scripting][hypermedia friendly]
Borrowing from <NAME>’s notion of "constraints" defining REST, we offer
two constraints of hypermedia-friendly scripting. You are scripting in an
HDA-compatible manner if the following two constraints are adhered to:
- The main data format exchanged between server and client must be hypermedia, the
same as it would be without scripting.
- Client-side state, outside the DOM itself, is kept to a minimum.
The goal of these constraints is to confine scripting to where it shines best
and where nothing else comes close: _interaction design_. Business logic and
presentation logic are the responsibility of the server, where we can pick
whichever languages or tools are appropriate for our business domain.
#block(breakable: false,
sidebar[The Server][Keeping business logic and presentation logic both "on the server" does not mean
these two "concerns" are mixed or coupled. They can be modularized on the
server. In fact, they _should_ be modularized on the server, along with all the
other concerns of our application.
Note also that, especially in web development parlance, the humble
"server" is usually a whole fleet of racks, virtual machines, containers and
more. Even a worldwide network of datacenters is reduced to "the server" when
discussing the server-side of a Hypermedia-Driven Application.])
Satisfying these two constraints sometimes requires us to diverge from what is
typically considered best practice for JavaScript. Keep in mind that the
cultural wisdom of JavaScript was largely developed in JavaScript-centric SPA
applications.
The Hypermedia-Driven Application cannot as comfortably fall back on this
tradition. This chapter is our contribution to the development of a new style
and best practices for what we are calling Hypermedia-Driven Applications.
Unfortunately, simply listing "best practices" is rarely convincing or edifying.
To be honest, it’s boring.
Instead, we will demonstrate these best practices by implementing client-side
features in Contact.app. To cover different aspects of hypermedia-friendly
scripting, we will implement three different features:
- An overflow menu to hold the _Edit_, _View_ and
_Delete_ actions, to clean up visual clutter in our list of contacts.
- An improved interface for bulk deletion.
- A keyboard shortcut for focusing the search box.
The important takeaway in the implementation of each of these features is that,
while they are implemented entirely on the client-side using scripting, they _don’t exchange information with the server_ via
a non-hypermedia format, such as JSON, and that they don’t store a significant
amount of state outside of the DOM itself.
=== Scripting Tools for the Web <_scripting_tools_for_the_web>
The primary scripting language for the web is, of course, JavaScript, which is
ubiquitous in web development today.
A bit of interesting internet lore, however, is that JavaScript was not always
the only built-in option. As the quote from <NAME> at the start of this
chapter hints, "applets" written in other languages such as Java were considered
to be part of the scripting infrastructure of the web. In addition, there was a
time period when Internet Explorer supported VBScript, a scripting language
based on Visual Basic.
Today, we have a variety of _transcompilers_ (often shortened to
_transpilers_) that convert many languages to JavaScript, such as TypeScript,
Dart, Kotlin, ClojureScript, F\# and more. There is also the WebAssembly (WASM)
bytecode format, which is supported as a compilation target for C, Rust, and the
WASM-first language AssemblyScript.
However, most of these options are not geared towards a hypermedia-friendly
style of scripting. Compile-to-JS languages are often paired with SPA-oriented
libraries (Dart and AngularDart, ClojureScript and Reagent, F\# and Elm), and
WASM is currently mainly geared toward linking to C/C++ libraries from
JavaScript.
We will instead focus on three client-side scripting technologies that
_are_ hypermedia-friendly:
- VanillaJS, that is, using JavaScript without depending on any framework.
- Alpine.js, a JavaScript library for adding behavior directly in HTML.
- \_hyperscript, a non-JavaScript scripting language created alongside htmx. Like
AlpineJS, \_hyperscript is usually embedded in HTML.
Let’s take a quick look at each of these scripting options, so we know what we
are dealing with.
Note that, as with CSS, we are going to show you just enough of each of these
options to give a flavor of how they work and, we hope, spark your interest in
looking into any of them more extensively.
=== Vanilla #indexed[JavaScript]
#blockquote(attribution: [Merb (Ruby web framework), motto])[
No code is faster than no code.
]
Vanilla JavaScript is simply using plain JavaScript in your application, without
any intermediate layers. The term "Vanilla" entered frontend web dev parlance as
it became assumed that any sufficiently "advanced" web app would use some
library with a name ending in ".js". As JavaScript matured as a scripting
language, however, standardized across browsers and provided more and more
functionality, these frameworks and libraries became less important.
Somewhat ironically though, as JavaScript became more powerful and removed the
need for the first generation of JavaScript libraries such as jQuery, it also
enabled people to build complex SPA libraries. These SPA libraries are often
even more elaborate than the original first generation of JavaScript libraries.
A quote from the website #link("http://vanilla-js.com"), which is well worth
visiting even though it’s slightly out of date, captures the situation well:
#blockquote(
attribution: [http:\/\/vanilla-js.com],
)[
VanillaJS is the lowest-overhead, most comprehensive framework I’ve ever used.
]
With JavaScript having matured as a scripting language, this is certainly the
case for many applications. It is especially true in the case of HDAs, since, by
using hypermedia, your application will not need many of the features typically
provided by more elaborate Single Page Application JavaScript frameworks:
- Client-side routing
- An abstraction over DOM manipulation (i.e., templates that automatically update
when referenced variables change)
- Server side rendering #footnote[Rendering here refers to HTML generation. Framework support for server-side
rendering is not needed in a HDA because generating HTML on the server is the
default.]
- Attaching dynamic behavior to server-rendered tags on load (i.e.,
"hydration")
- Network requests
Without all this complexity being handled in JavaScript, your framework needs
are dramatically reduced.
One of the best things about VanillaJS is how you install it: you don’t have to!
You can just start writing JavaScript in your web application, and it will
simply work.
That’s the good news. The bad news is that, despite improvements over the last
decade, JavaScript has some significant limitations as a scripting language that
can make it less than ideal as a stand-alone scripting technology for
Hypermedia-Driven Applications:
- Being as established as it is, it has accreted a lot of features and warts.
- It has a complicated and confusing set of features for working with asynchronous
code.
- Working with events is surprisingly difficult.
- DOM APIs (a large portion of which were originally designed for Java, yes _Java_)
are verbose and don’t have a habit of making common functionality easy to use.
None of these limitations are deal-breakers, of course. Many of them are
gradually being fixed and many people prefer the "close to the metal" (for lack
of a better term) nature of vanilla JavaScript over more elaborate client-side
scripting approaches.
==== A Simple Counter <_a_simple_counter>
To dive into vanilla JavaScript as a front end scripting option, let’s create a
simple counter widget.
Counter widgets are a common "Hello World" example for JavaScript frameworks, so
looking at how it can be done in vanilla JavaScript (as well as the other
options we are going to look at) will be instructive.
Our counter widget will be very simple: it will have a number, shown as text,
and a button that increments the number.
One problem with tackling this problem in vanilla JavaScript is that it lacks
one thing that most JavaScript frameworks provide: a default code and
architectural style.
With vanilla JavaScript, there are no rules!
This isn’t all bad. It presents a great opportunity to take a small journey
through various styles that people have developed for writing their JavaScript.
===== An inline implementation <_an_inline_implementation>
To begin, let’s start with the simplest thing imaginable: all of our JavaScript
will be written inline, directly in the HTML. When the button is clicked, we
will look up the `output` element holding the number, and increment the number
contained within it.
#figure(caption: [Counter in vanilla JavaScript, inline version])[
```html
<section class="counter">
<output id="my-output">0</output> <1>
<button
onclick=" <2>
document.querySelector('#my-output') <3>
.textContent++ <4>
"
>Increment</button>
</section>
``` ]
1. Our output element has an ID to help us find it.
2. We use the `onclick` attribute to add an event listener.
3. Find the output via a querySelector() call.
4. JavaScript allows us use the `++` operator on strings.
Not too bad.
It’s not the most beautiful code, and can be irritating especially if you aren’t
used to the DOM APIs.
It’s a little annoying that we needed to add an `id` to the `output`
element. The `document.querySelector()` function is a bit verbose compared with,
say, the `$` function, as provided by jQuery.
But it works. It’s also easy enough to understand, and crucially it doesn’t
require any other JavaScript libraries.
So that’s the simple, inline approach with VanillaJS.
===== Separating our scripting out <_separating_our_scripting_out>
While the inline implementation is simple in some sense, a more standard way to
write this would be to move the code into a separate JavaScript file. This
JavaScript file would then either be linked to via a
`<script src>` tag or placed into an inline `<script>` tag by a build process.
Here we see the HTML and JavaScript _separated out_ from one another, in
different files. The HTML is now "cleaner" in that there is no JavaScript in it.
The JavaScript is a bit more complex than in our inline version: we need to look
up the button using a query selector and add an _event listener_ to handle the
click event and increment the counter.
#figure(caption: [Counter HTML])[
```html
<section class="counter">
<output id="my-output">0</output>
<button class="increment-btn">Increment</button>
</section>
``` ]
#figure(caption: [Counter JavaScript])[
```js
const counterOutput = document.querySelector("#my-output"), <1>
incrementBtn = document.querySelector(".counter .increment-btn") <2>
incrementBtn.addEventListener("click", e => { <3>
counterOutput.innerHTML++ <4>
})
``` ]
1. Find the output element.
2. Find the button.
3. We use `addEventListener`, which is preferable to `onclick` for many reasons.
4. The logic stays the same, only the structure around it changes.
#index[Separation of Concerns (SoC)]
In moving the JavaScript out to another file, we are following a software design
principle known as _Separation of Concerns (SoC)._
Separation of Concerns posits that the various "concerns" (or aspects) of a
software project should be divided up into multiple files, so that they don’t "pollute"
one another. JavaScript isn’t markup, so it shouldn’t be in your HTML, it should
be _elsewhere_. Styling information, similarly, isn’t markup, and so it belongs
in a separate file as well (A CSS file, for example.)
For quite some time, this Separation of Concerns was considered the
"orthodox" way to build web applications.
A stated goal of Separation of Concerns is that we should be able to modify and
evolve each concern independently, with confidence that we won’t break any of
the other concerns.
However, let’s look at exactly how this principle has worked out in our simple
counter example. If you look closely at the new HTML, it turns out that we’ve
had to add a class to the button. We added this class so that we could look the
button up in JavaScript and add in an event handler for the "click" event.
Now, in both the HTML and the JavaScript, this class name is just a string and
there isn’t any process to _verify_ that the button has the right classes on it
or its ancestors to ensure that the event handler is actually added to the right
element.
Unfortunately, it has turned out that the careless use of CSS selectors in
JavaScript can cause what is known as _#indexed[jQuery soup]_. jQuery soup is a
situation where:
- The JavaScript that attaches a given behavior to a given element is difficult to
find.
- Code reuse is difficult.
- The code ends up wildly disorganized and "flat", with lots of unrelated event
handlers mixed together.
The name "jQuery soup" comes from the fact that most JavaScript-heavy
applications used to be built in jQuery (many still are), which, perhaps
inadvertently, tended to encourage this style of JavaScript.
So, you can see that the notion of Separation of Concerns doesn’t always work as
well as promised: our concerns end up intertwined or coupled pretty deeply, even
when we separate them into different files.
#asciiart(read("images/diagram/separation-of-concerns.txt"), caption: [What concerns?])
To show that it isn’t just naming between concerns that can get you into
trouble, consider another small change to our HTML that demonstrates the
problems with our separation of concerns: imagine that we decide to change the
number field from an `<output>` tag to an
`<input type="number">`.
This small change to our HTML will break our JavaScript, despite the fact we
have "separated" our concerns.
The fix for this issue is simple enough (we would need to change the
`.textContent` property to `.value` property), but it demonstrates the burden of
synchronizing markup changes and code changes across multiple files. Keeping
everything in sync can become increasingly difficult as your application size
increases.
The fact that small changes to our HTML can break our scripting indicates that
the two are _tightly coupled_, despite being broken up into multiple files. This
tight coupling suggests that separation between HTML and JavaScript (and CSS) is
often an illusory separation of concerns: the concerns are sufficiently related
to one another that they aren’t easily separated.
In Contact.app we are not _concerned_ with "structure," "styling" or "behavior";
we are concerned with collecting contact info and presenting it to users. SoC,
in the way it’s formulated in web development orthodoxy, is not really an
inviolate architectural guideline, but rather a stylistic choice that, as we can
see, can even become a hindrance.
===== Locality of Behavior
#index[Locality of Behavior (LoB)]
It turns out that there is a burgeoning reaction _against_ the Separation of
Concerns design principle. Consider the following web technologies and
techniques:
- JSX
- LitHTML
- CSS-in-JS
- Single-File Components
- Filesystem based routing
Each of these technologies _colocate_ code in various languages that address a
single _feature_ (typically a UI widget).
All of them mix _implementation_ concerns together in order to present a unified
abstraction to the end-user. Separating technical detail concerns just isn’t as
much of an, ahem, concern.
Locality of Behavior (LoB) is an alternative software design principle that we
coined, in opposition to Separation of Concerns. It describes the following
characteristic of a piece of software:
#blockquote(
attribution: [https:\/\/htmx.org/essays/locality-of-behaviour/],
)[
The behavior of a unit of code should be as obvious as possible by looking only
at that unit of code.
]
In simple terms: you should be able to tell what a button does by simply looking
at the code or markup that creates that button. This does not mean you need to
inline the entire implementation, but that you shouldn’t need to hunt for it or
require prior knowledge of the codebase to find it.
We will demonstrate Locality of Behavior in all of our examples, both the
counter demos and the features we add to Contact.app. Locality of behavior is an
explicit design goal of both \_hyperscript and Alpine.js (which we will cover
later) as well as htmx.
All of these tools achieve Locality of Behavior by having you embed attributes
directly within your HTML, as opposed to having code look up elements in a
document through CSS selectors in order to add event listeners onto them.
In a Hypermedia-Driven Application, we feel that the Locality of Behavior design
principle is often more important than the more traditional Separation of
Concerns design principle.
===== What to do with our counter?
#index[Javascript][on\*]
So, should we go back to the `onclick` attribute way of doing things? That
approach certainly wins in Locality of Behavior, and has the additional benefit
that it is baked into HTML.
Unfortunately, however, the `on*` JavaScript attributes also come with some
drawbacks:
- They don’t support custom events.
- There is no good mechanism for associating long-lasting variables with an
element --- all variables are discarded when an event listener completes
executing.
- If you have multiple instances of an element, you will need to repeat the
listener code on each, or use something more clever like event delegation.
- JavaScript code that directly manipulates the DOM gets verbose, and clutters the
markup.
- An element cannot listen for events on another element.
Consider this common situation: you have a popup, and you want it to be
dismissed when a user clicks outside of it. The listener will need to be on the
body element in this situation, far away from the actual popup markup. This
means that the body element would need to have listeners attached to it that
deal with many unrelated components. Some of these components may not even be on
the page when it was first rendered, if they are added dynamically after the
initial HTML page is rendered.
So vanilla JavaScript and Locality of Behavior don’t seem to mesh
_quite_ as well as we would like them to.
The situation is not hopeless, however: it’s important to understand that LoB
does not require behavior to be _implemented_ at a use site, but merely _invoked_ there.
That is, we don’t need to write all our code on a given element, we just need to
make it clear that a given element is _invoking_ some code, which can be located
elsewhere.
Keeping this in mind, it _is_ possible to improve LoB while writing JavaScript
in a separate file, provided we have a reasonable system for structuring our
JavaScript.
==== RSJS
#index[RSJS] (the "Reasonable System for JavaScript Structure,"
#link("https://ricostacruz.com/rsjs/")) is a set of guidelines for JavaScript
architecture targeted at "a typical non-SPA website." RSJS provides a solution
to the lack of a standard code style for vanilla JavaScript that we mentioned
earlier.
Here are the RSJS guidelines most relevant for our counter widget:
- "Use `data-` attributes" in HTML: invoking behavior via adding data attributes
makes it obvious there is JavaScript happening, as opposed to using random
classes or IDs that may be mistakenly removed or changed.
- "One component per file": the name of the file should match the data attribute
so that it can be found easily, a win for LoB.
To follow the RSJS guidelines, let’s restructure our current HTML and JavaScript
files. First, we will use _data attributes_, that is, HTML attributes that begin
with `data-`, a standard feature of HTML, to indicate that our HTML is a counter
component. We will then update our JavaScript to use an attribute selector that
looks for the
`data-counter` attribute as the root element in our counter component and wires
in the appropriate event handlers and logic. Additionally, let’s rework the code
to use `querySelectorAll()` and add the counter functionality to _all_ counter
components found on the page. (You never know how many counters you might want!)
Here is what our code looks like now:
#figure(caption: [Counter in vanilla JavaScript, with RSJS])[
```html
<section class="counter" data-counter> <1>
<output id="my-output" data-counter-output>0</output> <2>
<button class="increment-btn" data-counter-increment>Increment</button>
</section>
``` ]
1. Invoke a JavaScript behavior with a data attribute.
2. Mark relevant descendant elements.
#figure[
```js
// counter.js <1>
document.querySelectorAll("[data-counter]") <1>
.forEach(el => {
const
output = el.querySelector("[data-counter-output]"),
increment = el.querySelector("[data-counter-increment]"); <3>
increment.addEventListener("click", e => output.textContent++); <4>
});
```]
1. File should have the same name as the data attribute, so that we can locate it
easily.
2. Get all elements that invoke this behavior.
3. Get any child elements we need.
4. Register event handlers.
Using RSJS solves, or at least alleviates, many of the problems we pointed out
with our first, unstructured example of VanillaJS being split out to a separate
file:
- The JS that attaches behavior to a given element is _clear_
(though only through naming conventions).
- Reuse is _easy_ --- you can create another counter component on the page and it
will just work.
- The code is _well-organized_ --- one behavior per file.
All in all, RSJS is a good way to structure your vanilla JavaScript in a
Hypermedia-Driven Application. So long as the JavaScript isn’t communicating
with a server via a plain data JSON API, or holding a bunch of internal state
outside of the DOM, this is perfectly compatible with the HDA approach.
Let’s implement a feature in Contact.app using the RSJS/vanilla JavaScript
approach.
==== VanillaJS in Action: An Overflow Menu <_vanillajs_in_action_an_overflow_menu>
Our homepage has "Edit", "View" and "Delete" links for every contact in our
table. This uses a lot of space and creates visual clutter. Let’s fix that by
placing these actions inside a drop-down menu with a button to open it.
If you’re less familiar with JavaScript and the code here starts to feel too
complicated, don’t worry; the Alpine.js and \_hyperscript examples --- which
we’ll look at next --- are easier to follow.
Let’s begin by sketching the markup we want for our dropdown menu. First, we
need an element, we’ll use a `<div>`, to enclose the entire widget and mark it
as a menu component. Within this div, we will have a standard `<button>` that
will function as the mechanism that shows and hides our menu items. Finally,
we’ll have another `<div>` that holds the menu items that we are going to show.
These menu items will be simple anchor tags, as they are in the current contacts
table.
Here is what our updated, RSJS-structured HTML looks like:
#figure[
```html
<div data-overflow-menu> <1>
<button type="button" aria-haspopup="menu"
aria-controls="contact-menu-{{ contact.id }}"
>Options</button> <2>
<div role="menu" hidden id="contact-menu-{{ contact.id }}"> <3>
<a role="menuitem"
href="/contacts/{{ contact.id }}/edit">Edit</a> <4>
<a role="menuitem" href="/contacts/{{ contact.id }}">View</a>
<!-- ... -->
</div>
</div>
```]
1. Mark the root element of the menu component
2. This button will open and close our menu
3. A container for our menu items
4. Menu items
The roles and ARIA attributes are based on the Menu and Menu Button patterns
from the ARIA Authoring Practices Guide.
#sidebar[What is #indexed[ARIA]?][
As we web developers create more interactive, app-like websites, HTML’s
repertoire of elements won’t have all we need. As we have seen, using CSS and
JavaScript, we can endow existing elements with extended behavior and
appearances, rivaling those of native controls.
However, there was one thing web apps couldn’t replicate. While these widgets
may _look_ similar enough to the real deal, assistive technology (e.g., screen
readers) could only deal with the underlying HTML elements.
Even if you take the time to get all the keyboard interactions right, some users
often are unable to work with these custom elements easily.
ARIA was created by W3C’s Web Accessibility Initiative (WAI) in 2008 to address
this problem. At a surface level, it is a set of attributes you can add to HTML
to make it meaningful to assistive software such as a screen reader.
ARIA has two main components that interact with one another:
The first is the `role` attribute. This attribute has a predefined set of
possible values: `menu, dialog, radiogroup` etc. The `role` attribute
_does not add any behavior_ to HTML elements. Rather, it is a promise you make
to the user. When you annotate an element as
`role='menu'`, you are saying: _I will make this element work like a menu._
If you add a `role` to an element but you _don’t_ uphold the promise, the
experience for many users will be _worse_ than if the element had no `role` at
all. Thus, it is written:
#blockquote(attribution: [W3C, Read Me First | APG,
https:\/\/www.w3.org/WAI/ARIA/apg/practices/read-me-first/])[
No ARIA is better than Bad ARIA.
]
The second component of ARIA is the _states and properties_, all sharing the `aria-` prefix: `aria-expanded, aria-controls, aria-label`
etc. These attributes can specify various things such as the state of a widget,
the relationships between components, or additional semantics. Once again, these
attributes are _promises_, not implementations.
Rather than learn all the roles and attributes and try to combine them into a
usable widget, the best course of action for most developers is to rely on the
ARIA Authoring Practices Guide (APG), a web resource with practical information
aimed directly at web developers.
If you’re new to ARIA, check out the following W3C resources:
- ARIA: Read Me First:
#link("https://www.w3.org/WAI/ARIA/apg/practices/read-me-first/")
- ARIA UI patterns: #link("https://www.w3.org/WAI/ARIA/apg/patterns/")
- ARIA Good Practices:
#link("https://www.w3.org/WAI/ARIA/apg/practices/")
Always remember to #strong[test] your website for accessibility to ensure all
users can interact with it easily and effectively.
]
On the JS side of our implementation, we’ll begin with the RSJS boilerplate:
query for all elements with some data attribute, iterate over them, get any
relevant descendants.
Note that, below, we’ve modified the RSJS boilerplate a bit to integrate with
htmx; we load the overflow menu when htmx loads new content.
#figure[
```js
function overflowMenu(tree = document) {
tree.querySelectorAll("[data-overflow-menu]").forEach(menuRoot => { <1>
const
button = menuRoot.querySelector("[aria-haspopup]"), <2>
menu = menuRoot.querySelector("[role=menu]"), <3>
items = [...menu.querySelectorAll("[role=menuitem]")];
});
}
addEventListener("htmx:load", e => overflowMenu(e.target)); <4>
```]
1. With RSJS, you’ll be writing `document.querySelectorAll(…).forEach` a lot.
2. To keep the HTML clean, we use ARIA attributes rather than custom data
attributes here.
3. Use the spread operator to convert a `NodeList` into a normal `Array`.
4. Initialize all overflow menus when the page is loaded or content is inserted by
htmx.
Conventionally, we would keep track of whether the menu is open using a
JavaScript variable or a property in a JavaScript state object. This approach is
common in large, JavaScript-heavy web applications.
However, this approach has some drawback:
- We would need to keep the DOM in sync with the state (harder without a
framework).
- We would lose the ability to serialize the HTML (as this open state isn’t stored
in the DOM, but rather in JavaScript).
Instead of taking this approach, we will use the DOM to store our state. We’ll
lean on the `hidden` attribute on the menu element to tell us it’s closed. If
the HTML of the page is snapshotted and restored, the menu can be restored as
well by simply re-running the JS.
#figure[
```js
items = [...menu.querySelectorAll("[role=menuitem]")]; <1>
const isOpen = () => !menu.hidden; <2>
```]
1. We get the list of menu items at the start. This implementation
will not support dynamically adding or removing menu items.
2. The `hidden` attribute is helpfully reflected as a `hidden`
_property_, so we don’t need to use `getAttribute`.
We’ll also make the menu items non-tabbable, so we can manage their focus
ourselves.
#figure[
```js
items.forEach(item => item.setAttribute("tabindex", "-1"));
```]
Now let’s implement toggling the menu in JavaScript:
#figure[
```js
function toggleMenu(open = !isOpen()) { <1>
if (open) {
menu.hidden = false;
button.setAttribute("aria-expanded", "true");
items[0].focus(); <2>
} else {
menu.hidden = true;
button.setAttribute("aria-expanded", "false");
}
}
toggleMenu(isOpen()); <3>
button.addEventListener("click", () => toggleMenu()); <4>
menuRoot.addEventListener("blur", e => toggleMenu(false)); <5>
```]
1. Optional parameter to specify desired state. This allows us to use one function
to open, close, or toggle the menu.
2. Focus first item of menu when opened.
3. Call `toggleMenu` with current state, to initialize element attributes.
4. Toggle menu when button is clicked.
5. Close menu when focus moves away.
Let’s also make the menu close when we click outside it, a nice behavior that
mimics how native drop-down menus work. This will require an event listener on
the whole window.
Note that we need to be careful with this kind of listener: you may find that
listeners accumulate as components add listeners and fail to remove them when
the component is removed from the DOM. This, unfortunately, leads to difficult
to track down memory leaks.
There is not an easy way in JavaScript to execute logic when an element is
removed. The best option is what is known as the `MutationObserver`
API. A `MutationObserver` is very useful, but the API is quite heavy and a bit
arcane, so we won’t be using it for our example.
Instead, we will use a simple pattern to avoid leaking event listeners: when our
event listener runs, we will check if the attaching component is still in the
DOM, and, if the element is no longer in the DOM, we will remove the listener
and exit.
This is a somewhat hacky, manual form of _garbage collection_. As is (usually)
the case with other garbage collection algorithms, our strategy removes
listeners in a nondeterministic amount of time after they are no longer needed.
Fortunately for us, With a frequent event like "the user clicks anywhere in the
page" driving the collection, it should work well enough for our system.
#figure[
```js
window.addEventListener("click", function clickAway(event) {
if (!menuRoot.isConnected)
window.removeEventListener("click", clickAway); <1>
if (!menuRoot.contains(event.target)) toggleMenu(false); <2>
});
```]
1. This line is the garbage collection.
2. If the click is outside the menu, close the menu.
Now, let’s move on to the keyboard interactions for our dropdown menu. The
keyboard handlers turn out to all be pretty similar to one another and not
particularly intricate, so let’s knock them all out in one go:
#figure[
```js
const currentIndex = () => { <1>
const idx = items.indexOf(document.activeElement);
if (idx === -1) return 0;
return idx;
}
menu.addEventListener("keydown", e => {
if (e.key === "ArrowUp") {
items[currentIndex() - 1]?.focus(); <2>
} else if (e.key === "ArrowDown") {
items[currentIndex() + 1]?.focus(); <3>
} else if (e.key === "Space") {
items[currentIndex()].click(); <4>
} else if (e.key === "Home") {
items[0].focus(); <5>
} else if (e.key === "End") {
items[items.length - 1].focus(); <6>
} else if (e.key === "Escape") {
toggleMenu(false); <7>
button.focus(); <8>
}
});
```]
1. Helper: Get the index in the items array of the currently focused menu item (0
if none).
2. Move focus to the previous menu item when the up arrow key is pressed.
3. Move focus to the next menu item when the down arrow key is pressed.
4. Activate the currently focused element when the space key is pressed.
5. Move focus to the first menu item when Home is pressed.
6. Move focus to the last menu item when End is pressed.
7. Close menu when Escape is pressed.
8. Return focus to menu button when closing menu.
That should cover all our bases, and we’ll admit that’s a lot of code. But, in
fairness, it’s code that encodes a lot of behavior.
Now, our drop-down menu isn’t perfect, and it doesn’t handle a lot of things.
For example, we don’t support submenus, or menu items being added or removed
dynamically to the menu. If we needed more menu features like this, it might
make more sense to use an off-the-shelf library, such as GitHub’s
#link(
"https://github.com/github/details-menu-element",
)[`details-menu-element`].
But, for our relatively simple use case, vanilla JavaScript does a fine job, and
we got to explore ARIA and RSJS while implementing it.
=== Alpine.js
OK, so that’s an in-depth look at how to structure plain VanillaJS-style
JavaScript. Let’s turn our attention to an actual JavaScript framework that
enables a different approach for adding dynamic behavior to your application, #link("https://alpinejs.dev")[#indexed[Alpine.js]].
Alpine is a relatively new JavaScript library that allows developers to embed
JavaScript code directly in HTML, akin to the `on*` attributes available in
plain HTML and JavaScript. However, Alpine takes this concept of embedded
scripting much further than `on*` attributes.
Alpine bills itself as a modern replacement for jQuery, the widely used, older
JavaScript library. As you will see, it definitely lives up to this promise.
#index[Alpine.js][installing]
Installing Alpine is very easy: it is a single file and is dependency-free, so
you can simply include it via a CDN:
#figure(caption: [Installing Alpine])[ ```html
<script src="https://unpkg.com/alpinejs"></script>
``` ]
You can also install it via a package manager such as NPM, or vendor it from
your own server.
#index[Alpine.js][x-data]
Alpine provides a set of HTML attributes, all of which begin with the
`x-` prefix, the main one of which is `x-data`. The content of `x-data`
is a JavaScript expression which evaluates to an object. The properties of this
object can, then, be accessed within the element that the
`x-data` attribute is located.
To get a flavor of AlpineJS, let’s look at how to implement our counter example
using it.
For the counter, the only state we need to keep track of is the current number,
so let’s declare a JavaScript object with one property, `count`, in an `x-data` attribute
on the div for our counter:
#figure(caption: [Counter with Alpine, line 1])[ ```html
<div class="counter" x-data="{ count: 0 }">
``` ]
#index[Alpine.js][x-text]
This defines our state, that is, the data we are going to be using to drive
dynamic updates to the DOM. With the state declared like this, we can now use it _within_ the
div element it is declared on. Let’s add an `output` element with an `x-text` attribute.
Next, we will _bind_ the `x-text` attribute to the `count`
attribute we declared in the `x-data` attribute on the parent `div`
element. This will have the effect of setting the text of the `output`
element to whatever the value of `count` is: if `count` is updated, so will the
text of the `output`. This is "reactive" programming, in that the DOM will "react"
to changes to the backing data.
#figure(caption: [Counter with Alpine, lines 1-2])[ ```html
<div x-data="{ count: 0 }">
<output x-text="count"></output> <1>
``` ]
1. The `x-text` attribute.
Next, we need to update the count, using a button. Alpine allows you to attach
event listeners with the `x-on` attribute.
To specify the event to listen for, you add a colon and then the event name
after the `x-on` attribute name. Then, the value of the attribute is the
JavaScript you wish to execute. This is similar to the plain
`on*` attributes we discussed earlier, but it turns out to be much more
flexible.
We want to listen for a `click` event, and we want to increment `count`
when a click occurs, so here is what the Alpine code will look like:
#figure(caption: [Counter with Alpine, the full thing])[```html
<div x-data="{ count: 0 }">
<output x-text="count"></output>
<button x-on:click="count++">Increment</button> <1>
</div>
```]
1. With `x-on`, we specify the event in the attribute _name_.
And that’s all it takes. A simple component like a counter should be simple to
code, and Alpine delivers.
==== "x-on:click" vs. "onclick"
#index[Alpine.js][x-on:click]
As we said, the Alpine `x-on:click` attribute (or its shorthand, the
`@click` attribute) is similar to the built-in `onclick` attribute. However, it
has additional features that make it significantly more useful:
- You can listen for events from other elements. For example, the
`.outside` modifier lets you listen to any click event that is
_not_ within the element.
- You can use other modifiers to:
- throttle or debounce event listeners
- ignore events that are bubbled up from descendant elements
- attach passive listeners
- You can listen to custom events. For example, if you wanted to listen for the `htmx:after-request` event
you could write
`x-on:htmx:after-request="doSomething()"`.
==== Reactivity and Templating
We hope you’ll agree that the AlpineJS version of the counter widget is better,
in general, than the VanillaJS implementation, which was either somewhat hacky
or spread out over multiple files.
A big part of the power of AlpineJS is that it supports a notion of
"reactive" variables, allowing you to bind the count of the `div`
element to a variable that both the `output` and the `button` can reference, and
properly updating all the dependencies when a mutation occurs. Alpine allows for
much more elaborate data bindings than we have demonstrated here, and it is an
excellent general purpose client-side scripting library.
==== Alpine.js in Action: A Bulk Action Toolbar <_alpine_js_in_action_a_bulk_action_toolbar>
Let’s implement a feature in Contact.app with Alpine. As it stands currently,
Contact.app has a "Delete Selected Contacts" button at the very bottom of the
page. This button has a long name, is not easy to find and takes up a lot of
room. If we wanted to add additional "bulk" actions, this wouldn’t scale well
visually.
In this section, we’ll replace this single button with a toolbar. Furthermore,
the toolbar will only appear when the user starts selecting contacts. Finally,
it will show how many contacts are selected and let you select all contacts in
one go.
The first thing we will need to add is an `x-data` attribute, to hold the state
that we will use to determine if the toolbar is visible or not. We will need to
place this on an ancestor element of both the toolbar that we are going to add, as
well as the checkboxes, which will be updating the state when they are checked
and unchecked. The best option given our current HTML is to place the attribute
on the `form` element that surrounds the contacts table. We will declare a
property,
`selected`, which will be an array that holds the selected contact ids, based on
the checkboxes that are selected.
Here is what our form tag will look like:
#figure[```html
<form x-data="{ selected: [] }"> <1>
```]
1. This form wraps around the contacts table.
#index[Alpine.js][x-if]
Next, at the top of the contacts table, we are going to add a `template`
tag. A template tag is _not_ rendered by a browser, by default, so you might be
surprised that we are using it. However, by adding an Alpine `x-if` attribute,
we can tell Alpine: if a condition is true, show the HTML within this template.
Recall that we want to show the toolbar if and only if one or more contacts are
selected. But we know that we will have the ids of the selected contacts in the `selected` property.
Therefore, we can check the _length_ of that array to see if there are any
selected contacts, quite easily:
#figure[```html
<template x-if="selected.length > 0"> <1>
<div class="box info tool-bar">
<slot x-text="selected.length"></slot>
contacts selected
<button type="button" class="bad bg color border">Delete</button> <2>
<hr aria-orientation="vertical">
<button type="button">Cancel</button> <2>
</div>
</template>
```]
1. Show this HTML if there are 1 or more selected contacts.
2. We will implement these buttons in just a moment.
#index[Alpine.js][x-model]
The next step is to ensure that toggling a checkbox for a given contact adds (or
removes) a given contact’s id from the `selected` property. To do this, we will
need to use a new Alpine attribute, `x-model`. The
`x-model` attribute allows you to _bind_ a given element to some underlying
data, or its "model."
In this case, we want to bind the value of the checkbox inputs to the
`selected` property. This is how we do this:
#figure[```html
<td>
<input type="checkbox" name="selected_contact_ids"
value="{{ contact.id }}" x-model="selected"> <1>
</td>
```]
1. The `x-model` attribute binds the `value` of this input to the
`selected` property
Now, when a checkbox is checked or unchecked, the `selected` array will be
updated with the given row’s contact id. Furthermore, mutations we make to the `selected` array
will similarly be reflected in the checkboxes' state. This is known as a _two-way_ binding.
With this code written, we can make the toolbar appear and disappear, based on
whether contact checkboxes are selected.
Very slick.
Before we move on, you may have noticed our code here includes some
"class\=" references. These are for css styling, and are not part of Alpine.js.
We’ve included them only as a reminder that the menu bar we’re building will
require css to work well. The classes in the code above refer to a minimal css
library called Missing.css. If you use other css libraries, such as Bootstrap,
Tailwind, Bulma, Pico.css, etc., your styling code will be different.
===== Implementing actions <_implementing_actions>
Now that we have the mechanics of showing and hiding the toolbar, let’s look at
how to implement the buttons within the toolbar.
Let’s first implement the "Clear" button, because it is quite easy. All we need
to do is, when the button is clicked, clear out the `selected`
array. Because of the two-way binding that Alpine provides, this will uncheck
all the selected contacts (and then hide the toolbar)!
For the _Cancel_ button, our job is simple:
#figure[```html
<button type="button" @click="selected = []">Cancel</button> <1>
```]
1. Reset the `selected` array.
Once again, AlpineJS makes this very easy.
The "Delete" button, however, will be a bit more complicated. It will need to do
two things: first it will confirm if the user indeed intends to delete the
contacts selected. Then, if the user confirms the action, it will use the htmx
JavaScript API to issue a `DELETE` request.
#figure[```html
<button type="button" class="bad bg color border"
@click="
confirm(`Delete ${selected.length} contacts?`) && <1>
htmx.ajax('DELETE', '/contacts',
{ source: $root, target: document.body }) <2>
">
Delete
</button>
```]
1. Confirm the user wishes to delete the selected number of contacts.
2. Issue a `DELETE` using the htmx JavaScript API.
Note that we are using the short-circuiting behavior of the `&&`
operator in JavaScript to avoid the call to `htmx.ajax()` if the
`confirm()` call returns false.
#index[htmx][htmx.ajax()]
The `htmx.ajax()` function is just a way to access the normal, HTML-driven
hypermedia exchange that htmx’s HTML attributes give you directly from
JavaScript.
Looking at how we call `htmx.ajax`, we first pass in that we want to issue a `DELETE` to `/contacts`.
We then pass in two additional pieces of information: `source` and `target`. The `source` property
is the element from which htmx will collect data to include in the request. We
set this to `$root`, which is a special symbol in Alpine that will be the
element that has the `x-data` attribute declared on it. In this case, it will be
the form containing all of our contacts. The `target`, or where the response
HTML will be placed, is just the entire document’s body, since the `DELETE` handler
returns a whole page when it completes.
Note that we are using Alpine here in a Hypermedia-Driven Application compatible
manner. We _could_ have issued an AJAX request directly from Alpine and perhaps
updated an `x-data` property depending on the results of that request. But,
instead, we delegated to htmx’s JavaScript API, which made a _hypermedia exchange_ with
the server.
This is the key to scripting in a hypermedia-friendly manner within a
Hypermedia-Driven Application.
So, with all of this in place, we now have a much improved experience for
performing bulk actions on contacts: less visual clutter and the toolbar can be
extended with more options without creating bloat in the main interface of our
app.
=== \_hyperscript
#index[\_hyperscript]
The final scripting technology we are going to look at is a bit further afield: #link("https://hyperscript.org")[\_hyperscript].
The authors of this book initially created \_hyperscript as a sibling project to
htmx. We felt that JavaScript wasn’t event-oriented enough, which made adding
small scripting enhancements to htmx applications cumbersome.
While the previous two examples are JavaScript-oriented, \_hyperscript has a
completely different syntax than JavaScript, based on an older language called
HyperTalk. HyperTalk was the scripting language for a technology called
HyperCard, an old hypermedia system available on early Macintosh Computers.
The most noticeable thing about \_hyperscript is that it resembles English prose
more than it resembles other programming languages.
Like Alpine, \_hyperscript is a modern jQuery replacement. Also like Alpine,
\_hyperscript allows you to write your scripting inline, in HTML.
Unlike Alpine, however, \_hyperscript is _not_ reactive. It instead focuses on
making DOM manipulations in response to events easy to write and easy to read.
It has built-in language constructs for many DOM operations, preventing you from
needing to navigate the sometimes-verbose JavaScript DOM APIs.
We will give a small taste of what scripting in the \_hyperscript language is
like, so you can pursue the language in more depth later if you find it
interesting.
#index[\_hyperscript]
Like htmx and AlpineJS, \_hyperscript can be installed via a CDN or from npm
(package name `hyperscript.org`):
#figure(caption: [Installing \_hyperscript via CDN])[ ```html
<script src="//unpkg.com/hyperscript.org"></script>
``` ]
\_hyperscript uses the `_` (underscore) attribute for putting scripting on DOM
elements. You may also use the `script` or `data-script`
attributes, depending on your HTML validation needs.
Let’s look at how to implement the simple counter component we have been looking
at using \_hyperscript. We will place an `output` element and a
`button` inside of a `div`. To implement the counter, we will need to add a
small bit of \_hyperscript to the button. On a click, the button should
increment the text of the previous `output` tag.
As you’ll see, that last sentence is close to the actual \_hyperscript code:
#figure[```html
<div class="counter">
<output>0</output>
<button _="on click
increment the textContent of the previous <output/>"> <1>
Increment
</button>
</div>
```]
1. The \_hyperscript code added inline to the button.
Let’s go through each component of this script:
- `on click` is an event listener, telling the button to listen for a
`click` event and then executing the remaining code.
- `increment` is a "command" in \_hyperscript that "increments" things, similar to
the `++` operator in JavaScript.
- `the` doesn’t have any semantic meaning in \_hyperscript, but can be used to
make scripts more readable.
- `textContent of` is one form of _property access_ in \_hyperscript. You are
probably familiar with the JavaScript syntax
`a.b`, meaning "Get the property `b` on object
`a`. \_hyperscript supports this syntax, but also supports the forms `b of a`
and `a’s b`. Which one you use should depend on which one is most readable.
- `previous` is an expression in \_hyperscript that finds the previous element in
the DOM that matches some condition.
- `<output />` is a _query literal_, which is a CSS selector wrapped between `<` and `/>`.
In this code, the `previous` keyword (and the accompanying `next`
keyword) is an example of how \_hyperscript makes DOM operations easier: there
is no such native functionality to be found in the standard DOM API, and
implementing this in VanillaJS is trickier than you might think!
So, you can see, \_hyperscript is very expressive, particularly when it comes to
DOM manipulations. This makes it easier to embed scripts directly in HTML: since
the scripting language is more powerful, scripts written in it tend to be
shorter and easier to read.
#sidebar[Natural Language Programming?][Seasoned programmers may be suspicious of \_hyperscript: There have been many "natural
language programming" (NLP) projects that target non-programmers and beginner
programmers, assuming that being able to read code in their "natural language"
will give them the ability to write it as well. This has led to some badly
written and structured code and has failed to live up to the (often over the
top) hype.
\_hyperscript is _not_ an NLP programming language. Yes, its syntax is inspired
in many places by the speech patterns of web developers. But \_hyperscript's
readability is achieved not through complex heuristics or fuzzy NLP processing,
but rather through judicious use of common parsing tricks, coupled with a
culture of readability.
As you can see in the above example, with the use of a _query reference_, `<output/>`,
\_hyperscript does not shy away from using DOM-specific, non-natural language
when appropriate.]
==== \_hyperscript in Action: A Keyboard Shortcut <_hyperscript_in_action_a_keyboard_shortcut>
While the counter demo is a good way to compare various approaches to scripting,
the rubber meets the road when you try to actually implement a useful feature
with an approach. For \_hyperscript, let’s add a keyboard shortcut to
Contact.app: when a user hits Alt+S in our app, we will focus the search field.
Since our keyboard shortcut focuses the search input, let’s put the code for it
on that search input, satisfying locality.
Here is the original HTML for the search input:
#figure[```html
<input id="search" name="q" type="search" placeholder="Search Contacts">
```]
#index[\_hyperscript][event listener]
#index[\_hyperscript][event filter]
#index[\_hyperscript][filter expression]
We will add an event listener using the `on keydown` syntax, which will fire
whenever a keydown occurs. Further, we can use an _event filter_ syntax in
\_hyperscript using square brackets after the event. In the square brackets we
can place a _filter expression_ that will filter out `keydown` events we aren’t
interested in. In our case, we only want to consider events where the Alt key is
held down and where the "S" key is being pressed. We can create a boolean
expression that inspects the `altKey` property (to see if it is `true`) and the `code`
property (to see if it is `"KeyS"`) of the event to achieve this.
So far our \_hyperscript looks like this:
#figure(caption: [A start on our keyboard shortcut])[
```hyperscript
on keydown[altKey and code is 'KeyS'] ...
``` ]
#index[\_hyperscript][from]
Now, by default, \_hyperscript will listen for a given event _on the element where it is declared_.
So, with the script we have, we would only get `keydown` events if the search
box is already focused. That’s not what we want! We want to have this key work _globally_,
no matter which element has focus.
Not a problem! We can listen for the `keyDown` event elsewhere by using a `from` clause
in our event handler. In this case we want to listen for the `keyDown` from the
window, and our code ends up looking, naturally, like this:
#figure(caption: [Listening globally])[
```hyperscript
on keydown[altKey and code is 'KeyS'] from window ...
``` ]
Using the `from` clause, we can attach the listener to the window while, at the
same time, keeping the code on the element it logically relates to.
Now that we’ve picked out the event we want to use to focus the search box,
let’s implement the actual focusing by calling the standard
`.focus()` method.
Here is the entire script, embedded in HTML:
#figure(caption: [Our final script])[
```html
<input id="search" name="q" type="search" placeholder="Search Contacts"
_="on keydown[altKey and code is 'KeyS'] from the window
focus() me"> <1>
``` ]
1. "me" refers to the element that the script is written on.
Given all the functionality, this is surprisingly terse, and, as an English-like
programming language, pretty easy to read.
==== Why a New Programming Language? <_why_a_new_programming_language>
This is all well and good, but you may be thinking "An entirely new scripting
language? That seems excessive." And, at some level, you are right: JavaScript
is a decent scripting language, is very well optimized and is widely understood
in web development. On the other hand, by creating an entirely new front end
scripting language, we had the freedom to address some problems that we saw
generating ugly and verbose code in JavaScript:
/ Async transparency: #[
#index[\_hyperscript][async transparency] In \_hyperscript, asynchronous
functions (i.e., functions that return
`Promise` instances) can be invoked _as if they were synchronous_. Changing a
function from sync to async does not break any \_hyperscript code that calls it.
This is achieved by checking for a Promise when evaluating any expression, and
suspending the running script if one exists (only the current event handler is
suspended and the main thread is not blocked). JavaScript, instead, requires
either the explicit use of callbacks _or_ the use of explicit `async` annotations
(which can’t be mixed with synchronous code).
]
/ Array property access: #[
#index[\_hyperscript][array property access] In \_hyperscript, accessing a
property on an array (other than `length`
or a number) will return an array of the values of property on each member of
that array, making array property access act like a flat-map operation. jQuery
has a similar feature, but only for its own data structure.
]
/ Native CSS Syntax: #[
#index[\_hyperscript][native CSS syntax] In \_hyperscript, you can use things
like CSS class and ID literals, or CSS query literals, directly in the language,
rather than needing to call out to a wordy DOM API, as you do in JavaScript.
]
/ Deep Event Support: #[
#index[\_hyperscript][event support] Working with events in \_hyperscript is far
more pleasant than working with them in JavaScript, with native support for
responding to and sending events, as well as for common event-handling patterns
such as
"debouncing" or rate limiting events. \_hyperscript also provides declarative
mechanisms for synchronizing events within a given element and across multiple
elements.
]
Again we wish to stress that, in this example, we are not stepping outside the
lines of a Hypermedia-Driven Application: we are only adding frontend,
client-side functionality with our scripting. We are not creating and managing a
large amount of state outside of the DOM itself, or communicating with the
server in a non-hypermedia exchange.
Additionally, since \_hyperscript embeds so well in HTML, it keeps the focus _on the hypermedia_,
rather than on the scripting logic.
It may not fit all scripting styles or needs, but \_hyperscript can provide an
excellent scripting experience for Hypermedia-Driven Applications. It is a small
and obscure programming language worth a look to understand what it is trying to
achieve.
=== Using Off-the-Shelf Components <_using_off_the_shelf_components>
That concludes our look at three different options for _your_
scripting infrastructure, that is, the code that _you_ write to enhance your
Hypermedia-Driven Application. However, there is another major area to consider
when discussing client side scripting: "off the shelf" components. That is,
JavaScript libraries that other people have created that offer some sort of
functionality, such as showing modal dialogs.
#index[components]
Components have become very popular in the web development world, with libraries
like #link("https://datatables.net/")[DataTables] providing rich user
experiences with very little JavaScript code on the part of a user.
Unfortunately, if these libraries aren’t integrated well into a website, they
can begin to make an application feel "patched together." Furthermore, some
libraries go beyond simple DOM manipulation, and require that you integrate with
a server endpoint, almost invariably with a JSON data API. This means you are no
longer building a Hypermedia-Driven Application, simply because a particular
widget demands something different. A shame!
#sidebar[Web Components][
Web Components is the collective name of a few standards; Custom Elements and
Shadow DOM, and `<template>` and `<slot>`.
#index[web components]
All of these standards bring useful capabilities to the table.
`<template>` elements remove their contents from the document, while still
parsing them as HTML (unlike comments) and making them accessible to JavaScript.
Custom Elements let us initialize and tear down behaviors when elements are
added or removed, which would previously require manual work or
MutationObservers. Shadow DOM lets us encapsulate elements, leaving the "light"
(non-shadow) DOM clean.
However, trying to reap these benefits is often frustrating. Some difficulties
are simply growing pains of new standards (like the accessibility problems of
Shadow DOM) that are actively being worked on. Others are the result of Web
Components trying to be too many things at the same time:
- An extension mechanism for HTML. To this end, each custom element is a tag we
add to the language.
- A lifecycle mechanism for behaviors. Methods like `createdCallback`,
`connectedCallback`, etc. allow behavior to be added to elements without needing
to be manually invoked when those elements are added.
- A unit of encapsulation. Shadow DOM insulates elements from their surroundings.
The result is that if you want any one of these things, the others come along
for the ride. If you want to attach some behaviors to some elements using
lifecycle callbacks, you need to create a new tag, which means you can’t have
multiple behaviors on one element, and you isolate elements you add from
elements already in the page, which is a problem if they need to have ARIA
relationships.
When should we use Web Components? A good rule of thumb is to ask yourself: "Could
this reasonably be a built-in HTML element?" For example, a code editor is a
good candidate, since HTML already has
`<textarea>` and `contenteditable` elements. In addition, a fully-featured code
editor will have many child elements that won’t provide much information anyway.
We can use features like
#link(
"https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM",
)[Shadow DOM]
to encapsulate these elements#footnote[Beware that Shadow DOM is a newer web platform feature that’s still in
development at the time of writing. In particular, there are some accessibility
bugs that may occur when elements inside and outside the shadow root interact.].
We can create a
#link(
"https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements",
)[custom element],
`<code-area>`, that we can drop into our page whenever we want.
]
==== Integration Options <_integration_options>
The best JavaScript libraries to work with when you are building a
Hypermedia-Driven Application are ones that:
- Mutate the DOM but don’t communicate with a server over JSON
- Respect HTML norms (e.g., using `input` elements to store values)
- Trigger many custom events as the library updates things
The last point, triggering many custom events (over the alternative of using
lots of methods and callbacks) is especially important, as these custom events
can be dispatched or listened to without additional glue code written in a
scripting language.
Let’s take a look at two different approaches to scripting, one using JavaScript
call backs, and one using events.
#index[SweetAlert2]
To make things concrete, let’s implement a better confirmation dialog for the `DELETE` button
we created in Alpine in the previous section. In the original example we used
the `confirm()` function built in to JavaScript, which shows a pretty bare-bones
system confirmation dialog. We will replace this function with a popular
JavaScript library, SweetAlert2, that shows a much nicer looking confirmation
dialog. Unlike the `confirm()` function, which blocks and returns a boolean (`true` if
the user confirmed, `false` otherwise), SweetAlert2 returns a `Promise`
object, which is a JavaScript mechanism for hooking in a callback once an
asynchronous action (such as waiting for a user to confirm or deny an action)
completes.
===== Integrating using callbacks <_integrating_using_callbacks>
With SweetAlert2 installed as a library, you have access to the `Swal`
object, which has a `fire()` function on it to trigger showing an alert. You can
pass in arguments to the `fire()` method to configure exactly what the buttons
on the confirmation dialog look like, what the title of the dialog is, and so
forth. We won’t get into these details too much, but you will see what a dialog
looks like in a bit.
So, given we have installed the SweetAlert2 library, we can swap it in place of
the `confirm()` function call. We then need to restructure the code to pass a _callback_ to
the `then()` method on the `Promise`
that `Swal.fire()` returns. A deep dive into Promises is beyond the scope of
this chapter, but suffice to say that this callback will be called when a user
confirms or denies the action. If the user confirmed the action, then the `result.isConfirmed` property
will be `true`.
Given all that, our updated code will look like this:
#figure(
caption: [A callback-based confirmation dialog],
)[ ```html
<button type="button" class="bad bg color border"
@click="Swal.fire({ <1>
title: 'Delete these contacts?', <2>
showCancelButton: true,
confirmButtonText: 'Delete'
}).then((result) => { <3>
if (result.isConfirmed) htmx.ajax('DELETE', '/contacts',
{ source: $root, target: document.body })
});"
>Delete</button>
``` ]
1. Invoke the `Swal.fire()` function
2. Configure the dialog
3. Handle the result of the user’s selection
And now, when this button is clicked, we get a nice looking dialog in our web
application (@fig-swal-screenshot) --- much nicer than the system confirmation dialog. Still, this feels a little
wrong. This is a lot of code to write just to trigger a slightly nicer `confirm()`,
isn’t it? And the htmx JavaScript code we are using here feels awkward. It would
be more natural to move the htmx out to attributes on the button, as we have
been doing, and then trigger the request via events.
#figure(
image("images/screenshot_sweet_alert.png"),
caption: [A SweetAlert dialog box]
)<fig-swal-screenshot>
So let’s take a different approach and see how that looks.
===== Integrating using events <_integrating_using_events>
To clean this code up, we will pull the `Swal.fire()` code out to a custom
JavaScript function we will create called `sweetConfirm()`.
`sweetConfirm()` will take the dialog options that are passed into the
`fire()` method, as well as the element that is confirming an action. The big
difference here is that the new `sweetConfirm()` function, rather than calling
some htmx directly, will instead trigger a
`confirmed` event on the button when the user confirms they wish to delete.
Here is what our JavaScript function looks like:
#figure(caption: [An event-based confirmation dialog])[
```javascript
function sweetConfirm(elt, config) {
Swal.fire(config) <1>
.then((result) => {
if (result.isConfirmed) {
elt.dispatchEvent(new Event('confirmed')); <2>
}
});
}
``` ]
1. Pass the config through to the `fire()` function.
2. If the user confirmed the action, trigger a `confirmed` event.
With this method available, we can now tighten up our delete button quite a bit.
We can remove all the SweetAlert2 code that we had in the
`@click` Alpine attribute, and simply call this new `sweetConfirm()`
method, passing in the arguments `$el`, which is the Alpine syntax for getting
"the current element" that the script is on, and then the exact
configuration we want for our dialog.
If the user confirms the action, a `confirmed` event will be triggered on the
button. This means that we can go back to using our trusty htmx attributes!
Namely, we can move `DELETE` to an `hx-delete` attribute, and we can use `hx-target` to
target the body. And then, and here is the crucial step, we can use the `confirmed` event
that is triggered in the `sweetConfirm()` function, to trigger the request, but
adding an
`hx-trigger` for it.
Here is what our code looks like:
#figure(caption: [An Event-based Confirmation Dialog])[
```html
<button type="button" class="bad bg color border"
hx-delete="/contacts" hx-target="body" hx-trigger="confirmed" <1>
@click="sweetConfirm($el, { <2>
title: 'Delete these contacts?', <3>
showCancelButton: true,
confirmButtonText: 'Delete'
})">
``` ]
1. Our htmx attributes are back.
2. We pass the button in to the function, so an event can be triggered on it.
3. We pass through the SweetAlert2 configuration information.
#index[htmx patterns][wrapping to emit events]
As you can see, this event-based code is much cleaner and certainly more
"HTML-ish." The key to this cleaner implementation is that our new
`sweetConfirm()` function fires an event that htmx is able to listen for.
This is why a rich event model is important to look for when choosing a library
to work with, both with htmx and with Hypermedia-Driven Applications in general.
Unfortunately, due to the prevalence and dominance of the JavaScript-first
mindset today, many libraries are like SweetAlert2: they expect you to pass a
callback in the first style. In these cases you can use the technique we have
demonstrated here, wrapping the library in a function that triggers events in a
callback, to make the library more hypermedia and htmx-friendly.
=== Pragmatic Scripting <_pragmatic_scripting>
#blockquote(
attribution: [W3C, HTML Design Principles § 3.2 Priority of Constituencies],
)[
In case of conflict, consider users over authors over implementors over
specifiers over theoretical purity.
]
We have looked at several tools and techniques for scripting in a
Hypermedia-Driven Application. How should you pick between them? The sad truth
is that there will never be a single, always correct answer to this question.
Are you committed to vanilla JavaScript-only, perhaps due to company policy?
Well, you can use vanilla JavaScript effectively to script your
Hypermedia-Driven Application.
Do you have more leeway and like the look of Alpine.js? That’s a great way to
add more structured, localized JavaScript to your application, and offers some
nice reactive features as well.
Are you a bit more bold in your technical choices? Maybe \_hyperscript is worth
a look. (We certainly think so.)
Sometimes you might even consider picking two (or more) of these approaches
within an application. Each has its own strengths and weaknesses, and all of
them are relatively small and self-contained, so picking the right tool for the
job at hand might be the best approach.
In general, we encourage a _pragmatic_ approach to scripting: whatever feels
right is probably right (or, at least, right
_enough_) for you. Rather than being concerned about which particular approach
is taken for your scripting, we would focus on these more general concerns:
- Avoid communicating with the server via JSON data APIs.
- Avoid storing large amounts of state outside of the DOM.
- Favor using events, rather than hard-coded callbacks or method calls.
And even on these topics, sometimes a web developer has to do what a web
developer has to do. If the perfect widget for your application exists but uses
a JSON data API? That’s OK.
Just don’t make it a habit.
#html-note[HTML is for Applications][
A prevalent meme among developers suggests that HTML was designed for
"documents" and is unsuitable for "applications." In reality, hypermedia is not
only a sophisticated, modern architecture for applications, but it can allow us
to do away with this artificial app/document split for good.
#blockquote(
attribution: [<NAME>, #link(
"https://www.slideshare.net/royfielding/a-little-rest-and-relaxation",
)[A little REST and Relaxation]],
)[
When I say Hypertext, I mean the simultaneous presentation of information and
controls such that the information becomes the affordance through which the user
obtains choices and selects actions.
]
HTML allows documents to contain rich multimedia including images, audio, video,
JavaScript programs, vector graphics and (with some help) 3D environments. More
importantly, however, it allows interactive controls to be embedded within these
documents, allowing the information itself to be the app through which it is
accessed.
Consider: Is it not mind-boggling that a single application --- which works on
all types of computers and OSs --- can let you read news, place video calls,
compose documents, enter virtual worlds, and do almost any other everyday
computing task?
Unfortunately, it is the interactive capabilities of HTML that is its least
developed aspect. For reasons unknown to us, while HTML made it to version 5 and
became a Living Standard, accreting many game-changing features on the way, the
data interactions in it are still mainly restricted to links and forms. It’s up
to developers to extend HTML, and we want to do so in a way that doesn’t
abstract over its simplicity with an imitation of classical "native" toolkits.
#blockquote(
attribution: [<NAME>, <EMAIL>],
)[
- #smallcaps[Software was not supposed to use native toolkits]
- #smallcaps[Years of windows UI libraries] yet #smallcaps[no real-world use found] for going lower level
than #smallcaps[the Web]
- Wanted a window anyway for a laugh? We had a tool for that: It was called "#smallcaps[Electron]"
- "yes I would love to write 4 #smallcaps[different] copies of the same UI" - Statements
dreamed up by the Utterly Deranged
]
]
|
https://github.com/ShapeLayer/ucpc-solutions__typst | https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/docs/presets.md | markdown | Other | ---
title: ucpc.presets
supports: ["0.1.0"]
---
This is a module that predefines expressions mainly used in algorithm competitions.
## difficulties
**General**
```typst
difficulties.easy
difficulties.normal
difficulties.hard
difficulties.challenging
```
**solved.ac Difficulty Tiers**
```typst
difficulties.bronze
difficulties.silver
difficulties.gold
difficulties.platinum
difficulties.diamond
difficulties.ruby
```
|
https://github.com/ofurtumi/formleg | https://raw.githubusercontent.com/ofurtumi/formleg/main/h02/h2.typ | typst | #set heading(numbering: "1.a")
= Are the statements correct
== This is false
$A != A^*$ we can proof this by counterexample, let $A = {1}$ then $A^*$ equals the regular expression $1^*$, which corresponds to every possible combination of $1$ including $epsilon$, and it is obvious that $1 != 111...$
== This is true
Since $A^*$ includes all combinations of $A$ it also includes $A$ so it does not matter whether or not it is concatinated
== This is true
The order of operations does not matter for concatination
= State diagrams
#grid(columns: (1fr, 1fr), gutter: 16pt, [
==
#image("../imgs/h2-2a.png")
],[
==
Here is the code for the NFA tester
```
Init: q0
Accept: q1, q2
q0,0,q1
q0,1,q2
q1,0,q1
q2,1,q2
```
])
==
To do the same task as a DFA we would need to add a trap state to the NFA that catches the inputs not currently in the NFA. $S_1$ would then transition into itself on a $0$ but into $S_3$ on a $1$ and $S_2$ would transition into itself on a $1$ but into $S_t$ on a $0$. $S_T$ would transition into itself on both $0$ and $1$. So we would need 4 states in total, one more than in the NFA.
#pagebreak()
= Funnis application language
#grid(columns: ( 4fr, 1fr ), gutter: 16pt, [
== NFA
#align(center, figure(image("../imgs/h2-3a.png"), caption: [Here is a NFA for the language, this shows that the language is in fact regular]))
],[
== Simulator code
```
Init: q0
Accept: q6
q0,A,q1
q0,1,q2
q1,a,q1
q1,n,q6
q1,s,q3
q2,1,q2
q2,n,q6
q2,s,q3
q3,a,q4
q3,1,q5
q4,a,q4
q4,s,q3
q4,n,q6
q5,1,q4
q5,s,q3
q5,n,q6
q6,A,q1
q6,1,q2
```])
|
|
https://github.com/imatpot/typst-ascii-ipa | https://raw.githubusercontent.com/imatpot/typst-ascii-ipa/main/src/lib/converters.typ | typst | MIT License | #import "utils.typ": sanitize
#import "converters/branner.typ": convert-branner
#import "converters/praat.typ": convert-praat
#import "converters/sil.typ": convert-sil
#import "converters/xsampa.typ": convert-xsampa
#let branner(text, reverse: false) = convert-branner(
sanitize(text),
reverse: reverse,
)
#let praat(text, reverse: false) = convert-praat(
sanitize(text),
reverse: reverse,
)
#let sil(text, reverse: false) = convert-sil(
sanitize(text),
reverse: reverse,
)
#let xsampa(text, reverse: false) = convert-xsampa(
sanitize(text),
reverse: reverse,
)
|
https://github.com/Student-Smart-Printing-Service-HCMUT/ssps-docs | https://raw.githubusercontent.com/Student-Smart-Printing-Service-HCMUT/ssps-docs/main/contents/categories/task3/3.conclude.typ | typst | Apache License 2.0 | #{include "./3.1.typ"}
#{include "./3.2.typ"} |
https://github.com/OrangeX4/typst-sympy-calculator | https://raw.githubusercontent.com/OrangeX4/typst-sympy-calculator/main/tests/debug.typ | typst | MIT License | #let null = math.op("N")
```typst-sympy-calculator
@func_mat()
def convert_null(mat):
return sympy.Matrix(mat).nullspace()
``` |
https://github.com/pluttan/typst-bmstu | https://raw.githubusercontent.com/pluttan/typst-bmstu/main/bmstu/g7.32-2017.typ | typst | MIT License | #import "g7.32-2017/decoration.typ": *
#import "g7.32-2017/blocks.typ": *
|
https://github.com/jujimeizuo/ZJSU-typst-template | https://raw.githubusercontent.com/jujimeizuo/ZJSU-typst-template/master/template/template.typ | typst | Apache License 2.0 | #import "font.typ": *
#let Thesis(
// 参考文献bib文件路径
) = {
set page(paper: "a4",
margin: (
top: 2.54cm,
bottom: 2.54cm,
left: 2.5cm,
right: 2cm),
footer: [
#set align(center)
#set text(size: 10pt, baseline: -3pt)
#counter(page).display(
"1")
]
)
// 封面
include "cover.typ"
set page(
header: {
set text(font: songti, 10pt, baseline: 8pt, spacing: 3pt)
[毕业论文(设计):正文\
毕业论文(设计)题目:C++高性能高并发服务器框架]
line(length: 100%, stroke: 0.1pt)
}
)
// 摘要
include "abstract.typ"
// 目录
include "toc.typ"
// 正文
include "body.typ"
// 参考文献
include "reference.typ"
// 致谢
include "acknowledgement.typ"
//附录
include "appendix.typ"
}
|
https://github.com/andreasKroepelin/typst-notebook | https://raw.githubusercontent.com/andreasKroepelin/typst-notebook/main/examples/example-notes.typ | typst | MIT License | #import "../template-notebook.typ": notebook
#set text(font: ("Inria Sans", "OpenMoji"))
#show: notebook.with(
title: [My cool notebook],
author: [<NAME>],
tags: (
work: orange,
family: aqua,
)
)
= My first entry
This is a very important note about @work.
You can find more details in @fermat-s-1st-theorem.
@work
= Birthday party #emoji.party
TODO Don't forget to buy a present for grandma! #emoji.cake
TODO Write card.
DONE Organise cake.
@family
= Fermat's 1st theorem $a^p ident a med (mod p)$
This extends @my-first-entry by an interesting note about number theory.
TODO Read more about primes.
|
https://github.com/yongweiy/cv | https://raw.githubusercontent.com/yongweiy/cv/master/education.typ | typst | // Imports
#import "@preview/brilliant-cv:2.0.2": cvSection, cvEntry, hBar
#let metadata = toml("./metadata.toml")
#let cvSection = cvSection.with(metadata: metadata, highlighted: false)
#let cvEntry = cvEntry.with(metadata: metadata)
#cvSection("Education")
#cvEntry(
title: [Ph.D. in Computer Science],
society: [Purdue University],
date: [2020 - now (expected Aug 2025)],
location: [West Lafayette, IN, USA],
// logo: image("../src/logos/ucla.png"),
description: list(
[Thesis: Trace-Guided Reasoning of Functional Programs (tentative)],
[Selected Courses: Programming Languages #hBar() Compiling and Programming Systems #hBar() Neurosymbolic Program Synthesis],
),
)
#cvEntry(
title: [B.S. in Computer Science],
society: [University of Michigan],
date: [2018 - 2020],
location: [Ann Arbor, MI, USA],
// logo: image("../src/logos/ucla.png"),
description: list(
// [Thesis: Exploring the Use of Machine Learning Algorithms for Predicting Stock Prices: A Comparative Study of Regression and Time-Series Models],
[Selected Courses: Operating System #hBar() Introduction to Machine Learning #hBar() Conversational Artificial Intelligence],
),
)
#cvEntry(
title: [B.S. in Electrical and Computer Engineering],
society: [Shanghai Jiao Tong University],
date: [2016 - 2020],
location: [Shanghai, China],
description: list(),
)
// Local Variables:
// tp--master-file: "/home/slark/Desktop/brilliant-cv/cv.typ"
// End:
|
|
https://github.com/mrcinv/nummat-typst | https://raw.githubusercontent.com/mrcinv/nummat-typst/master/06_fizikalna_graf.typ | typst | = Fizikalna metoda za vložitev grafov
== Naloga
- Izpelji sistem enačb za koordinate vozlišč grafa, tako da so v ravnovesju.
- Pokaži, da je matrika sistema diagonalno dominantna in negativno definitna.
- Napiši funkcijo, ki za dani graf in koordinate fiksiranih vozlišč, poišče koordinate vseh vozlišč, tako da reši sistem enačb z metodo konjugiranih gradientov.
- V ravnini nariši #link("https://en.wikipedia.org/wiki/Ladder_graph#Circular_ladder_graph")[graf krožno lestev], tako da polovico vozlišč razporediš enakomerno po enotski krožnici.
- V ravnini generiraj naključni oblak točk v notranjosti in na robu kvadrata $[0, 1]^2$. Nariši graf, ki ga dobiš z #link("https://sl.wikipedia.org/wiki/Delaunayeva_triangulacija")[Delaunayevo triangulacijo]. Fiksiraj točke na robu. |
|
https://github.com/imatpot/typst-ascii-ipa | https://raw.githubusercontent.com/imatpot/typst-ascii-ipa/main/src/lib/utils.typ | typst | MIT License | #let sanitize(value) = {
if (type(value) == str) { return value }
if (type(value) == content and value.func() == raw) { return value.text }
panic("Cannot convert value " + repr(value) + ". Please make sure the value is wrapped in \" or `")
}
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/docs/external/pdfpc.md | markdown | ---
sidebar_position: 1
---
# Pdfpc
[pdfpc](https://pdfpc.github.io/) is a "Presenter Console with multi-monitor support for PDF files." This means you can use it to display slides in the form of PDF pages and it comes with some known excellent features, much like PowerPoint.
pdfpc has a JSON-formatted `.pdfpc` file that can provide additional information for PDF slides. While you can manually write this file, you can also manage it through Touying.
## Adding Metadata
Touying remains consistent with [Polylux](https://polylux.dev/book/external/pdfpc.html) to avoid conflicts between APIs.
For example, you can add notes using `#pdfpc.speaker-note("This is a note that only the speaker will see.")`.
## Pdfpc Configuration
To add pdfpc configurations, you can use
```typst
#let s = (s.methods.append-preamble)(self: s, pdfpc.config(
duration-minutes: 30,
start-time: datetime(hour: 14, minute: 10, second: 0),
end-time: datetime(hour: 14, minute: 40, second: 0),
last-minutes: 5,
note-font-size: 12,
disable-markdown: false,
default-transition: (
type: "push",
duration-seconds: 2,
angle: ltr,
alignment: "vertical",
direction: "inward",
),
))
```
Add the corresponding configurations. Refer to [Polylux](https://polylux.dev/book/external/pdfpc.html) for specific configuration details.
## Exporting .pdfpc File
Assuming your document is `./example.typ`, you can export the `.pdfpc` file directly using:
```sh
typst query --root . ./example.typ --field value --one "<pdfpc-file>" > ./example.pdfpc
```
With the compatibility of Touying and Polylux, you can make Polylux also support direct export by adding the following code:
```typst
#import "@preview/touying:0.2.1"
#locate(loc => touying.pdfpc.pdfpc-file(loc))
``` |
|
https://github.com/dismint/docmint | https://raw.githubusercontent.com/dismint/docmint/main/linear/pset5.typ | typst | #import "template.typ": *
#show: template.with(
title: "PSET 5",
subtitle: "18.06",
pset: true,
toc: false,
)
#set math.mat(delim: "[")
#set math.vec(delim: "[")
Collaborators: <NAME>
= 4.3.1
Let us do some calculations on the left side of the equation $A^T A hat(x) = A^T b$
$
A &= mat(1, 0; 1, 1; 1, 3; 1, 4)\
A^T &= mat(1, 1, 1, 1; 0, 1, 3, 4)\
A^T A &= mat(1, 1, 1, 1; 0, 1, 3, 4) mat(1, 0; 1, 1; 1, 3; 1, 4)\
&= mat(4, 8; 8, 26)\
$
Now we do the right side:
$
b &= mat(0; 8; 8; 20)\
A^T b &= mat(1, 1, 1, 1; 0, 1, 3, 4) mat(0; 8; 8; 20)\
&= mat(36; 112)\
$
Thus we end up with the equation:
$
mat(4, 8; 8, 26) mat(C; D) &= mat(36; 112)\
mat(4, 8; 0, 10) mat(C; D) &= mat(36; 40)\
$
Therefore $boxed(D = 4), boxed(C = 1)$
The four heights are then:
$ p_1, p_2, p_3, p_4 = 1, 5, 13, 17 $
And then the errors are:
$ vec(0, 8, 8, 20) - vec(1, 5, 13, 17) &= vec(-1, 3, -5, 3)\ $
And the sum of the squares of the errors is $ (-1)^2 + (3)^2 + (-5)^2 + (3)^2 = 1 + 9 + 25 + 9 = boxed(44) $
= 4.3.12
== (a)
Let us solve for $hat(x)$
$
a^T a hat(x) &= a^T b\
m hat(x) &= b_1 + dots + b_m\
hat(x) &= (b_1 + dots + b_m) / m\
$
Thus we have shown that $hat(x)$ is the average of the $b_i$
== (b)
Now let us solve for $e$
$
e &= b - a hat(x)\
&= b - a hat(x)\
&= boxed(vec(b_1 - hat(x), dots.v, b_m - hat(x)))\
$
Therefore the variance $||e||^2$ is:
$ ||e||^2 = boxed(sum_(i=1)^m (b_i - hat(x))^2)\ $
And the standard deviation $||e||$ is:
$ ||e|| = boxed(sqrt(sum_(i=1)^m (b_i - hat(x))^2))\ $
== (c)
The error vector must be:
$ vec(3, 3, 3) - vec(1, 2, 6) &= boxed(vec(2, 1, -3))\ $
And thus the dot product with $p = (3, 3, 3)$ is:
$ vec(2, 1, -3) dot vec(3, 3, 3) = 6 + 3 - 9 = boxed(0) $
Now we will find the projection matrix of $(1, dots, 1)$
$
P &= A (A^T A)^(-1) A^T\
&= vec(1, dots.v, 1) (vec(1, dots.v, 1)^T vec(1, dots.v, 1))^(-1) vec(1, dots.v, 1)^T\
&= (vec(1, dots.v, 1) vec(1, dots.v, 1)^T) / m\
&= mat(1/m, dots_m, 1/m; dots.v_m, dots.down_m, dots.v_m; 1/m, dots_m, 1/m)\
$
Thus for this specific $3 times 3$:
$ P &= boxed(mat(1/3, 1/3, 1/3; 1/3, 1/3, 1/3; 1/3, 1/3, 1/3))\ $
= 4.3.17
We have $b = (7, 7, 21)$ for $t = (-1, 1, 2)$
Our three equations for the line $b = C + D t$ are then:
$
7 &= C - D\
7 &= C + D\
21 &= C + 2D\
$
Then we will find the least squares solution for $C$ and $D$:
$
A &= mat(1, -1; 1, 1; 1, 2)\
A^T &= mat(1, 1, 1; -1, 1, 2)\
A^T A &= mat(3, 2; 2, 6)\
A^T b &= vec(35, 42)\
mat(3, 2; 2, 6) mat(C; D) &= vec(35, 56/3)\
mat(3, 2; 0, 14/3) mat(C; D) &= vec(35, 56/3)\
$
Thus we have $D = 4$ and $C = 9$
#bimg("imgs/lss.png")
= 4.3.18
The projection is equal to:
$
p &= mat(1, -1; 1, 1; 1, 2) vec(9, 4)\
&= vec(5, 13, 17)\
$
Then the error vector is:
$
e &= vec(7, 7, 21) - vec(5, 13, 17)\
&= vec(2, -6, 4)\
$
It must be the case that $P e = 0$ since we want to minimize the error, so thus, it must be the case that they are orthogonal, and the dot product is equal to zero.
= 4.4.2
The lengths of the vectors are $sqrt(4 + 4 + 1) = 3$ and $sqrt(1 + 4 + 4) = 3$. We then have our orthogonal vectors:
$
q_1 &= vec(2/3, 2/3, -1/3)\
q_2 &= vec(-1/3, 2/3, 2/3)\
$
Resulting in the matrix:
$ Q &= mat(2/3, -1/3; 2/3, 2/3; -1/3, 2/3) $
Now we will calculate the two matrix products:
$
Q^T Q &= mat(2/3, 2/3, -1/3; -1/3, 2/3, 2/3) mat(2/3, -1/3; 2/3, 2/3; -1/3, 2/3)\
&= boxed(mat(1, 0; 0, 1))\
$
$
Q Q^T &= mat(2/3, -1/3; 2/3, 2/3; -1/3, 2/3) mat(2/3, 2/3, -1/3; -1/3, 2/3, 2/3)\
&= boxed(mat(5/9, 2/9, -4/9; 2/9, 8/9, 2/9; -4/9, 2/9, 5/9))\
$
= 4.4.5
We want to find two orthogonal vectors in the plane $x + y + 2z = 0$
We can simply set one vector as:
$ vec(1, -1, 0) $
Thus we can find another vector simply by setting the first two to cancel out and the third to match the plane equation since we have a zero to work with in the first vector:
$ vec(1, 1, -1) $
To make them orthonormal, we can divide by the length of the vector, which are $sqrt(2), sqrt(3)$
Thus we have the two vectors:
$
v_1 &= boxed(vec(1/sqrt(2), -1/sqrt(2), 0))\
v_2 &= boxed(vec(1/sqrt(3), 1/sqrt(3), -1/sqrt(3)))\
$
= 4.4.7
We have $Q x = b$ where $Q$ is the matrix of orthonormal columns. Transforming this into the least squares solution form we get:
$ Q^T Q x = Q^T b $
But we know that the columns of $Q$ are orthonormal, so $Q^T Q = I$, and thus we have:
$ x = boxed(Q^T b) $
= 4.4.18
We have the three vectors:
$
a = (1, -1, 0, 0)\
b = (0, 1, -1, 0)\
c = (0, 0, 1, -1)\
$
Let us start by setting $A = a$. Then we can calculate $B$ as follows:
$
B &= b - (A^T b) / (A^T A) A\
A &= boxed(vec(1, -1, 0, 0))\
A^T &= mat(1, -1, 0, 0)\
A^T A &= mat(1, -1, 0, 0) vec(1, -1, 0, 0)\
&= 2\
A^T b &= mat(1, -1, 0, 0) vec(0, 1, -1, 0)\
&= -1\
B &= b + 1/2 vec(1, -1, 0, 0)\
&= vec(0, 1, -1, 0) + vec(1/2, -1/2, 0, 0)\
B &= boxed(vec(1/2, 1/2, -1, 0))\
$
Next let us solve for $C$:
$
C &= c - (A^T c) / (A^T A) A - (B^T c) / (B^T B) B\
A &= vec(1, -1, 0, 0)\
B &= vec(1/2, 1/2, -1, 0)\
A^T &= mat(1, -1, 0, 0)\
B^T &= mat(1/2, 1/2, -1, 0)\
A^T A &= 2\
B^T B &= 3/2\
A^T c &= mat(1, -1, 0, 0) vec(0, 0, 1, -1)\
&= 0\
B^T c &= mat(1/2, 1/2, -1, 0) vec(0, 0, 1, -1)\
&= -1\
C &= c + 2/3 vec(1/2, 1/2, -1, 0)\
&= vec(0, 0, 1, -1) + 2/3 vec(1/2, 1/2, -1, 0)\
C &= boxed(vec(1/3, 1/3, 1/3, -1))\
$
|
|
https://github.com/taooceros/MATH-542-HW | https://raw.githubusercontent.com/taooceros/MATH-542-HW/main/HW6/HW6.typ | typst | #import "@local/homework-template:0.1.0": *
= 12.1
== 11
#let div = $\/$
We can see that $p^(k-1)M$ and $p^k M$ is a $R$-module.
Consider the ideal $I = (p^(k-1), a)$ and $J = (p^k, a)$.
Consider the homomorhism of $I->p^(k-1)M$ which is the restriction to $I$ of the homomorphism $R-> R/(a) = M$.
Thus, we have $I/J cong (p^(k-1)M)/(p^k M)$ as $R$-module by isomorphism theorem. Then we can see that $I/J$ will be $R div (p)$ if $k<=n$ and $(0)$ if $k>n$ as $I = (gcd(p^(k-1), a)), J = (gcd(p^k, a))$.
== 12
===
#let cplus = $plus.circle$
By previous exercise we can see that $p^(k-1) M div p^k M cong p^(k-1)(M_1 cplus ... cplus M_n) div p^(k)(M_1 cplus ... cplus M_n)$, where $M_i$ is generated by the elementary divisors of $M$. By previous exercise, we can see that each $p^(k-1) M_i / p^k M_i cong R div (p)$ if the $i$-th elementary divisor is power of $p^(a)$ with $a>=k$.
===
Since $M_1 cong M_2$, then they both can be written as some direct sum of $R div (a)$. Then follows the previous part, we can conclude they have the same number of elementary divisor $p^a$ with $a >= k$. Since this is true for all elementary divisors in $R$, we can conclude that $M_1$ and $M_2$ have the same set of elementary divisors.
= 12.2
== 10
It suffices to find all invariant factor where the largest one is $(x+2)^2 (x-1)$.
We can see that we have
$
(x+2), (x+2) (x-1), (x+2)^2 (x-1)\
(x+2), (x+2)^2, (x+2)^2 (x-1)\
(x+2), (x+2), (x+2), (x+2)^2 (x-1)\
(x-1), (x-1), (x-1), (x+2)^2(x-1)\
(x-1), (x+2)(x-1), (x+2)^2(x-1)\
(x+2)^2 (x-1), (x+2)^2 (x-1)
$
Each will have a representator that can be written based on the rational canonical form construction.
$
A_p = mat(0, 0, ..., 0, -a_0/a_n;
1, 0, ..., 0, -a_1/a_n;
dots.v, 1, dots.down, , dots.v;
dots.v, dots.v, dots.down, ,dots.v;
0,0,...,1,-a_(n-1)/a_n)
$
== 12
Given that the matrix satisfy $A^6 = I$, we have the minimal polynomial satisfying $x^6 - 1 = 0$.
$
x^6-1 = (x-1)(x+1)(x^2+x+1)(x^2-x+1) = (x+1)^2(x^2+x+1)^2
$
Thus the minimal polynomial needs to be a factor of $(x+1)^2(x^2+x+1)^2$.
We have choice $x+1, (x+1)^2, (x^2+x+1), (x+1)(x^2+x+1)$.
Thus results are
$
mat(1,0,0;
0,1,0;
0,0,1;),
mat(1,0,0;
0,0,1;
0,1,0;),
mat(0,0,1;
1,0,0;
0,1,0;),
$
For $4 times 4$ matrices satifying $B^20 = I$. We have a similar expression.
$
x^20 - 1 = 0\
(x - 1)^2 (x^4 + x^3 + x^2 + x + 1)^2 (x^10 + 1) = 0
$
For the minimal polynomial, we have
$
(x-1)^i #h(1em) forall i <= 4\
(x^4 + x^3 + x^2 + x + 1)
$
Thus we can construct similar matrix based on these minimal polynomials as before.
= 12.3
== 18
By factoring out the elementary divisors
$
(x-2)^3, (x-3)^2\
(x-2)^2, (x-2), (x-3)^2\
(x-2), (x-2), (x-2), (x-3)^2\
(x-2)^3, (x-3), (x-3)\
(x-2)^2, (x-2), (x-3), (x-3)\
(x-2), (x-2), (x-2), (x-3), (x-3)\
$
Then constructing the Jordon Canonical form based on that
$
(x-2)^3, (x-3)^2\
mat(2,1,0,0,0;
0,2,1,0,0;
0,0,2,0,0;
0,0,0,3,1;
0,0,0,0,3)
$
Others are similar.
== 22
This suggests that we have the minimal polynomial a factor of $x^3 - x = 0 = (x+1)(x-1)x$. Then we can see that the minimal polynomial have no repeated root, which means it is diagnolizable.
This is not true over any field $F$ as we can have $(x+1) = (x-1)$ in $FF_2$.
== 22
$
phi(nu_j) = -a_(1 j)v_1 - ... - a_(j-1 j)v_(j-1) + (x-a_(j j))v_j - a_(j+1 j) v_(j+1) - ... a_(n j) v_n
$
By applying the definition of $x(v_j)$, we have this equal to $0$.
Assume we have some $v$ lies in $ker(phi)$.
Then
$
phi(v_j) = phi(sum a_i xi_i) = sum phi(a_i xi_i) = sum a_i phi(xi_i) = sum a_i v_i
$
== 23
===
We have the homomorphism $phi : F[x]^n -> V$.
$
phi(x xi_j) = x phi (xi_j) = x v_j = a_(1 j) v_1 + ... + a_(n j) v_n
$
Thus consider the preimage of such an element, which will be in some form of $sum f_i$ plus the kernel of $phi$, which is $nu_j$.
===
We have $F[x] xi_i = F xi_i + F' xi_i$ where $F'$ denotes all polynomial with constant term $0$. Since $F' xi_i = F[x] x(xi_j) = F[x] (nu_j + f_j)$ the claim follows.
===
By previous claim we have
$
sum F[x] xi_i = sum F[x] nu_i + sum F xi_i
$
For an element to be in the kernel of $phi$, the constant term must be $0$. Thus we have any element in $ker(phi)$ can be written as $sum F[x] nu_i$.
===
This claim follows by the definition of $nu_i$. We have
$
nu_j = -a_(1 j) xi_1 - ... - a_(j-1 j) xi_(j-1) + (x-a_(j j)) xi_j - a_(j+1 j) xi_(j+1) - ... - a_(n j) xi_n
$
Thus the $j$-th column of the relations matrix will be as $mat(-a_(1 j);dots.v; x-a_(j j); dots.v; -a_(n j))$.
Since this is a matrix represented by a set of elements generate the kernel of $phi$, we can change the basis of the kernel to the basis of the relations matrix, and thus results a diagonal matrix. The transpose won't change the diagonal property, and thus we can prove the claim. |
|
https://github.com/loqusion/typix | https://raw.githubusercontent.com/loqusion/typix/main/README.md | markdown | MIT License | <h1 align="center">
<img
src="https://raw.githubusercontent.com/loqusion/typix/main/.github/assets/logo_1544x1544.png"
alt="Typix Logo"
width="150"
/><br />
Typix
</h1>
<p align="center">
<a href="https://flakehub.com/flake/loqusion/typix">
<img src="https://img.shields.io/endpoint?style=for-the-badge&color=95b6f9&labelColor=302D41&url=https://flakehub.com/f/loqusion/typix/badge"></a>
</p>
Typix aims to make it easier to use [Nix](https://nixos.org/) in
[Typst](https://github.com/typst/typst) projects.
- **Dependency management**: supports arbitrary dependencies including fonts,
images, and data
- **Reproducible**: via a hermetically sealed build environment
## Features
- Automatically fetch dependencies and compile in a single command (`nix run
.#build`)
- Watch input files and recompile on changes (`nix run .#watch`)
- Set up a shell environment with all dependencies made available via
environment variables and symlinks
- Extensible via
[`mkTypstDerivation`](https://loqusion.github.io/typix/api/derivations/mk-typst-derivation.html)
- Support for dependencies such as:
- [fonts](https://typst.app/docs/reference/text/text/#parameters-font)
- [images](https://typst.app/docs/reference/visualize/image/)
- [data](https://typst.app/docs/reference/data-loading/)
[Typst packages](https://typst.app/docs/packages/) are currently unsupported,
however there is a
[workaround](https://loqusion.github.io/typix/recipes/using-typst-packages.html).
## Getting Started
After [installing Nix](https://github.com/DeterminateSystems/nix-installer) and
[enabling
flakes](https://nixos.wiki/wiki/Flakes#Enable_flakes_permanently_in_NixOS), you
can initialize a flake from the default template:
```bash
nix flake init -t github:loqusion/typix
```
Here are some commands you can run from the default template:
- `nix run .#watch` — watch the input files and recompile on changes
- `nix run .#build` — compile and copy the output to the current directory
---
For more information, check out [the docs](https://loqusion.github.io/typix/).
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/061.%20america.html.typ | typst | america.html
Why Startups Condense in America
May 2006(This essay is derived from a keynote at Xtech.)Startups happen in clusters. There are a lot of them in Silicon
Valley and Boston, and few in Chicago or Miami. A country that
wants startups will probably also have to reproduce whatever makes
these clusters form.I've claimed that the recipe is a
great university near a town smart
people like. If you set up those conditions within the US, startups
will form as inevitably as water droplets condense on a cold piece
of metal. But when I consider what it would take to reproduce
Silicon Valley in another country, it's clear the US is a particularly
humid environment. Startups condense more easily here.It is by no means a lost cause to try to create a silicon valley
in another country. There's room not merely to equal Silicon Valley,
but to surpass it. But if you want to do that, you have to
understand the advantages startups get from being in America.1. The US Allows Immigration.For example, I doubt it would be possible to reproduce Silicon
Valley in Japan, because one of Silicon Valley's most distinctive
features is immigration. Half the people there speak with accents.
And the Japanese don't like immigration. When they think about how
to make a Japanese silicon valley, I suspect they unconsciously
frame it as how to make one consisting only of Japanese people.
This way of framing the question probably guarantees failure.A silicon valley has to be a mecca for the smart and the ambitious,
and you can't have a mecca if you don't let people into it.Of course, it's not saying much that America is more open to
immigration than Japan. Immigration policy is one area where a
competitor could do better.2. The US Is a Rich Country.I could see India one day producing a rival to Silicon Valley.
Obviously they have the right people: you can tell that by the
number of Indians in the current Silicon Valley. The problem with
India itself is that it's still so poor.In poor countries, things we take for granted are missing. A friend
of mine visiting India sprained her ankle falling down the steps
in a railway station. When she turned to see what had happened,
she found the steps were all different heights. In industrialized
countries we walk down steps our whole lives and never think about
this, because there's an infrastructure that prevents such a staircase
from being built.The US has never been so poor as some countries are now. There
have never been swarms of beggars in the streets of American cities.
So we have no data about what it takes to get from the swarms-of-beggars
stage to the silicon-valley stage. Could you have both at once,
or does there have to be some baseline prosperity before you get a
silicon valley?I suspect there is some speed limit to the evolution
of an economy. Economies are made out of people, and attitudes can
only change a certain amount per generation.
[1]3. The US Is Not (Yet) a Police State.Another country I could see wanting to have a silicon valley is
China. But I doubt they could do it yet either. China still seems
to be a police state, and although present rulers seem enlightened
compared to the last, even enlightened despotism can probably only
get you part way toward being a great economic power.It can get you factories for building things designed elsewhere.
Can it get you the designers, though? Can imagination flourish
where people can't criticize the government? Imagination means
having odd ideas, and it's hard to have odd ideas about technology
without also having odd ideas about politics. And in any case,
many technical ideas do have political implications. So if you
squash dissent, the back pressure will propagate into technical
fields.
[2]Singapore would face a similar problem. Singapore seems very aware
of the importance of encouraging startups. But while energetic
government intervention may be able to make a port run efficiently,
it can't coax startups into existence. A state that bans chewing
gum has a long way to go before it could create a San Francisco.Do you need a San Francisco? Might there not be an alternate route
to innovation that goes through obedience and cooperation instead
of individualism? Possibly, but I'd bet not. Most imaginative
people seem to share a certain prickly independence,
whenever and wherever they lived. You see it in Diogenes telling
Alexander to get out of his light and two thousand years later in
Feynman breaking into safes at Los Alamos.
[3]
Imaginative people
don't want to follow or lead. They're most productive when everyone
gets to do what they want.Ironically, of all rich countries the US has lost the most civil
liberties recently. But I'm not too worried yet. I'm hoping once
the present administration is out, the natural openness of American
culture will reassert itself.4. American Universities Are Better.You need a great university to seed a silicon valley, and so far
there are few outside the US. I asked a handful of American computer
science professors which universities in Europe were most admired,
and they all basically said "Cambridge" followed by a long pause
while they tried to think of others. There don't seem to be many
universities elsewhere that compare with the best in America, at
least in technology.In some countries this is the result of a deliberate policy. The
German and Dutch governments, perhaps from fear of elitism, try to
ensure that all universities are roughly equal in quality. The
downside is that none are especially good. The best professors
are spread out, instead of being concentrated as they are in the
US. This probably makes them less productive, because they don't
have good colleagues to inspire them. It also means no one university
will be good enough to act as a mecca, attracting talent from abroad
and causing startups to form around it.The case of Germany is a strange one. The Germans invented the
modern university, and up till the 1930s theirs were the best in
the world. Now they have none that stand out. As I was mulling
this over, I found myself thinking: "I can understand why German
universities declined in the 1930s, after they excluded Jews. But
surely they should have bounced back by now." Then I realized:
maybe not. There are few Jews left in Germany and most Jews I know
would not want to move there. And if you took any great American
university and removed the Jews, you'd have some pretty big gaps.
So maybe it would be a lost cause trying to create a silicon valley
in Germany, because you couldn't establish the level of university
you'd need as a seed.
[4]It's natural for US universities to compete with one another because
so many are private. To reproduce the quality of American universities
you probably also have to reproduce this. If universities are
controlled by the central government, log-rolling will pull them
all toward the mean: the new Institute of X will end up at the
university in the district of a powerful politician, instead of
where it should be.5. You Can Fire People in America.I think one of the biggest obstacles to creating startups in Europe
is the attitude toward employment. The famously rigid labor laws
hurt every company, but startups especially, because startups have
the least time to spare for bureaucratic hassles.The difficulty of firing people is a particular problem for startups
because they have no redundancy. Every person has to do their
job well.But the problem is more than just that some startup might have a
problem firing someone they needed to. Across industries and
countries, there's a strong inverse correlation between performance
and job security. Actors and directors are fired at the end of
each film, so they have to deliver every time. Junior professors
are fired by default after a few years unless the university chooses
to grant them tenure. Professional athletes know they'll be pulled
if they play badly for just a couple games. At the other end of
the scale (at least in the US) are auto workers, New York City
schoolteachers, and civil servants, who are all nearly impossible
to fire. The trend is so clear that you'd have to be willfully
blind not to see it.Performance isn't everything, you say? Well, are auto workers,
schoolteachers, and civil servants happier than actors,
professors, and professional athletes?European public opinion will apparently tolerate people being fired
in industries where they really care about performance. Unfortunately
the only industry they care enough about so far is soccer. But
that is at least a precedent.6. In America Work Is Less Identified with Employment.The problem in more traditional places like Europe and Japan goes
deeper than the employment laws. More dangerous is the attitude
they reflect: that an employee is a kind of servant, whom the
employer has a duty to protect. It used to be that way in America
too. In 1970 you were still supposed to get a job with a big
company, for whom ideally you'd work your whole career. In return
the company would take care of you: they'd try not to fire you,
cover your medical expenses, and support you in old age.Gradually employment has been shedding such paternalistic overtones
and becoming simply an economic exchange. But the importance of
the new model is not just that it makes it easier for startups to
grow. More important, I think, is that it it makes it easier for
people to start startups.Even in the US most kids graduating from college still think they're
supposed to get jobs, as if you couldn't be productive without being
someone's employee. But the less you identify work with employment,
the easier it becomes to start a startup. When you see your career
as a series of different types of work, instead of a lifetime's
service to a single employer, there's less risk in starting your
own company, because you're only replacing one segment instead of
discarding the whole thing.The old ideas are so powerful that even the most successful startup
founders have had to struggle against them. A year after the
founding of Apple, <NAME> still hadn't quit HP. He still
planned to work there for life. And when Jobs found someone to
give Apple serious venture funding, on the condition that Woz quit,
he initially refused, arguing that he'd designed both the Apple I
and the Apple II while working at HP, and there was no reason he
couldn't continue.7. America Is Not Too Fussy.If there are any laws regulating businesses, you can assume larval
startups will break most of them, because they don't know what the
laws are and don't have time to find out.For example, many startups in America begin in places where it's
not really legal to run a business. Hewlett-Packard, Apple, and
Google were all run out of garages. Many more startups, including
ours, were initially run out of apartments. If the laws against
such things were actually enforced, most startups wouldn't happen.That could be a problem in fussier countries. If Hewlett and Packard
tried running an electronics company out of their garage in
Switzerland, the old lady next door would report them to the municipal
authorities.But the worst problem in other countries is probably the effort
required just to start a company. A friend of mine started a company
in Germany in the early 90s, and was shocked to discover, among
many other regulations, that you needed $20,000 in capital to
incorporate. That's one reason I'm not typing this on an Apfel
laptop. Jobs and Wozniak couldn't have come up with that kind of
money in a company financed by selling a VW bus and an HP calculator.
We couldn't have started Viaweb either.
[5]Here's a tip for governments that want to encourage startups: read
the stories of existing startups, and then try to simulate what
would have happened in your country. When you hit something that
would have killed Apple, prune it off.Startups are marginal.
They're started by the poor and the
timid; they begin in marginal space and spare time; they're started
by people who are supposed to be doing something else; and though
businesses, their founders often know nothing about business. Young
startups are fragile. A society that trims its margins sharply
will kill them all.8. America Has a Large Domestic Market.What sustains a startup in the beginning is the prospect of getting
their initial product out. The successful ones therefore make the
first version as simple as possible. In the US they usually begin
by making something just for the local market.This works in America, because the local market is 300 million
people. It wouldn't work so well in Sweden. In a small country,
a startup has a harder task: they have to sell internationally from
the start.The EU was designed partly to simulate a single, large domestic
market. The problem is that the inhabitants still speak many
different languages. So a software startup in Sweden is still at
a disadvantage relative to one in the US, because they have to deal
with internationalization from the beginning. It's significant
that the most famous recent startup in Europe, Skype, worked on a
problem that was intrinsically international.However, for better or worse it looks as if Europe will in a few
decades speak a single language. When I was a student in Italy in
1990, few Italians spoke English. Now all educated people seem to
be expected to-- and Europeans do not like to seem uneducated. This
is presumably a taboo subject, but if present trends continue,
French and German will eventually go the way of Irish and Luxembourgish:
they'll be spoken in homes and by eccentric nationalists.9. America Has Venture Funding.Startups are easier to start in America because funding is easier
to get. There are now a few VC firms outside the US, but startup
funding doesn't only come from VC firms. A more important source,
because it's more personal and comes earlier in the process, is
money from individual angel investors. Google might never have got
to the point where they could raise millions from VC funds if they
hadn't first raised a hundred thousand from <NAME>. And
he could help them because he was one of the founders of Sun. This
pattern is repeated constantly in startup hubs. It's this pattern
that makes them startup hubs.The good news is, all you have to do to get the process rolling is
get those first few startups successfully launched. If they stick
around after they get rich, startup founders will almost automatically
fund and encourage new startups.The bad news is that the cycle is slow. It probably takes five
years, on average, before a startup founder can make angel investments.
And while governments might be able to set up local VC funds
by supplying the money themselves and recruiting people from existing
firms to run them, only organic growth can produce angel investors.Incidentally, America's private universities are one reason there's
so much venture capital. A lot of the money in VC funds comes from
their endowments. So another advantage of private universities is
that a good chunk of the country's wealth is managed by enlightened
investors.10. America Has Dynamic Typing for Careers.Compared to other industrialized countries the US is disorganized
about routing people into careers. For example, in America people
often don't decide to go to medical school till they've finished
college. In Europe they generally decide in high school.The European approach reflects the old idea that each person has a
single, definite occupation-- which is not far from the idea that
each person has a natural "station" in life. If this were true,
the most efficient plan would be to discover each person's station
as early as possible, so they could receive the training appropriate
to it.In the US things are more haphazard. But that turns out to be an
advantage as an economy gets more liquid, just as dynamic typing
turns out to work better than static for ill-defined problems. This
is particularly true with startups. "Startup founder" is not the
sort of career a high school student would choose. If you ask at
that age, people will choose conservatively. They'll choose
well-understood occupations like engineer, or doctor, or lawyer.Startups are the kind of thing people don't plan, so you're more
likely to get them in a society where it's ok to make career decisions
on the fly.For example, in theory the purpose of a PhD program is to train you
to do research. But fortunately in the US this is another rule
that isn't very strictly enforced. In the US most people in CS PhD
programs are there simply because they wanted to learn more. They
haven't decided what they'll do afterward. So American grad schools
spawn a lot of startups, because students don't feel they're failing
if they don't go into research.Those worried about America's "competitiveness" often suggest
spending more on public schools. But perhaps America's lousy public
schools have a hidden advantage. Because they're so bad, the kids
adopt an attitude of waiting for college. I did; I knew I was
learning so little that I wasn't even learning what the choices
were, let alone which to choose. This is demoralizing, but it does
at least make you keep an open mind.Certainly if I had to choose between bad high schools and good
universities, like the US, and good high schools and bad universities,
like most other industrialized countries, I'd take the US system.
Better to make everyone feel like a late bloomer than a failed child
prodigy.AttitudesThere's one item conspicuously missing from this list: American
attitudes. Americans are said to be more entrepreneurial, and less
afraid of risk. But America has no monopoly on this. Indians and
Chinese seem plenty entrepreneurial, perhaps more than Americans.Some say Europeans are less energetic, but I don't believe it. I
think the problem with Europe is not that they lack balls, but that
they lack examples.Even in the US, the most successful startup founders are often
technical people who are quite timid, initially, about the idea of
starting their own company. Few are the sort of backslapping
extroverts one thinks of as typically American. They can usually
only summon up the activation energy to start a startup when they
meet people who've done it and realize they could too.I think what holds back European hackers is simply that they don't
meet so many people who've done it. You see that variation even
within the US. Stanford students are more entrepreneurial than
Yale students, but not because of some difference in their characters;
the Yale students just have fewer examples.I admit there seem to be different attitudes toward ambition in
Europe and the US. In the US it's ok to be overtly ambitious, and
in most of Europe it's not. But this can't be an intrinsically
European quality; previous generations of Europeans were as ambitious
as Americans. What happened? My hypothesis is that ambition was
discredited by the terrible things ambitious people did in the first
half of the twentieth century. Now swagger is out. (Even now the
image of a very ambitious German presses a button or two, doesn't
it?)It would be surprising if European attitudes weren't affected by
the disasters of the twentieth century. It takes a while to be
optimistic after events like that. But ambition is human nature.
Gradually it will re-emerge.
[6]How To Do BetterI don't mean to suggest by this list that America is the perfect
place for startups. It's the best place so far, but the sample
size is small, and "so far" is not very long. On historical time
scales, what we have now is just a
prototype.So let's look at Silicon Valley the way you'd look at a product
made by a competitor. What weaknesses could you exploit? How could
you make something users would like better? The users in this case
are those critical few thousand people you'd like to move to your
silicon valley.To start with, Silicon Valley is too far from San Francisco. Palo
Alto, the original ground zero, is about thirty miles away, and the
present center more like forty. So people who come to work in
Silicon Valley face an unpleasant choice: either live in the boring
sprawl of the valley proper, or live in San Francisco and endure
an hour commute each way.The best thing would be if the silicon valley were not merely closer
to the interesting city, but interesting itself. And there is a
lot of room for improvement here. Palo Alto is not so bad, but
everything built since is the worst sort of strip development. You
can measure how demoralizing it is by the number of people who will
sacrifice two hours a day commuting rather than live there.Another area in which you could easily surpass Silicon Valley is
public transportation. There is a train running the length of it,
and by American standards it's not bad. Which is to say that to
Japanese or Europeans it would seem like something out of the third
world.The kind of people you want to attract to your silicon valley like
to get around by train, bicycle, and on foot. So if you want to
beat America, design a town that puts cars last. It will be a while
before any American city can bring itself to do that.Capital GainsThere are also a couple things you could do to beat America at the
national level. One would be to have lower capital gains taxes.
It doesn't seem critical to have the lowest income taxes,
because to take advantage of those, people have to move.
[7]
But
if capital gains rates vary, you move assets, not yourself, so
changes are reflected at market speeds. The lower the rate, the
cheaper it is to buy stock in growing companies as opposed to real
estate, or bonds, or stocks bought for the dividends they pay.So if you want to encourage startups you should have a low rate on
capital gains. Politicians are caught between a rock and a hard
place here, however: make the capital gains rate low and be accused
of creating "tax breaks for the rich," or make it high and starve
growing companies of investment capital. As Galbraith said,
politics is a matter of choosing between the unpalatable and the
disastrous. A lot of governments experimented with the disastrous
in the twentieth century; now the trend seems to be toward the
merely unpalatable.Oddly enough, the leaders now are European countries like Belgium,
which has a capital gains tax rate of zero.ImmigrationThe other place you could beat the US would be with smarter immigration
policy. There are huge gains to be made here. Silicon valleys are
made of people, remember.Like a company whose software runs on Windows, those in the current
Silicon Valley are all too aware of the shortcomings of the INS,
but there's little they can do about it. They're hostages of the
platform.America's immigration system has never been well run, and since
2001 there has been an additional admixture of paranoia. What
fraction of the smart people who want to come to America can even
get in? I doubt even half. Which means if you made a competing
technology hub that let in all smart people, you'd immediately get
more than half the world's top talent, for free.US immigration policy is particularly ill-suited to startups, because
it reflects a model of work from the 1970s. It assumes good technical
people have college degrees, and that work means working for a big
company.If you don't have a college degree you can't get an H1B visa, the
type usually issued to programmers. But a test that excludes Steve
Jobs, <NAME>, and <NAME> can't be a good one. Plus you
can't get a visa for working on your own company, only for working
as an employee of someone else's. And if you want to apply for
citizenship you daren't work for a startup at all, because if your
sponsor goes out of business, you have to start over.American immigration policy keeps out most smart people, and channels
the rest into unproductive jobs. It would be easy to do better.
Imagine if, instead, you treated immigration like recruiting-- if
you made a conscious effort to seek out the smartest people and get
them to come to your country.A country that got immigration right would have a huge advantage.
At this point you could become a mecca for smart people simply by
having an immigration system that let them in.A Good VectorIf you look at the kinds of things you have to do to create an
environment where startups condense, none are great sacrifices.
Great universities? Livable towns? Civil liberties? Flexible
employment laws? Immigration policies that let in smart people?
Tax laws that encourage growth? It's not as if you have to risk
destroying your country to get a silicon valley; these are all good
things in their own right.And then of course there's the question, can you afford not to? I
can imagine a future in which the default choice of ambitious young
people is to start their own company
rather than work for someone else's. I'm not sure that will happen,
but it's where the trend points now. And if that is the future,
places that don't have startups will be a whole step behind,
like those that missed the Industrial Revolution.Notes[1]
On the verge of the Industrial Revolution, England was already
the richest country in the world. As far as such things can be
compared, per capita income in England in 1750 was higher than
India's in 1960.Deane, Phyllis, The First Industrial Revolution, Cambridge
University Press, 1965.[2]
This has already happened once in China, during the Ming
Dynasty, when the country turned its back on industrialization at
the command of the court. One of Europe's advantages was that it
had no government powerful enough to do that.[3]
Of course, Feynman and Diogenes were from adjacent traditions,
but Confucius, though more polite, was no more willing to be told
what to think.[4]
For similar reasons it might be a lost cause to try to establish
a silicon valley in Israel. Instead of no Jews moving there, only
Jews would move there, and I don't think you could build a silicon
valley out of just Jews any more than you could out of just Japanese.(This is not a remark about the qualities of these groups, just their
sizes. Japanese are only about 2% of the world population, and
Jews about .2%.)[5]
According to the World Bank, the initial capital requirement
for German companies is 47.6% of the per capita income. Doh.World Bank, Doing Business in 2006, http://doingbusiness.org[6]
For most of the twentieth century, Europeans looked back on
the summer of 1914 as if they'd been living in a dream world. It
seems more accurate (or at least, as accurate) to call the years
after 1914 a nightmare than to call those before a dream. A lot
of the optimism Europeans consider distinctly American is simply
what they too were feeling in 1914.[7]
The point where things start to go wrong seems to be about
50%. Above that people get serious about tax avoidance. The reason
is that the payoff for avoiding tax grows hyperexponentially (x/1-x
for 0 < x < 1). If your income tax rate is 10%, moving to Monaco
would only give you 11% more income, which wouldn't even cover the
extra cost. If it's 90%, you'd get ten times as much income. And
at 98%, as it was briefly in Britain in the 70s, moving to Monaco
would give you fifty times as much income. It seems quite likely
that European governments of the 70s never drew this curve.Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading
drafts of this, and to <NAME> for inviting me to speak.French TranslationRussian TranslationJapanese TranslationArabic Translation
|
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/007.%20langdes.html.typ | typst | #set page(
paper: "a5",
margin: (x: 1.8cm, y: 1.5cm),
)
#set text(
font: "Liberation Serif",
size: 10pt,
hyphenate: false
)
#set par(justify: true)
#set quote(block: true)
#v(10pt)
= Five Questions about Language Design
#v(10pt)
_May 2001_
_(These are some notes I made for a panel discussion on programming language design at MIT on May 10, 2001.)_
== Guiding Philosophy
=== 1. Programming Languages Are for People.
Programming languages are how people talk to computers. The computer would be just as happy speaking any language that was unambiguous. The reason we have high level languages is because people can't deal with machine language. The point of programming languages is to prevent our poor frail human brains from being overwhelmed by a mass of detail.
Architects know that some kinds of design problems are more personal than others. One of the cleanest, most abstract design problems is designing bridges. There your job is largely a matter of spanning a given distance with the least material. The other end of the spectrum is designing chairs. Chair designers have to spend their time thinking about human butts.
Software varies in the same way. Designing algorithms for routing data through a network is a nice, abstract problem, like designing bridges. Whereas designing programming languages is like designing chairs: it's all about dealing with human weaknesses.
Most of us hate to acknowledge this. Designing systems of great mathematical elegance sounds a lot more appealing to most of us than pandering to human weaknesses. And there is a role for mathematical elegance: some kinds of elegance make programs easier to understand. But elegance is not an end in itself.
And when I say languages have to be designed to suit human weaknesses, I don't mean that languages have to be designed for bad programmers. In fact I think you ought to design for the best programmers, but even the best programmers have limitations. I don't think anyone would like programming in a language where all the variables were the letter x with integer subscripts.
=== 2. Design for Yourself and Your Friends.
If you look at the history of programming languages, a lot of the best ones were languages designed for their own authors to use, and a lot of the worst ones were designed for other people to use.
When languages are designed for other people, it's always a specific group of other people: people not as smart as the language designer. So you get a language that talks down to you. Cobol is the most extreme case, but a lot of languages are pervaded by this spirit.
It has nothing to do with how abstract the language is. C is pretty low-level, but it was designed for its authors to use, and that's why hackers like it.
The argument for designing languages for bad programmers is that there are more bad programmers than good programmers. That may be so. But those few good programmers write a disproportionately large percentage of the software.
I'm interested in the question, how do you design a language that the very best hackers will like? I happen to think this is identical to the question, how do you design a good programming language?, but even if it isn't, it is at least an interesting question.
=== 3. Give the Programmer as Much Control as Possible.
Many languages (especially the ones designed for other people) have the attitude of a governess: they try to prevent you from doing things that they think aren't good for you. I like the opposite approach: give the programmer as much control as you can.
When I first learned Lisp, what I liked most about it was that it considered me an equal partner. In the other languages I had learned up till then, there was the language and there was my program, written in the language, and the two were very separate. But in Lisp the functions and macros I wrote were just like those that made up the language itself. I could rewrite the language if I wanted. It had the same appeal as open-source software.
=== 4. Aim for Brevity.
Brevity is underestimated and even scorned. But if you look into the hearts of hackers, you'll see that they really love it. How many times have you heard hackers speak fondly of how in, say, APL, they could do amazing things with just a couple lines of code? I think anything that really smart people really love is worth paying attention to.
I think almost anything you can do to make programs shorter is good. There should be lots of library functions; anything that can be implicit should be; the syntax should be terse to a fault; even the names of things should be short.
And it's not only programs that should be short. The manual should be thin as well. A good part of manuals is taken up with clarifications and reservations and warnings and special cases. If you force yourself to shorten the manual, in the best case you do it by fixing the things in the language that required so much explanation.
=== 5. Admit What Hacking Is.
A lot of people wish that hacking was mathematics, or at least something like a natural science. I think hacking is more like architecture. Architecture is related to physics, in the sense that architects have to design buildings that don't fall down, but the actual goal of architects is to make great buildings, not to make discoveries about statics.
What hackers like to do is make great programs. And I think, at least in our own minds, we have to remember that it's an admirable thing to write great programs, even when this work doesn't translate easily into the conventional intellectual currency of research papers. Intellectually, it is just as worthwhile to design a language programmers will love as it is to design a horrible one that embodies some idea you can publish a paper about.
== Open Problems
=== 1. How to Organize Big Libraries?
Libraries are becoming an increasingly important component of programming languages. They're also getting bigger, and this can be dangerous. If it takes longer to find the library function that will do what you want than it would take to write it yourself, then all that code is doing nothing but make your manual thick. (The Symbolics manuals were a case in point.) So I think we will have to work on ways to organize libraries. The ideal would be to design them so that the programmer could guess what library call would do the right thing.
=== 2. Are People Really Scared of Prefix Syntax?
This is an open problem in the sense that I have wondered about it for years and still don't know the answer. Prefix syntax seems perfectly natural to me, except possibly for math. But it could be that a lot of Lisp's unpopularity is simply due to having an unfamiliar syntax. Whether to do anything about it, if it is true, is another question.
== 3. What Do You Need for Server-Based Software?
I think a lot of the most exciting new applications that get written in the next twenty years will be Web-based applications, meaning programs that sit on the server and talk to you through a Web browser. And to write these kinds of programs we may need some new things.
One thing we'll need is support for the new way that server-based apps get released. Instead of having one or two big releases a year, like desktop software, server-based apps get released as a series of small changes. You may have as many as five or ten releases a day. And as a rule everyone will always use the latest version.
You know how you can design programs to be debuggable? Well, server-based software likewise has to be designed to be changeable. You have to be able to change it easily, or at least to know what is a small change and what is a momentous one.
Another thing that might turn out to be useful for server based software, surprisingly, is continuations. In Web-based software you can use something like continuation-passing style to get the effect of subroutines in the inherently stateless world of a Web session. Maybe it would be worthwhile having actual continuations, if it was not too expensive.
=== 4. What New Abstractions Are Left to Discover?
I'm not sure how reasonable a hope this is, but one thing I would really love to do, personally, is discover a new abstraction -- something that would make as much of a difference as having first class functions or recursion or even keyword parameters. This may be an impossible dream. These things don't get discovered that often. But I am always looking.
== Little-Known Secrets
=== 1. You Can Use Whatever Language You Want.
Writing application programs used to mean writing desktop software. And in desktop software there is a big bias toward writing the application in the same language as the operating system. And so ten years ago, writing software pretty much meant writing software in C. Eventually a tradition evolved: application programs must not be written in unusual languages. And this tradition had so long to develop that nontechnical people like managers and venture capitalists also learned it.
Server-based software blows away this whole model. With server-based software you can use any language you want. Almost nobody understands this yet (especially not managers and venture capitalists). A few hackers understand it, and that's why we even hear about new, indy languages like Perl and Python. We're not hearing about Perl and Python because people are using them to write Windows apps.
What this means for us, as people interested in designing programming languages, is that there is now potentially an actual audience for our work.
=== 2. Speed Comes from Profilers.
Language designers, or at least language implementors, like to write compilers that generate fast code. But I don't think this is what makes languages fast for users. Knuth pointed out long ago that speed only matters in a few critical bottlenecks. And anyone who's tried it knows that you can't guess where these bottlenecks are. Profilers are the answer.
Language designers are solving the wrong problem. Users don't need benchmarks to run fast. What they need is a language that can show them what parts of their own programs need to be rewritten. That's where speed comes from in practice. So maybe it would be a net win if language implementors took half the time they would have spent doing compiler optimizations and spent it writing a good profiler instead.
=== 3. You Need an Application to Drive the Design of a Language.
This may not be an absolute rule, but it seems like the best languages all evolved together with some application they were being used to write. C was written by people who needed it for systems programming. Lisp was developed partly to do symbolic differentiation, and McCarthy was so eager to get started that he was writing differentiation programs even in the first paper on Lisp, in 1960.
It's especially good if your application solves some new problem. That will tend to drive your language to have new features that programmers need. I personally am interested in writing a language that will be good for writing server-based applications.
[During the panel, <NAME> also made this point, with the additional suggestion that the application should not consist of writing the compiler for your language, unless your language happens to be intended for writing compilers.]
=== 4. A Language Has to Be Good for Writing Throwaway Programs.
You know what a throwaway program is: something you write quickly for some limited task. I think if you looked around you'd find that a lot of big, serious programs started as throwaway programs. I would not be surprised if most programs started as throwaway programs. And so if you want to make a language that's good for writing software in general, it has to be good for writing throwaway programs, because that is the larval stage of most software.
=== 5. Syntax Is Connected to Semantics.
It's traditional to think of syntax and semantics as being completely separate. This will sound shocking, but it may be that they aren't. I think that what you want in your language may be related to how you express it.
I was talking recently to <NAME>, and he pointed out that operator overloading is a bigger win in languages with infix syntax. In a language with prefix syntax, any function you define is effectively an operator. If you want to define a plus for a new type of number you've made up, you can just define a new function to add them. If you do that in a language with infix syntax, there's a big difference in appearance between the use of an overloaded operator and a function call.
== Ideas Whoose Time Has Returned
=== 1. New Programming Languages.
Back in the 1970s it was fashionable to design new programming languages. Recently it hasn't been. But I think server-based software will make new languages fashionable again. With server-based software, you can use any language you want, so if someone does design a language that actually seems better than others that are available, there will be people who take a risk and use it.
=== 2. Time-Sharing.
<NAME> gave this as an idea whose time has come again in the last panel, and I completely agree with him. My guess (and Microsoft's guess, it seems) is that much computing will move from the desktop onto remote servers. In other words, time-sharing is back. And I think there will need to be support for it at the language level. For example, I know that Richard and <NAME> have done a lot of work implementing process scheduling within Scheme 48.
=== 3. Efficiency.
Recently it was starting to seem that computers were finally fast enough. More and more we were starting to hear about byte code, which implies to me at least that we feel we have cycles to spare. But I don't think we will, with server-based software. Someone is going to have to pay for the servers that the software runs on, and the number of users they can support per machine will be the divisor of their capital cost.
So I think efficiency will matter, at least in computational bottlenecks. It will be especially important to do i/o fast, because server-based applications do a lot of i/o.
It may turn out that byte code is not a win, in the end. Sun and Microsoft seem to be facing off in a kind of a battle of the byte codes at the moment. But they're doing it because byte code is a convenient place to insert themselves into the process, not because byte code is in itself a good idea. It may turn out that this whole battleground gets bypassed. That would be kind of amusing.
== Pitfalls and Gotchas
=== 1. Clients.
This is just a guess, but my guess is that the winning model for most applications will be purely server-based. Designing software that works on the assumption that everyone will have your client is like designing a society on the assumption that everyone will just be honest. It would certainly be convenient, but you have to assume it will never happen.
I think there will be a proliferation of devices that have some kind of Web access, and all you'll be able to assume about them is that they can support simple html and forms. Will you have a browser on your cell phone? Will there be a phone in your palm pilot? Will your blackberry get a bigger screen? Will you be able to browse the Web on your gameboy? Your watch? I don't know. And I don't have to know if I bet on everything just being on the server. It's just so much more robust to have all the brains on the server.
=== 2. Object-Oriented Programming.
I realize this is a controversial one, but I don't think object-oriented programming is such a big deal. I think it is a fine model for certain kinds of applications that need that specific kind of data structure, like window systems, simulations, and cad programs. But I don't see why it ought to be the model for all programming.
I think part of the reason people in big companies like object-oriented programming is because it yields a lot of what looks like work. Something that might naturally be represented as, say, a list of integers, can now be represented as a class with all kinds of scaffolding and hustle and bustle.
Another attraction of object-oriented programming is that methods give you some of the effect of first class functions. But this is old news to Lisp programmers. When you have actual first class functions, you can just use them in whatever way is appropriate to the task at hand, instead of forcing everything into a mold of classes and methods.
What this means for language design, I think, is that you shouldn't build object-oriented programming in too deeply. Maybe the answer is to offer more general, underlying stuff, and let people design whatever object systems they want as libraries.
=== 3. Design by Committee.
Having your language designed by a committee is a big pitfall, and not just for the reasons everyone knows about. Everyone knows that committees tend to yield lumpy, inconsistent designs. But I think a greater danger is that they won't take risks. When one person is in charge he can take risks that a committee would never agree on.
Is it necessary to take risks to design a good language though? Many people might suspect that language design is something where you should stick fairly close to the conventional wisdom. I bet this isn't true. In everything else people do, reward is proportionate to risk. Why should language design be any different?
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/a2c-nums/0.0.1/demo.typ | typst | Apache License 2.0 | #import "@preview/a2c-nums:0.0.1": int-to-cn-num, int-to-cn-ancient-num, int-to-cn-simple-num, num-to-cn-currency
#set heading(numbering: "1.1")
= a2c-nums 示例
== int-to-cn-simple-num
#int-to-cn-simple-num(2024)
== int-to-cn-num 0-999
#{
let i = 0;
while i < 1000 {
int-to-cn-num(i) + " "
i += 1
}
}
== others
#int-to-cn-num(2024)
#int-to-cn-num(987654321)
=== 一个0:
#int-to-cn-num(907654321)
#int-to-cn-num(907054321)
#int-to-cn-num(907050321)
#int-to-cn-num(907050301)
=== 两个0:
#int-to-cn-num(900654321)
#int-to-cn-num(980054321)
#int-to-cn-num(987004321)
#int-to-cn-num(987600321)
#int-to-cn-num(987650021)
#int-to-cn-num(987654001)
#int-to-cn-num(987654300)
=== 三个0:
#int-to-cn-num(900054321)
#int-to-cn-num(980004321)
#int-to-cn-num(987000321)
#int-to-cn-num(987600021)
#int-to-cn-num(987650001)
#int-to-cn-num(987654000)
=== 四个0:
#int-to-cn-num(900004321)
#int-to-cn-num(980000321)
#int-to-cn-num(987000021)
#int-to-cn-num(987600001)
#int-to-cn-num(987650000)
=== 五个0:
#int-to-cn-num(900000321)
#int-to-cn-num(980000021)
#int-to-cn-num(987000001)
#int-to-cn-num(987600000)
=== 六个0:
#int-to-cn-num(900000021)
#int-to-cn-num(980000001)
#int-to-cn-num(987000000)
=== 七个0:
#int-to-cn-num(900000001)
#int-to-cn-num(980000000)
=== 八个0:
#int-to-cn-num(900000000)
== int-to-cn-ancient-num
#int-to-cn-ancient-num(2024)
#{
let i = 0;
while i < 1000 {
int-to-cn-ancient-num(i) + " "
i += 1
}
}
== num-to-cn-currency
#num-to-cn-currency(1234.56)
#num-to-cn-currency(0.5678)
#num-to-cn-currency(1203405602.5678)
#num-to-cn-currency(234) |
https://github.com/gaoachao/uniquecv-typst | https://raw.githubusercontent.com/gaoachao/uniquecv-typst/main/main.typ | typst | #import "template.typ": *
// 让标题变成cv-blue
#show heading: set text(cv-blue)
// 项目具体描述的item设定
#set list(
indent: 1em,
body-indent: 0.5em,
)
// 个人信息
#show: project.with(name: "姓名")
#info(
phone: [(+86) 155-5555-5555],
email: link("<EMAIL>"),
github: link("github.com/username"),
)
= 教育背景
#education(
school: [华中科技大学],
major: [职业:主播],
degree: [本科],
date: [2021 年 -- 2025 年],
grade: [成绩:年级前 *50%*],
English: [英语: CET-6],
)[]
= 专业技能
C/C++、Rust、Typst、Vue、React、JavaScript、TypeScript、CSS、Golang、Linux、Git、数据结构与算法、计算机网络
= 获奖情况
#prize((
(
grade: [一等奖],
game: [全国大学生数学建模竞赛],
date: [2021 年 10 月 -- 2021 年 12 月],
),
(
grade: [一个名字很长的奖项],
game: [一个名字很长的软件开发大赛],
date: [2021 年 10 月 -- 2021 年 12 月],
),
(
grade: [二等奖],
game: [全国大学生数学建模竞赛],
date: [2021 年 10 月 -- 2021 年 12 月],
),
))
= 项目经历
#proj-exps((
(
name: [名字巨长无比的分布式流体计算项目],
type: [导师项目],
tech: [性能优化、并行计算、C/C++],
date: [2021 年 02 月 -- 2021 年 04 月],
description: [
将一个单机的流体计算程序移植到*多机平台*
- 计算节点内部使用 OpenMP 并行化
- 计算节点间使用 MPI 并行化
- 单机优化性能达 2x,多机接近线性加速比
],
),
(
name: [C--Compiler],
type: [个人项目],
tech: [性能优化、并行计算、C/C++],
date: [2021 年 02 月 -- 2021 年 04 月],
description: [
实现了一个狗屁不通编译器
- 支持C11标准大部分标准
- 实现了类似 lex/flex 的词法解析器生成工具
- 实现了类似 yacc/bison 的语法解析器生成工具
],
),
(
name: [UniqueStudio--SSO],
type: [团队项目],
tech: [golang、React、Typescript],
date: [2022 年 06 月 -- 2022 年 09 月],
description: [
UniqueStudio单点登录系统和统一的权限控制系统
- 按照 CAS 的标准实现
- 支持手机、邮箱等多种登录方式
],
),
(
name: [电棍活字印刷合成器],
type: [整活项目],
tech: [Python、OpenCV],
date: [2022 年 06 月 -- 2022 年 09 月],
description: box(height: 6em)[
#columns(2)[
- 将汉字和英文字母转换为汉语拼音,在语音库内查找比对并进行拼接。
- 可以适当调整内置效果器的参数,以达到更丰富的整活效果。
- 大家好啊,我是说的道理。今天来点大家想看的东西
- 奥利安费!All in!
]
],
),
))
= 校园经历
#prize((
(grade: [], game: [华中科技大学联创团队], date: [2020 年 09 月 -- 至今]),
))
|
|
https://github.com/Daillusorisch/HYSeminarAssignment | https://raw.githubusercontent.com/Daillusorisch/HYSeminarAssignment/main/template/components/abstract.typ | typst | #import "../utils/style.typ": *
#let abstract(
keywords: (),
display_name: "",
title_name: "",
keyword_name: "",
keyword_sep: "",
title_font: (),
content_font: (),
content
) = {
set heading(level: 1, numbering: none)
show <_abstract_>: {
align(center)[
#v(5pt)
#text(
font: title_font,
size: 字号.小二,
weight: "bold"
)[#display_name]
]
}
[= #title_name <_abstract_>]
v(15pt)
par(
leading: 1.5em,
first-line-indent: 2em
)[
#text(
font: content_font,
size: 字号.小四,
)[#content]
]
v(5pt)
text(
font: content_font,
size: 字号.小四,
weight: "bold"
)[#keyword_name]
text(
font: content_font,
size: 字号.小四,
)[#keywords.join([#keyword_sep])]
}
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compiler/label.typ | typst | Apache License 2.0 | // Test labels.
---
// Test labelled headings.
#show heading: set text(10pt)
#show heading.where(label: <intro>): underline
= Introduction <intro>
The beginning.
= Conclusion
The end.
---
// Test label after expression.
#show strong.where(label: <v>): set text(red)
#let a = [*A*]
#let b = [*B*]
#a <v> #b
---
// Test labelled text.
#show "t": it => {
set text(blue) if it.has("label") and it.label == <last>
it
}
This is a thing #[that <last>] happened.
---
// Test abusing dynamic labels for styling.
#show <red>: set text(red)
#show <blue>: set text(blue)
*A* *B* <red> *C* #label("bl" + "ue") *D*
---
// Test that label ignores parbreak.
#show <hide>: none
_Hidden_
<hide>
_Hidden_
<hide>
_Visible_
---
// Test that label only works within one content block.
#show <strike>: strike
*This is* #[<strike>] *protected.*
*This is not.* <strike>
---
// Test that incomplete label is text.
1 < 2 is #if 1 < 2 [not] a label.
---
// Test label on text, styled, and sequence.
// Ref: false
#test([Hello<hi>].label, <hi>)
#test([#[A *B* C]<hi>].label, <hi>)
#test([#text(red)[Hello]<hi>].label, <hi>)
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/3%20-%20PB/Documentazione%20esterna/Verbali/24-03-07/24-03-07.typ | typst | #import "/template.typ": *
#show: project.with(
date: "07/03/24",
subTitle: "Aggiornamento sullo stato dei lavori",
docType: "verbale",
authors: (
"<NAME>",
),
externalParticipants : (
(name: "<NAME>", role: "Referente aziendale"),
),
timeStart: "16:00",
timeEnd: "16:40",
location: "Zoom",
);
= Ordine del giorno
- ER;
- Aggiornamento sul colloquio con il #cardin\;
- Mock-up;
- MVP;
- Meeting futuri.
== ER
È stato mostrato lo schema ER del database di supporto, modificato secondo le considerazioni fatte nell'ultimo meeting (29/02/2024).
Il Proponente ha approvato tutte le modifiche apportate e si ritiene soddisfatto dello schema ER, che può quindi essere considerato come definitivo.
== Aggiornamento sul colloquio con il #cardin
Il Proponente è stato aggiornato sul colloquio tenuto con il #cardin in data 06/03/2024, in particolare riguardo la presenza di business logic nel capitolato.
== Mock-up
È stato mostrato al Proponente il mock-up aggiornato. Grazie ad esso vengono discusse le seguenti funzionalità:
- chiamata alle API RESTful;
- scaling della planimetria.
=== Chiamata alle API RESTful
Il gruppo ha previsto la chiamata alle API RESTful per qualsiasi movimentazione di prodotti. Viene invece avanzata dal Proponente la possibilità di chiamare le API solamente quando lo spostamento avviene da bin a bin, ed evitare la chiamata nel caso di collocamento di prodotti inizialmente privi di posizione.
=== Scaling della planimetria
Per quanto riguarda il ridimensionamento di planimetrie create manualmente viene sempre data la possibilità di aumentare le dimensioni del piano, mentre la riduzione potrà avvenire soltanto nel caso in cui non siano presenti scaffali.
Se la planimetria è creata a partire da un file SVG, questo verrà posizionato sul più piccolo rettangolo che riesca a contenerlo. Il ridimensionamento verrà limitato inferiormente dalle dimensioni del SVG, mentre l'aumento di dimensioni avverrà solamente per il rettangolo su cui è posizionato il file. In questo modo si può aggiungere spazio al magazzino senza deformare il modello SVG di base.
== MVP
Vengono mostrati al Proponente i primi avanzamenti del MVP, e si espongono i prossimi obiettivi nel suo sviluppo.
== Meeting futuri
Viene fissato il prossimo appuntamento per venerdì 15/03/2024 alle ore 14:00.
|
|
https://github.com/usertam/curriculum-vitae | https://raw.githubusercontent.com/usertam/curriculum-vitae/resume/template.typ | typst | Other | #let project(
title: "",
author: (name: "", email: "", email-alt: "", bio: ""),
bio: "",
links: (),
body,
) = {
// Set the document's basic properties.
set document(title: title, author: author.name)
set page(paper: "a4", margin: 1in)
set par(justify: true, leading: .55em)
set text(10pt, font: "Cormorant Garamond", weight: "medium")
set list(indent: 1.25em)
set underline(stroke: .2pt)
// Set page footer.
set page(footer: context {
set align(center)
set text(weight: "semibold", tracking: .5pt)
show text: smallcaps
"page "
counter(page).display()
" of "
[#counter(page).final().first()]
})
// Set mono text style.
let mono = text.with(
0.8em,
font: "DM Mono",
weight: "light",
tracking: -.1pt
)
// Website links.
let website(icon, url) = {
box(move(dx: -.4em, dy: .125em,
image(width: .95em, icon)))
link(url)
linebreak()
}
v(1fr)
// Header with name, description and links.
columns(2, gutter: -100em, {
text(1.6em,
weight: "semibold",
features: (smcp: 1),
tracking: .5pt,
author.name
)
h(.5em)
link(
"mailto:" + author.email,
mono("<" + author.email + ">")
)
linebreak()
v(.75em, weak: true)
text(features: (smcp: 1), tracking: 0.2pt,
author.bio
)
if bio != "" {
linebreak()
v(1.25em, weak: true)
text(bio)
v(.5em)
}
colbreak()
set align(right)
set par(leading: .25em)
show text: mono
if author.email-alt != "" {
link(
"mailto:" + author.email-alt,
"General: <" + author.email-alt + ">"
)
linebreak()
}
show link: underline
links.map(it => website(..it))
.fold("", (x, y) => x + y)
})
show link: underline
body
v(2fr)
}
#let experience(body) = style(styles => block({
let title = text(1.2em,
weight: "bold",
tracking: .5pt,
features: (smcp: 1),
body
)
title
h(1fr)
box(
height: measure(" ", styles).height,
align(right + horizon,
line(stroke: 0.1pt,
end: (100% - 0.75em - measure(title, styles).width, 0%)
)
)
)
}))
#let item(title, subtitle, date, location, body) = columns(2, gutter: -100%, {
stack(dir: ltr,
move(dy: -0em,
text(font: "Noto Sans Symbols 2",
sym.diamond.filled.small)),
h(.75em),
box(
text(weight: "bold", title) +
if subtitle != "" {
linebreak()
text(style: "italic", subtitle)
}
)
)
colbreak()
place(right,
text(weight: "semibold", date)
+ linebreak()
+ location
)
}) + if (body != []) {
v(1em, weak: true)
body
}
#let gh_item(title, desc, date, url, url_desc: "Source", body) = item(
smallcaps(title),
desc,
date,
box(place(right + bottom,
move(dx: -.25em, dy: .1em,
image(width: .8em, "icons/github.svg"))))
+ link("https://github.com/" + url, url_desc),
body
)
#let mono = text.with(
0.8em,
font: "DM Mono",
weight: "light",
tracking: -.1pt
)
#let github(url) = {
mono(link("https://github.com/" + url, url))
}
#let dot = {
h(.4em) + box(place(center + bottom, $dot$)) + h(.4em)
}
#let course(sem, courses, extra: none) = {
set text(hyphenate: false)
list({
smallcaps(text(weight: "semibold", sem))
courses.fold("", (x, y) => x + dot + y)
if (extra != none) {
dot
smallcaps(text(weight: "semibold", extra.at(0)))
extra.at(1).fold("", (x, y) => x + dot + y)
}
})
}
#let TeX = {
"T"
h(-.22em)
box(move(dy: .21em, "E"))
h(-.11em)
"X"
}
#let LaTeX = {
"L"
h(-.29em)
box(move(dy: -.175em, text(.74em, "A")))
h(-.1em)
TeX
}
#let ConTeXt = {
"Con"
h(-.1em)
TeX
h(-.05em)
"t"
}
#show "HKUST": text(0.95 * 10pt, "HKUST")
#show "HKUSTSU": text(0.95 * 10pt, "HKUSTSU")
#show "(2023)": text(0.825 * 10pt, "(") + "2023" + text(0.825 * 10pt, ")")
#show "(2024)": text(0.825 * 10pt, "(") + "2024" + text(0.825 * 10pt, ")")
|
https://github.com/WindowDump/typst-ttrpg | https://raw.githubusercontent.com/WindowDump/typst-ttrpg/main/wodu-remix-sheet-halfletter.typ | typst | The Unlicense | // World of Dungeons Remix (WoDu Remix)
// character sheet by Window Dump
// https://github.com/WindowDump/typst-ttrpg
// wodu remix - https://katamoiran.itch.io/remix
// wodu - https://johnharper.itch.io/world-of-dungeons
// titles: Fraunces - https://github.com/undercasetype/Fraunces
// headings: Jost - https://indestructibletype.com/Jost
// Typst doesn't support variable fonts - use the static versions
#set document(
title: "WoDu Remix Character Sheet - Half Letter",
author: "<NAME>",
keywords: ("world of dungeons", "wodu", "pbta", "osr"),
)
#set page(
paper: "us-letter",
flipped: true,
margin: (x: 36pt, top: 36pt, bottom: 36pt),
)
// outline of small boxes players write in
// set to 0.25pt for increased legibility, nice with single contrast sheet
#let small_box_stroke = 0pt
#let thick_grid = 3pt
#let thin_grid = 1.5pt
// labels in writeable areas of sheet
#let sheet_label(it) = text(
font: "Jost*",
size: 8pt,
weight: 400,
number-width: "proportional",
tracking: 0.05em,
upper(it),
)
// small writeable box
#let sheet_box(
it,
) = rect(
fill: white,
width: 100%,
height: 100%,
inset: 2pt,
stroke: small_box_stroke,
sheet_label(it),
)
// rectangle with quarter-circle cutouts
#let cutout_box(
width: 30pt,
height: 30pt,
corner_cut: 4pt,
box_stroke: (paint: black, thickness: 1pt),
) = path(
(corner_cut, 0pt),
(width - corner_cut, 0pt),
((width, corner_cut), (-corner_cut, 0pt), (0pt, 0pt)),
(width, height - corner_cut),
((width - corner_cut, height), (0pt, -corner_cut), (0pt, 0pt)),
(corner_cut, height),
((0pt, height - corner_cut), (corner_cut, 0pt), (0pt, 0pt)),
(0pt, corner_cut),
((corner_cut, 0pt), (0pt, corner_cut), (0pt, 0pt)),
closed: true,
fill: white,
stroke: box_stroke,
)
// cutout box with label
#let sheet_box_cutout(it, box_stroke: none) = {
place(cutout_box(height: 100%, width: 100%, box_stroke: box_stroke))
place(dx: 6pt, dy: 2pt, sheet_label(it))
}
// thicker label for use on colored background
#let sheet_label_light(block_fill: none, text_fill: white, it) = {
set par(leading: thick_grid)
block(
fill: block_fill,
outset: (1pt),
text(
font: "Jost*",
size: 8pt,
weight: 500,
fill: text_fill,
number-width: "proportional",
tracking: 0.05em,
upper(it),
),
)
}
// header text on top of colored backgroung
#let sheet_header(block_fill: none, text_fill: white, it) = block(
fill: block_fill,
outset: (1pt),
radius: 2pt,
text(
font: "Fraunces 9pt Soft",
size: 9pt,
weight: 800,
tracking: 0.03em,
fill: text_fill,
upper(it),
),
)
// big box with big label
#let attribute_box(it, stroke: 1pt) = {
let corner_cut = 4pt
grid(
columns: (auto, auto, 1fr),
grid.cell(
rowspan: 2,
rect(
height: 100%,
width: 0pt,
outset: (left: thick_grid, right: corner_cut - 0.5pt),
fill: white,
stroke: none,
),
),
grid.cell(
rowspan: 2,
x: 2,
align: left + horizon,
block(
height: 100%,
width: 100%,
inset: (left: 4pt),
outset: (left: corner_cut - 0.5pt),
fill: white,
text(
font: "Fraunces 72pt SuperSoft",
size: 20pt,
weight: 700,
tracking: 0.03em,
it,
),
),
),
grid.cell(
x: 1,
y: 1,
align: center + horizon,
cutout_box(
width: 30pt,
height: 30pt,
corner_cut: corner_cut,
box_stroke: stroke,
),
),
)
}
// circle with name
#let skill(it) = grid(
columns: (auto, 1fr),
inset: ((left: 0.5pt), 0pt),
column-gutter: 2.5pt,
align: left + horizon,
circle(radius: 3pt, fill: white, stroke: 0.5pt),
text(font: "Jost*", size: 7pt, weight: 500, tracking: 0.06em, upper(it)),
)
// little box
#let firstaid_max_track() = rect(
width: 100%,
height: 100%,
radius: 1pt,
fill: white,
stroke: small_box_stroke,
)
// little circle
#let firstaid_used_track() = circle(
radius: auto,
fill: white,
stroke: small_box_stroke,
)
// hack to expand special abilities
#let row_spacing = for value in range(1, 11) {
if value == 9 {
(1fr,)
} else {
(24pt,)
}
}
// the main sheet
#let main_sheet(
header_outline,
header_fill,
label_outline,
label_fill,
background_fill: black,
) = grid(
columns: (1fr,) * 10,
rows: row_spacing,
gutter: thin_grid,
// identity
grid.cell(colspan: 3, sheet_box[Name]),
grid.cell(colspan: 3, sheet_box[Class]),
grid.cell(colspan: 3, sheet_box[Heritage]),
grid.cell(align: top + center, sheet_box[Level]),
grid.cell( // attributes
colspan: 6,
rowspan: 5,
grid(
columns: (1fr, 1fr),
rows: (auto, 1fr),
column-gutter: thin_grid,
grid.cell(
colspan: 2,
inset: (top: thick_grid - thin_grid, bottom: thick_grid),
align: top + center,
)[
#place( // left side cutout
top + left,
dx: -thick_grid - 6.5pt,
dy: thick_grid,
rect(fill: white, height: 100% + 6.5pt, width: 13pt, radius: 6.5pt)
)
#sheet_header(block_fill: header_outline, text_fill: header_fill)[Attributes]
],
attribute_box(stroke: 0.5pt)[STR],
attribute_box(stroke: 0.5pt)[INT],
attribute_box(stroke: 0.5pt)[DEX],
attribute_box(stroke: 0.5pt)[WIS],
attribute_box(stroke: 0.5pt)[CON],
attribute_box(stroke: 0.5pt)[CHA],
),
),
grid.cell( // skills
colspan: 4,
rowspan: 5,
grid(
columns: 1fr,
rows: (auto, 1fr),
grid.cell(
inset: (top: thick_grid - thin_grid, bottom: thick_grid, right: thick_grid*2),
align: top + center,
)[
#place( // right side cutout
top + right,
dx: thick_grid*3 + 6.5pt,
dy: thick_grid,
rect(fill: white, height: 100% + 6.5pt, width: 13pt, radius: 6.5pt)
)
#sheet_header(block_fill: header_outline, text_fill: header_fill)[Skills]
],
rect(
fill: white,
width: 100% - thick_grid*2 - 0.5pt,
height: 100%,
inset: (x: 2pt, y: 4pt),
stroke: none,
grid(
columns: (1fr, 1fr),
column-gutter: 2pt,
row-gutter: 1fr,
align: left + horizon,
skill[Athletics],
skill[Lore],
skill[Awareness],
skill[Medicine],
skill[Craft],
skill[Music],
skill[Deception],
skill[Mysteries],
skill[Decipher],
skill[Stealth],
skill[Focus],
skill[Survival],
skill[Heal],
skill[Tactics],
skill[Leadership],
skill[Use Devices],
skill[#align(bottom, line(length: 95%, stroke: (0.5pt)))],
skill[#align(bottom, line(length: 95%, stroke: (0.5pt)))],
),
),
),
),
grid.cell( // special abilities
colspan: 10,
rowspan: 3,
grid(
rows: (auto, 1fr),
columns: 1fr,
grid.cell(
inset: (top: thick_grid - thin_grid, bottom: thick_grid),
align: top + center,
sheet_header(
block_fill: header_outline,
text_fill: header_fill
)[Special Abilities]
),
sheet_box_cutout[],
),
),
grid.cell(colspan: 4, rowspan: 4, inset: (top: thick_grid - thin_grid, right: (thick_grid - thin_grid)/2), sheet_box_cutout[Weapons]),
grid.cell(colspan: 6, rowspan: 4, inset: (top: thick_grid - thin_grid, left: (thick_grid - thin_grid)/2), sheet_box_cutout[Equipment]),
grid.cell( // misc stats
colspan: 10,
rowspan: 3,
align: center + horizon,
inset: (y: thick_grid - thin_grid),
grid(
rows: (1fr, 24pt, 1fr, 24pt),
columns: (1fr,) * 10,
gutter: thick_grid,
grid.cell(
colspan: 6,
sheet_header(block_fill: header_outline, text_fill: header_fill)[Armor],
),
grid.cell(
colspan: 2,
sheet_header(block_fill: header_outline, text_fill: header_fill)[Hit Dice],
),
grid.cell(
colspan: 2,
sheet_header(block_fill: header_outline, text_fill: header_fill)[Hit Points],
),
grid.cell(
colspan: 6,
inset: (x: 6pt),
grid(
columns: (1fr, auto, 1fr, auto, 1fr, auto,),
column-gutter: thick_grid,
align: right + horizon,
sheet_label_light(block_fill: label_outline, text_fill: label_fill)[Worn Armor],
circle(fill: white, stroke: small_box_stroke),
sheet_label_light(block_fill: label_outline, text_fill: label_fill)[Shield],
circle(fill: white, stroke: small_box_stroke),
sheet_label_light(block_fill: label_outline, text_fill: label_fill)[Total Armor],
path(
((0pt, 0pt), (0pt, 0pt), (0pt, 0pt)),
((24pt, 0pt), (0pt, 0pt), (0pt, 20pt)),
((12pt, 100%), (4pt, 0pt), (-4pt, 0pt)),
((0pt, 0pt), (0pt, 20pt), (0pt, 0pt)),
fill: white,
stroke: small_box_stroke,
)
),
),
grid.cell(colspan: 2, sheet_box_cutout(box_stroke: small_box_stroke)[]),
grid.cell(colspan: 2, sheet_box_cutout(box_stroke: small_box_stroke)[]),
grid.cell(
colspan: 3,
sheet_header(block_fill: header_outline, text_fill: header_fill)[Bonus Damage],
),
grid.cell(
colspan: 3,
sheet_header(block_fill: header_outline, text_fill: header_fill)[Debilities],
),
grid.cell(
colspan: 4,
sheet_header(block_fill: header_outline, text_fill: header_fill)[First Aid],
),
grid.cell(colspan: 3, sheet_box_cutout(box_stroke: small_box_stroke)[]),
grid.cell(colspan: 3, sheet_box_cutout(box_stroke: small_box_stroke)[]),
grid.cell(colspan: 4, inset: (x: 16pt), align: horizon, grid(
columns: (auto, 1fr, 1fr, 1fr, 1fr, 1fr),
rows: 1fr,
column-gutter: (thick_grid, thin_grid),
row-gutter: thick_grid,
grid.cell(
align: right,
sheet_label_light(
block_fill: label_outline,
text_fill: label_fill,
)[Max],
),
firstaid_max_track(),
firstaid_max_track(),
firstaid_max_track(),
firstaid_max_track(),
firstaid_max_track(),
grid.cell(
align: right,
sheet_label_light(
block_fill: label_outline,
text_fill: label_fill,
)[Used],
),
firstaid_used_track(),
firstaid_used_track(),
firstaid_used_track(),
firstaid_used_track(),
firstaid_used_track(),
)),
),
),
grid.cell( // remarks
colspan: 10,
rowspan: 2,
sheet_box_cutout[Remarks],
),
grid.cell(
colspan: 5,
align: right + horizon,
inset: (top: thick_grid - thin_grid),
)[
#place(
bottom + left,
dx: -thick_grid - 4.5pt,
dy: thick_grid + 4.5pt,
circle(fill: white, radius: 4.5pt)
)
#grid(
columns: 2,
column-gutter: thick_grid,
block(inset: 2pt, radius: 3pt, fill: header_outline,
text(
font: "Fraunces 9pt Soft",
size: 14pt,
weight: 800,
fill: header_fill,
tracking: 0.03em,
upper[Coin]
)
),
cutout_box(width: 100%, height: 100%, corner_cut: 4pt, box_stroke: small_box_stroke)
)
],
grid.cell(
colspan: 2,
align: right + horizon,
inset: (top: thick_grid - thin_grid, x: thick_grid),
block(inset: 2pt, radius: 3pt, fill: header_outline, text(
font: "Fraunces 9pt Soft",
size: 14pt,
weight: 800,
fill: header_fill,
tracking: 0.03em,
upper[XP],
)
)
),
grid.cell(
colspan: 3,
inset: (top: thick_grid - thin_grid),
)[
#place(
bottom + right,
dx: thick_grid + 4.5pt,
dy: thick_grid + 4.5pt,
circle(fill: white, radius: 4.5pt),
)
#cutout_box(width: 100%, height: 100%, corner_cut: 4pt, box_stroke: small_box_stroke)
],
)
// text at top of sheet - "WoDu Remix"
#let default_header = (
text(
font: "Fraunces 9pt",
weight: 700,
tracking: -0.02em,
size: 24pt,
)[WoDu],
text(
font: "Fraunces 9pt SuperSoft",
style: "italic",
weight: 300,
tracking: -0.05em,
size: 24pt,
)[Remix],
)
// just a full rectangle
#let full_rect(fill) = rect(
fill: fill,
width: 100%,
height: 100%,
)
// header, background, main sheet
#let halfsheet(
sheet_bg: full_rect(black),
sheet_header: default_header,
header_outline: none,
header_fill: white,
label_outline: none,
label_fill: white,
) = block(height: 100%)[
#place(sheet_bg)
#set block(below: 0pt, above: 0pt)
#rect(
fill: white,
outset: (x: 1pt, top: 1pt),
inset: (bottom: thin_grid, top: 0pt, x: 0pt),
height: 24pt,
grid( // sheet header
columns: (auto, auto, 1fr),
rows: 24pt,
inset: (bottom: 2pt),
column-gutter: 4pt,
align: bottom + left,
..sheet_header,
grid.cell(align: top + right, sheet_label[Player]),
),
)
#rect( // main body
height: 8.5 * 72pt - 72pt - 24pt,
width: 100%,
inset: thick_grid,
stroke: none,
main_sheet(
header_outline,
header_fill,
label_outline,
label_fill,
background_fill: sheet_bg.fill,
),
)
]
#show: rest => columns(2, gutter: 72pt, rest)
// set up gradients for the grid
#let mako_radial = gradient.radial(
..color.map.mako,
focal-center: (50%, 35%),
focal-radius: 10%,
radius: 90%,
)
#let icefire_radial = gradient.radial(
..color.map.icefire,
focal-center: (50%, 30%),
focal-radius: 0%,
radius: 80%,
)
#let viridis_radial = gradient.radial(
..color.map.viridis,
center: (25%, 80%),
radius: 145%,
focal-center: (50%, 40%),
).repeat(2, mirror: true)
#let flare_linear = gradient.linear(
..color.map.flare,
angle: 75deg,
).repeat(4, mirror: true)
#let wodu_blue = rgb("#007295")
#let PINK = color.hsv(355deg, 25%, 100%)
#let blackcurrant = rgb("#492950")
#let risus_green = color.hsv(302.997deg, 100%, 44.7%)
// big VGA DOS game vibes
#let chrome_text = gradient.linear(
(luma(85%), 0%),
(luma(100%), 10%),
(luma(90%), 55%),
(luma(65%), 80%),
(luma(100%), 100%),
angle: 90deg,
)
// li'l hack to stroke text without going into the main fill
// pass text.with() to it. note that stroke will be about half of listed
// value since it's obscured by the main text
#let text_stroke(base_text, fill: black, stroke: 0.5pt) = [
#place(base_text(stroke: stroke))
#base_text(fill: fill)
]
// alternate header with the BG fill on "WoDu" and chrome "Remix"
#let bg_chrome_header(fill: white) = (
text_stroke(
text.with(
font: "Fraunces 72pt",
weight: 700,
tracking: 0.04em,
size: 24pt,
)[WoDu],
fill: fill,
stroke: 1pt,
),
block(
text_stroke(
text.with(
font: "Fraunces 9pt SuperSoft",
style: "italic",
weight: 300,
tracking: -0.03em,
size: 24pt,
)[Remix],
fill: chrome_text,
stroke: 1pt,
),
),
)
// let's render some sheets!
#halfsheet()
#halfsheet()
#let flare_chrome = halfsheet(
sheet_bg: full_rect(flare_linear),
header_outline: luma(0%, 35%),
header_fill: chrome_text,
sheet_header: bg_chrome_header(fill: flare_linear),
)
// #flare_chrome
// #flare_chrome
#let mako_chrome = halfsheet(
sheet_bg: full_rect(mako_radial),
header_outline: luma(0%, 50%),
header_fill: chrome_text,
sheet_header: bg_chrome_header(fill: mako_radial),
)
// #mako_chrome
// #mako_chrome
// set small_box_stroke = 0.25pt for increased visibility
// TODO: be able to set it down here? idk
#let low_ink = halfsheet(
sheet_bg: full_rect(luma(85%)),
header_fill: black,
label_fill: black,
)
// #low_ink
// #low_ink
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/patterns/weeks/week7.typ | typst | #import "../../utils.typ": *
#subsection([Reflection])
#set text(size: 14pt)
Problem | How do you load code during runtime, e.g. without recompiling?\
Context | Plugin system\
#set text(size: 11pt)
// images
There is two aspects to reflection:
- *introspection*\
The ability for a program to observe and therefore reason about its own state.\
e.g. query for object properties, methods etc.
- intercession\
This is the part where you change code during runtime -> or rather load a
dynamic library\
Programming languages like javascript can be changed directly during runtime.
#align(
center,
[#image("../../Screenshots/2023_11_03_09_36_00.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_03_09_37_20.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_03_09_42_02.png", width: 80%)],
)
cloning an object using reflection:\
```java
if (origin instanceof Cloneable) {
cloned = ((Cloneable)origin).clone();
} else {
cloned = origin.getClass().getDeclaredConstructor().newInstance();
// ...
BeanUtils.copyProperties(origin, cloned); // get data from getters, fill into
setters
// beanutils copies things dynamically at runtime without your code doing anything
}
```
#columns(
2,
[
#text(green)[Benefits]
- flexibility -> allows for a base platform to be more powerful without more code
- functionality can be added later on
#colbreak()
#text(red)[Liabilities]
- security risks -> dynamic library is essentially arbitrary code!
- performance hit -> dynamic libraries are an overhead
- limited type safety
- control flow is hard to understand -> requires that you also read the dyn
libraries etc.
],
)
#subsection([Type Object])
#set text(size: 14pt)
Problem | In a library, media (books, videos etc) share certain attributes, like
author, year, etc.\
At the same time, you might have a certain book multiple times.\
Also Videos might have a additional properties like length in minutes.\
Solution | Create a Variant Type -> Enum -> Video/Book, can be checked
dynamically or more types can be added later on.
#set text(size: 11pt)
// images
#align(
center,
[#image("../../Screenshots/2023_11_03_09_49_46.png", width: 40%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_03_09_53_16.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_03_09_53_28.png", width: 80%)],
)
Jafuck example:
#align(
center,
[#image("../../Screenshots/2023_11_03_09_55_40.png", width: 80%)],
)
#columns(
2,
[
#text(green)[Benefits]
- more categories can be added easily -> games in the example
- avoids explosion of subclasses with attributes etc
- allows multiple type object levels -> type object for type object
#colbreak()
#text(red)[Liabilities]
- lower efficiency -> indirection
- separation not always easy to understand directly
- changing database schemas can be tricky
- Solution needs to store different object layouts persistently (mitigated with
OR-mapping)
],
)
#subsection([Property List])
#set text(size: 14pt)
Problem | How do you provide properties that can be used on any arbitrary object
-> e.g. for example in a game engine, add properties at any level with
properties still attached?\
Or in IPC, how do we transfer a list of properties that can be expanded or
shrinked dynamically?\
Solution | Hashmap with properties -> PropList in dbus-rs\
#set text(size: 11pt)
// images
#align(
center,
[#image("../../Screenshots/2023_11_03_09_57_05.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_03_09_57_20.png", width: 80%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_03_09_56_32.png", width: 80%)],
)
#columns(2, [
#text(green)[Benefits]
- black box expendability
- object extension while keeping identity and type
- same attributes can be used across hierarchy
#colbreak()
#text(red)[Liabilities]
- indirection for each property
- no type safety
- naming not checked by compiler -> at runtime!
- semantics of attributes not given by class
])
#subsection([Introducing Bridge Method])
#set text(size: 14pt)
Problem | Property lists can cause issues with types and certain attributes
existing or rather not existing. How can we enforce the same access for these
properties as regular properties?\
Solution | Create a bridge method or struct that converts the property list to
static properties, usually done with Optional\<T\> or using default values.
#set text(size: 11pt)
// images
Java example: -> this is via byte code patching -> not a bridge struct like rust
#align(
center,
[#image("../../Screenshots/2023_11_03_10_03_49.png", width: 80%)],
)
Example of a bridge using rust and dbus.
#align(
center,
[#image("../../Screenshots/2023_11_03_10_08_11.png", width: 40%)],
)
#columns(2, [
#text(green)[Benefits]
- static usage of properties
- type safety
#colbreak()
#text(red)[Liabilities]
- conversion requires performance
- new attribute means new conversion -> not very flexible
])
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/meta/footnote-container.typ | typst | Apache License 2.0 | // Test footnotes in containers.
---
// Test footnote in caption.
Read the docs #footnote[https://typst.app/docs]!
#figure(
image("/files/graph.png", width: 70%),
caption: [
A graph #footnote[A _graph_ is a structure with nodes and edges.]
]
)
More #footnote[just for ...] footnotes #footnote[... testing. :)]
---
// Test duplicate footnotes.
#let lang = footnote[Languages.]
#let nums = footnote[Numbers.]
/ "Hello": A word #lang
/ "123": A number #nums
- "Hello" #lang
- "123" #nums
+ "Hello" #lang
+ "123" #nums
#table(
columns: 2,
[Hello], [A word #lang],
[123], [A number #nums],
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-2D00.typ | typst | Apache License 2.0 | #let data = (
("GEORGIAN SMALL LETTER AN", "Ll", 0),
("GEORGIAN SMALL LETTER BAN", "Ll", 0),
("GEORGIAN SMALL LETTER GAN", "Ll", 0),
("GEORGIAN SMALL LETTER DON", "Ll", 0),
("GEORGIAN SMALL LETTER EN", "Ll", 0),
("GEORGIAN SMALL LETTER VIN", "Ll", 0),
("GEORGIAN SMALL LETTER ZEN", "Ll", 0),
("GEORGIAN SMALL LETTER TAN", "Ll", 0),
("GEORGIAN SMALL LETTER IN", "Ll", 0),
("GEORGIAN SMALL LETTER KAN", "Ll", 0),
("GEORGIAN SMALL LETTER LAS", "Ll", 0),
("GEORGIAN SMALL LETTER MAN", "Ll", 0),
("GEORGIAN SMALL LETTER NAR", "Ll", 0),
("GEORGIAN SMALL LETTER ON", "Ll", 0),
("GEORGIAN SMALL LETTER PAR", "Ll", 0),
("GEORGIAN SMALL LETTER ZHAR", "Ll", 0),
("GEORGIAN SMALL LETTER RAE", "Ll", 0),
("GEORGIAN SMALL LETTER SAN", "Ll", 0),
("GEORGIAN SMALL LETTER TAR", "Ll", 0),
("GEORGIAN SMALL LETTER UN", "Ll", 0),
("GEORGIAN SMALL LETTER PHAR", "Ll", 0),
("GEORGIAN SMALL LETTER KHAR", "Ll", 0),
("GEORGIAN SMALL LETTER GHAN", "Ll", 0),
("GEORGIAN SMALL LETTER QAR", "Ll", 0),
("GEORGIAN SMALL LETTER SHIN", "Ll", 0),
("GEORGIAN SMALL LETTER CHIN", "Ll", 0),
("GEORGIAN SMALL LETTER CAN", "Ll", 0),
("GEORGIAN SMALL LETTER JIL", "Ll", 0),
("GEORGIAN SMALL LETTER CIL", "Ll", 0),
("GEORGIAN SMALL LETTER CHAR", "Ll", 0),
("GEORGIAN SMALL LETTER XAN", "Ll", 0),
("GEORGIAN SMALL LETTER JHAN", "Ll", 0),
("GEORGIAN SMALL LETTER HAE", "Ll", 0),
("GEORGIAN SMALL LETTER HE", "Ll", 0),
("GEORGIAN SMALL LETTER HIE", "Ll", 0),
("GEORGIAN SMALL LETTER WE", "Ll", 0),
("GEORGIAN SMALL LETTER HAR", "Ll", 0),
("GEORGIAN SMALL LETTER HOE", "Ll", 0),
(),
("GEORGIAN SMALL LETTER YN", "Ll", 0),
(),
(),
(),
(),
(),
("GEORGIAN SMALL LETTER AEN", "Ll", 0),
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/curryst/0.1.0/README.md | markdown | Apache License 2.0 | # Curryst
A Typst package for typesetting proof trees. You can import this package with :
```typst
#import "@preview/curryst:0.1.0"
```
## Examples
Here is a basic usage example:
```typst
#let r = curryst.rule(name: "Rule name", "Conclusion", "Premise 1", "Premise 2", "Premise 3")
#curryst.proof-tree(r)
```
Result:

Here is a more complete example, to typeset a proof tree in [natural deduction](https://en.wikipedia.org/wiki/Natural_deduction). First, define the set of rules :
```typst
#let ax(ccl) = curryst.rule(name: "ax", ccl)
#let and_i(ccl, p1, p2) = curryst.rule(name: $and_i$, ccl, p1, p2)
#let and_el(ccl, p) = curryst.rule(name: $and_e^l$, ccl, p)
#let and_er(ccl, p) = curryst.rule(name: $and_e^r$, ccl, p)
#let or_il(ccl, p1) = curryst.rule(name: $or_i^l$, ccl, p1)
#let or_ir(ccl, p2) = curryst.rule(name: $or_i^r$, ccl, p2)
#let or_e(ccl, por, p1, p2) = curryst.rule(name: $or_e$, ccl, por, p1, p2)
#let impl_i(ccl, p) = curryst.rule(name: $attach(->, br: i)$, ccl, p)
#let impl_e(ccl, pi, p1) = curryst.rule(name: $attach(->, br: e)$, ccl, pi, p1)
#let not_i(ccl, p) = curryst.rule(name: $not_i$, ccl, p)
#let not_e(ccl, pf, pt) = curryst.rule(name: $not_e$, ccl, pf, pt)
#let absurd(ccl, p) = curryst.rule(name: $bot$, ccl, p)
```
Next, combine these rules to build a proof tree:
```typst
#curryst.proof-tree(
impl_i(
$tack (p -> q) -> not (p and not q)$,
not_i(
$p -> q tack not (p and not q)$,
not_e(
$p -> q, p and not q tack bot$,
impl_e(
$Gamma tack q$,
ax($Gamma tack p -> q$),
and_el(
$Gamma tack p$,
ax($Gamma tack p and not q$)
)
),
and_er(
$Gamma tack not q$,
ax($Gamma tack p and not q$)
)
)
)
)
)
```
Result:
 |
https://github.com/m-pluta/bias-in-ai-report | https://raw.githubusercontent.com/m-pluta/bias-in-ai-report/main/report/main.typ | typst | #import "template.typ": *
#show highlight: it => {
it // Remove to get rid of highlighted notes
}
#ieee(
title: [ Assessing the use of Facial Emotion Recognition (FER) for consumer sentiment analysis ],
abstract: [
In this paper, we discuss the ethical considerations necessary for an emotion recognition system used for dynamic ad placement to exist. By conducting an Ethical Impact Assessment informed by Value Sensitive Design, we offer recommendations to ensure the system's implementation is minimally biased and reduces potential harm to stakeholder groups.
],
authors: (
(
name: "<NAME>",
cis: "vsdc48"
),
),
bibliography-file: "refs.bib",
pre_body: include "intro.typ",
table: include "table.typ",
post_body: include "recommend.typ",
) |
|
https://github.com/Shuenhoy/citext | https://raw.githubusercontent.com/Shuenhoy/citext/master/package/lib.typ | typst | MIT License | #import "@preview/jogs:0.2.3": compile-js, call-js-function, list-global-property
#import "@preview/mitex:0.2.4": mi
#let cite-src = read("./dist/index.iife.js")
#let cite-bytecode = compile-js(cite-src)
#let gb-t-7714-2015-numeric-bilingual = read("gb-t-7714-2015-numeric-bilingual.csl")
#let locales-zh-CN = read("locales-zh-CN.xml")
#let init_citation(bib, csl: gb-t-7714-2015-numeric-bilingual, locales: locales-zh-CN) = {
return call-js-function(cite-bytecode, "citext", bib.replace("$", "\\$"), csl, locales)
}
#let extcitefull(bib, id) = {
show regex("\$.+?\$"): it => mi(it)
bib.at(id).at("bibliography")
}
#let citeauthor-one-two-more(authors, ETAL: none, AND: none) = {
let len = authors.len()
if len > 2 {
return authors.at(0).family + ETAL
} else if len == 2 {
return authors.at(0).family + AND + authors.at(1).family
} else {
return authors.at(0).family
}
}
#let en-US-citeauthor = citeauthor-one-two-more.with(AND: " and ", ETAL: " et al.")
#let zh-CN-citeauthor = citeauthor-one-two-more.with(AND: "和", ETAL: "等")
#let extciteauthor(
bib,
id,
mapping: (
en-US: zh-CN-citeauthor,
zh-CN: zh-CN-citeauthor,
),
) = {
let entry = bib.at(id)
mapping.at(entry.at("language"))(entry.at("author"))
}
#let cite-targets = state("cite-targets", ())
#let show-extcite(s, bib: (:)) = {
show ref: it => {
if it.element != none {
// Citing a document element like a figure, not a bib key
// So don't update refs
it
return
}
cite-targets.update(old => {
if it.target not in old {
old.push(it.target)
}
old
})
it
}
show cite: it => {
cite-targets.update(old => {
if it.key not in old {
old.push(it.key)
}
old
})
it
}
show ref.where(label: <citeauthor>): it => {
extciteauthor(bib, str(it.target))
}
show ref.where(label: <citep>): it => {
[#extciteauthor(bib, str(it.target)) #cite(it.target)]
}
show ref.where(label: <citet>): it => {
show super: it => it.body
[#extciteauthor(bib, str(it.target)) #cite(it.target)]
}
show ref.where(label: <citef>): it => {
[#footnote[#extcitefull(bib, str(it.target))]]
}
s
}
#let extbib(bib) = {
locate(loc => {
grid(columns: 2,
column-gutter: 0.65em,
row-gutter: 1.2em,
..cite-targets
.at(loc)
.enumerate()
.map(x => {
let i = x.at(0) + 1
let target = x.at(1)
([\[#i\]], extcitefull(bib, str(target)))
})
.flatten()
)
})
} |
https://github.com/Daillusorisch/HYSeminarAssignment | https://raw.githubusercontent.com/Daillusorisch/HYSeminarAssignment/main/template/components/abstract-en.typ | typst | #import "abstract.typ": abstract
#import "../utils/style.typ": *
#let abstract-en(
keywords: (),
content
) = {
abstract(
keywords: keywords,
display_name: "ABSTRACT",
title_name: "ABSTRACT",
keyword_name: "Keywords: ",
keyword_sep: "; ",
title_font: 字体.宋体,
content_font: 字体.宋体,
content
)
} |
|
https://github.com/buxx/cv | https://raw.githubusercontent.com/buxx/cv/master/modules/professional.typ | typst | #import "../brilliant-CV/template.typ": *
#cvSection("Expérience Professionnelle", highlighted: true, letters: 3)
#cvEntry(
title: [Algoo],
society: [],
date: [2015 - Aujourd'hui],
location: [Moirans (Grenoble), Isère],
vdiff: -6pt,
description: list(
[Conception et développement d'un logiciel de mesure scientifique embarqué.],
[Collaboration étroite avec les équipes UX/UI et de logiciels anexes.],
[Construction d'environnements de contrôle qualité.],
[Développement backend sur le logiciel Tracim.],
[Formation et animation d'ateliers et conférences.],
)
)
#cvEntry(
title: [Auto-Entreprenariat],
society: [],
date: [2010 - Aujourd'hui],
location: [],
vdiff: -6pt,
description: list(
[Gestion de projet et programmation logicielle : GEM Altigliss Challenge.],
[Programmation logicielle : mesure des émotions et réactions d'un auditoire en temps réel (École de management de Grenoble)],
[Administration système et hébergement web.],
)
)
#cvEntry(
title: [XSALTO],
society: [],
date: [2013 - 2015],
location: [Digne-les-Bains, Alpes-de-haute-Provence],
vdiff: -6pt,
description: list(
[Développement du framework web.],
[Réalisation de sites web et de plateformes e-commerce.],
)
)
#cvEntry(
title: [“Vous avez choisi ?” et “Sport Easy”],
society: [],
date: [2010-2011],
location: [Paris (Télétravail complet)],
vdiff: -6pt,
description: list(
[Développement d'une plateforme d'organisation de recontres sportives.],
[Développement d'une plateforme de commandes de repas.],
)
)
// #cvEntry(
// title: [IDOS Informatique],
// society: [],
// date: [2009],
// location: [Chateau-arnoux-Saint-Auban, Alpes-de-haute-Provence],
// description: list(
// [Développement d’applications orientées web.],
// [Installations réseaux.],
// )
// )
|
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/3%20-%20PB/Documentazione%20interna/Verbali/24-04-14/24-04-14.typ | typst | #import "/template.typ": *
#show: project.with(
date: "14/04/24",
subTitle: "Meeting di retrospettiva e pianificazione",
docType: "verbale",
authors: (
"<NAME>",
),
missingMembers: (
"<NAME>",
"<NAME>",
),
timeStart: "15:00",
timeEnd: "15:30",
);
= Ordine del giorno
- Valutazione del progresso generale;
- Analisi retrospettiva;
- Pianificazione.
= Valutazione del progresso generale <avanzamento>
Lo Sprint 23 si è soffermato sulla preparazione alla valutazione PB con il #cardin e alla revisione dei documenti.
Il giorno mercoledì 10/04/2024 si è svolto lo sportello di valutazione PB con il #cardin, il cui esito non è stato ad oggi comunicato.
Come previsto, le ore di lavoro svolte in questo Sprint sono state minori rispetto agli Sprint precedenti in quanto è ridotto il lavoro rimanente per completare il progetto.
== #ndp
Il documento è stato nuovamente revisionato dal capitolo 5.5 al 5.9.
== #pdq
Le tabelle relative agli unit test e agli integration test sono state separate.
Inoltre è stata redatta la sezione relativa ai test di sistema.
== #man
Sono state apportate le seguenti modifiche al documento:
- aggiunta della sezione riguardante la guida all'apertura della pagina atta all'utilizzo di WMS3;
- rimozione della sezione "Supporto tecnico";
- aggiornamento delle immagini presenti nel documento.
= Analisi retrospettiva
Il rendimento positivo dello Sprint è sostenuto dalle principali metriche esposte dal #pdq_v\:
- CPI di progetto a 1.01, rappresenta un valore ottimale in quanto $>=1$;
- EAC diminuisce passando da € 12.992,10 a € 12.968,71 rientrando nel budget previsto;
- $"SEV" >= "SPV"$, come testimoniato anche dalla metrica CPI, che indica un avanzamento positivo del progetto.
\
Maggiori dettagli in merito al valore delle metriche alla loro analisi sono reperibili all'interno dei documenti #pdq_v e #pdp_v.
== Keep doing <keep-doing>
Persiste una buona collaborazione tra i membri del gruppo e il ritmo di lavoro rimane soddisfacente nonostante la sua preventivata riduzione.
== Improvements <improvements>
=== Criticità evidenziate
*P01*: Durante la valutazione PB il #cardin ha evidenziato delle criticità relativamente all'architettura del MVP.
=== Soluzioni predisposte
#figure(caption: [Soluzioni individuate alle criticità riscontrate.],
table(
align: left,
columns: (auto, 1fr, auto),
[ID risoluzione], [Titolo], [Criticità affrontate],
[R1], [Analisi da parte del gruppo riguardo alle criticità espresse], [P01]
)
)
= Pianificazione <pianificazione>
#let table-json(data) = {
let keys = data.at(0).keys()
table(
align: left,
columns: keys.len(),
..keys,
..data.map(
row => keys.map(
key => row.at(key, default: [n/a])
)
).flatten()
)
}
#show figure: set block(breakable: true)
#figure(caption: [Task pianificate per lo Sprint 24.],
table-json(json("tasks.json"))
)
|
|
https://github.com/WalrusGumboot/Typst-documents | https://raw.githubusercontent.com/WalrusGumboot/Typst-documents/main/aca/template.typ | typst | #let cursussen = csv("cursussen.csv")
#let marginLeft = 14mm
#let header(author, year, course, sem) = {
let code = none
for (course_name, course_code, study_points) in cursussen {
if course_name == course {
code = course_code
}
}
locate(loc => if loc.page() == 1 {
[
#set text(8pt)
#move(dx: -marginLeft, table(fill: luma(230),
stroke: none,
align: (left, right, right),
columns: (1fr, 1fr, 1fr),
inset: 0.9em,
[#author],[#code],[#emph[#year sem. #sem, #course]]))
]
} else {[]}
)
}
#let propCounter = counter("propCounter");
#let stellingCounter = counter("stellingCounter");
#let doc(
title: "Notities",
author: "<NAME>",
year: "23/24",
sem: 1,
course: "Calculus I",
body
) = {
set document(title: title, author: author)
set text(font: "Iosevka NF", size: 10.5pt)
set page(margin: (y:20mm, rest:marginLeft), header: header(author, year, course, sem), numbering: "1")
set heading(numbering: "[1.1.1] ")
show "Not.": set text(weight: "bold", style: "italic", fill: rgb(70, 100, 150))
show "Vb.": set text(weight: "bold", style: "italic", fill: rgb(150, 100, 70))
show "Def.": set text(weight: "bold", style: "italic", fill: rgb(150, 70, 100))
show "Bew.": _ => text(weight: "bold", style: "italic", fill: rgb(100, 150, 70), "Bewijs.")
show "Prop.": it => {
propCounter.step()
text(weight: "bold", style: "italic", fill: rgb(70, 150, 100), [#it #propCounter.display("1.")])
}
show "St.": {
stellingCounter.step()
text(weight: "bold", style: "italic", fill: rgb(100, 150, 70), [Stelling #stellingCounter.display("1.")])
}
text(size: 22pt, weight: "bold", title)
body
}
|
|
https://github.com/dogezen/badgery | https://raw.githubusercontent.com/dogezen/badgery/main/example/main.typ | typst | MIT License | #import "../badgery.typ": ui-action, menu, badge-gray, badge-red, badge-yellow, badge-green, badge-blue, badge-purple
= Badgery
This package defines some colourful badges and boxes around text that represent user interface actions such as a click or following a menu.
== Badges
```typ
#badge-gray("Gray badge"),
#badge-red("Red badge"),
#badge-yellow("Yellow badge"),
#badge-green("Green badge"),
#badge-blue("Blue badge"),
#badge-purple("Purple badge")
```
#stack(
dir: ttb,
spacing: 5pt,
badge-gray("Gray badge"),
badge-red("Red badge"),
badge-yellow("Yellow badge"),
badge-green("Green badge"),
badge-blue("Blue badge"),
badge-purple("Purple badge")
)
== User interface actions
This is a user interface action (ie. a click):
```typ
#ui-action("Click X")
```
#ui-action("Click X")
This is an action to follow a user interface menu (2 steps):
```typ
#menu("File", "New File...")
```
#menu("File", "New File...")
This is a menu action with multiple steps:
```typ
#menu("Menu", "Sub-menu", "Sub-sub menu", "Action")
```
#menu("Menu", "Sub-menu", "Sub-sub menu", "Action")
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/2%20-%20RTB/Documentazione%20esterna/Verbali/23-11-23/23-11-23.typ | typst | #import "/template.typ": *
#show: project.with(
date: "23/11/23",
subTitle: "Analisi dei Requisiti, approfondimento dominio applicativo",
docType: "verbale",
externalParticipants : (
(name: "<NAME>", role: "Referente aziendale"),
),
authors: (
"<NAME>",
),
timeStart: "14:00",
timeEnd: "14:45",
location: "Zoom",
);
= Ordine del giorno
- Presentazione, supportata da una board Miro, delle ipotesi fatte dal gruppo durante il periodo di individuazione degli use case;
- Presentazione, supportata da una board Miro, delle domande raccolte dal gruppo riguardo l'Analisi dei Requisiti. Le domande si articolano in:
- Use Case;
- chiarimenti tecnici;
- device da supportare;
- requisiti non funzionali.
- Richieste al Proponente riguardo materiale utile durante il progetto;
- Organizzazione di un prossimo meeting.
\
== Presentazione delle ipotesi fatte
+ Il gruppo ha iniziato il meeting presentando delle ipotesi al Proponente, per avere un riscontro riguardo la loro validità.\
+ La prima ipotesi specificava la presenza di un solo prodotto per ogni bin, ed è stata confermata e ritenuta una semplificazione utile. Per aree di carico/scarico questa supposizione non è valida, ma per semplicità di sviluppo si può tenere questa semplificazione.\
+ La seconda ipotesi specificava la presenza di scaffali in dimensioni standard, ma è stata rifiutata, poichè lo scaffale va costruito parametricamente, eventualmente fornendo opzioni preimpostate.
+ La terza ipotesi riguardava la possibilità di eliminare scaffali solo se vuoti, che ha trovato il favore del Proponente.\
+ L'ultima ipotesi, che riguardava la presenza di dimensioni fisse per i bin, è stata rifiutata poichè si devono prevedere bin di dimensioni diverse.
\
== Presentazione delle domande raccolte
=== Use case
Si sono discussi i seguenti use case:
- possibilità di passare in modalità modifica in qualsiasi momento: gli utenti avranno la flessibilità di attivare la modalità di modifica quando lo ritengono opportuno, consentendo loro di apportare modifiche e aggiornamenti in modo tempestivo;
- richiesta utente di sincronizzazione dei dati del DB;
- ricerca per ID, per nome, per scaffale: è stata discussa una funzionalità di ricerca che consente agli utenti di recuperare informazioni in base all'identificativo del prodotto, al nome o alla collocazione sullo scaffale. Si è discusso anche di un'interfaccia grafica per rendere chiara e accessibile questa funzionalità di ricerca;
- possibilità di ottenerne le informazioni di uno specifico prodotto cliccandoci sopra.
I suddetti use case sono stati sottoposti all'approvazione del Proponente, garantendo così la congruenza con le esigenze e gli obiettivi aziendali. \
=== Chiarimenti tecnici
Si è discusso su alcuni aspetti tecnici del progetto, e in seguito ai chiarimenti dati dal Proponente si è giunti alle seguenti conclusioni:
- il file SVG rappresenta solo la piantina del magazzino e segue standard XML;
- non è richiesta la persistenza dei dati;
- il DB contiene tutte le informazioni necessarie a ricreare lo scenario;
- lo spostamento di un prodotto è gestito dalla business logic del servizio esterno col quale ci si interfaccia tramite REST API. Il nostro progetto deve occuparsi solo di inviare la richiesta.
\
=== Device da supportare
Il gruppo ha discusso insieme al Proponente se l'applicazione dovesse supportare altri device come smartphone e tablet, e di conseguenza come sarebbero cambiate le feature e le modalità di visualizzazione. Il Proponente ha chiarito che l'applicazione deve essere progettata principalmente per l'utilizzo su desktop, e in misura minore su tablet. Non si presuppone l'utilizzo da parte degli utenti tramite telefono, le funzionalità fornite saranno uniformi su entrambi i dispositivi, senza differenze sostanziali. È importante sottolineare che gli operatori non faranno uso di funzionalità 3D nell'ambito delle operazioni svolte tramite l'applicazione.
\
=== Requisiti non funzionali
Il gruppo ha chiesto informazioni riguardo possibili vincoli sui requisiti non funzionali in vista della loro individuazione. Il Proponente ha specificato l'assenza di vincoli a riguardo.
\
== Richieste al Proponente riguardo materiale utile durante il progetto
Il gruppo ha avanzato la richiesta di materiale e informazioni come le caratteristiche dei prodotti, esempi di codifica di scaffali e bin ed esempi di piantina di magazzino. Le proposte sono state accolte dal Proponente, che ci ha assicurato il soddisfacimento delle nostre richieste.
== Organizzazione di un prossimo meeting
L'incontro si è concluso con la proposta del prossimo meeting in data 30 novembre 2023, in orario alle 16:00 o alle 17:00, ancora da confermare.
= Azioni da intraprendere
A seguito del meeting sono state individuate le seguenti operazioni da svolgere:
- modifica delle ipotesi in seguito ai chiarimenti forniti dal Proponente;
- continuazione del lavoro di stesura degli use case;
- organizzazione di un meeting interno post meeting esterno per riflettere meglio sul lavoro da fare e sulla sua suddivisione.
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/goto_definition/inside_import.typ | typst | Apache License 2.0 | // path: base.typ
#let f() = 1;
-----
.
#import "base.typ": /* ident after */ f;
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/spacing_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Linebreak and leading-sized weak spacing are equivalent.
#box[A \ B] #box[A #v(0.65em, weak: true) B]
// Eating up soft spacing.
Inv#h(0pt)isible
// Multiple spacings in a row.
Add #h(10pt) #h(10pt) up
// Relative to area.
#let x = 25% - 4pt
|#h(x)|#h(x)|#h(x)|#h(x)|
// Fractional.
| #h(1fr) | #h(2fr) | #h(1fr) |
|
https://github.com/giZoes/justsit-thesis-typst-template | https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/utils/unpairs.typ | typst | MIT License | // 将 pairs 数组转成 dict 字典
#let unpairs(pairs) = {
let dict = (:)
for pair in pairs {
dict.insert(..pair)
}
dict
} |
https://github.com/ysthakur/PHYS121-Notes | https://raw.githubusercontent.com/ysthakur/PHYS121-Notes/main/Notes/Ch02.typ | typst | MIT License | = Chapter 2
== Uniform Motion
*Uniform motion* (aka constant-velocity motion) is straight-line motion with equal displacements during anys uccessive equal-time intervals
An object's motion is uniform iff *the position vs time graph is a straight line.*
Some equations:
$ v_x = (Delta x)/(Delta t) = (x_f - x_i)/(t_f - t_i) $
$ x_f = x_i + v_x Delta t $
$ Delta x = v_x Delta t $
== Instantaneous Velocity
Speed and direction at a specific instant of time $t$
== Acceleration
$ a_x = (Delta v_x)/(Delta t) = (v_x_f - v_x_i)/(Delta t) $
$ v_x_f = v_x_i + a_x Delta t $
$ x_f = x_i + v_x_i Delta t + 1/2 a_x Delta t^2 $
$ (v_x_f)^2 = (v_x_i)^2 + 2 a_x Delta x $
|
https://github.com/spherinder/ethz-infk-thesis | https://raw.githubusercontent.com/spherinder/ethz-infk-thesis/master/src/main.typ | typst | #import "../template.typ": template
// #import "@preview/eth-zurich-infk-thesis:0.1.0": template
#import "dependencies.typ": *
#show: template.with(
title: "Assembly Code Generation for Black-Box Hardware Fuzzing",
author: "<NAME>",
author-email: "<EMAIL>",
document-type: "Bachelor's thesis",
semester: "6",
student-nr: "24-681-012",
supervisor: "Prof. Dr. Example",
tutor: "Dr. Example",
text-font: "New Computer Modern",
sans-font: "New Computer Modern Sans",
incl-declaration-of-originality: true,
incl-list-of-figures: true,
incl-list-of-tables: true,
incl-listings: true,
declaration-of-originality-choice: 2,
timespan: "October 2024 to April 2025",
header-logo: image("assets/header-image.svg", width: 100%),
keywords: ("Live", "Universe", "Everything"),
abstract: lorem(30),
)
// Enable glossary
// Use: @key, #gls("key") or @key:pl, #glspl("key") to reference and #print-glossary to print it
// More documentation: https://typst.app/universe/package/glossarium/
#show: make-glossary
// Include chapters of thesis
#pagebreak(weak: true)
#include "chapters/01-introduction.typ"
#include "chapters/02-background.typ"
// Print glossary
// #pagebreak(weak: true)
// #include "glossary.typ"
// Print abbreviations
#pagebreak(weak: true)
#include "abbreviations.typ"
// Print bibliography
#pagebreak(weak: true)
#bibliography("bibliography.bib")
|
|
https://github.com/Airsequel/interpreted-languages-benchmark | https://raw.githubusercontent.com/Airsequel/interpreted-languages-benchmark/main/bucket-calc/main.typ | typst | #{
// Constants
let start = 1
let end = 100000
let num_bins = 20
// Calculating the base of the logarithm
let log_base = calc.pow((end / start), (1 / num_bins))
// Calculating the bin edges
let bin_edges = for i in range(num_bins + 1) {
(start * calc.pow(log_base, i),)
}
// Uncomment below line to get bin_edges before rounding
// [bin_edges before rounding: #bin_edges]
// Rounding the bin edges to the nearest integer
let bin_edges_int = bin_edges.map(edge => int(calc.round(edge)))
// Uncomment below line to include integer bin edges
// [bin_edges_int: #bin_edges_int]
bin_edges_int.map(str).join(",")
} <main>
|
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/dynamic/internals.md | markdown | # Internals
Here, topics regarding the internal implementation of dynamic content in polylux
is discussed.
Usually, you can completely ignore this section.
## Internal number of repetitions
**TL;DR:**
For slides with more than ten subslides, you need to set the `max-repetitions`
argument of the `#polylux-slide` function to a higher number.
For technical reasons (this might change in the future when we find a better
solution), producing PDF pages for subslides is implemented in the following way:
Each dynamic element, such as `#only` or `#beginning` "knows" how many subslides a
logical slide must have for it to "make sense".
For example, a `#beginning(5)[...]` only makes sense if at least 5 subslides are
produced.
Internally, when typesetting a slide, we now look at all the dynamic elements in
it and find the maximum of those individual "required" subslide counts.
So if a slide contains a `#only(2)[...]`, a `#until(4)[...]`, and nothing else,
we know that exactly 4 subslides are necessary.
However, we only acquire this knowledge _after_ the first subslide has been
produced, i.e. when all of the slide's content has been "looked at" once.
This is why we cannot simply implement something like "produce 4 pages by
iterating this loop 4 times".
Instead, the (admittedly hacky) solution is to iterate "very often" and check in
each iteration if we still need to produce another page.
This works because we always need to produce at least one page for a slide, so
we can unhurriedly inspect all dynamic elements and find the maximum subslide
count at the first iteration.
After that, we have the information we need.
Now, the question arises how often "very often" should be.
This requires a trade-off:
Iterating too few times (say, twice) will lead to frequent situations where we
ignore dynamic behaviour that was supposed to happen in later subslides (say, in
the third).
Iterating, say, a thousand times means that we will practically never encounter
such situations but we now perform a thousand iterations _per slide_.
Especially when you want to see a live update of your produced PDF as you type,
this leads to severe lagging that somewhat defeats the purpose of Typst's speed.
(Still faster than LaTeX, though...)
It appears reasonable that occasions are rare where one needs more than ten
subslides for one slide.
Therefore, ten is the default value for how often we try to create a new subslide.
This should not produce noticable lag.
(If it does for you, consider
[creating an issue](https://github.com/andreasKroepelin/polylux/issues)
so we can discuss this.)
For those hopefully rare occasions where you do, in fact, need more than ten
subslides, you can manually increase this number using the `max-repetitions`
argument of the `#slide` function:
```typ
#polylux-slide(max-repetitions: 20)[
This is gonna take a while:
#uncover(20)[I can wait...]
]
```
Again, use this feature sparingly, as it decreases typesetting performance.
|
|
https://github.com/An-314/Notes-of-Fundamentals_of_Electronics | https://raw.githubusercontent.com/An-314/Notes-of-Fundamentals_of_Electronics/main/chap1.typ | typst | #import "@local/mytemplate:1.0.0": *
#import "@preview/physica:0.9.2": *
= 半导体基础知识
== 半导体二极管和晶体管 semiconductor materials
=== 本征半导体
导电性介于导体与绝缘体之间的物质称为半导体。硅(Si)、锗(Ge),均为四价元素,它们原子的最外层电子受原子核的束缚力介于导体与绝缘体之间。
本征半导体是*纯净的晶体结构*的半导体。
#figure(
image("pic/2024-02-29-08-08-35.png", width: 80%),
caption: [
本征半导体结构
],
)
- 载流子:运载电荷的粒子——自由电子、空穴。本征半导体中的电流是两种载流子电流之和。
- 复合:自由电子与空穴相遇,互相消失。
- 随着*温度*的升高,本征半导体的导电性会增强。
=== 杂质半导体
杂质半导体主要靠多数载流子导电。*掺入杂质*越多,多子浓度越高,导电性越强,实现
导电性可控。
还是两种载流子,但是多数载流子的浓度远远大于少数载流子。
==== N型半导体
在本征半导体中加入少量五价元素,如磷(P)、砷(As)等,称为N型半导体。
#figure(
image("pic/2024-02-29-08-14-26.png", width: 30%),
caption: [
N型半导体结构
],
)
此时空穴比未加杂质时的数目少。
==== P型半导体
在本征半导体中加入少量三价元素,如硼(B)、铝(Al)等,称为P型半导体。
#figure(
image("pic/2024-02-29-08-17-52.png", width: 30%),
caption: [
P型半导体结构
],
)
在杂质半导体中,温度变化时,载流子的数目也会发生变化。少子与多子变化的数目相同。多数载流子与少数载流子的浓度变化,少数载流子更明显。
=== PN结的形成及其单向导电性
==== PN结的形成
#figure(
image("pic/2024-02-29-08-23-39.png", width: 80%),
caption: [
PN结的形成
],
)
扩散运动使靠近接触面P区的空穴浓度降低、靠近接触面N区的自由电子浓度降低(浓度梯形变化),产生内电场。该电场阻碍了多数载流子的*扩散运动*,有利于少数载流子的*漂移运动*。最终达到动态平衡,形成*PN结*。
#figure(
image("pic/2024-02-29-08-31-50.png", width: 40%),
caption: [
形成空间电荷区
],
)
=== PN结的单向导电性
#figure(
image("pic/2024-02-29-08-34-06.png", width: 80%),
caption: [
PN结的单向导电性
],
)
正向需要*开启电压*,来克服PN结的内电场,使得多数载流子能够通过PN结。反向时,内电场增强,阻碍多数载流子通过PN结,使得电流几乎为0。
- *PN结加正向电压导通*:耗尽层变窄,扩散运动加剧,由于外电源的作用,形成扩散电流,PN结处于导通状态。
- *PN结加反向电压截止*:耗尽层变宽,阻止扩散运动,有利于漂移运动,形成漂移电流。由于电流很小,故可近似认为其截止。
=== PN结的电容效应
==== 势垒电容
PN结外加电压变化时, *空间电荷区的宽度*将发生变化,有电荷的积累和释放的过程,与电容的充放电相同,其等效电容称为势垒电容$C_b$。
==== 扩散电容
PN结外加的正向电压变化时,在扩散路程中*载流子的浓度及其梯度*均有变化,也有电荷的积累和释放的过程,其等效电容称为扩散电容$C_d$。
==== 结电容
一个PN结的等效电容$C_j$由势垒电容和扩散电容组成。*结电容*不是常量。
$
C_j = C_b + C_d
$
一个PN结可以看作一个电容(直流时候不考虑)和一个可变电阻的并联(但还有个开启电压)。直流情况下,该电容不起作用;若PN结外加电压频率高到一定程度,则*失去单向导电性*。
== 半导体二极管及其基本应用
=== 二极管的组成
将PN结封装,引出两个电极,就构成了二极管。
#grid(
columns: (1fr, 3fr),
align(center)[
#figure(
image("pic/2024-02-29-08-45-42.png", width: 80%),
caption: [
二极管
],
)
#figure(
image("pic/2024-02-29-08-47-05.png", width: 80%),
caption: [
四种二极管
],
)
],
align(center)[
#figure(
image("pic/2024-02-29-08-46-21.png", width: 80%),
caption: [
二极管的分类#footnote[螺丝帽:用来固定和散热。]
],
)
]
)
=== 二极管的伏安特性及电流方程
#grid(
columns: (1fr, 1fr),
align(center)[
#figure(
image("pic/2024-02-29-08-56-02.png", width: 80%),
caption: [
二极管的伏安特性
],
)
电阻:限流并便于测量。
],
[
#figure(
image("pic/2024-02-29-09-34-39.png", width: 70%),
caption: [
二极管的电流方程
],
)
]
)
- 开启电压:需要克服PN结的内电场,使得少数载流子能够通过PN结
- 反向电流:等效一个微弱的恒流源,内阻无穷大。
- 击穿#footnote[两种击穿:
- 雪崩击穿:当外加电压超过了器件的临界击穿电压时,少数载流子(电子或空穴)在PN结的耗尽区获得足够的能量,以至于它们在撞击晶格时能够敲击出更多的电子-空穴对。
- 齐纳击穿:齐纳击穿也是一种在高电压下发生的击穿机制,但它主要发生在高掺杂浓度的PN结二极管中。在齐纳击穿中,当电场强度足够高时,电场可以直接将价带中的电子“拉”到导带中,通过量子力学中的隧穿效应产生大量的电子-空穴对。]
电压:当外加电压超过了器件的临界击穿电压时,PN结的内电场被击穿,电流急剧增大。
$
i = I_s (e^(u/U_T) - 1)
$
常温下,$U_T = 26"mV"$。
#align(center)[
#table(
columns: (auto, auto, auto, auto),
inset: 10pt,
align: horizon,
[材料],[开启电压],[导通电压],[反向饱和电流],
"硅Si", $0.5V$, $0.5~0.8V$ ,$1"µA以下"$,
"锗Ge", $0.1V$ ,$0.1~0.3V$ ,$"几十µA"$
)
]
从二极管的伏安特性可以反映出:
1. 单向导电性
当正向电压$u >> U_T$,则$i -> I_s e^(u/U_T)$,此时二极管处于导通状态。
当方向电压$u < 0$,则$i -> -I_s$,此时二极管处于截止状态。
2. 伏安特性受温度影响
$T(℃)$ ↑→在电流不变情况下管压降$u$↓→反向饱和电流#footnote[温度对少子影响更大]$I_S$↑#footnote[增大1倍/10℃],$ U_("BR")$ ↓
$T(℃)$ ↑→正向特性左移,反向特性下移
#figure(
image("pic/2024-02-29-09-14-40.png", width: 40%),
caption: [
随温度变化的伏安特性
],
)
=== 二极管的等效电路
==== 伏安特性折线化——静态模型(直流)
#figure(
image("pic/2024-02-29-09-17-06.png", width: 60%),
caption: [
选取合适的模型
],
)
==== 微变等效电路——动态模型(交流)
有时候传递信息用的是交流的小信号,前面的静态模型无法满足需求。
#figure(
image("pic/2024-02-29-09-26-40.png", width: 60%),
caption: [
小信号模型
],
)
当二极管在静态基础上有一动态信号作用时,则可将二极管等效为一个电阻,称为动态电阻,也就是微变等效电路。
根据电流方程,可以计算到动态电阻的值:
$
r_d = U_T / I_S (e^(- u/U_T)) ~ U_T / I_D
$
=== 普通二极管的基本应用
- 整流电路:忽略正向压降和反向电流
将交流电压转换成直流电压,称为整流
#figure(
image("pic/2024-03-05-08-22-59.png", width: 80%),
caption: [
整流电路
],
)
- 开关电路:二极管导通电压为0.7V
#figure(
image("pic/2024-03-05-08-24-17.png", width: 80%),
caption: [
与门
],
)
把二极管反向,并把高电平变成低电平,则成为或门。
=== 稳压二极管
由一个PN结组成,*反向击穿*后在一定的电流范围内端电压基本不变,为稳定电压。
#figure(
image("pic/2024-03-05-08-28-23.png", width: 50%),
caption: [
稳压二极管
],
)
==== 主要参数
- 稳定电压$U_Z$
- 稳定电流$I_Z$
- 最大功耗$P_(Z M) = I_(Z M) U_Z$
- 动态电阻$r_z= (Δ U_Z) /(Δ I_Z)$
==== 基本电路的组成
电流太小则不稳压,电流太大则会因功耗过大而损坏,因而稳压管电路中必需有限制稳压管电流的限流电阻。
$
I_(D Z min) = I_(R min) - I_L > I_(Z min)\
I_(D Z max) = I_(R max) - I_L< I_(Z max)
$
#figure(
image("pic/2024-03-05-08-33-22.png", width: 20%),
caption: [
稳压二极管的基本电路
],
)
== 晶体三极管及其基本放大电路
=== 晶体三极管
==== 晶体三极管的结构和符号
#figure(
image("pic/2024-03-05-08-36-05.png", width: 80%),
caption: [
晶体三极管的结构和符号#footnote[箭头:P指向N]
],
)
- 发射区高掺杂,基区低掺杂,集电区低掺杂、面积大。
- 发射结正向偏置,集电结反向偏置。
==== 晶体管的放大原理
发射结正偏:利于发射区多子注入,其多子扩散到基区(发射区多子浓度高),变为非平衡少子;只有极少数和空穴复合(因基区薄且多子浓度低)。
极电结反偏:在外电场作用下大部分扩散到基区的电子漂移到集电区(因集电区面积大)。
*扩散运动形成发射极电流$I_E$,复合运动形成基极电流$I_B$,漂移运动形成集电极电流$I_C$。*#footnote[基区扩散电流和少数载流子的运动忽略]
#figure(
image("pic/2024-03-05-08-55-23.png", width: 80%),
caption: [
晶体三极管的放大原理
],
)
$
"放大的条件"cases(
u_(B E) > U_(o n) "发射结正偏",
u_(C E) >= 0 "即"u_(C E)>=u_(B E) "集电结反偏",
)
$
有电流分配:
$
I_E = I_B + I_C
$
定义:直流电流放大系数
$
overline(beta) = I_C / I_B
$
交流电流放大系数
$
beta = (Δ i_C) / (Δ i_B)
$
以及,如果考虑穿透电流:
$
I_(C E O)#footnote[基极开路集电极回路] = (1 + overline(beta)) I_(C B O)
$
其中$I_(C E O)$是基极开路时的集电极电流,穿透电流;$I_(C B O)$是发射极开路时的集电结反向饱和电流。
==== 晶体管的共射输入特性和输出特性
#figure(
image("pic/2024-03-05-09-02-41.png", width: 20%),
caption: [
晶体管的共射连接
],
)
===== 输入特性
#figure(
image("pic/2024-03-05-09-06-00.png", width: 30%),
caption: [
输入特性$i_B = f(U_(B E)) |_(U_(C E))$
],
)
- $U_(C E) = 0$时,等同于两个二极管并联;
- $U_(C E) > 0$时,被分流,$I_B$减小;
- 最后会饱和,$I_B$几乎不变。
===== 输出特性
#figure(
image("pic/2024-03-05-09-10-36.png", width: 70%),
caption: [
输出特性$i_C = f(u_(C E)) |_(I_B)$
],
)
本质与PN结反向特性一致,非平衡少子的数量不同,导致$I_B$的饱和值不同。
饱和区:流控电流源;放大区:小电阻;截止区:开路#footnote[一般的数字电路工作在饱和区和截止区,模拟电路工作在放大区。]。
$beta$不是一个常数(但在局部的$beta$会比较稳定)。*理想晶体管*就是$beta$不变的晶体管。
#align(center)[
#table(
columns: (auto, auto, auto, auto),
inset: 10pt,
align: horizon,
[*工作区*],[*$u_(B E)$*],[*$i_C$*],[*$u_(C E)$*],
"截止区", [$< U_(o n)$], [$I_(C E O)$],[$V_(C C)$],
"放大区", [$>= U_(o n)$], [$beta i_B$],[$>= V_(B E)$],
"饱和区", [$>= U_(o n)$], [$< beta i_B$],[$<= V_(B E)$]
)
]
===== 温度对晶体管特性的影响
#figure(
image("pic/2024-03-05-22-51-20.png", width: 60%),
caption: [
温度对晶体管特性的影响
],
)
$
T (℃) ↑&→I_(C E O) ↑\
&→beta ↑\
&→u_(B E)"不变时" i_B ↑ , i_B "不变时" u_(B E) ↓
$
===== 主要参数
- 直流参数:$overline(beta)$,$overline(alpha)= I_C/I_E$,$I_(C B O)$, $I_(C E O)$
- 交流参数: $β$、 $α=beta/(1 + beta)$、 $f_T$(使$β= 1$的信号频率,由于电容,$beta$在频率高时会减少)
- 极限参数:
- $I_(C M)$最大集电极电流,$u_(C E)=1"V "$时的$i_C$就是$I_(C M)$
- $P_(C M)$最大集电极耗散功率, $P_(C M) = i_C u_(C E)$
- $U_((B R) C E O)$ $c-e$间击穿电压
#figure(
image("pic/2024-03-07-08-17-15.png", width: 50%),
caption: [
晶体管的极大参数
],
)
=== 放大电路的组成原则
==== 放大的概念
#figure(
image("pic/2024-03-07-08-22-14.png", width: 80%),
caption: [
放大电路
],
)
输入信号为零时为静态。
- 放大的信号:*变化量*——常用正弦波作为测试信号
- 放大的本质:能量的控制,利用有源元件实现
- 放大的特征:*功率*放大
- 放大的基本要求:不失真——放大的前提
*放大研究的是动态性能。*
#figure(
image("pic/2024-03-07-08-31-04.png", width: 80%),
caption: [
对信号而言,任何放大电路均可看成二端口网络。#footnote[希望$R_i$无穷大、$accent(I_i, dot)$趋于$0$来减少对输入信号的影响。希望$R_O=0$。]
],
)
*放大倍数*: 输出量与输入量之比
$
accent(A_(u u), dot) = accent(U_o, dot) / accent(U_i, dot), accent(A_(i i), dot) = accent(I_o, dot) / accent(I_i, dot) , accent(A_(u i), dot) = accent(U_o, dot) / accent(I_i, dot), accent(A_(i u), dot) = accent(I_o, dot) / accent(U_i, dot)
$
后两个称为*互阻*和*互导*。
*输入电阻和输出电阻*:
- 从输入端看进去的等效电阻
计算
$
R_i = U_i / I_i
$
- 将输出等效成有内阻的电压源,内阻就是输出电阻。
计算
$
R_o = (U_o'-U_o) / (U_O/R_L)
$
*通频带*:衡量放大电路对不同频率信号的适应能力。
由于电容、电感及半导体元件的电容效应,使放大电路在信号频率较低和较高时电压放大倍数数值下降,并产生相移。
#figure(
image("pic/2024-03-07-08-44-58.png", width: 80%),
caption: [
放大电路的通频带
],
)
*最大不失真输出电压$U_(o m)$*: 交流有效值
*最大输出功率和效率*:功率放大电路的主要指标参数
==== 基本共射放大电路的工作原理
===== 电路的组成及各元件的作用
#figure(
image("pic/2024-03-07-08-55-34.png", width: 50%),
caption: [
基本共射放大电路
],
)
$T$:有源器件,能够控制能量
$V_(B B)$、$R_b$:使$U_(B E)>U_(o n)$,且有合适的$I_B$,限流
$V_(C C)$:使$U_(C E)≥U_(B E)$,同时作为负载的能源
$R_c$:将$Δ_(i C)$转换成$Δ u_(C E)(u_O)$
$
Delta u_I -> Delta i_B -> Delta i_C -> Delta u_(R_c) -> Delta u_(C E)(u_O)
$
输入电压$u_i$为零时,晶体管各极的电流、$b-e$间的电压、管压降称为静态工作点$Q$#footnote[设置合适的静态工作点,首先要解决失真问题(可能不到开启电压)],记作$I_(B Q)$、 $I_(C Q)$($I_(E Q)$)、 $U_(B E Q)$、 $U_(C E Q)$。
要想不失真,就要在信号的整个周期内保证晶体管始终工作在放大区。
#figure(
image("pic/2024-03-07-09-18-19.png", width: 80%),
caption: [
基本共射放大电路的波形分析
],
)
#figure(
image("pic/2024-03-07-09-22-18.png", width: 80%),
caption: [
两种失真
],
)
==== 组成放大电路
===== 组成原则
- 静态工作点合适:合适的直流电源、合适的电路参数大了的动态信号。
- 对实用放大电路的要求:*共地、直流电源种类尽可能少、负载上无直流分量*。
===== 两种实用放大电路
*直接耦合放大电路*
将两个电源变成一个,取$R_o < R_(b 2)$
#figure(
image("pic/2024-03-07-09-32-45.png", width: 80%),
caption: [
直接耦合放大电路
],
)
静态时,$U_(B E Q) = U_(R_(b 1))$
动态时,$b-e$间电压是$u_i$与$V_"CC"$的共同作用的结果
*阻容耦合放大电路*
#figure(
image("pic/2024-03-07-09-35-21.png", width: 50%),
caption: [
阻容耦合放大电路
],
)
静态时,$U_(C 1)=U_(B E Q)$, $U_(C 2)=U_(C E Q)$
动态时,$u_(B E)=u_i + U_(B E Q)$信号驮载在静态之上。负载上只有交流信号。
=== 放大电路的分析方法
==== 放大电路的直流通路和交流通路
1. 直流通路:① $U_s=0$,保留$R_s$;②电容开路;③电感相当于短路(忽略线圈电阻)。
2. 交流通路:①大容量电容(如耦合电容、旁路电容相当于短路;②直流电源相当于短路(理想电压源内阻为0)。
_例:*直接耦合放大电路*的直流通路和交流通路_
#grid(
columns: (1fr, 2fr),
align(center)[
#figure(
image("pic/2024-03-12-08-25-07.png", width: 65%),
caption: [
直流通路
],
)
],
[
#figure(
image("pic/2024-03-12-08-25-19.png", width: 90%),
caption: [
交流通路
],
)
]
)
静态:
$
I_(B Q) &= (V_"BB" - U_(B E Q)) / R_b\
I_(C Q) &= beta I_(B Q)\
U_(C E Q) &= V_"CC" - I_(C Q) R_c
$
列晶体管输入、输出回路方程,将$U_(B E Q)$作为已知条件,令$I_(C Q)= β I_(B Q)$,可估算出静态工作点。
_例:*阻容耦合放大电路*的交流通路_
#figure(
image("pic/2024-03-12-08-28-49.png", width: 50%),
caption: [
阻容耦合放大电路的交流通路
],
)
==== 图解法
===== 静态分析:图解二元方程
#figure(
image("pic/2024-03-12-08-33-40.png", width: 80%),
caption: [
静态分析
],
)
===== 电压放大倍数的分析
$
u_(B E) = V_"BB" - i_B R_b + Delta u_i
$
#grid(
columns: (1fr, 1fr),
align(center)[#figure(
image("pic/2024-03-12-08-35-56.png", width: 80%),
caption: [
输入信号的放大
],
)],
align(center)[#figure(
image("pic/2024-03-12-08-38-25.png", width: 90%),
caption: [
输出信号的放大
],
)]
)
$
Delta u_I -> Delta i_B -> Delta i_C -> Delta u_(C E)(Delta u_O) -> A_u
$
可以发现输出的放大倍输入是反向的。
===== 失真分析
// 补:失真的分析和解决方法
*截止失真*:截止失真是在输入回路首先产生失真。
#grid(
columns: (1fr, 1fr),
[#figure(
image("pic/2024-03-12-08-50-21.png", width: 70%),
caption: [
截止失真的输入
],
)],
[#figure(
image("pic/2024-03-12-08-51-21.png", width: 90%),
caption: [
截止失真的输出
],
)]
)
截至失真是从输入回路开始的,输入回路底部被削平,导致输出回路失真。
消除方法:
- 增大$V_"BB"$,即向上平移输入回路负载线
#figure(
image("pic/2024-03-17-13-21-47.png", width: 60%),
caption: [
对于截止失真的消除
],
)
- 减小$R_b$,即向上平移截距
#figure(
image("pic/2024-03-17-13-23-56.png", width: 70%),
caption: [
对于截止失真的消除
],
)
*饱和失真*:饱和失真是输出回路产生失真。
#figure(
image("pic/2024-03-17-13-29-00.png", width: 80%),
caption: [
饱和失真的输入和输出
],
)
部分输出不在放大区,而在饱和区。
消除方法:
- 增大$R_b$、减小$beta$、减小$V_"BB"$——使得$Q'$沿着输出特性曲线向下移动
- 减少$R_c$、增大$V_"CC"$——使得$Q'$向右移动(一般不采用)
*最大不失真输出电压$U_"om"$*:
比较($U_(C E Q) - U_(C E S)$)与( $V_"CC" -U_(C E Q)$ )最小者,除以$sqrt(2)$得到$U_"om"$。
*直流负载线和交流负载线*:
#figure(
image("pic/2024-03-17-16-39-13.png", width: 40%),
caption: [
直流负载线和交流负载线
],
)
负载线应过$Q$点,斜率由负载决定。
==== 等效电路法
半导体器件的非线性特性使放大电路的分析复杂化。利用线性元件建立模型,来描述非线性器件的特性。
===== 直流模型:适于$Q$点的分析
$
I_(B Q) &= (V_"BB" - U_(B E Q)) / R_b\
I_(C Q) &= beta I_(B Q)\
U_(C E Q) &= V_"CC" - I_(C Q) R_c
$
#figure(
image("pic/2024-03-12-08-58-15.png", width: 40%),
caption: [
直流模型
],
)
===== 交流模型:晶体管的$h$参数等效模型
在低频、小信号作用下的关系式:
$
dd(u_(B E)) &= (diff u_(B E))/(diff i_B)bar_(U_(C E)) dd(i_B) + (diff u_(B E))/(diff u_(C E))bar_(I_B) dd(u_(C E))\
dd(i_C) &= (diff i_C)/(diff i_B)bar_(U_(C E)) dd(i_B) + (diff i_C)/(diff u_(C E))bar_(I_B) dd(u_(C E))
$
用相量表示:
$
accent(U, dot)_(B E) &= h_(11) accent(I, dot)_B + h_(12) accent(U, dot)_(C E)\
accent(I, dot)_C &= h_(21) accent(I, dot)_B + h_(22) accent(U, dot)_(C E)
$
可以得到交流等效模型:
#figure(
image("pic/2024-03-12-09-05-02.png", width: 40%),
caption: [
交流模型
],
)
*$h$参数的物理意义*:
- $h_(11) = ((diff u_(B E))/(diff i_B))bar_(U_(C E)) = r_(b e)$:$b-e$间的动态电阻
- $h_(12) = (diff u_(B E))/(diff u_(C E))bar_(I_B)$:内反馈系数
- $h_(21) = (diff i_C)/(diff i_B)bar_(U_(C E)) = beta$:电流放大系数
- $h_(22) = (diff i_C)/(diff u_(C E))bar_(I_B)= 1/r_(c e)$:$c-e$间的电导
$h_(12)$和$h_(22)$的作用可忽略不计。
#figure(
image("pic/2024-03-14-08-19-06.png", width: 80%),
caption: [
交流模型的等效电路
],
)
$
r_(b e)= U_(b e)/I_B = r_(b b')+r_(b' e) = r_(b b') + (beta + 1) U_T / I_(E Q)
$
其中,$r_(b b')$是基区的电阻,$r_(b' e)$是发射区的电阻;$U_T = 26"mV"$。在输入特性曲线上,$Q$点越高,$r_(b e)$越小。
===== 共射放大电路的动态分析
#figure(
image("pic/2024-03-18-00-47-36.png", width: 80%),
caption: [
动态电路等效电路
],
)
$
accent(A, dot)_u &= (accent(U, dot)_o) / (accent(U, dot)_i) = - (beta R_C) / (R_b + r_(b e))\
R_i &= U_i / I_i = R_b + r_(b e)\
R_o &= R_C
$
*阻容耦合共射放大电路的动态分析*
#figure(
image("pic/2024-03-18-00-54-59.png", width: 80%),
caption: [
阻容耦合共射放大电路
],
)
$
accent(A, dot)_u &= (accent(U, dot)_o) / (accent(U, dot)_i) = - (beta (R_L parallel R_C)) / (r_(b e))\
accent(A, dot)_(u s) &= (accent(U, dot)_o) / (accent(U, dot)_S) = (accent(U, dot)_o) / (accent(U, dot)_i) dot (accent(U, dot)_i) / (accent(U, dot)_s) = (R_i)/(R_i + R_s) accent(A, dot)_u\
R_i &= R_b parallel r_(b e)\
R_o &= R_C
$
_静态工作点稳定的共射放大:_
1. 温度对静态工作点的影响
$
T(℃) →cases(
β↑,I_(C E O)↑,若 U_(C E Q) 不 变,I_(B Q) ↑\
)→I_(C Q)↑ →Q'
$
#newpara()
2、静态工作点稳定的典型电路——分压式电流负反馈工作点稳定电路
#figure(
image("pic/2024-03-14-08-21-57.png", width: 80%),
caption: [
电路组成
],
)
可以看到,二者的直流通路一致。
#figure(
image("pic/2024-03-18-10-17-16.png", width: 20%),
caption: [
分压式电流负反馈工作点稳定电路的直流通路
],
)
+ 稳定原理
为了稳定$Q$点,通常$I_1 >> I_B$,即$I_1 ≈ I_2$;因此
$
U_(B Q) approx (R_(b 1))/(R_(b 1) + R_(b 2)) V_"CC"
$
基本不随温度变化。
$
I_(E Q) = (U_(B Q) - U_(B E Q))/R_e
$
设$U_(B E Q) = U_(B E) + Δ U_(B E)$,若$U_(B Q) - U_(B E)>>Δ U_(B E)$,则$I_(E Q)$稳定。
$R_e$的作用:
$
T(℃)↑→I_C↑→U_E↑→U_(B E)↓(U_B"基本不变") → I_B ↓→ I_C↓
$
$R_e$起直流负反馈作用,其值越大,反馈越强,$Q$点越稳定。
+ Q点分析
#figure(
image("pic/2024-03-18-10-36-25.png", width: 20%),
caption: [
直流通路等效电路
],
)
$
V_"BB" &= R_(b 1)/(R_(b 1) + R_(b 2)) V_"CC"\
R_b &= R_(b 1) parallel R_(b 2)\
$
$R_b$上静态电压是否可忽略不计?
$
V_"BB" = I_(B Q) R_b + U_(B E Q) + (1 + beta)I_(B Q) R_e
$
如果$R_b << (1 + beta)R_e$,则可忽略。
剩余参数:
$
U_(B Q) &= R_(b 1)/(R_(b 1) + R_(b 2)) V_"CC"\
I_(E Q) &= (U_(B Q) - U_(B E Q))/R_e\
I_(B Q) &= I_(E Q) / (1 + beta)\
U_(C E Q) &= V_"CC" - I_(C Q) R_C - I_(E Q) R_e approx V_"CC" - I_(E Q) (R_C + R_e)
$
+ 动态分析
#figure(
image("pic/2024-03-14-08-35-12.png", width: 80%),
caption: [
分压式电流负反馈动态电路
],
)
$
accent(A, dot)_u &= (accent(U, dot)_o) / (accent(U, dot)_i) = - (beta R_L) / (r_(b e))\
R_i &= R_(b 1) parallel R_(b 2) parallel r_(b e)\
R_o &= R_C
$
#figure(
image("pic/2024-03-18-10-44-50.png", width: 80%),
caption: [
分压式电流负反馈动态电路——无旁路电容
],
)
$
accent(A, dot)_u &= (accent(U, dot)_o) / (accent(U, dot)_i) = - (beta (R_L parallel R_C)) / (r_(b e) + (1 + beta) R_e) ->^((1+beta)R_e >> r_(b e)) - (R_L) / ( R_e)\
R_i &= R_(b 1) parallel R_(b 2) parallel (r_(b e) + (1 + beta) R_e)\
$
#figure(
image("pic/2024-03-18-10-52-38.png", width: 80%),
caption: [
稳定工作点的放大电路
],
)
=== 晶体管放大电路的三种接法
==== 基本共集放大电路
#figure(
image("pic/2024-03-18-10-54-36.png", width: 40%),
caption: [
基本共集放大电路
],
)
===== 静态分析
#figure(
image("pic/2024-03-18-10-55-14.png", width: 35%),
caption: [
静态分析电路
],
)
$
V_"BB" &= I_(B Q) R_b + U_(B E Q) + I_(E Q) R_e\
V_"CC" &= U_(C E Q) + I_(E Q) R_e\
$
$
I_(B Q) &= (V_"BB" - U_(B E Q)) / (R_b + (1 + beta) R_e)\
I_(E Q) &= (1 + beta) I_(B Q)\
U_(C E Q) &= V_"CC" - I_(E Q) R_e
$
===== 动态分析
#figure(
image("pic/2024-03-18-10-59-56.png", width: 40%),
caption: [
动态分析电路
],
)
$
accent(A, dot)_u &= (accent(U, dot)_o) / (accent(U, dot)_i) = ((1 + beta)R_e) / (R_b + r_(b e) + (1 + beta)R_e)\
$
若$(1+beta)R_e >> R_b + r_(b e)$,则$accent(A, dot)_u -> 1$:*射极跟随器*。
$
R_i &= R_b + r_(b e) + (1 + beta) R_e\
$
从基极看$R_e$,被增大到$1+beta$倍。带负载电阻后:
$
R_i &= R_b + r_(b e) + (1 + beta) (R_e parallel R_L)\
$
*$R_i$与负载有关。*
$
R_o &= R_e parallel (R_b + r_(b e))/(1 + beta)
$
从射极看基极回路电阻,被减小到$1+β$倍。
===== 特点
*输入电阻大,输出电阻小;只放大电流(功率),不放大电压;在一定条件下有电压跟随作用。*
==== 基本共基放大电路
#figure(
image("pic/2024-03-18-11-07-00.png", width: 40%),
caption: [
基本共基放大电路
],
)
===== 静态分析
$
V_"BB" &= U_(B E Q) + I_(E Q) R_e\
V_"CC" &= U_(C E Q) - U_(B E Q) + I_(C Q) R_e\
$
$
I_(E Q) &= (V_"BB" - U_(B E Q)) / R_e\
I_(B Q) &= I_(E Q) / (1 + beta)\
U_(C E Q) &= V_"CC" - I_(E Q) R_e + U_(B E Q)
$
===== 动态分析
#figure(
image("pic/2024-03-18-11-12-12.png", width: 40%),
caption: [
动态分析电路
],
)
$
accent(A, dot)_u &= (accent(U, dot)_o) / (accent(U, dot)_i) = (beta R_c) / (r_(b e) + (1 + beta) R_e)\
R_i &= R_e + r_(b e)/(1 + beta)\
R_o &= R_c
$
===== 特点
*输入电阻小,频带宽。只放大电压,不放大电流。电流跟随。*
==== 三种接法的比较:空载情况下
#figure(
table(
columns: (auto, auto, auto, auto),
inset: 10pt,
align: horizon,
[接法],[*共射*],[*共集*],[*共基*],
[$A_u$],[大],[小于1],[大],
[$A_i$],[$beta$],[$1+beta$],[$alpha$],
[$R_i$],[中],[大],[小],
[$R_o$],[大],[小],[大],
[频带],[窄],[中],[宽],
),
caption: [
三种接法的比较
],
)
== 放大电路的频率响应
=== 频率响应的有关概念
放大电路对信号频率的适应程度,即信号频率对放大倍数的影响。
由于放大电路中耦合电容、旁路电容、半导体器件极间电容的存在,使放大倍数为频率的函数。
在使用一个放大电路时应了解其信号频率的适用范围,在设计放大电路时,应满足信号频率的范围要求。
==== 高通电路和低通电路
*高通电路*:信号频率越高,输出电压越接近输入电压。
#figure(
image("pic/2024-03-19-08-15-31.png", width: 80%),
caption: [
高通电路
],
)
*低通电路*:信号频率越低,输出电压越接近输入电压。
#figure(
image("pic/2024-03-19-08-15-49.png", width: 80%),
caption: [
低通电路
],
)
==== 放大电路中的频率参数
在低频段,随着信号频率逐渐降低,耦合电容、旁路电容等的容抗增大,使动态信号损失,放大能力下降。
在高频段,随着信号频率逐渐升高,晶体管极间电容和分布电容、寄生电容等杂散电容的容抗减小,使动态信号损失,放大能力下降。
#figure(
image("pic/2024-03-19-08-19-41.png", width: 80%),
caption: [
放大电路中的频率参数
],
)
== 场效应管及其应用
=== 结型场效应管(以N沟道为例)
#grid(
columns: (1fr, 1fr),
align(center)[
#figure(
image("pic/2024-03-19-08-25-29.png", width: 40%),
caption: [
结型场效应管符号
],
)],
[
#figure(
image("pic/2024-03-19-08-25-49.png", width: 40%),
caption: [
结型场效应管结构
],
)
]
)
场效应管有三个极:源极(s)、栅极(g)、漏极(d)。
===== 工作原理
*栅-源电压对导电沟道宽度的控制作用*
#figure(
image("pic/2024-03-19-08-28-15.png", width: 80%),
caption: [
栅-源电压对导电沟道宽度的控制作用
],
)
$u_(G S)$可以控制导电沟道的宽度。g-s必须加负电压#footnote[P沟道的必须要加正压],才能使沟道导电。否则PN结导通。
*漏-源电压对漏极电流的影响*
#figure(
image("pic/2024-03-19-08-33-26.png", width: 80%),
caption: [
漏-源电压对漏极电流的影响
],
)
对外等效电阻越来越大,但$V_"DD"$的增大,几乎全部用来克服沟道的电阻,$i_D$几乎不变,进入恒流区。$U_(D S)$的增大会把$i_D$带向恒流区。
===== 特性
*转移特性*$i_D = f(u_(G S))|_(U_(D S)="常量")$
场效应管工作在恒流区,因而$u_(G S)>U_(G S("off"))$,且$u_(G D)< U_(G D("off"))$。
#figure(
image("pic/2024-03-19-08-40-26.png", width: 40%),
caption: [
结型场效应管的转移特性
],
)
在恒流区时
$
i_D = I_"DSS" (1 - u_(G S)/U_(G S("off")))^2
$
#newpara()
*输出特性*
#figure(
image("pic/2024-03-19-08-43-00.png", width: 80%),
caption: [
结型场效应管的输出特性
],
)
- 恒流区:压控电流源
- 不同型号的管子$U_(G S("off"))$ 、$I_"DSS"$将不同。
- 跨导:
$
g_m = (diff i_D)/(diff u_(G S)) |_(U_(D S))
$
==== MOSFET(金属氧化物半导体场效应管)
*增强型MOS管*
#figure(
image("pic/2024-03-21-00-35-40.png", width: 80%),
caption: [
MOSFET的结构
],
)
对N沟道的MOSFET,在g-b加电场时候,电子被吸引到绝缘的氧化层底部(但不形成电流),形成反型层(局部N型半导体),导通sd沟道。
$u_(G S)$增大,反型层(导电沟道)将变厚变长。当反型层将两个N区相接时,形成导电沟道。
#figure(
image("pic/2024-03-19-09-14-55.png", width: 80%),
caption: [
增强型MOSFET
],
)
一般把源极和衬底短接,即$u_(G S) = u_(G D)$。
#figure(
image("pic/2024-03-21-00-38-24.png", width: 80%),
caption: [
$u_(D S)$对$i_D$的影响
],
)
用场效应管组成放大电路时应使之工作在恒流区。N沟道增强型MOS管工作在恒流区的条件是$u_(G S) > U_(G S("off"))$。
*耗尽型MOS管*
#figure(
image("pic/2024-03-21-00-43-58.png", width: 80%),
caption: [
耗尽型MOSFET
],
)
在原来增强型的基础上,加了一个P型衬底(使得原来$"SiO"_2$的地方充满正离子),使得$U_(G S("off")) < 0$。
耗尽型MOS管在$u_(G S)> 0$、$u_(G S)< 0$、$u_(G S) = 0$时均可导通,且与结型场效应管不同,由于$"SiO"_2$绝缘层的存在,在$u_(G S)> 0$时仍保持g-s间电阻非常大的特点。
===== MOSFET的特性
#figure(
image("pic/2024-03-19-09-21-02.png", width: 80%),
caption: [
增强型MOS管
],
)
#figure(
image("pic/2024-03-19-09-23-28.png", width: 80%),
caption: [
耗尽型MOS管
],
)
在恒流区时
$
i_D = I_"DO" (1 - u_(G S)/U_(G S("th")))^2
$
其中$I_"DO"$为$u_(G S) = 2 U_(G S("th"))$时的漏极电流$i_D$。
===== 场效应管的分类
工作在恒流区时g-s、 d-s间的电压极性。
$
"场效应管"
cases(
"结型场效应管"
cases(
"N沟道型" (u_(G S) < 0, u_(D S) > 0),
"P沟道型" (u_(G S) > 0, u_(D S) < 0)
),
"绝缘栅型场效应管"
cases(
"增强型"
cases(
"N沟道型" (u_(G S) > 0, u_(D S) > 0),
"P沟道型" (u_(G S) < 0, u_(D S) < 0)
),
"耗尽型"
cases(
"N沟道型" (u_(G S) "极性任意", u_(D S) > 0),
"P沟道型" (u_(G S) "极性任意", u_(D S) < 0)
)
),
)
$
== 场效应管基本放大电路
=== 场效应管静态工作点的设置方法
==== 基本共源放大电路
根据场效应管工作在恒流区的条件,在g-s、d-s间加极性合适的电源:
#figure(
image("pic/2024-03-19-09-26-08.png", width: 40%),
caption: [
基本共源放大电路
],
)
$
U_"DSQ" &= V_"BB" \
I_"DQ" &= I_"DO" (1 - u_"BB"/U_("G S(th)"))^2\
U_"DSQ" &= V_"DD" - I_"DQ" R_D
$
==== 自给偏压电路
#figure(
image("pic/2024-03-21-00-55-22.png", width: 40%),
caption: [
自给偏压电路
],
)
$
U_(G Q) &= 0, U_(S Q)=I_(D Q)R_s\
U_(G S Q) &= U_(G Q) - U_(S Q) = -I_(D Q)R_s\
$
由正电源获得负偏压称为自给偏压。
$
I_(D Q) &= I_"DSS" (1 - U_(G S Q)/U_(G S("OFF")))^2\
U_(D S Q) &= V_"DD" - I_(D Q) (R_d +R_s)
$
==== 分压式偏置电路
即典型的Q点稳定电路
#figure(
image("pic/2024-03-21-00-57-05.png", width: 40%),
caption: [
分压式偏置电路
],
)
$
U_(G Q) &= U_(A Q) = R_(g 1)/(R_(g 1) + R_(g 2)) V_"DD"\
U_(S Q) &= I_(D Q) R_s\
I_(D Q) &= I_"DO" (1 - U_(G S Q)/U_(G S("th")))^2\
U_(D S Q) &= V_"DD" - I_(D Q) (R_d + R_s)
$
=== 场效应管放大电路的动态分析
==== 场效应管的交流等效模型
#figure(
image("pic/2024-03-21-08-13-10.png", width: 40%),
caption: [
场效应管的交流等效模型
],
)
其中g-s断路是因为绝缘。而$r_"ds"$可以认为忽略不计。
根据$i_D$的表达式或转移特性可以求得$g_m$。
结型N沟道管:
$
g_m approx - 2/U_(G S("off")) sqrt(I_"DSS" I_"DQ")
$
==== 基本共源放大电路的动态分析
#grid(
columns: (1fr, 1fr),
align(center)[
#figure(
image("pic/2024-03-21-08-17-35.png", width: 40%),
caption: [
基本共源放大电路
],
)],
[
#figure(
image("pic/2024-03-21-08-17-42.png", width: 80%),
caption: [
基本共源放大电路的动态分析
],
)
]
)
可以与共射电路对比:方向放大。
$
accent(A, dot)_u &= (accent(U, dot)_o) / (accent(U, dot)_i) = - g_m R_D \
R_i &= oo \
R_o &= R_D
$
==== 基本共漏放大电路的动态分析
#grid(
columns: (1fr, 1fr),
align(center)[
#figure(
image("pic/2024-03-21-08-19-59.png", width: 40%),
caption: [
基本共漏放大电路
],
)],
[
#figure(
image("pic/2024-03-21-08-20-05.png", width: 80%),
caption: [
基本共漏放大电路的动态分析
],
)
]
)
可以与共基电路对比:跟随器。
$
accent(A, dot)_u &= (accent(U, dot)_o) / (accent(U, dot)_i) = (accent(I, dot)_d R_s)/(accent(U, dot)_"gs" + accent(I, dot)_d R_s) = (g_m R_s)/(1 + g_m R_s) approx 1\
R_i &= oo\
R_o &= U_o/I_o =^(U_"gs"=U_o) U_o / (U_o/R_s + g_m U_o) = R_s parallel (1/g_m)
$
== 集成运算放大电路 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.