repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/Namacha411/shogi-board | https://raw.githubusercontent.com/Namacha411/shogi-board/main/manual.typ | typst | MIT License | #import "@preview/tidy:0.2.0"
#import "shogi-board.typ": shogi-board-from-sfen
= 概要
SFEN形式の入力から将棋盤を簡単に作成するtypstのモジュールです。
= 例
```typ
#shogi-board-from-sfen("lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b -")
```
#shogi-board-from-sfen("lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b -")
```typ
#shogi-board-from-sfen("4k4/9/4P4/9/9/9/9/9/9 b G")
```
#shogi-board-from-sfen("4k4/9/4P4/9/9/9/9/9/9 b G")
= API Reference
#let docs = tidy.parse-module(read("shogi-board.typ"))
#tidy.show-module(docs) |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/import-00.typ | typst | Other | // Test basic syntax and semantics.
// Ref: true
// Test that this will be overwritten.
#let value = [foo]
// Import multiple things.
#import "module.typ": fn, value
#fn[Like and Subscribe!]
#value
// Should output `bye`.
// Stop at semicolon.
#import "module.typ": a, c;bye
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/circuiteria/0.1.0/gallery/platypus.typ | typst | Apache License 2.0 | #import "../src/lib.typ": *
#set page(width: auto, height: auto, margin: .5cm)
#let teal = rgb(37, 155, 166)
#let orange = rgb(254, 160, 93)
#let brown = rgb(97, 54, 60)
#circuit({
element.group(id: "platypus", name: "A platypus", {
element.block(
x: 0, y: 0, w: 2, h: 3, id: "body",
fill: teal,
ports: (
east: (
(id: "out"),
)
),
ports-margins: (
east: (50%, 10%)
)
)
element.block(
x: 2.5, y: 1.5, w: 1.5, h: 1, id: "beak",
fill: orange,
ports: (
south: (
(id: "in"),
)
)
)
wire.wire("w1", ("body-port-out", "beak-port-in"), style: "zigzag", zigzag-ratio: 100%)
})
let O = (rel: (2, 0), to: "platypus.south-east")
element.group(id: "perry", name: "Perry the platypus", {
element.block(
x: (rel: 0, to: O), y: 0, w: 2, h: 3, id: "body",
fill: teal,
ports: (
east: (
(id: "out"),
)
),
ports-margins: (
east: (50%, 10%)
)
)
element.block(
x: (rel: 2.5, to: O), y: 1.5, w: 1.5, h: 1, id: "beak",
fill: orange,
ports: (
south: (
(id: "in"),
)
)
)
element.block(
x: (rel: 0.25, to: O), y: 3.2, w: 1.5, h: 0.5, id: "hat",
fill: brown
)
wire.wire("w2", ("body-port-out", "beak-port-in"), style: "zigzag", zigzag-ratio: 100%)
})
wire.wire(
"w3",
("platypus.east", (horizontal: "perry.west", vertical: ())),
directed: true,
bus: true
)
}) |
https://github.com/hitszosa/universal-hit-thesis | https://raw.githubusercontent.com/hitszosa/universal-hit-thesis/main/harbin/bachelor/pages/outline.typ | typst | MIT License | #import "../config/constants.typ": special-chapter-titles
#import "../../../common/theme/type.typ": 字体
#let outline-page() = [
#set par(first-line-indent: 0em)
#[
#show heading: none
#heading(special-chapter-titles.目录, level: 1, outlined: false)
]
#show outline.entry: (entry, label: <outline-page-modified-entry>) => {
if entry.at("label", default: none) == label {
entry // prevent infinite recursion
} else {
let fields = entry.fields()
if entry.level == 1 {
fields.body = [#text(font: 字体.黑体)[#fields.body]]
}
[#outline.entry(..fields.values()) #label]
}
}
#outline(title: align(center)[#special-chapter-titles.目录], indent: n => [#h(1em)] * n)
// #outline(title: align(center)[#special-chapter-titles.目录], indent: auto)
] |
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/2%20-%20RTB/Documentazione%20interna/Verbali/23-12-23/23-12-23.typ | typst | #import "/template.typ": *
#show: project.with(
date: "23/12/23",
subTitle: "Meeting di retrospettiva e pianificazione",
docType: "verbale",
authors: (
"<NAME>",
),
missingMembers: (
"<NAME>",
),
timeStart: "15:00",
timeEnd: "16:45",
);
= Ordine del giorno:
+ Valutazione dell'avanzamento;
+ Analisi di retrospettiva;
+ Confronto sull'implementazione delle Norme di Progetto;
+ Pianificazione.
== Valutazione dell'avanzamento
In vista delle festività natalizie si riassumono gli avanzamenti riportati dai membri del gruppo e sostanziati dall'ITS.
=== Analisi dei Requisiti
È assente il tracciamento tra requisiti e fonti dei requisiti. Occorre migliorare la resa grafica dei diagrammi UML.
=== Glossario <avanzamento-glossario>
L'evidenziazione dei termini nei documenti è migliorabile rendendola _case insensitive_ e introducendo la possibilità di gestire acronimi e plurali dei termini di Glossario.
=== Norme di Progetto
Il documento è in scrittura. L'avanzamento, come espresso in @improvements, non è soddisfacente.
=== Piano di Progetto
Consuntivi e preventivi sono conformi. Non sono state rilevate criticità.
=== Piano di Qualifica
Il documento è in scrittura. Sono state identificate alcune metriche di base.
=== PoC
L'integrazione dei PoC realizzati procede senza ritardi. Si sta valutando la realizzazione delle API con Next.js anziché Express.
== Analisi di retrospettiva
=== Keep doing
Non sono stati rilevati comportamenti virtuosi diversi da quelli dello sprint precedente. I membri del gruppo continuano a lavorare in autonomia con profitto soddisfacente.
=== Improvements <improvements>
- Automatismi relativi ai ticket di Jira bloccati a causa dell'esaurimento del pool mensile incluso nel piano gratuito;
- Alcune correzioni individuate durante la review devono attendere più di una giornata per l'approvazione;
- Alcuni commenti di review sono poco chiari e/o sbrigativi;
- Il progresso sulle Norme di Progetto è scarso rispetto agli sprint precedenti ed è in ritardo rispetto alla pianificazione;
- Il tracciamento delle attività relative al PoC non ha lo stesso livello di precisione delle attività documentali.
=== Soluzioni adottate <soluzioni>
- Richiedere l'upgrade gratuito a Jira Standard per progetti open source;
- Notificare, tramite i canali dedicati, chi debba apportare correzioni così da velocizzare i tempi di approvazione;
- Impegnarsi a fornire commenti di review più precisi:
- indicando con precisione la natura dell'errore e, se utile, la sua localizzazione all'interno della riga;
- fornendo, quando possibile, una correzione appropriata;
- nel caso di più occorrenze dello stesso errore, segnalarle tutte. Per evitare ripetizioni, fornire una valutazione della prima occorrenza ed inserire un riferimento a tale conversazione nelle occorrenze successive;
- Per accelerare il lavoro sulle Norme di Progetto, chi ha redatto le Norme di Progetto nel corso degli sprint precedenti continuerà l'affiancamento nel corso dello sprint successivo;
- La natura esplorativa del PoC richiede flessibilità nella pianificazione, ma si sottolinea la necessità di continuare a tracciare le attività per riferimento futuro.
== Pianificazione
- Redazione delle Norme di Progetto, recuperando i capitoli in ritardo ed espandendone altri (totale di 7 capitoli, tra aggiunte e aggiornamenti);
- Proseguimento dello sviluppo del PoC;
- Tracciamento requisiti-fonti e rifacimento dei diagrammi UML in formato SVG;
- Miglioramento del Glossario come descritto in @avanzamento-glossario;
- Realizzazione di un sito web che raccolga i documenti realizzati finora;
- Realizzazione di una dashboard per il monitoraggio delle metriche definite nel Piano di Qualifica.
Lo sprint successivo ha durata inferiore all'usuale perché le attività sono sospese nelle giornate del 24 e 25 dicembre. |
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/AI/Reinforce%20Learning/MARL.typ | typst | ---
order: 4
---
#import "/src/components/TypstTemplate/lib.typ": *
#show: project.with(
title: "AI 笔记之强化学习",
lang: "zh",
)
#let ba = $bold(a)$
#let bw = $bold(w)$
= MARL
- 从这一讲开始引入多智能体。之前的单智能体并不意味着场上只有一个智能体(比如围棋双方都是智能体,但认为是单智能体,也有多智能体的实现),它更多强调只有单个智能体受己方控制;而多智能体则是多个智能体相互作用,我们简单分为三类
+ 多智能体合作:最大化全队分享奖励;多智能体协调问题
+ 多智能体竞争:完全利己主义,最大化提高个人回报;零和博弈;Minimax均衡
+ 混合合作博弈:部分利己主义,平衡团队回报与个人回报;总和博弈;纳什均衡
- 博弈论简介:略
- 多智能体信用分配
- 模型:假设每个智能体都可以获取全局状态(MA-MDP)
- 智能体:$i in I = {1,2, dots , N}$
- 状态:$s in S$
- 行为:$a_i in A$,联合行为:$ba =< a_1, dots, a_N >∈ A^N$
- 状态转移函数:$P(s'|s, ba)$
- 奖励:$r(s, ba)$
- 折扣因子:$gamma$
- 智能体$i$的策略$pi_i (s): S -> A$
- 目标:搜索一个联合策略$bold(pi) = <pi_1, dots , pi>$来最大化期望累积回报$R =sum_(t=0)^infty gamma^t r_t$
- 状态行为价值函数:$Q^pi (s, ba) = EE[R|s_0 = s, ba_0 = ba, bold(pi)]$
- 最优策略 $pi^*(s) = argmax_ba Q^*(s, ba)$
- 模型:每个智能体只能看到全局状态的投影(Dec-POMDP)
- 观测:$o_i in Omega$
- 观测函数:$o_i in Omega wave O(s, i)$
- 智能体 $i$ 的分布式策略:$pi_i (tau_i): T -> A$
- 行为-观测历史:$tau_i in T = (Omega times A)^*$
- 集中训练分布式执行(CTDE):
- 训练过程中智能体可以获取全局状态
- 测试过程中智能体智能看到局部观测
- MARL(Multi-Agents RL) 挑战
- 可扩展性:维度诅咒
- 多智能体信用分配:每个智能体对整体博弈的贡献
- 样本利用率:需要大量的交互数据
- 受限的观测:受限传感器等,无法获取全局信息
- 探索:指数级别的联合策略空间
- MARL 范例
#fig("/public/assets/AI/AI_RL/img-2024-07-09-10-17-41.png")
- 可扩展的集中训练与分布式执行过程
- 满足IGM原则:智能体个体最优决策即全局最优联合决策
- 与纳什均衡矛盾?(个体最优并非全局最优)好像确实是这样的
== MARL with Factored Value Functions
- 值分解算法(线性)
- 方法一(VDN)
#fig("/public/assets/AI/AI_RL/img-2024-07-09-10-28-30.png")
- 方法二(DOP)
#fig("/public/assets/AI/AI_RL/img-2024-07-09-10-29-09.png")
- 线性值分解局限性
- 有限的表征能力
- 没有全局收敛保证
#let Qtot = $Q_"tot"$
- QMIX
- QMIX 的思想其实与 VDN 类似,也是去中心化思想(假设个体最优即为全局最优,即 IGM 假设),不过每个智能体对群体的贡献是加权的,权重由超网络生成(即生成网络的网络)
- 为了保证 IGM,需要限定网络参数非负,使 #Qtot 对任意 $Q_i$ 都是单调递增的。这有点像是人为转化了问题,限制了解法的可能性,但是确实能够保证 IGM,而且它 work
- 不难看出,当 $pa Qtot \/ pa Q_i = 1$ 时,QMIX 退化为 VDN
- QMIX 的模型由两大部分组成(三个网络组成),一个是 agent network,输出单智能体的 $Q_i$ 的函数,mixing network 则是以 $Q_i~(i=1 wave n)$ 作为输入,输出为联合 #Qtot。为了保证单调性,mixing network 的网络参数 $bw, bold(b)$ 通过 hypernetworks 网络计算得出,并且 hypernetworks 输出的网络权重都必须大于0,对偏置没有要求
- 在训练上,QMIX 就是一个 MA 版本的 DQN,因此也是用 target agent network 和 target mixing network 算 $y_j$,计算它与用当前 agent network 和 mixing network 得到的 $Q_i$ 的 MSE,然后用梯度下降更新当前网络参数,隔一段时间将当前网络(eval)参数复制到 target 网络参数
#fig("/public/assets/AI/AI_RL/img-2024-07-09-10-44-22.png")
- QPLEX
- 相当于 MA 版本的 DQN $->$ Dueling DQN,把 $Q$ 值改为 Advantage
#fig("/public/assets/AI/AI_RL/img-2024-07-09-10-49-41.png")
== 其它 MARL 方法
- 动态共享学习目标 $->$ ROMA
- 多智能体强化学习需要更大的样本量,所以参数共享作为减少样本量的方法,对于多智能体强化学习非常重要
- 但是用这种方法,智能体倾向于学习到均质行为策略,而实际上,不同的智能体在环境交互中往往需要异质性策略
- 因此动态目标学习可以使智能体根据其目标最大化个体差异
- ROMA
- 相似角色的智能体分享相似的学习目标和分享相似的行为策略。
- 相似角色 $<=>$ 相似子任务 $<=>$ 相似行为策略
- 角色可以作为短期博弈轨迹的编码并嵌入到输入。
- 智能体以对应的角色作为条件进行策略学习。
- 智能体在不同的场景下动态更换其角色。
- 价值分解局限性 $->$ NDQ(Nearly Decomposable Q-Value Learning)
- 不确定性:价值分解可以导致合作失调;在分布式执行的过程中也会导致行为浪费
- 因此可以引入智能体之间的交流
- NDQ:允许智能体间交流,但是需要最小化交流信道;智能体学习什么时候、向谁、交流什么内容
- W-QMIX
- Boosting Multi-agent Reinforcement Learning via Contextual Prompting(助教的私货)
- 上下文预测模型
- 啥也听不懂。。。
= MARL with Actor Critic
- Value-based的算法的核心是要估准每个状态-行为价值函数$Q_i (tau, a)$,再根据最大值 $Q_i (tau, a)$ 选择最优的行为。即 $Q_i (tau, a)$ 的准确性可以影响策略的优劣与收敛。大多数提升算法在解决连续空间、过高估计等问题。
- Policy-based方法建立输入和输出之间的可微参数模型,然后通过梯度优化搜索合适的参数,其输出为动作的分布而不是状态动作价值。多数提升算法在于解决MC采样带来的大方差问题以及奖励裁剪问题。
- AC-based方法中Actor前身是Policy Gradient,可以轻松地在连续空间内选择合适动作。但是Actor根据每个episode的累积奖励更新,所以效率比较慢。用一个value-based的算法作为Critic就可以使用TD方法实现单步更新,这其实可以看做是拿偏差换方差。
#info(caption: "介绍的四个算法")[
+ MADDPG
+ COMA
+ LICA
+ MAPPO
]
#let bx = $bold(x)$
== MADDPG
- 首先回顾 DDPG
#fig("/public/assets/AI/AI_RL/img-2024-07-11-09-45-21.png")
- 传统算法在多智能体环境中有以下几个困境
+ 环境的变化由所有智能体共同影响,对于单个智能体,环境是不稳定的,这违反了Q-learning所需的马尔可夫假设;
+ 由于环境的不稳定,策略不同时,状态转移矩阵也不同,因此不能直接将过去经验$(s, a_i, r_i, s')$进行回放;
+ 策略梯度方法中大方差的问题加剧。基于这样的局限性,使用集中训练分布式执行的方式(CTDE);以及假设 IGM 原则(假设较强,但没有别的好方法,而且它 work)
- 而使用 MADDPG
+ 学习到的策略可以分布式执行,即智能体根据自己的观察结果来决策;
+ 不需要假定环境动态系统是可微的,也不需要假设智能体之间的通讯方式有任何特性结构,即世界模型和通信模型都不要求是可微的;
+ 因为每个智能体最大化各自的累积奖励,MADDPG不仅可以应用于具有明确通信渠道的合作博弈,还可以应用于竞争博弈。
- MADDPG 是一个多智能体的基于 AC 算法的架构,为此先介绍 MAAC 架构
- 随机离散Multi-Agent的AC思路:
- $N$个智能体,策略参数分别为:$bold(th) = {t1, dots, tN}$,策略:$bold(pi) = {p1, dots, pn}$
- 针对智能体$i$的策略梯度公式:#mitex(`\nabla_{\theta_{i}}J(\theta_{i})=\mathbb{E}_{s\sim p}\pi_{,a\sim\pi_{\theta}}[\nabla_{\theta_{i}}l o g\pi_{i}(a_{i}|o_{i})Q_{i}^{\pi}(\bold{x},a_{1},\ldots a_{N})]`)
- 其中 $Q_i^pi (bx, a_1, dots, a_N)$ 是一个集中的动作价值函数,它将所有智能体的动作 $a_1, dots, a_N$,以及一些状态信息$bx$作为输入,输出每个智能体的动作价值;
- $bx$中包含所有智能体的观测信息$bx=(o_1, dots, 0_N)$,以及其他额外信息如通信信息等;
- 由于 $Q_i^pi$ 都是独立学习到,因此每个智能体可以有任何的奖励结构,包括合作或竞争以及混合奖励。
- MADDPG算法思路基于以下原理:
- 每个智能体都只输出一个确定性动作,而不是基于概率分布$pi$采样的随机变量。则:
#mitex(`P(s^{\prime}|a_{1},\ldots a_{N},\pi_{1},\ldots\pi_{N})=P(s^{\prime}|a_{1},\ldots a_{N})=P(s^{\prime}|a_{1},\ldots a_{N},\pi_{1}^{\prime},\ldots\pi_{N}^{\prime}),\qquad\pi_{i}^{\prime}\ne\pi_{i}`)
- 即不论策略是否相同,只要其产生的动作$a_i$相同,那么其状态转移可以视为不变。
- 如果已知各个智能体的动作,即便生成的策略不同,环境依旧是稳定的。
- 可以直接将DDPG的目标损失拓展到多智能体版本。
- 算法流程如下:
#fig("/public/assets/AI/AI_RL/img-2024-07-12-11-31-06.png")
== COMA
- 系统的联合动作空间(joint action space)将会随智能体数量指数性地扩大。因此,直接从这么大的联合动作空间中学习出一个比较好用的联合策略会非常困难。
- 考虑一种分布式策略,让每个智能体根据自己的观测,输出各自的动作,使得该分布式策略对全局性能来说是最优的。尤其在当每个智能体的观测是局部观测并且互相之间的通信受到限制时,这种分布式策略更是必须要考虑的。
- 假设CTDE,智能体执行动作的时候策略是分布式的,但是在学习的过程中,我们还是假设能够获取更多的全局信息。
- CTDE存在多智能体信用分配,COMA提出了一种方法用于学习非中心式的、部分可观测的多智能体协同的控制策略。
- COMA 可以认为是 MA 版本的 A2C,使用*反事实基线*实现 Advantage
#fig("/public/assets/AI/AI_RL/img-2024-07-11-10-11-13.png")
== LICA
- LICA-Critic
- 自适应熵正则化
- 听不懂思密达
== MAPPO
- 论文名《The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games》
- 也就是说 PPO 在合作多智能体中的效果出乎意料的好,本质上就是 PPO 的多智能体版本
- MAPPO:价值函数的输入
- CL:所有本地观测的串联(concatenation of local observations, CL)形成的全局状态。
- EP:采用了一个包含环境状态概况信息的环境提供的全局状态(Environment-Provided global state, EP)
- AS(EP+特定 agent 的观测):特定智能体的全局状态(Agent-Specific Global State, AS),它通过连接 EP 状态和 $o_i$ 为智能体 $i$ 创建全局状态。这为价值函数提供了对环境状态的更全面描述。(会冗余重复)
- FP:为了评估这种增加的维度对性能的影响,MAPPO通过移除 AS 状态中重复的特征,创建了一个特征剪枝的特定智能体全局状态(Featured-Pruned Agent-Specific Global State, FP)
- MAPPO:训练数据利用
- PPO 的一个重点特性是使用重要性采样(importance sampling)进行非策略(off-policy)校正,这允许重复使用样本数据。也就是将收集的大量样本分成小批次,并进行多个 epochs 的训练。
- 在单智能体连续控制领域,常见做法是将大量样本分成大约 32 或 64个小批次,并进行数十个训练周期。然而,在多智能体领域,我们发现当样本被过度重用时,MAPPO 的性能会降低(也就是不能重复使用次数太多)。
- 这可能是由于多智能体强化学习中的非平稳性(non-stationarity):减少每次更新的训练周期数可以限制智能体策略的变化,这可能有助于提高策略和价值学习的稳定性。
- MAPPO-Clip
- PPO 的另一个核心特征是利用剪切的重要性比例(clipped importance ratio)和价值损失(value loss),以防止策略和价值函数在迭代过程中发生剧烈变化。剪切的强度由超参数$ep$控制:较大的$ep$值允许对策略和价值函数进行更大的更新。
- 与训练周期数类似,假设策略和价值的剪切可以限制由于智能体策略在训练中的变化而引起的非平稳性。对于较小的$epsilon$,智能体的策略在每次更新中的变化可能会更小,因此可以在可能牺牲学习速度的情况下,提高整体学习的稳定性。 |
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compiler/ops-assoc.typ | typst | Apache License 2.0 | // Test operator associativity.
// Ref: false
---
// Math operators are left-associative.
#test(10 / 2 / 2 == (10 / 2) / 2, true)
#test(10 / 2 / 2 == 10 / (2 / 2), false)
#test(1 / 2 * 3, 1.5)
---
// Assignment is right-associative.
{
let x = 1
let y = 2
x = y = "ok"
test(x, none)
test(y, "ok")
}
|
https://github.com/Fr4nk1inCs/typreset | https://raw.githubusercontent.com/Fr4nk1inCs/typreset/master/src/bundles/utils.typ | typst | MIT License | #import "../utils/title.typ": make-title
#import "../utils/header.typ": make-header
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/foundations-15.typ | typst | Other | // Error: 7-12 expected identifier
#eval("let")
|
https://github.com/chaosarium/typst-templates | https://raw.githubusercontent.com/chaosarium/typst-templates/main/notebook/components/blocks.typ | typst | /* Blocks */
// Pls add or remove elements in this array first,
// if you want to add or remove the class of blocks
#let classes = (
"Definition",
"Lemma",
"Theorem",
"Corollary",
"Ponder",
"Example",
"Fact",
"Note",
"Strategy",
"Algorithm"
)
#let h1_marker = counter("h1")
#let h2_marker = counter("h2")
#let note_block(body, class: "Block", fill: rgb("#FFFFFF"), stroke: rgb("#000000"), identifier: "") = {
let block_counter = counter(class)
locate(loc => {
// Returns the serial number of the current block
// The format is just like "Definition 1.3.1"
let serial_num = (
h1_marker.at(loc).last(),
h2_marker.at(loc).last(),
block_counter.at(loc).last() + 1)
.map(str)
.join(".")
let serial_label = label(class + " " + serial_num)
let named_label = label(identifier)
rect(fill:fill,
width: 100%,
inset:8pt,
// radius: 4pt,
stroke:stroke,
[
#text(12pt, weight: "bold")[#class #serial_num #serial_label #named_label #block_counter.step()]
#body
])
})
}
#let def(body, id: "") = note_block(
body, class: "Definition", fill: rgb("#f0fdf4"), stroke: rgb("#16a34a"), identifier: id
)
#let ponder(body) = note_block(
body, class: "Ponder", fill: rgb("#f1f5f9"), stroke: rgb("#475569")
)
#let note(body) = note_block(
body, class: "Note", fill: rgb("#fffbeb"), stroke: rgb("#d97706")
)
#let ex(body) = note_block(
body, class: "Example", fill: rgb("#eff6ff"), stroke: rgb("#2563eb")
)
#let fact(body) = note_block(
body, class: "Fact", fill: rgb("#f5f3ff"), stroke: rgb("#7c3aed")
)
#let alg(body) = note_block(
body, class: "Algorithm", fill: rgb("#fef2f2"), stroke: rgb("#dc2626")
)
#let thm(body) = note_block(
body, class: "Theorem", fill: rgb("#fff7ed"), stroke: rgb("#ea580c")
)
#let corol(body) = note_block(
body, class: "Corollary", fill: rgb("#ecfeff"), stroke: rgb("#0891b2")
)
#let lemma(body) = note_block(
body, class: "Lemma", fill: rgb("#fefce8"), stroke: rgb("#ca8a04")
)
#let strategy(body) = note_block(
body, class: "Strategy", fill: rgb("#f0fdfa"), stroke: rgb("#0d9488")
) |
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas6/2_Utorok.typ | typst | #let V = (
"HV": (
("","Otčájannaja žitijá rádi","Któ mené ne pláčetsja, prestupívšaho zápoviď výšňaho, nevozderžánija rádi? Vo ád vselíchsja, vmísto rajá, sňídi sládkija viďínijem, smérť ischodátajstvujuščija, i stránen jejá rádi Bóžija slávy i žízni javíchsja: no prijimí mja kájuščasja Hóspodi, jáko mílostiv i čelovikoľúbec, velíkija rádi tvojejá mílosti."),
("","","Vížď mojú skórb i boľízň, i prehrišénij bezmírnoje mnóžestvo, duší mojejá ozloblénije, i úmnoje preľščénije: razumíj hlás otčájannaho i osuždénnaho. i dážď mí Hóspodi, dúch sokrušén, i smirénno sérdce, i podážď istóčnik sléz. i mnóhich prehrišénij proščénije, velíkija rádi tvojejá mílosti."),
("","","Bóže, choťáj vsím čelovíkom spastísja, prízri i uslýši molítvu mojú, i da ne mojá slézy otríneši, jáko sújetny: któ bo prijíde k tebí pláčja, i ne ábije spasén býv? Któ že li vozopí tépľi k tebí, i ne ábije uslýšan býsť? No o Vladýko! skór obritáješisja vo spasénije moľáščymsja tí vsím, jáko v mílosti nepobidím."),
("","","V putí zabludívšaho mjá žitijá, ne prézri predtéče Spásov: serdéčniji bo óči k tebí vozvoždú, i postávi na kámeni pokajánija stopý duší mojejá, pokaží púť práv chodíti mí, vvoďáščij vo vratá spasíteľnaja: i ne otríni stenánije skorbjáščaho sérdca mojehó, v roždénnych vsích preizjáščnyj."),
("","","Krestíteľu i predtéče Spásov, pomóščnik mí búdi blažénne, uhľíbšemu v timíniji pomyšlénij nečístych, rúku mí podážď prikosnúvšujusja verchú netľínnomu, ďilá tvoríti pokajánija ukripí dóblestvenňi, jéže propovídal jesí, i cárstvija vnútr býti, jéže pérvyj naučíl jesí, spodóbi mjá rabá tvojehó."),
("","","Íže máterneje neplódstvo, i ótčeje bezhlásije razrišívyj roždestvóm tvojím, bezplódstvije razriší bezčádnaho mojehó sérdca: vsjáko že bezslovésije duší otimí vskóri, Slóvu bo hlás sýj, vozhlašájušč pokajánije, jéže spodóbi mjá sijé soveršáti vsehdá, ot Bóha udalívšahosja ľínosti rádi, Christóv Krestíteľu."),
("Bohoródičen","","Čelovikoľúbija tvojehó pučínu, i blahoutróbija tvojehó hlubinú, i bláhosti ščedróty neizčétnyja pokaží prečístaja Ďívo, na mňí okajánňim. Utolí pážiť hrichóvnuju, cilomúdrije podávši, i sobľudí s dušéju i ťílo mojé neskvérno, jáže Spása róždšaja."),
),
"S": (
("","","Vo strášnoje prišéstvije tvojé Christé, da ne uslýšim, ne vím vás: upovánije bo Spáse, na ťá vozložíchom, ášče i tvojá poveľínija ne sochraníchom za nebrežénije náše, no poščadí dúšy náša, mólimsja."),
("","","Pokajánija ne sťažách, nižé páki sléz, sehó rádi moľú ťa Christé Bóže, préžde koncá obratíti, i dáti umilénije mňí, jáko da izbávľusja ot múki."),
("Múčeničen","","Strástotérpcy múčenicy nebésniji hráždane, na zemlí postradávše, mnóhi múki preterpíša: molítvami ích Hóspodi, i molénijem, vsích nás sochraní."),
("Bohoródičen","","Niktóže pritekájaj k tebí, posrámlen ot tebé ischódit, prečístaja Bohoródice Ďívo: no prósit blahodáti, i prijémlet darovánije k poléznomu prošéniju."),
),
)
#let P = (
"1": (
("","","Jáko po súchu pišešéstvovav Izráiľ, po bézdňi stopámi, honíteľa faraóna víďa potopľájema, Bóhu pobídnuju písň poím, vopijáše."),
("","","Preklonén mnóžestvom iskušénij, i ľútych ďijánij, výju dušévnuju i ťilésnuju prekloňáju tebí čístaja, i vopijú ti priľížno: tý mja isprávi."),
("","","O vseneporóčnaja otrokovíce, krípkaja vírnych pómošč, i upovánije christiján! tý mja svobodí plotskích slastéj že i strastéj, borjúščichsja so mnóju."),
("","","Svitovodíteľnica súščym vo ťmí: svít mýslennyj róždši prečístaja, prosvití mojú dúšu, i úm osvjatí, strastéj i prehrišénij ťmú rišášči."),
("","","Omračénnyja duší mojejá, navedéňmi bezmístnych pomyšlénij ťmú razruší, Bohoródice Vladýčice, svítom svjatých zápovidej Voploščénnaho iz tebé."),
),
"3": (
("","","Ňísť svját, jákože tý Hóspodi Bóže mój, voznesýj róh vírnych tvojích bláže, i utverdívyj nás na kámeni ispovídanija tvojehó."),
("","","Na ťá čístaja i prečístaja naďíjavsja, da ne otpadú jéže k tebí čájanija, jáko Máti čelovikoľúbca Bóha mílostiva, sitéj mjá vrážijich izbávi."),
("","","Maríje <NAME>, spasénija dvéri, jéjuže prójde jedín íže vsích tvoréc, pokajánija nýňi božéstvennyja dvéri otvérzi mí prečístaja."),
("","","Pristánišče búdi mí i chraníteľnica čístaja, ľútymi trevolnéniji strastéj oburevájemomu vsehdá v móri žitijá, jedína prisnoďívo."),
("","","<NAME>, prosvití dúšu mojú pomračénuju ľúťi mnóhimi hrichí, i strilóju lukávaho ujázvlenuju, i iznemóhšuju."),
),
"4": (
("","","Christós mojá síla, Bóh i Hospóď, čestnája cérkov Bohoľípno pojét vzyvájušči, ot smýsla čísta, o Hóspoďi prázdnujušči."),
("","","Kríposť mojá prečístaja, i pribížišče, i neoborímaja sťiná, i k Bóhu molítvennica súšči, víčnujuščaho plámene i hejénny svobodí mja."),
("","","Maríje vsečístaja, strastéj molvú mojehó umá, i iskušénij búrju razorí, jáže bezstrástija istóčnik róždši, Máti prisnoďívo."),
("","","Čístaja i vseneporóčnaja, jáže čistotý bývši prijátelišče vmístňi božéstvennaho vselénija, dušévnuju mojú skvérnu i nečistotú potrebí."),
("","","Jedínu prečístuju, jedínu neskvérnuju, moľú ťa otrokovíce, sládostnymi oskvernívšasja strasťmí, i okaľávša dúšu, tvojími molítvami očísti."),
),
"5": (
("","","Bóžijim svítom tvojím bláže, útreňujuščich tí dúšy ľubóviju ozarí, moľúsja: ťá víďiti Slóve Bóžij, ístinnaho Bóha, ot mráka hrichóvnaho vzyvájušča."),
("","","Oskvernén pómyslom i okaľán mnóhimi padéňmi, <NAME>ja, ťá moľú jedína neskvérnaja, uščédri i spasí mja chodátajstvom tvojím."),
("","","Božéstvennym sijánijem tvojím blahája, prosvití dúšu mojú omračénnuju sladosťmí, i k spasénija stezí naprávi, jedína Spása Christá róždšaja."),
("","","Hrichóvnyja mí plenícy rastórhni tvojím chodátajstvom Ďívo, i zastuplénijem, i rádosti božéstvennyja tišiný ispólni dúšu mojú okajánnuju, i ťmý izbávi."),
("","","Ťá jedínu božéstvennoje pribížišče nýňi sťažáv blahája, zovú ti, i vírno pripádaju: tý mňí zastuplénije, i pokróv spasénija búdi Vladýčice míra, i spasí mja."),
),
"6": (
("","","Žitéjskoje móre vozdvizájemoje zrjá napástej búreju, k tíchomu pristánišču tvojemú priték vopijú ti: vozvedí ot tlí živót mój, mnohomílostive."),
("","","Povínen sýj hrichámi, i ľúťi ujazvíchsja okajánnyj, k tebí Bohomáti mílostivij pribiháju moľásja: napadénija potrebí prehrišénij mojích."),
("","","Dvére blahodátnaja, otvérzšaja vírnym dvér nebésnuju, pokajánija dvér svítluju otvérzi mí Vladýčice, i vrát smértnych svobodí."),
("","","Strasťmí mja preklonéna ot soprotívnych prilóh, Máti Bóžija utverdí, jáže bezstrástija róždši istóčnik: k tebí bo pribihóch, okajánnyja mojejá duší uťíšiteľnice."),
("","","Prízri Vladýčice, na mjá smirénnaho, i nenadéždno spasí mja: tý bo jesí upovánije i pokróv mí, žízň i svít sérdcu mojemú Bohoródice i utverždénije."),
),
"S": (
("","","Bezpomóščnym kríposť, tý voístinnu presvjatája Ďívo Máti, otsjúdu smirénniji tobóju vozvyšájemsja, o tebí vysóci deržímsja: vsím tý jesí pokróv, i k Bóhu chodátaica."),
),
"7": (
("","","Rosodáteľnu úbo péšč soďíla ánhel prepodóbnym otrokóm, chaldéji že opaľájuščeje veľínije Bóžije mučíteľa uviščá vopíti: blahoslovén jesí Bóže otéc nášich."),
("","","Očiščénije ímamy ťá vsehdá k Bóhu, preneporóčnaja: ťímže isprosí izbáviti vsích prečístaja, támo mučénij strášnych, Bohoródicu voístinnu ispovídajuščich ťá."),
("","","Ľínostiju mjá oderžíma, vozdvíhni k ďílaniju prečístaja božéstvennych ďijánij, ukripľájušči mjá na vrahí prísno borjúščyja mjá ľúťi, i soprotívnymi pomyšléniji preľščájuščyja."),
("","","Ne ostávi mené Ďívo, pohibáti, ni popustí sňíď býti prísno žážduščemu mojú páhubu zmíju ľútomu: no podážď mí tvojú bohátuju mílosť."),
("","","Moľášči ne prestáj čelovikoľúbca Bóha nášeho vseneporóčnaja, jáko da priímem soveršénnoje proščénije čístaja: i ulučím nebésnych uhotóvannych bláh, i neotjémlemuju rádosť."),
),
"8": (
("","","Iz plámene prepodóbnym rósu istočíl jesí, i právednaho žértvu vodóju popalíl jesí: vsjá bo tvoríši Christé, tókmo jéže choťíti, ťá prevoznósim vo vsjá víki."),
("","","Jákože roždestvóm tvojím vsečístaja, blahích ďíl pokaží plodonósno neplódnoje sérdce mojé, Bóha umoľájušči."),
("","","Moľbú Ďívo Bóhu prinesí, dúšy náša spastí Bohoblahodátnaja, i strastéj prijátija izbávi nás, i ot bisóv zláho iskušénija."),
("","","K tvojemú pribiháju pokróvu vseneporóčnaja, i predstáteľnicu životá mojehó nýňi predlaháju, izbávi mjá otrokovíce sudá strášnaho, i ispytánija, i ohňá víčnaho."),
("","","Pokolebávšujusja zlóboju borcá dúšu mojú utverdí, Ďívo čístaja, i óhnennaho izmí mja mučénija, i kózlišč boľíznennyja části."),
),
"9": (
("","","Bóha čelovíkom ne vozmóžno víďiti, na nehóže ne smíjut číni ánheľstiji vziráti: tobóju že vsečístaja, javísja čelovíkom Slóvo voploščénno, jehóže veličájušče, s nebésnymi vóji ťá ublažájem."),
("","","Strastéj volnénije smuščájet mjá, i slasťmí pohružájet mjá, Ďívo preneporóčnaja, jáže kórmčiju Christá róždšaja: rúku mí pómošči prostrí i spasí mja, jedína spasénije víroju blažáščich ťá."),
("","","Čertóže i prestóle cárstvujuščaho, horó Bóžija, i hráde izbránnyj, i rajú sólnca óblače vsesvítlyj, prosvití dúšu mojú, óblak othoňájušči hrichóv mojích mnóhich Bohoblahodátnaja."),
("","","Čístaja Ďívo Bohoobrádovannaja, dvére svíta dvéri duší mojejá otvérzi, hrichá vchód zakľučájušči: da mjá ne priímet ruká ľstívaho, vedúšči ľúťi ko vsepáhubňij i strášňij múci."),
("","","Dušé, vozníkni, i pobdí v molítvach i vo vseblahích popečénijich unýnija són othoňájušči, bódruju zastúpnicu imúšči vsehdá, čístuju Máter Bóžiju vseščédruju."),
),
)
#let U = (
"S1": (
("","","Pomyšľáju déň strášnyj, i pláčusja ďijánij mojích lukávych, káko otviščáju bezsmértnomu carjú? Kójim že derznovénijem vozzrjú na sudijú, blúdnyj áz? Bláhoutróbnyj Ótče, Sýne jedinoródnyj, i Dúše svjatýj, pomíluj mjá."),
("","","Vo judóli plačévňij, na mísťi, iďíže položí, jehdá sjádeši mílostive, sotvoríti právednyj súd, ne obličí mojá sokrovénnaja, nižé posramí mené pred ánhely: no poščadí mja Bóže, i pomíluj mjá."),
("Bohoródičen","","Milosérdija dvéri otvérzi nám blahoslovénnaja Bohoródice Ďívo, naďíjuščijisja na ťá da ne pohíbnem, no da izbávimsja tobóju o bíd: tý bo jesí spasénije róda christijánskaho."),
),
"S2": (
("","","Dušé mojá, vskúju unyvájušči hrichú rabótaješi? I vskúju boľášči, ko vračú ne prichódiši? Vozníkni próčeje ot zól, jáže soďílala jesí, i vozopíj ko Spásu, hlahóľušči: nadéžde nenadéžnych, životé otčájannych Spáse, vozdvíhni, i spasí mja."),
("","","Múdrych ďív dáruj mí Hóspodi, bďínije, i duší mojejá sviščú prosvití jeléjem ščedrót tvojích, da písň ánheľskuju pojú ti: allilúia."),
("Múčeničen","","Strástotérpčeskij pódvih preterpívše svjatíji, i póčesti pobídy ot tebé prijáša: uprazdníša pomyšlénija bezzakónnych, i vosprijáša vincý netľínnyja. Ťích rádi Bóže, umolén býv, dáruj nám véliju mílosť."),
("Bohoródičen","","Upovánije míra, blahája Bohoródice Ďívo, tvojé i jedínoje strášnoje predstáteľstvo prósim: umilosérdisja na ľúdi bezpomóščnyja, molí mílostivaho Bóha, izbávitisja dušám nášym ot vsjákaho preščénija, jedína blahoslovénnaja."),
),
"S3": (
("","Vsjú otložívše","Životá jáko pokazál jesí putí ľúdem Joánne, vopijá: isprávite serdcá váša Hóspodevi: spasí mnohohríšnuju mojú dúšu, ko umiléniju privedí okamenénuju mýsľ, i izbávi búduščija múki tvojími molítvami, Predtéče Spásov."),
("","","Strastéj mjá búrja, i ľútoje trevolnénije prehrišénij, vo otčájanija hlubiný potopí Slóve: no prostrí mi deržávnuju tvojú desnícu, i spasí mja jákože Petrá, svjaščénnymi molítvami Predtéči tvojehó, iz hlubiný zloľútych bezzakónij mojích."),
("Bohoródičen","","Íže préžde vík ot Otcá bez mátere, róždšahosja Sýna i Slóva Bóžija, i v posľídňaja ľíta rodilá jesí voploščénna ot čístych krovéj tvojích, Bohorodíteľnice, kromí múža, jehóže molí, darováti nám hrichóv proščénije préžde koncá."),
),
"K": (
"P1": (
"1": (
("","","Pomóščnik i pokrovíteľ býsť mňí vo spasénije, séj mój Bóh, i proslávľu jehó, Bóh otcá mojehó, i voznesú jehó: slávno bo proslávisja."),
("","","Izbáviteľu mój Iisúse, jákože izbávil jesí mnóhich prehrišénij bludnícu, inohdá pokájavšujusja dóbri: moľúsja tí, i mené izbávi bezčíslennych zól mojích jáko mílostiv."),
("","","Plávaja v sújetňim pomyšléniji žitijá, Iisúse, ľútuju sijú pučínu, vo istoplénija vpadóch mnóhaja, ot níchže izbáviv spasí mja."),
("Múčeničen","","Dóblestvennyja stradáľcy, čuždáho potrebíteli, terpilívno postradávšyja, i vincý prijímšyja, ot Bóha pobídnyja, rádostno da počtím."),
("Múčeničen","","Vitíjstvujušče múdriji, derznovénijem Bóha Slóva vitíj zlých pobidíste: i vsják víd podjémše rán, veľmí proslávistesja."),
("Bohoródičen","","Javílasja jesí vratá životá, smérti vratá zatvórši roždestvóm tvojím čístaja: javílasja jesí zemľá izbránnaja, jéjuže voznesésja ot zemlí na nebesá čelovíčeskoje smišénije."),
),
"2": (
("","","Čúvstvennyj faraón potoplén býsť so vsevójinstvom, Izrájiľ že prošéd posreďí mórja, vopijáše: Hóspodevi Bóhu nášemu pojím, jáko proslávisja."),
("","","Ánhel božéstvennyj tvojé roždestvó, ánhele Bóžij, predvozviščájet Otcú: s nímže nás pomjaní, jéže v déň súdnyj obristí nám mílosť, svjatýj Predtéče."),
("","","Prozjabénije sýj krásnoje pustýnnoje predtéče Christóv, vo mňí neprestánno prozjabájuščuju ľínosť iz kórene istórhnuv, pokajánija mjá prinosíti plodý sotvorí."),
("","","Utróba bezčádna ťá, plód raždájet preslávno, blahoplódnaja serdcá, jáže préžde neplódnaja pokazávšaja, no víroju vopijú ti: Krestíteľu, neplódnaja mojá pomyšlénija istórhni."),
("Bohoródičen","","Léstiju neprestánno vráh lóvit mjá lukávyj, tohó mjá lovlénija vseneporóčnaja, ischití, i tvoríti Bohoródice, nastávi Vladýčňuju božéstvennuju vóľu."),
),
),
"P3": (
"1": (
("","","Utverdí Hóspodi, na kámeni zápovidej tvojích, podvíhšejesja sérdce mojé, jáko jedín svját jesí i Hospóď."),
("","","Mílostivnym tvojím ókom prízri na mjá, jehdá choščú pred tobóju predstáti, i sudítisja jedíne blahopreminíteľu Hóspodi."),
("","","Vozdychájušča mjá prijimí, jákože mytarjá iz hlubiný dušévnyja, i pokajánije mí dáruj Spáse, hrichá vsjákaho mjá izbavľájuščeje."),
("Múčeničen","","Tečénijem svjatíji presvjatých vášich krovéj, mérzskaja króv prestá, prinosímaja bisóm inohdá v trébiščach."),
("Múčeničen","","Dúchom presvjatým ukripľájemi svjatíji, nizverhóste kápišča pohíbeľnaja, vsích k víri utverždájušče."),
("Bohoródičen","","Začalá jesí presvjatája soderžáščaho vés mír: sehó rádi moľúsja tí, izbávi mjá vsjákaho soderžáščaho mučénija."),
),
"2": (
("","","Na tvérďim víry tvojejá kámeni pomyšlénije utverdív duší mojejá, utverdí Hóspodi: ťá bo ímamy bláže, pribížišče i utverždénije."),
("","","Obraščénije ot putí zablúždšemu dážď mí nýňi: i prostrí mí rúku blažénne Predtéče, v pučíňi ľútych vsehdá plávajušču."),
("","","Živú ľínostno, i posičénije približájetsja: tvojími molítvami vozniknovénije mí dážď prisnoslávnyj Predtéče, da ne jáko bezplóden otslán búdu vo óhň neuhasímyj."),
("","","Strášnyj déň pri dvérich, i ľútymi obložén jésm brémeňmi, ot níchže mjá oblehčí Hospódeň Krestíteľu, čístymi tvojími moľbámi."),
("Bohoródičen","","Prestól Bóžij javílasja jesí Bohoródice, na némže plótiju síde Christós, ot pérvaho padénija čelovíki vozdvíže, vo hlásich rádostnych pojúščyja ťá."),
),
),
"P4": (
"1": (
("","","Uslýša prorók prišéstvije tvojé Hóspodi, i ubojásja, jáko chóščeši ot Ďívy rodítisja, i čelovíkom javítisja, i hlahólaše: uslýšach slúch tvój i ubojáchsja: sláva síľi tvojéj Hóspodi."),
("","","Tóki sléz dážď mí izsušájuščyja strastéj mojích istóčniki, i hrichá vsjákaho timínija otmyvájuščyja ščédre, mnohomílostive, i uhašájuščija ohňá hejénskaho víčnujuščij plámeň neuhasímyj."),
("","","Neprestánno češú strúpy duší mojejá slastoľúbijem, i prebyváju neiscílen, v čúvstvo sám prijití ne choťá, któ búdu? Ičtó sotvorjú? Christé ščédryj, iscilív spasí mja."),
("Múčeničen","","Vód pohíbeľnych, i búri zlóbnyja okormlénijem božéstvennym múčenicy prisnoblažénniji, víroju preplývše pučínu nepostojánnuju, v bezbídnoje i nebúrnoje cárstvija nebésnaho pristánišče dospíste."),
("Múčeničen","","Prosvíščnicy blahočéstija, svitíla ístiny bývše, svítom pódvihov potrebíste ťmú bezbóžija mnohoboľíznennuju: čudés že zarjámi múčenicy strástéj mhlú razhoňájete."),
("Bohoródičen","","Sedmosvítlyj ťá svíščnik, óhň Bohorazúmija nosjášč otrokovíce, prorók drévle províďi, sviťášč vo ťmí nevíďinija bídstvujuščym. Ťímže vopijú ti vseneporóčnaja: prosvití mja, moľúsja."),
),
"2": (
("","","Uslýšach slúch tvój i ubojáchsja, razumích ďilá tvojá, i užasóchsja: sláva síľi tvojéj Hóspodi."),
("","","Uvračúj Predtéče, ujázvlenoje na putéch razbójničeskich sérdce mojé, moľúsja tí, ďíteľnoju božéstvennych tvojích molítv ciľbóju."),
("","","Nizloží Predtéče, íže ješčé živúščij v duší mojéj hrích: i vozniknovénije nýňi dáruj mí, k slastém popolzájuščemusja."),
("","","Pristánišče nám javísja oburevájemym v pučíňi žitéjskija búri, preloží vsích v tišinú preboháte."),
("Bohoródičen","","Da ne osúdiši mené Hóspodi, po ďilóm mojím, no mílostiv mí javísja vseščédryj: mólit ťá so Krestítelem róždšaja ťá."),
),
),
"P5": (
"1": (
("","","Ot nóšči útreňujušča, čelovikoľúbče, prosvití moľúsja, i nastávi i mené na poveľínija tvojá, i naučí mja Spáse, tvoríti vóľu tvojú."),
("","","Sé íže talánt tvój sokrývyj, Christé, ľinívyj ráb tvój, i uprazdnívyjsja lukávymi strastéj ďijániji, áz jésm: ťímže ne poslí mené vo óhň."),
("","","Tvój sýn býv blahodátiju, blahoutróbne Christé, porabótichsja vrahú, i ot tebé udalíchsja žív blúdno. Ťímže obratív mjá spasí."),
("Múčeničen","","Múčenicy stojáchu pred sudíščem, ščít víry obnosjášče. Ťímže strilámi léstnymi, ujazvíti ťích ľútyj otstúpnik ne vozmóže."),
("Múčeničen","","Umerščvľájemi ťilesý múčenicy, vsjá umertvíša kózni vrážija: i k žízni nestaríjuščejsja prijidóša v rádosti, vincý pobídy priímše."),
("Bohoródičen","","Vratá neprochodímaja, otvérzi mí vratá, moľúsja, pokajánija ístinnaho: i pokaží mi stezjú pokajánija čístaja, vsích nastávnice."),
),
"2": (
("","","K tebí útreňuju, milosérdija rádi sebé istoščívšemu neprelóžno, i do strastéj bezstrástno preklóňšemusja Slóve Bóžij, mír podážď mí pádšemu čelovikoľúbče."),
("","","Chrám býl jesí božéstvennyja Tróicy, i v chrámi tvojém svjatóm sém sóbranniji, víroju téploju mólim ťá Predtéče: izbávi nás ot iskušénij i skorbéj, vsechváľne."),
("","","Ustranívyjsja vsjákija dobroďíteli úm mój, tebé stránnym chodívša putém v žitijí blažénne, nýňi moľú: vsjáčeskich Bóhu mjá prisvój, lúčša tvorjá mja izjáščnymi pripodáňmi."),
("","","Pohruzívyj vo Jordánskich strujách, bézdnu milosérdija, proróče, tóki strastéj mojích molítvami tvojími izsuší nýňi, istóčniki mí sléz podavája."),
("Bohoródičen","","Preukrašénna božéstvennymi lučámi, krásnaho dobrótoju rodilá jesí Ďívo: tohó úbo prísno molí, spastí nás ot tlí, íže víroju i ľubóviju ťá slávjaščyja."),
),
),
"P6": (
"1": (
("","","Vozopích vsím sérdcem moím k ščédromu Bóhu, i uslýša mjá ot áda preispódňaho, i vozvedé ot tlí živót mój."),
("","","Ne pokaží mené bisóm obrádovanije v déň strášnyj, Christé Iisúse: da ne uslýšu tohdá hlása otsylájuščaho vo óhň hejénskij."),
("","","Pohruzí mja vo hlubiňí prehrišénij, íže právednych vráh: i k ščedrót tvojích pritekáju pučíňi, Iisúse, k pristánišču žízni nýňi naprávi mjá."),
("Múčeničen","","Boľíznej mnóhich rálom, obnóvľše, dušévnuju brazdú premúdriji božéstvennym símenem víry, mnohoplódnyj mučénija klás jávi plodonosíste."),
("Múčeničen","","Jázvami ujazvíste ujazvívšaho vás blahočestíviji orúžnicy. Ťímže prestávľšesja k žízni, strásti nýňi čelovíčeskija isciľájete."),
("Bohoródičen","","Chrám Bóhu javílasja jesí vseneporóčnaja, vóňže vselívsja svjáščénne, čelovíčeskoje suščestvó oboží, sotvoríl jésť vírnych chrámy sebí."),
),
"2": (
("","","Bézdna posľídňaja hrichóv obýde mjá, i volnénija ne ktomú terpjá, jáko Jóna Vladýci, vopijú ti: ot tlí mja vozvedí."),
("","","Ótrasľ proróče kórene prozjábl jesí, i serdcá neplódnaja vsjákaho blahorazúmija, blahoplódna v pochvalú Bóhu pokazál jesí."),
("","","Sokruší vskóri lukávaho nohámi nášimi, i isprávi stopý náša mýslennyja na púť míra, predstáteľstvy tvojími, Predtéče."),
("","","Ohradí, proróče, právdoju stádo tvojé, izbavľája nás vsjákaho navíta bisóvskaho, i víčnujuščija múki."),
("Bohoródičen","","Písň tebí, Ďívo, blahodarénija prinósim nýňi: tobóju čístaja, spaséni bývše ot kľátvy drévnija, i vsjáko blahoslovénije plodím."),
),
),
"P7": (
"1": (
("","","Sohrišíchom, bezzakónnovachom, neprávdovachom pred tobóju, nižé sobľudóchom, nižé sotvoríchom, jákože zapovídal jesí nám: no ne predážď nás do koncá, otcév Bóže."),
("","","Vziráju na mílosť tvojú bezmírnuju, bezmírno sohrišívyj, vím tvojé milosérdije, vím dolhoterpínije i nezlóbije: pokajánija mí dáruj plodý, ščédryj Christé, i spasí mja."),
("","","Uvračúj, ščédre, sérdca mojehó neiscíľnyja strásti, dáruj otsičénije dolhóv mojích, ťážkoje brémja oblehčí: da vo umiléniji ťá slávľu prísno otcév Bóha."),
("Múčeničen","","Vjážemi, ssicájemi, i sňidájemi ohném veščéstvennym, ľvóm predajémi na sňíď, i proťazájemi na kolesích, ne otverhóšasja tebé živáho Bóha nášeho, božéstvenniji i svjaščénniji stradáľcy."),
("Múčeničen","","Razďiľájemi býste ot ťilés, no ne razďiléni ot Bóha javístesja múčenicy, sovokuplénija rádi božéstvennaho, sebé sojedinívšaho nám netľínno. Jehóže prísno molíte, izbávitisja nám vsjákija núždy."),
("Bohoródičen","","Prozjablá jesí bez símene, jehóže rodí Otéc netľínno, prebylá jesí po roždeství Ďíva, jákože i préžde roždestvá. Ťímže ublážájema jesí, i proslavľájema prečístaja neprestánno, jáko Máti súšči Bóžija."),
),
"2": (
("","","Ótrocy vo Vavilóňi péščnaho plámene ne ubojášasja, no posreďí plámene vvérženi, orošájemi pojáchu: blahoslovén jesí Hóspodi Bóže otéc nášich."),
("","","Hlás sýj Slóva, nýňi hlásy náša prijimí Krestíteľu: i strastéj i bíd, i mnóhich obstojánij, i víčnaho mučénija izbávi ľúdi tvojá."),
("","","Rukóju pokazúješi proróče, áhnca Bóžija, míra vzémľuščaho hrichí: jehóže prísno molí, otjáti mojá sohrišénija ľútaja, i ľíty uderžánnaja, i životá spodóbiti mjá."),
("","","Dušé mojá, potščísja, i vozopíj, omračénije ostávľši bezslovésnych ďijánij: uščédri mjá Iisúse, moľbámi krestíteľa, i ischití mja timínija ďíl mojích."),
("Bohoródičen","","Jemúže predstoját s trépetom nebésniji číni, tohó rodilá jesí čístaja, sojedinívšahosja čelovíkom za bláhosť: jehóže priľížno molí uščédriti rabý tvojá."),
),
),
"P8": (
"1": (
("","","Jehóže vójinstva nebésnaja slávjat, i trepéščut Cheruvími i Serafími, vsjáko dychánije i tvár, pójte, blahoslovíte, i prevoznosíte vo vsjá víki."),
("","","Vziráju na velíkuju mílosť ščedrót tvojích Christé, jákože Davíd, sohrišív páče ónaho, i zovú so ónem: jedíne mílostive, pomíluj mjá vskóri."),
("","","Konéc bláh býti mí moľúsja, položíti že lukávym ďijánijem kohdá konéc, ne usérdstvuju, ožestočénnoje imíja mojé sérdce: uščédri mjá Bóžij Slóve."),
("Múčeničen","","Jáko izbránnyja i neporóčnyja žértvy, požéršemusja nás rádi, jedinoródnomu Slóvu, vóleju prinesóstesja, žértvy vsjá upražňájušče démonskija, strástonóscy."),
("Múčeničen","","Žílam sičénija, zubóm iskorenénija, otjátije že rukám, razdroblénije udóm, i vsjákoje tomlénije ínoje preterpíste dóblestvenne múčenicy, pojúšče Christá jedínaho podvihopolóžnika."),
("Bohoródičen","","Nóva nám mladénca rodilá jesí, vétchaho déňmi, nóvyja na zemlí stezí pokazújuščaho, i obetšávšeje jestestvó obnovľájušča, beznevístnaja blahoslovénnaja."),
),
"2": (
("","","Za zakóny otéčeskija blažénniji vo Vavilóňi júnoši predbídstvujušče, carjújuščaho opleváša poveľínije bezúmnoje, i sovokúpleni ímže ne svaríšasja ohném, deržávstvujuščemu dostójnuju vospiváchu písň: Hóspoda pójte ďilá, i prevoznosíte vo vsjá víki."),
("","","Nad Slóvo kreščájemo, vo víďi holubíňi, nizchoďášča víďil jesí Dúcha svjatáho, i hlás Otéč slýšati spodóbilsja jesí blažénne: séj jésť Sýn mój soprestóľnyj, jehóže pojét vsjá tvár: Hóspoda pójte ďilá, i prevoznosíte vo vsjá víki."),
("","","Ohném proróče, tvojích molítv chvrástnyja strásti smýsla mojehó popalív, i uhašénnyj sérdca mojehó svíščnik vozžzí páki: jáko da jásno smotrjája, vospiváju sozdávšaho svít poveľínij: Hóspoda pójte ďilá, i prevoznosíte vo vsjá víki."),
("","","Sokrývyj ráb talánt, jehóže v ďílanije ot tebé prijách, áz jésm okajánnyj, i čtó sotvorjú, jehdá na súd priídeši, kojehóždo ďílo isťazúja? No poščadí mja moľbámi predtéči tvojehó, i ne vo óhň poslí vopijúšča: Hóspoda vospivájte ďilá, i prevoznosíte jehó vo víki."),
("Bohoródičen","","Sobľudí mój smýsl vo smiréniji otrokovíce Bohoblahodátnaja, jáže roždestvóm tvojím sokrušívšaja voznošénije démonskoje, i vozdvíhni mjá ot hnójišča strastéj, i álčušča mjá nasýti blahodáti tvojejá, pojúšča: Hóspoda pójte ďilá, i prevoznosíte vo vsjá víki."),
),
),
"P9": (
"1": (
("","","Bezsímennaho začátija roždestvó neskazánnoje, Mátere bezmúžnyja netľínen plód: Bóžije bo roždénije obnovľájet jestestvá. Ťímže ťá vsí ródi jáko Bohonevístnuju Máter, pravoslávno veličájem."),
("","","Iisúse čelovikoľúbče, jedíne némošč nášu vídyj: v sijú bo obléklsja jesí milosérdija rádi, choťá sijú očístiti: ťímže skvérny lukávyja i hnojénija zól mojích očísti, i spasí mja."),
("","","Jáko bludníca slézy prinošú ti čelovikoľúbče: jáko mytár steňá vzyváju tí: očísti, i spasí mja. jákože chananéja vopijú: pomíluj mjá, jákože Petrá pokájavšasja, proščénija spodóbi."),
("Múčeničen","","Plótiju splétšesja bezplótnomu mirodéržcu, pódvihami stradánij tohó nizložíste, i pobídy vincý prijáste dostójno. Ťímže molítesja priľížno o vsích, víroju voschvaľájuščich vás, svjatíji."),
("Múčeničen","","Osvjátíl jesí Hóspodi, zémľu svjatými krovmí svjatých tvojích, i ťích vsesvjáte dúchi, duchovóm síl svjatých sovokupíl jesí: vsehdá že sími osvjaščáješi víroju ístinnoju tebé osvjaščájuščyja."),
("Bohoródičen","","Hlás tí prinósim archánhelov vsečístaja, blahoslovénnaja, rádujsja vmistívšaja Bóha nevmistímaho: rádujsja kľátvy razrišénije, i blahoslovénija vvedénije: rádujsja, jedína rájskuju dvér otvérzšaja."),
),
"2": (
("","","Stránstvija Vladýčňa, i bezsmértnyja trapézy na hórňim mísťi, vysókimi umý, vírniji prijidíte nasladímsja, vozšédša slóva, ot slóva naučívšesja, jehóže veličájem."),
("","","Uvračúj mój úm, slastoľúbijem žitéjskim ľúťi ujazvlényj, i utolí zíľňi vozmuščájuščuju mjá búrju, i pokaží mi pokajánija putí právyja, Hospódeň Predtéče."),
("","","Víďin býl jesí posreďí stojá vétchaho že i nóvaho, óvomu úbo Proróče, prestáti tvorjá, óvaho že svít javľája. Ímže chodíti spíšno nastávi nás, sóvistiju božéstvennoju, jáko da ťmý izbávimsja víčnujuščija."),
("","","Sočetálsja jesí s vójinstvy nebésnymi Bohomúdre, s nímiže Christá molí, súščich na zemlí nás spastí počitájuščich ťá v čestňím tvojém sém chrámi, krestíteľu Joánne, Hospódeň predtéče."),
("","","Déň ispólň járosti, déň ťmý jésť, ďilá imúščym témnaja, súd strášnyj, krestíteľu Christóv i predtéče: molítvami tvojími tohdá izbávi osuždénija vsjákaho, tebé počitájuščich."),
("Bohoródičen","","Javílasja jesí cheruvím svjaťíjši Ďívo, jáko Bóha róždši presvjatáho, vsích nás osvjátí, vo hlásich svjatých víroju, v noščí i vo dní tebé osvjaščájuščich."),
),
),
),
"CH": (
("","","Náha mjá obrít dobroďítelej vráh, strilóju hrichóvnoju ujazví: no tý jáko vráč dúš i ťilés, jázvy duší mojejá iscilí, i pomíluj mjá."),
("","","Sérdca mojehó strúpy, ot mnóhich sohrišénij vozrástšyja mí iscilí Spáse, jáko dúš i ťilés vráč: podajá prosjáščym prehrišénij proščénije, prísno dáruj mí slézy pokajánija, dajá mi razrišénije dolhóv Hóspodi, i pomíluj mjá."),
("Múčeničen","","Hóspodi, ášče ne býchom svjatýja tvojá imíli molítvenniki, i blahostýňu tvojú mílujuščuju nás, káko smíli býchom Spáse, píti ťá, jehóže slavoslóvjat neprestánno ánheli? Serdcevídče, poščadí dúšy náša."),
("Bohoródičen","","Velíkich darovánij čístaja Ďívo Bohomáti, tý spodóbilasja jesí, jáko rodilá jesí plótiju jedínaho ot Tróicy, Christá žiznodávca, vo spasénije dúš nášich."),
),
)
#let L = (
"B": (
("","","Pomjaní mja Bóže Spáse mój, jehdá priídeši vo cárstviji tvojém: i spasí mja, jáko jedín čelovikoľúbec."),
("","","Íže Petróvo prijémyj rydánije, prijimí i mojé, Christé, pokajánije: i dáruj mí sohrišénij proščénije."),
("","","Propovídavyj pokajánije čelovíkom, Hospódeň Krestíteľu i Predtéče, pokájatisja mí ot duší, molísja."),
("","","Trevolnénija preterpívše stradánij, strastotérpcy, čelovíkov nedúhi nýňi isciľájete: ťímže blažími jesté."),
("","","Íže proróki proslavľájemyj Bóh v Tróici, prósťij že i neslijánňij, Predtéči moľbámi spasí mja."),
("","","Predstáteľstvo krípkoje súščym v skórbech, predstáni mí žitéjskim strastém priobščájuščemusja, i spasí mja, moľúsja."),
),
)
|
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Analyse_Chapitre_2024.typ | typst | #import "@preview/bubble:0.1.0": *
#import "@preview/fletcher:0.4.3" as fletcher: diagram, node, edge
#import "@preview/cetz:0.2.2": canvas, draw, tree
#import "@preview/cheq:0.1.0": checklist
#import "@preview/typpuccino:0.1.0": macchiato
#import "@preview/wordometer:0.1.1": *
#import "@preview/tablem:0.1.0": tablem
#show: bubble.with(
title: "Analyse_Chapitre_2024",
subtitle: "06/09/2024",
author: "<NAME>",
affiliation: "EPFL",
year: "2024/2025",
class: "Génie Mécanique",
logo: image("JOJO_magazine_Spring_2022_cover-min-modified.png"),
)
#set page(footer: context [
#set text(8pt)
#set align(center)
#text("page "+ counter(page).display())
]
)
#set heading(numbering: "1.1")
#show: checklist.with(fill: luma(95%), stroke: blue, radius: .2em)
= Chapitres
== Pas commencé
- Compléments
- Développements limités
- Séries
- Séries entières
- Suites récurrente ( à vérifier )
== En cours
- Intégrale ( Liste des primitives et Changement de variable )
- Suites réelles ( Comportements et théorème de Bolzano-Weierstrass )
== Fait
- Calcul Differentiel
- Fonctions Continues
- Fontions Réelles
- Integrale
- Integrales Généralisées
- Limite de fonction
- Nombres Complexes
- Nombres réels
== Révisé
|
|
https://github.com/floriandejonckheere/utu-thesis | https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/chapters/05-modular-monolith.typ | typst | #import "@preview/acrostiche:0.3.1": *
#import "/helpers.typ": *
= Modular monolith architecture <modularmonolith>
In this chapter, we discuss the modular monolith architecture.
We start by defining the architectural style, and then continue by discussing the advantages and drawbacks of the architecture.
We answer the following research question:
#link(<research_question_1>)[*Research Question 1*]: What is the modular monolith architecture, and what sets it apart from monolith and microservices architectures?
The motivation behind the research question is discussed in @introduction.
== Definition
While a traditional monolith architecture is a single-tiered software architecture that tightly couples the three layers (presentation, business logic, and data access), the modular monolith architecture focuses on separation of concerns by partitioning the application into modules based on their functionality @kucukoglu_2022.
The three layers are present in each module, but are not directly accessible from outside of the module boundary.
Instead, modules expose a well-defined interface that describes the capabilities and restrictions of the module.
Hence, the modules of a modular monolith are loosely coupled.
The architecture emphasizes interchangeability and potential reuse of modules, while maintaining an explicit interface between them @su_li_2024.
Focusing on business domains rather than technical capabilities improves the organization of the code, and increases comprehensibility.
@modular_monolith_architecture illustrates the difference between a traditional monolith, a modular monolith, and a microservices architecture.
#figure(
include("/figures/05-modular-monolith/modular-monolith.typ"),
caption: [Modular monolith architecture @tsechelidis_etal_2023]
) <modular_monolith_architecture>
While a traditional monolith architecture is not a bad choice for smaller applications, it becomes difficult to develop new and maintain existing functionality as the application grows.
Larger applications are likely to turn into a big ball of mud, where the code is tangled and difficult to understand.
A big ball of mud, a term coined by #cite_full(<foote_yoder_1997>) in #cite(<foote_yoder_1997>, form: "year"), is a software system that lacks a perceivable architecture.
Modular monolith architecture can also be used as a stepping stone towards a microservices architecture.
Once the application is modularized and the interfaces are well-defined and stable, individual modules can be extracted and turned into external microservices.
If the agreed upon interface is respected, the external microservice can be swapped out entirely by another implementation without affecting the rest of the application.
When all modules have been extracted from the monolith, the application has effectively been transformed into a microservices application.
#grid(
columns: (auto, auto),
gutter: 1em,
[
#figure(
include("/figures/05-modular-monolith/distributedness.typ"),
caption: [Physical and logical architectures @kucukoglu_2022]
) <distributedness>
],
[
Contrary to microservices applications, modular monolith applications are built as a single deployable unit.
The modules of the software system are separated logically (not physically), and are deployed together.
Horizontal scaling of a modular monolith architecture is more difficult than a microservices architecture.
@distributedness describes the software architectures in two dimensions: logical and physical.
]
)
The traditional monolith is both logically and physically monolithic, while a distributed monolith is only logically monolithic.
A microservices architecture is physically distributed, and logically modular.
The modular monolith architecture is logically modular, as the application is divided into modules, but physically monolithic, as the modules are deployed together.
#pagebreak()
#cite_full(<su_li_2024>) identified six characteristics of modular monolith architecture:
+ *Segregation* of modules: each module is independent and includes all three application layers. Modules are autonomously developed, tested, and deployed.
+ *Modularity*: modules have high internal cohesion and low external coupling. Communication between modules is done using well-defined interfaces, preferably asynchronously.
+ *Unified database*: the database schema is shared by all modules, in contrast with microservices where each microservice has its own database and schema.
+ *Monolith deployment*: the application is deployed as a single unit, although modules can be distributed across multiple hosts.
+ *Unified application process*: the application functions as a singular process, scaling uniformly depending on the requirements.
+ *Maintainability and scalability*: the architecture can efficiently manage increasing complexity, and facilitates growth.
In summary, the modular monolith architecture aims to find a middle ground between the monolith and microservices architectures by reaping the benefits of both approaches.
While opting for a modular monolith architecture already improves flexibility and comprehensibility, it can also be used as a step in the migration towards a microservices architecture.
== Advantages and drawbacks
In the #cite(<brown_2013>, form: "year") book _Software architecture for developers_, #cite_full(<brown_2013>) defined architectural drivers as a set of requirements that have significant influence over software architecture.
The author argues that architectural drivers are the most important requirements that shape the architecture of a software system.
#cite_full(<grzybek_2019_architectural_drivers>) classified architectural drivers in four categories: functional requirements, quality attributes, technical, and business constraints.
Any realized software architecture is a trade-off between several architectural drivers.
Subsequently, the choice of architecture depends on the context of the application it is being used in.
We attempted to qualitatively compare the architectural drivers of modular monolith architecture with traditional monolith and microservices architectures.
@modular_monolith_comparison provides an overview of the comparison.
A star rating system is used to indicate the performance of each architecture with respect to the architectural driver, with one star indicating the lowest performance, and three stars indicating the highest performance.
The ratings are based on several sources, including #cite_full(<grzybek_2019_architectural_drivers>), #cite_full(<fowler_2015>), #cite_full(<kodja_2023>), #cite_full(<kucukoglu_2022>), and #cite_full(<su_li_2024>).
#let star = (i) => range(1, (i + 1)).map(j => sym.star.filled).join()
#figure(
table(
columns: (auto, auto, auto, auto),
inset: 10pt,
stroke: (x: none),
align: (left, center, center, center),
[*Architectural driver*], [*Monolith*], [*Modular monolith*], [*Microservices*],
[Complexity], [#star(3)], [#star(2)], [#star(1)],
[Structure], [#star(2)], [#star(3)], [#star(1)],
[Testing], [#star(1)], [#star(2)], [#star(2)],
[Productivity], [#star(3)], [#star(2)], [#star(1)],
[Performance], [#star(1)], [#star(2)], [#star(3)],
[Fault tolerance], [#star(1)], [#star(3)], [#star(3)],
),
caption: [Comparison of modular monolith architecture]
) <modular_monolith_comparison>
==== Complexity
The complexity of a software system is related to the number of modules and their interactions @grzybek_2019_architectural_drivers.
In a monolith architecture, there is only one module (the monolith application itself), and no interactions.
This makes the architecture simple, and easy to deploy.
Microservices architecture improves the coupling by separating modules into independent microservices, but introduces complexity due to the communication between the microservices, and the additional tools and infrastructure required to manage them.
The modular monolith architecture uses the decoupled approach of microservices, but keeps the complexity down by bundling the modules together in a single deployable unit.
Modules in a modular monolith architecture have two ways of communicating: externally through #acr("API") calls, and internally through abstracted interfaces @su_li_2024.
The external #acr("API") calls can introduce additional complexity, although some tools (e.g. ServiceWeaver) hide this complexity behind abstractions of internal communication.
==== Structure
The source code of monolith and modular monolith applications is stored in the same repository.
This makes enacting changes to the codebase easier, as developers can modify multiple modules or layers at the same time.
In contract, microservices are usually stored in separate repositories, due to the independent nature of the services @kucukoglu_2022.
Monolith architecture makes modification across functional domains possible as well, although it introduces fragility due to the tight coupling of the code @su_li_2024.
In #cite(<conway_1968>, form: "year"), #cite_author(<conway_1968>) observed that the structure of a software system is often influenced by the communication structure of the organization that develops it @conway_1968.
The modular nature of modular monolith and microservices architectures makes it easier to align the architecture with the organization structure, while the inherent structure of a monolith architecture does not provide this ability.
==== Testing
Testing a monolith application can be difficult and tedious, as code is tightly coupled and changes in one module can affect other modules @su_li_2024.
Functionality cannot be tested independently, but must be tested in the context of the entire application.
In modular monolith and microservices architectures, functionality is separated into modules or microservices, which can be tested in isolation.
To ensure that the application works as expected, integration tests can be performed that test the integration between the modules or microservices.
==== Productivity
When designing a software system from scratch, a monolith architecture is often the most productive choice @fowler_2015.
Developers can focus on the business logic of the application, without having to worry about the underlying infrastructure or deployment model.
Using microservices architecture incurs additional investment of time and resources, as developers must define the interfaces between the microservices, and manage the communication.
Modular monolith architecture compromises between the two, by allowing developers to focus on the business logic first, while still providing the benefits of a distributed architecture.
The _Monolith First_ approach proposed by #cite_full(<fowler_2015>) suggests initiating new software projects with a monolith architecture, and only breaking out into microservices when the monolith architecture is showing its limitations.
==== Performance
Traditional monolith applications offer better performance than distributed architectures, due to the lower overhead incurred when processing requests @grzybek_2019_architectural_drivers.
However, monolith applications can only handle a limited number of requests until the application becomes slow and unresponsive.
Distributed architectures, such as microservices and modular monoliths, offer a solution for this problem by allowing the application to scale horizontally, at the cost of increased complexity and overhead.
Care must be taken when designing the distributed application to ensure that the transactional context of a request is not spread across multiple modules or microservices, as this can lead to performance issues @nunes_etal_2019.
Additionally, a microservices architecture is truly distributed in that every microservice is bundled with its own external dependencies, such as databases and caches.
This allows for better performance, as the dependencies can be scaled alongside the microservices @kodja_2023.
==== Fault tolerance
The impact of a failure in a monolith application is greater than in modular architectures, as the entire application is affected @grzybek_2019_architectural_drivers.
The risk of a system failure can be mitigated by replicating the application, but this comes with a significant cost.
Distributed architectures are more tolerant to individual failures, as the failure of one service does not affect the entire application, and can be resolved quicker @grzybek_2019_primer.
Communication between modules or microservices is done over a network, where failures and delays are expected.
Hence, distributed architectures fault-tolerant by design, and can handle unexpected failures more gracefully than monolith applications.
In summary, the modular monolith architecture strikes a balance between the monolith and microservices architectures.
It offers the simplicity of a monolith architecture, while providing the flexibility and scalability of a distributed architecture.
In particular, the modular monolith architecture is well-suited for smaller developments teams where the domain complexity of the application is manageable @kodja_2023.
On the other hand, when the requirements for scaling become more stringent, or the use of multiple, heterogeneous technologies is required, a microservices architecture might be a better choice @kodja_2023.
== Modularization
Modularization of monolith applications is not a new concept.
In #cite(<parnas_1972>, form: "year"), #cite_full(<parnas_1972>) stated that modularization is a mechanism that can improve the flexibility and comprehensibility of software systems.
The author argued that modularization separates the system into smaller and more manageable parts, which can be developed concurrently by multiple teams.
The process of modularization involves identifying the potential modules or services of the software system, defining the interfaces between them, and evaluating the impact of the modularization on the system.
Modularization techniques can be classified into three categories @abdellatif_etal_2021:
- *Top-down (forward) engineering*: starting from the domain artifacts of the application (e.g. requirements, use cases), and deriving the modules from these artifacts
- *Bottom-up (reverse) engineering*: mining functionalities from the existing system (source code, documentation) and developing the modules based on this structure
- *Hybrid/reuse approach*: mapping domain artifacts onto existing functionalities in the system, and identifying the modules based on the mapping
Top-down approaches are more suitable for new projects, where the requirements are known in advance, and little or no existing code is available.
For migration of legacy applications to a modular architecture, bottom-up approaches are more suitable, as they can leverage the existing codebase and development artifacts.
#cite_full(<abdellatif_etal_2021>) identified three main steps in the process of modularization of monolith applications:
+ *Collection*: extraction of useful information from the monolith application
+ *Decomposition*: partitioning the application into individual modules or microservices
+ *Analysis*: evaluating the impact of the modularization on the system
These steps can be done manually by the software architect, or automatically using tools that collect information about the application, and decompose it into a modular application.
Manual collection of data is feasible when the application is small, but becomes unrealistic as the application grows.
Automated tools can also help to extract implicit information from the application, such as the relationship between contributors and file changes, or the frequency of changes to a file.
Automated decomposition tools can help to identify the modules of the application, although for the most part they cannot rely on the knowledge that the software architect has about the application, rendering them less effective than manual decomposition.
The process of identifying modules or microservices for a modular monolith application is similar to the process of identifying them for a microservices architecture @tsechelidis_etal_2023.
However, the criteria for identifying modules are different, as the modules of a modular monolith application are not deployed as separate microservices.
Given the inherent complexity of manual modularization, we see a clear need for the development and improvement of (semi-)automated tools to assist in the modularization of monolith applications.
In particular, the information present in the codebase of the application is a prime candidate for automatic extraction and decomposition, as it contains valuable information about the structure and dependencies of the application.
== Conclusion
In this chapter, we discussed the modular monolith architecture.
We answered the following research question:
#link(<research_question_1>)[*Research Question 1*]: What is the modular monolith architecture, and what sets it apart from monolith and microservices architectures?
The modular monolith architecture arose as a response to the limitations of traditional monolith and microservices architectures.
It combines the simplicity of the monolith architecture with the flexibility and scalability of a microservices architecture.
Modular monolith applications retain a single codebase and deployment unit, but are segregated into loosely coupled modules that communicate through well-defined interfaces.
The software architecture allows small teams to develop applications quickly and efficiently, and allows the application to break out into microservices whenever the need arises.
|
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/05-features/lang-script.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/components.typ": note
#import "/template/lang.typ": russian
#import "/lib/glossary.typ": tr
#show: web-page-template
// ## Scripts and languages
== 语言和#tr[script]
// Lookups apply to particular combinations of *language* and *script*. You can, for example, substitute generic glyph forms for localised forms which are more appropriate in certain linguistic contexts: for example, the Serbian form of the letter be (б) is expected to look different from the Russian form. Both forms can be stored in the same font, and the choice of appropriate glyph made on the basis of the language of the text.
#tr[lookup]会应用于特定的*语言#tr[script]*二元组。比如你可以在某些语言环境下,将一些#tr[glyph]从通用样式替换为当地样式。具体来说,以字母 be(#russian[б])为例,它在塞尔维亚语中和在俄语中的样式就略有不同。这两种样式可以同时储存在字体中,然后根据文本的语言来选择使用合适的那一个。<position:serbian-letter-be>
// Again, so far we've handled this implicitly - any rules which are not tagged explicitly with the language and script combination that they refer to are considered to apply to the "default" script and "default" language. The script and language are described using four-character codes called "tags"; for example, the script tag for Malayalam is `mlm2`. You can find the list of [script tags](https://docs.microsoft.com/en-gb/typography/opentype/spec/scripttags) and [language tags](https://docs.microsoft.com/en-gb/typography/opentype/spec/languagetags) in the OpenType specification. The shaper is told, by the layout application, what language and script are being used by the input run of text. (It may also try guessing the script based on the Unicode characters in use.)
但之前我们也忽略了这个功能,使用了默认的处理方式。也就是没有被显式标记属于哪个语言#tr[script]二元组的规则统一都被视为属于“默认”语言和“默认”#tr[scripts]。这个二元组中的语言和#tr[scripts]都使用四个#tr[character]的代码表示,它们被称为“标签”。比如,马拉雅拉姆文的标签是“mlm2”。你可以在OpenType规范中的语言标签列表#[@Microsoft.OpenTypeLanguage]和#tr[scripts]标签列表#[@Microsoft.OpenTypeScript]中找到所有的可用标签。排版程序会告诉#tr[shaper]当前的输入文本属于哪种语言和#tr[script]。(它也可能会尝试根据文本包含的Unicode#tr[character]来进行猜测。)
// Inside the font, the GSUB and GPOS tables are arranged *first* by script, *then* by language, and finally by feature. But that's a confusing way for font designers to work, so AFDKO syntax allows you to do things the other way around: define your features and write script- and language-specific code inside them.
在字体内部,`GSUB`和`GPOS`表首先被按照#tr[scripts]分组,然后再按照语言分,最后才是各个特性。但这样的组织结构对于字体设计师来说比较难处理,所以 AFDKO 的语法允许使用另一种方式。我们可以在特性内部定义专门适用于某种#tr[script]和语言的代码块。
// To make this work, however, you have to define your "language systems" at the start of the feature file. For example, here is a font which will have support for Arabic and Urdu, as well as Turkish and "default" (non-language-specific) handling of the Latin script, non-language-specific handling of Arabic *script* (for instance, if the font is used for documents written in Persian; "Arabic" in this case includes Persian letters), and it will also have some rules that apply generally:
但为了使用这个功能,你需要在特性文件的开头定义你自己的“语言系统”。以下是一个在语言上支持阿拉伯语、乌尔都语、土耳其语以及“默认”语(未指定语言),在#tr[scripts]上支持拉丁文,未指定语言的阿拉伯文(阿拉伯文也被用于书写其他多种语言,比如波斯语,在这种情况下阿拉伯文也包括波斯字母),另外还包含一些通用规则的字体代码:
```fea
# languagesystem <文字标签> <语言标签>;
languagesystem DFLT dflt;
languagesystem arab dflt;
languagesystem arab ARA;
languagesystem arab URD;
languagesystem latn dflt;
languagesystem latn TRK;
```
// Once we have declared what systems we're going to work with, we can specify that particular lookups apply to particular language systems. So for instance, the Urdu digits four, five and seven have a different form to the Arabic digits. If our font is to support both Arabic and Urdu, we should make sure to substitute the expected forms of the digits when the input text is in Urdu.
一旦定义好了我们计划支持的语言#tr[script]系统,就可以为每个#tr[lookup]指明它适用于其中哪一个了。比如,乌尔都语中的数字四、五、七和阿拉伯数字不同。如果字体希望同时支持它们,就需要在输入文本是乌尔都语时进行适当的#tr[substitution]来显示符合预期的数字#tr[glyph]样式。
// We'll do this using a `locl` (localisation) feature, which only applies in the case of Urdu:
我们使用一个只在乌尔都语条件下激活的 `locl`(localisation,本地化)特性来实现这个功能:
```fea
feature locl {
script arab;
language URD;
# 直到下一个 script/language 语句为止,所有查询组都只会在
# 环境为使用阿拉伯文书写的乌尔都语时被应用
lookup urdu_digits {
sub four-ar by four-ar.urd;
sub five-ar by five-ar.urd;
sub seven-ar by seven-ar.urd;
} urdu_digits;
} locl;
```
// As mentioned above, any lookups which appear *before* the first `script` keyword in a setting are considered to apply to all scripts and languages. If you want to specify that they should *not* appear for a particular language environment, you need to use the declaration `exclude_dflt` like so:
之前提到过,任何出现在第一个`script`/*language怎么说?*/关键字之前的#tr[lookup]都会被视为在所有#tr[scripts]和语言时都可用。如果你希望它们在某些语言环境下*不要*被使用,则可以使用 `exclude_dflt`:
```fea
feature liga {
script latn;
lookup fi_ligature {
sub f i by fi; # 所有基于拉丁文的语言都激活此连字
} fi_ligature;
language TRK exclude_dflt; # 但土耳其语除外
} locl;
```
// You may also see `include_dflt` in other people's feature files. The default rules are included by, uh, default, so this doesn't actually do anything, but making that explicit can be useful documentation to help you figure out what rules are being applied. And speaking of what rules are being applied...
你可能会在其他的特性文件中看到 `include_dflt`。它实际上不起任何作用,但将它明确写出来可以作为一种辅助信息,帮助其他人理解这里到底应用了哪些规则。既然提到了“到底应用了哪些规则”这一话题……
|
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/VerbaliInterni/VerbaleInterno_040323/content.typ | typst | MIT License | #import "meta.typ": inizio_incontro, fine_incontro, luogo_incontro
#import "functions.typ": glossary, team
#let participants = csv("participants.csv")
= Partecipanti
/ Inizio incontro: #inizio_incontro
/ Fine incontro: #fine_incontro
/ Luogo incontro: #luogo_incontro
#table(
columns: (3fr, 1fr),
[*Nome*], [*Durata presenza*],
..participants.flatten()
)
= Sintesi Elaborazione Incontro
Nell'incontro si è discussa l'organizzazione del lavoro futuro con la discussione e risoluzione di alcune problematiche, discusse qui in seguito.
== Nuovi ruoli
Vengono stabiliti i seguenti i nuovi incarichi relativi allo sprint corrente:
- <NAME>: Progettista, Programmatore;
- <NAME>: Progettista, Programmatore;
- <NAME>: Verificatore, Amministratore, Analista;
- <NAME>: Progettista, Programmatore;
- <NAME>: Programmatore, Progettista;
- <NAME>: Responsabile, Programmatore.
Per questo sprint il team ha deciso di iniziare a sviluppare quanto progettato, continuando però a definire il resto dell'architettura del sistema. Proprio per questo in questo sprint si è deciso di far avanzare contemporaneamente l'attività di progettazione con quella di sviluppo allocando molte ore ad entrambe le attività.
== Discussione relativa alla revisione _Customer Acceptance_
Il team #team ha deciso di non effettuare la revisione _Customer Acceptance_ poiché vari componenti del team hanno espresso una forte volontà nel voler laurearsi per la sessione di luglio, e protrarre ulteriormente la durata del progetto ne sarebbe un ostacolo.
== Aggiornamento metriche PdQ
Si è deciso di aggiungere le seguenti metriche al documento _Piano Di Qualifica v2.0_:
- Dimensioni dello sprint (espresse in ore produttive): al fine di avere tracciamento quantitativo dell'ammontare di lavoro svolto per sprint;
- Tasso di completamento delle issue assegnate: per avere un punto di vista sulla produttività del gruppo e sulla capacità di perseguire l'efficacia di sprint in sprint;
In seguito si è discusso di approfondire ed informarsi, mediante l'uso di standard noti, riguardo ad ulteriori metriche da usare per perseguire qualità andando a creare un cruscotto più completo.
== Aggiornamento NdP
Al fine di poter utilizzare il _data flow diagram_ all'interno del documento _Specifiche Tecniche v1.0_, questo deve venire normato nel documento _Norme di Progetto v2.0_.
== Altre discussioni
=== Ridisciplinamento del team
Il team ha preso nota del fatto che nell'ultimo periodo i vari componenti hanno fatto fatica a partecipare ai vari meeting interni, oltre che agli standup.
Si è quindi deciso di fissare a priori blocchi temporali (non spostabili) presi come impegni importanti, durante la settimana, al fine di perseguire maggior rigore nella partecipazione ai vari colloqui.
=== Aumento del carico di lavoro
Ora che la sessione d'esami è veramente finita per ogni componente del gruppo, il team #team ha deciso di aumentare il carico di lavoro stando circa sulle 11 ore di lavoro produttivo a settimana, per poter perseguire con successo la prossima revisione. |
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/math/content.typ | typst | Apache License 2.0 | // Test arbitrary content in math.
---
// Test images and font fallback.
#let monkey = move(dy: 0.2em, image("/files/monkey.svg", height: 1em))
$ sum_(i=#emoji.apple)^#emoji.apple.red i + monkey/2 $
---
// Test tables.
$ x := #table(columns: 2)[x][y]/mat(1, 2, 3)
= #table[A][B][C] $
---
// Test non-equation math directly in content.
#math.attach($a$, t: [b])
---
// Test font switch.
#let here = text.with(font: "Noto Sans")
$#here[f] := #here[Hi there]$.
---
// Test boxes without a baseline act as if the baseline is at the base
#{
box(stroke: 0.2pt, $a #box(stroke: 0.2pt, $a$)$)
h(12pt)
box(stroke: 0.2pt, $a #box(stroke: 0.2pt, $g$)$)
h(12pt)
box(stroke: 0.2pt, $g #box(stroke: 0.2pt, $g$)$)
}
---
// Test boxes with a baseline are respected
#box(stroke: 0.2pt, $a #box(baseline:0.5em, stroke: 0.2pt, $a$)$)
|
https://github.com/anesthetice/typst-templates | https://raw.githubusercontent.com/anesthetice/typst-templates/main/main.typ | typst | The Unlicense | // heavily inspired by : https://github.com/dogeystamp/typst-templates/
// thank you dogeystamp
#let header-size = 22pt
#let regular-size = 12pt
#let font = "IBM Plex Serif"
#let template(
title: "",
subtitle: none,
author: "",
doc,
) = {
set document(
title: title,
author: author,
)
set page(
paper: "a4",
margin: (
top: 2.0cm,
right: 1.5cm,
bottom: 2.0cm,
left: 1.5cm,
)
)
set par(
justify: true
)
set text(
font: "IBM Plex Serif",
weight: "regular",
size: regular-size
)
set heading(numbering: "1.", bookmarked: true)
show heading: header => {
header
v(weak: true, 0.75em)
}
set figure.caption(position: bottom)
set figure(gap: 1em)
show figure.caption: emph
show figure: fig => {
show: pad.with(x: 1em, y: 0.6em)
show image: pad.with(y: 0.5em)
set image(width: 50%)
set align(center)
fig
}
set list(indent: 15pt, body-indent: 5pt)
set enum(indent: 15pt, body-indent: 5pt)
pad(left: -2%, {
text(size: header-size, weight: 550, title)
v(10pt, weak: true)
pad(left: 1.5pt, subtitle)
align(right,
rect(
width: 50%,
stroke: none,
{
author
})
)
v(10pt)
line(length: 100%, stroke: 1pt + rgb("#555555"))
})
v(5%, weak: true)
doc
}
|
https://github.com/Zarox28/TypstTemplate | https://raw.githubusercontent.com/Zarox28/TypstTemplate/main/Base.typ | typst | // ----- PACKAGES IMPORT -----
#import "@preview/gentle-clues:0.9.0": *
#import "@preview/outrageous:0.1.0"
#import "@preview/sourcerer:0.2.1": code
#import "@preview/splash:0.4.0": xcolor
#import "term.typ": term
// ----- MAIN CONFIGURATION -----
#let conf(body) = {
// Numbering
set page(numbering: "1", number-align: center)
// Font
set text(font: "Liberation Sans", lang: "fr")
// Table Of Contents
set outline(title: none, depth: 3, indent: 0.6em)
show outline.entry: outrageous.show-entry
show outline: it => {
align(center)[
#underline(
stroke: 1.2pt + red,
offset: 4pt,
text(weight: 700, 1.65em)[Table des matières]
)
]
it
}
// Code
set raw(tab-size: 2)
show raw.where(block: true): it => (
code(lang: upper(it.lang.first()) + it.lang.slice(1), it)
)
// List
set list(marker: ([•], [◦], [•]))
show list: it => move(dx: 3%, it)
show enum: it => move(dx: 3%, it)
// Table
set table(align: center + horizon, inset: 1em)
// Link
show link: it => {
if (it.dest != it.body.text) {
stack(
dir: ltr,
underline(stroke: 0.5pt + black, offset: 2.2pt, it.body),
move(dx: 0.6%, scale(x: 90%, y: 90%)[#emoji.chain])
)
} else {
underline(stroke: 0.5pt + black, offset: 2.2pt, it.dest)
}
}
// Page Content
body
}
// ----- CLASS CONFIGURATION -----
#let class(theme: "", theme_num: 1, chapter: "", chapter_num: 1, body) = {
// Heading
set heading(numbering: "I / A.1 - ")
show heading: it => {
block(below: 1.2em,
if (it.level < 4) {
if (it.level == 1) {
if (it.outlined) {
counter(heading).display("I / ")
}
} else {
counter(heading).display()
}
underline(stroke: 1.2pt + red, offset: 4pt, it.body)
} else {
underline(stroke: 1.2pt + blue, offset: 4pt, it.body)
}
)
}
// Theme Displaying
text(weight: 700, 1.65em)[
#align(left)[#underline(stroke: 1.2pt + red, offset: 4pt)[Thème #theme_num : ]]
#text(hyphenate: false, theme)
]
// Chapter Displaying
text(weight: 600, 1.58em)[
#align(left)[#underline(stroke: 1.2pt + blue, offset: 4pt)[Chapitre #chapter_num : ]]
#text(hyphenate: false, chapter)
]
// Seperator
align(center)[#line(length: 80%)]
// Table Of Contents
outline()
// Seperator
align(center)[#line(length: 80%)]
// Page Content
body
}
// ----- NOTE-TAKING CONFIGURATION -----
#let note(title: "", name: "", date: false, body) = {
// Heading
show heading: it => {
block(below: 1.2em,
if (it.level < 4) {
underline(stroke: 1.2pt + red, offset: 4pt, it.body)
} else {
underline(stroke: 1.2pt + blue, offset: 4pt, it.body)
}
)
}
// Name Displaying
text(1.3em)[
#align(left)[#underline(stroke: 1pt + black, offset: 4pt)[#name]]
]
// Today Date Displaying
if date {
text(1.3em)[
#align(left)[#underline(stroke: 1pt + black, offset: 4pt)[#datetime.today().display()]]
]
}
// Title Displaying
text(weight: 700, 1.58em)[
#align(center)[#underline(stroke: 1.2pt + red, offset: 4pt)[#title]]
]
// Seperator
line(length: 100%)
// Page Content
body
}
// ----- TAB FUNCTION -----
#let tab(size: 1, body) = {
move(dx: 5% * size, body)
}
// ----- SIZE FUNCTION -----
#let size(size, body) = {
scale(x: 100% * size, y: 100% * size)[#body]
}
// ----- UNDERLINE FUNCTION -----
#let under(color: red, body) = {
underline(stroke: 1.2pt + color, offset: 4pt)[#body]
}
// ----- CALLOUT FUNCTION -----
#let call(size: 0, body) = {
tab(size: size)[
#box(
width: 90%,
stack(
dir: ltr,
move(dy: -0.24%, emoji.arrow.filled),
move(dx: 1%, body)
)
)
]
}
// ----- WORD DEFINITION FUNCTION -----
#let def(word: "", ..args) = clue(
title: "Définition : " + word,
accent-color: yellow,
icon: emoji.book,
..args
)
|
|
https://github.com/loqusion/typix | https://raw.githubusercontent.com/loqusion/typix/main/docs/api/derivations/common/typst-project-source.md | markdown | MIT License | <!-- markdownlint-disable-file first-line-h1 -->
Typst input file to compile.
|
https://github.com/Dr00gy/Typst-thesis-template-for-VSB | https://raw.githubusercontent.com/Dr00gy/Typst-thesis-template-for-VSB/main/thesis_template/outlines.typ | typst | #let listChapters = {
show outline.entry.where(level: 1): it => {
v(1em)
text(size: 1.25em, weight: "bold")[#it]
}
// Contents
outline(indent: 1.2em, fill: repeat[#h(.6em).])
}
#let listImages = {
show outline: set heading(outlined: true)
outline(
title: context(if text.lang == "en" [List of Figures] else [Seznam obrázků]),
target: figure.where(kind: image),
)
}
#let listTables = {
show outline: set heading(outlined: true)
outline(
title: context(if text.lang == "en" [List of Tables] else [Seznam tabulek]),
target: figure.where(kind: table),
)
}
#let listSymbols(symbols) = {
symbols = symbols.sorted(key: it => it.at(0))
heading(
level: 1,
)[#context(if text.lang == "en" [List of symbols and abbreviations] else [Seznam použitých zkratek a symbolů])]
grid(
columns: (25%, auto, auto),
gutter: 15pt,
..for item in symbols {
(
item.at(0),
[---],
item.at(1),
)
},
)
}
|
|
https://github.com/yonatanmgr/university-notes | https://raw.githubusercontent.com/yonatanmgr/university-notes/main/0366-%5BMath%5D/03661111-%5BLinear%20Algebra%201A%5D/src/lectures/03661111_lecture_7.typ | typst | #import "/template.typ": *
#import "@preview/colorful-boxes:1.2.0": *
#show: project.with(
title: "אלגברה לינארית 1א׳ - שיעור 7",
authors: ("<NAME>",),
date: "26 בינואר, 2024",
)
// #include "/utils/toc.typ"
// #pagebreak()
#set enum(numbering: "(1.א)")
= תזכורת
== צירוף לינארי (צ״ל)
אם $V$ הוא מ״ו מעל שדה $F$, $v_1, dots, v_s$ הם סדרה של וקטורים ($0<=s in ZZ$) ו-$lambda_1, dots, lambda_s in F$ הם סקלרים בשדה, נגדיר את *הצירוף הלינארי* המתאים להיות: $ sum_(i=1)^s lambda_i v_i = lambda_1 v_1 + dots.h.c + lambda_s v_s $
(במקרה בו $s=0$, נגדיר $sum_(i=1)^0 lambda_i v_i := 0$).
==== צירופים לינארים טריוויאליים ולא טריוויאליים
הצ״ל נקרא *טריוויאלי* אם $lambda_1 = dots.h.c = lambda_s = 0$ *ולא טריוויאלי* אם קיים $i$ כך ש-$lambda_i !=0$.
== בסיס
נגיד שסדרה $B=(v_1, dots, v_s)$ של וקטורים ב-$V$ היא *בסיס* אם לכל $v in V$ קיים צ״ל יחיד\* של איברי $B$ כך שמתקיים:$ v=sum_(i=1)^s lambda_i v_i $
ניתן לדבר בצורה פשוטה גם על $B$ אינסופית (אך לא נעשה זאת).
\*כלומר: קיים $(lambda_1, dots, lambda_s) in F^n$ יחיד עבורו $v= sum_(i=1)^s lambda_i v_i$.
=== מימד
נגדיר את *המימד* של המרחב הוקטורי $V$ להיות מספר האיברים בבסיסו. נסמן $dim V = abs(B)$. לפעמים גם נסמן $dim _F V$.
=== לכל מרחב וקטורי $V$ מעל $F$ יש בסיס, וכל הבסיסים של $V$ הם מגודל (עוצמה) זהה
==== דוגמאות
+ $V=0$. הבסיס הוא הקבוצה הריקה - $B=nothing$. לכן, בהתאם לאינטואיציה, $dim V = 0$.
+ $V=F^n$ (המרחב הסטנדרטי). בהתאם, הבסיס הסטנדרטי הוא: $ B = (e_1 = vec(1,0, dots.v, 0), e_2 = vec(0,1, dots.v, 0), dots.h.c, e_n = vec(0, dots.v, 0, 1)) $
אכן, נוכל לבחור $vec(x_1, dots.v, x_n) = v in F^n$. אז מתקיים: $ v=vec(x_1, x_2, dots.v, x_n) = x_1 vec(1, 0, dots.v, 0) + x_2 vec(0,1, dots.v, 0) + dots.c.h + x_n vec(0, dots.v, 0, 1) = sum x_i e_i $
וזוהי הדרך היחידה. לכן, $dim F^n = n$.
+ $V=F[x]_(<=n)$ (מרחב הפולינומים ממעלה $<=n$ מעל $F$). נראה כי המרחב מוגדר גם להיות ${sum_(i=0)^n a_i x^i : a_i in F}$ ולכן $(1, x, dots, x^n)$ הוא הבסיס ו-$dim F[x]_(<=n) = n+1$.
= תלות לינארית
- סדרת וקטורים $(v_1, dots, v_s)$ ב-$F$ נקראת *תלויה לינארית* אם קיים צ״ל לא טריוויאלי ששווה לאפס. כלומר, קיימים $lambda_1, dots, lambda_s in F$ (לא כולם אפס) כך ש-$lambda_1 v_1 + dots.c.h + lambda_s v_s = 0$.
- סדרת וקטורים שהיא לא תלויה לינארית תקרא *בלתי תלויה לינארית* (בת״ל). כלומר, לכל $lambda_1, dots, lambda_s in F$ כך ש-$lambda_1 v_1 + dots.h.c + lambda_s v_s =0$ מתקיים $lambda_1=dots.h.c = lambda_s = 0$.
== דוגמאות
+ אם $0_V$ נמצא בסדרה אז היא תלויה לינארית. אכן, $0=1dot 0_V$.
+ אם $v_1 = v_2$, כלומר הסדרה היא $(v_1, v_1, v_3, v_4 dots)$ אז היא תלויה לינארית, הרי ש-$0=v_1-v_1$.
+ $V=RR^2$. ניקח את הסדרה להיות $(v_1 = (1,2), v_2 =(-2,3))$. נבדוק האם הם בת״ל:
ניקח $lambda_1, lambda_2 in F$ כך שמתקיים $lambda_1 v_1 + lambda_2 v_2 = 0$. צריך להוכיח ש-$lambda_1=lambda_2=0$ וצריך להראות שהם בת״ל. נראה כי:
$ lambda_1 v_1 + lambda_2 v_2 = 0 iff cases(lambda_1 - 2 lambda_2 &= 0, 2 lambda_1 + 3 lambda_2 &= 0 ) $
מדרגים את המטריצה המצומצמת $mat(1, -2; 2, 3)$ $arrow.squiggly.l$ $mat(1,0;0,1)$ ולכן יש פתרון יחיד ($lambda_1 = lambda_2 = 0$) והסדרה בת״ל.
== תזכורת: תת-מרחב לינארי
יהי $V$ מ״ו מעל $F$ ו-$U seq V$ תת-קבוצה. נגדיר את $U$ להיות תת-מרחב אם:
+ $0 in U$
+ $U$ סגור לחיבור.
+ $U$ סגור לכפל בסקלר.
#outlinebox(
title: "💡 הערות",
color: "black", centering: true
)[
- נוכל להחליף את דרישה (1) ב-$U != nothing$.
- נוכל להחליף את דרישות (2) ו-(3) בסגירות לצירופים לינאריים.
]
=== אם $U seq V$ תת-מרחב אז $U$ סגורה לצ״ל
==== הוכחה (באינדוקציה)
- בסיס האינדוקציה:
אם $s=0$ אז $sum_(i=1)^0 = 0 in U$.
- צעד האינדוקציה:
נניח את הנחת האינדוקציה - $forall v_i in U, lambda_i in F, sum_(i=1)^s lambda_i v_i in U$ ואז מתקיימת ההכלה הבאה:
$ overbracket(sum_(i=1)^(s+1) lambda_i v_i = underbracket((sum_(i=1)^s lambda_i v_i), in U \ "מהנחת האינדוקציה") + lambda_(s+1) v_(s+1) in U, \ "כי U סגורה לצ״ל מאורך 2") $
#QED
#pagebreak()
= קבוצה פורשת
סדרה $X=(v_1, dots, v_s)$ של וקטורים במ״ו נקראת *פורשת* אם לכל $v in V$ קיימים $lambda_1, dots, lambda_s in F$ כך ש-$v=sum_(i=1)^s lambda_i v_i$. אם $X$ פורשת, נרשום $span_F (X) = V$ או $span_F (v_1, dots, v_s) = V$. באופן יותר כללי: $ span_F (v_1, dots, v_s) = {sum_(i=1)^s lambda_i v_i : lambda_i in F} = "קבוצת כל הצירופים הלינאריים של האיברים" $
=== $span(v_1, dots, v_s)$ הוא תת-המרחב המינימלי של $V$ המכיל את $v_1, dots, v_s$
כלומר, $span(v_1, dots, v_s ) = sect.big U$ כאשר $U$ רץ על כל תתי-המרחבים של $V$ המכילים את $v_1, dots, v_s$.
==== הוכחה
נסמן $W=span(v_1, dots, v_s)$. נראה כי $sum_(i=1)^s 0 dot v_i = 0 in W$, ו-$W$ סגור לצ״ל: $ lambda underbracket(sum_(i=1)^s lambda_i v_i, in W) + mu underbracket(sum_(i=1)^s mu_i v_i, in W) = sum_(i=1)^s (lambda lambda_i + mu mu_i) v_i in W $
לכן, $W$ תת-מרחב. נוכיח כי $W$ תת-המרחב המינימלי שמכיל את $v_1, dots, v_s$.
יהי $U$ תת-מרחב של $V$ המכיל את $v_1, dots, v_s$. אז הוכחנו (היום) ש-$U$ סגור לצ״ל של $v_1, dots, v_s$ ולכן $W seq U$.
#QED
- דוגמה: $span_RR ((1,0)) = {(x,0) : x in RR} = x"ציר ה-"$.
== מרחב נוצר סופית
נאמר שמ״ו הוא נוצר סופית (נ״ס) אם קיימת תת-קבוצה סופית $X seq V$ שהיא פורשת.
=== דוגמאות
+ $F^n$ נ״ס כי $e_1, dots, e_n$ פורשים אותו.
+ $F[x]_(<=n)$ נ״ס כי $1, dots, x^n$ פורשים אותו.
+ $F[X]$ לא נ״ס.
+ $F^oo = {(a_1, dots, a_n, dots)}$ לא נ״ס.
+ $RR^RR$ לא נ״ס.
=== טענה על מרחבים נוצרים סופית
יהי $V$ מ״ו נ״ס על ידי $n$ איברים $v_1, dots, v_n$. אז לכל סדרה בת״ל יש לכל היותר $n$ איברים.
במילים אחרות, כל סדרה של יותר מ-$n$ איברים היא תלויה לינארית.
==== הוכחה
תהי $(w_1, dots, w_m)$ סדרה בת״ל. רוצים להוכיח ש-$m<=n$. נניח ש-$m>n$ ונוכיח ש-$(w_1, dots, w_m)$ תלויה לינארית. כלומר, צריכים למצוא $lambda_1, dots, lambda_m$ לא כולם אפס, כך ש-$sum_(i=1)^m lambda_i w_i = 0$.
כיוון ש-$v_1, dots, v_n$ פורשים, אז לכל $i$, $w_i$ הוא צ״ל שלהם. כלומר,
$ forall i in {1, dots, m} exists {a_(i 1), dots, a_(i n)} seq F: w_i = a_(i 1) v_1 + dots.c.h + a_(i n) v_n $
מחפשים $lambda_1, dots, lambda_m$ לא כולם אפס כך שמתקיים:
$ (**) arrow.l 0 = sum_(i=1)^m lambda_i w_i = sum_(i=1)^m sum_(j=1)^n lambda_i a_(i j) v_j = sum_(j=1)^n sum_(i=1)^m lambda_i a_(i j) v_j = sum_(j=1)^n (sum_(i=1)^m lambda_i a_(i j)) v_j $
אם $sum_(i=1)^m lambda_i a_(i j) = 0$ לכל $j$ אז ניצחנו.
אך נשים לב שזו צורה מקוצרת של מערכת המשוואות ההומוגנית:
$ (*) arrow.l cases(
lambda_1 a_(1 1) + dots.c.h + lambda_m a_(1 m) &= 0,
dots.v,
lambda_1 a_(n 1) + dots.c.h + lambda_m a_(n m) &= 0
) $
זוהי מערכת משוואות הומוגנית עם $m$ נעלמים ו-$n$ משתנים, ו-$m>n$ ולכן יש פתרון לא טריוויאלי.
כלומר יש $lambda_1, dots, lambda_m$ לא כולם אפס וכך $(*)$ מתקיים, ואז לפי $(**)$ גם $sum lambda_i w_i=0$.
== שרשור
אם $X=(v_1, dots, v_n)$ סדרה של וקטורים, נסמן ב-$X uu {v}$ את השרשור $(v_1, dots, v_n, v)$.
=== אם $v in V without span(X)$ אז $X uu {v}$ בת״ל
תהי $X seq V$ סדרה בת״ל של וקטורים ב-$V$. אם $v in V without span(X)$ אז $X uu {v}$ בת״ל.
==== הוכחה
נסמן $X=(v_1, dots, v_n)$ ונניח ש-$v in V without span(X)$. בנוסף, נניח בשלילה ש-$X uu {v}$ תלויה לינארית.
לכן יש $lambda_1, dots, lambda_n, lambda in F$ לא כולם אפס כך ש-$lambda_1 v_1 + dots.h.c + lambda_n v_n + lambda v = 0$. נחלק למקרים:
+ $lambda=0$ ואז $lambda_1 v_1 + dots.h.c + lambda_n v_n$ עם $lambda_1, dots, lambda_n$ לא כולם אפס, בסתירה לכך ש-$X$ בת״ל.
+ $lambda!=0$. נעביר את $lambda v$ אגף ונחלק ב-$lambda$, ונקבל: $ v=-frac(lambda_1, lambda) v_1 - dots.h.c - frac(lambda_n, lambda) v_n = -sum_(i=0)^n frac(lambda_i, lambda) v_i in span X $ בסתירה לכך ש-$v in.not span(X)$ ולכן השלילה לא נכונה, כלומר $X uu {v}$ בת״ל.
#QED
|
|
https://github.com/techtheriac/resume | https://raw.githubusercontent.com/techtheriac/resume/master/README.md | markdown | # References
[Typst Docs](https://typst.app/docs)
|
|
https://github.com/jneug/typst-tools4typst | https://raw.githubusercontent.com/jneug/typst-tools4typst/main/math.typ | typst | MIT License | #import "is.typ": same-type
// =================================
// Math
// =================================
/// Returns an array with the minimum of `a` and `b` as the first element and the maximum as the second:
/// #codesnippet[```typ
/// #let (min, max) = math.minmax(a, b)
/// ```]
/// Works with any comparable type.
///
/// // Tests
/// #test(
/// `math.minmax(50, 60) == (50, 60)`,
/// `math.minmax(60, 50) == (50, 60)`,
/// `math.minmax(5deg, -4deg) == (-4deg, 5deg)`,
/// `math.minmax(-5cm, -4cm) == (-5cm, -4cm)`,
/// )
///
/// - a (integer, float, length, relative length, fraction, ratio): First value.
/// - b (integer, float, length, relative length, fraction, ratio): Second value.
/// -> integer, float, length, relative length, fraction, ratio
#let minmax( a, b ) = (
calc.min(a, b),
calc.max(a, b)
)
/// Clamps a value between `min` and `max`.
///
/// In contrast to @@clamp() this function works for other values
/// than numbers, as long as they are comparable.
/// #codesnippet[```typ
/// text-size = math.clamp(0.8em, 1.2em, text-size)
/// ```]
/// Works with any comparable type.
///
/// // Tests
/// #test(
/// `math.clamp(0, 100, 50) == 50`,
/// `math.clamp(33%, 99%, 100%) == 99%`,
/// `math.clamp(-5in, 8in, -6in) == -5in`,
/// `math.clamp(-5in, 8in, 4in) == 4in`,
/// )
///
/// - min (integer, float, length, relative length, fraction, ratio): Minimum for `value`.
/// - min (integer, float, length, relative length, fraction, ratio): Maximum for `value`.
/// - value (integer, float, length, relative length, fraction, ratio): The value to clamp.
/// -> any
#let clamp( min, max, value ) = {
assert.eq(type(min), type(max),
message:"Can't clamp values of different types!"
)
assert.eq(type(min), type(value),
message:"Can't clamp values of different types!"
)
if value < min { return min }
else if value > max { return max }
else { return value }
}
/// Calculates the linear interpolation of `t` between `min` and `max`.
///
/// `t` should be a value between 0 and 1, but the interpolation works
/// with other values, too. To constrain the result into the given
/// interval, use @@clamp():
/// #codesnippet[```typ
/// #let width = math.lerp(0%, 100%, x)
/// #let width = math.lerp(0%, 100%, math.clamp(0, 1, x))
/// ```]
///
/// // Tests
/// #test(
/// `math.lerp(0, 100, .5) == 50`,
/// `math.lerp(0%, 100%, 1.1) == 110%`,
/// `math.lerp(-4em, 3em, -2) == -18em`,
/// `math.lerp(56.7, 423.8, 1) == 423.8`,
/// `math.lerp(56.7mm, 423.8mm, 0) == 56.7mm`,
/// )
///
/// - min (integer, float, length, relative length, fraction, ratio): Minimum for `value`.
/// - max (integer, float, length, relative length, fraction, ratio): Maximum for `value`.
/// - t (float): Interpolation parameter .
/// -> integer, float, length, relative length, fraction, ratio
#let lerp( min, max, t ) = {
assert.eq(type(min), type(max),
message:"Can't lerp values of different types!"
)
return (1 - t) * min + t * max;
}
/// Maps a `value` from the interval `[min, max]` into the interval `[range-min, range-max]`:
/// #codesnippet[```typ
/// #let text-weight = int(math.map(8pt, 16pt, 400, 800, text-size))
/// ```]
///
/// The types of `min`, `max` and `value` and the types of `range-min` and `range-max` have to be the same.
///
/// // Tests
/// #test(
/// `math.map(8pt, 16pt, 400, 800, 8pt) == 400`,
/// `math.map(8pt, 16pt, 400, 800, 16pt) == 800`,
/// `math.map(8pt, 16pt, 400, 800, 4pt) == 200`,
/// `math.map(8pt, 16pt, 400, 800, 32pt) == 1600`,
/// `math.map(0%, 100%, 5.6em, 0.8em, 100%) == 0.8em`,
/// `math.map(0%, 100%, 5.6em, 0.8em, 0%) == 5.6em`,
/// )
///
/// - min (integer, float, length, relative length, fraction, ratio): Minimum of the initial interval.
/// - min (integer, float, length, relative length, fraction, ratio): Maximum of the initial interval.
/// - range-min (integer, float, length, relative length, fraction, ratio): Minimum of the target interval.
/// - range-min (integer, float, length, relative length, fraction, ratio): Maximum of the target interval.
/// - value (integer, float, length, relative length, fraction, ratio): The value to map.
/// -> integer, float, length, relative length, fraction, ratio
#let map( min, max, range-min, range-max, value ) = {
assert.eq(type(min), type(max),
message:"Can't map values from ranges of different types!"
)
assert.eq(type(range-min), type(range-max),
message:"Can't map values to ranges of different types!"
)
assert.eq(type(min), type(value),
message:"Can't map values with different types as the initial range!"
)
let t = (value - min) / (max - min)
return (1 - t) * range-min + t * range-max;
}
|
https://github.com/MatheSchool/typst-g-exam | https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/test/grade-table/test-002-subquestion-point.typ | typst | MIT License | #import "../../src/lib.typ": *
#show: g-exam.with(
show-student-data: "first-page",
show-grade-table: true,
)
#g-question()[]
#g-subquestion(points:1)[]
#g-subquestion(points:1)[]
#g-question(points:3)[]
#g-subquestion(points:1.2)[]
#g-subquestion(points:1.3)[]
|
https://github.com/FinleyGe/typst-profile | https://raw.githubusercontent.com/FinleyGe/typst-profile/main/README.md | markdown | # Typst-Profile
使用 Typst 编写的个人简历模板。
样例:
[样例](/example.pdf)
PRs are welcome!
|
|
https://github.com/bpkleer/typst-academicons | https://raw.githubusercontent.com/bpkleer/typst-academicons/main/gallery.typ | typst | MIT License |
#import "lib.typ": *
#table(columns: (2fr, 1fr, 1fr), stroke: none, table.header([typst code], [default], [`fa-icon` with text]),
```typst #ai-academia()```, ai-academia(), ai-icon("academia"),
```typst #ai-academia-square()```, ai-academia-square(), ai-icon("academia-square"),
```typst #ai-acclaim()```, ai-acclaim(), ai-icon("acclaim"),
```typst #ai-acclaim-square()```, ai-acclaim-square(), ai-icon("acclaim-square"),
```typst #ai-acm()```, ai-acm(), ai-icon("acm"),
```typst #ai-acm-square()```, ai-acm-square(), ai-icon("acm-square"),
```typst #ai-acmdl()```, ai-acmdl(), ai-icon("acmdl"),
```typst #ai-acmdl-square()```, ai-acmdl-square(), ai-icon("acmdl-square"),
```typst #ai-ads()```, ai-ads(), ai-icon("ads"),
```typst #ai-ads-square()```, ai-ads-square(), ai-icon("ads-square"),
```typst #ai-africarxiv()```, ai-africarxiv(), ai-icon("africarxiv"),
```typst #ai-africarxiv-square()```, ai-africarxiv-square(), ai-icon("africarxiv-square"),
```typst #ai-archive()```, ai-archive(), ai-icon("archive"),
```typst #ai-archive-square()```, ai-archive-square(), ai-icon("archive-square"),
```typst #ai-arxiv()```, ai-arxiv(), ai-icon("arxiv"),
```typst #ai-arxiv-square()```, ai-arxiv-square(), ai-icon("arxiv-square"),
```typst #ai-biorxiv()```, ai-biorxiv(), ai-icon("biorxiv"),
```typst #ai-biorxiv-square()```, ai-biorxiv-square(), ai-icon("biorxiv-square"),
```typst #ai-ceur()```, ai-ceur(), ai-icon("ceur"),
```typst #ai-ceur-square()```, ai-ceur-square(), ai-icon("ceur-square"),
```typst #ai-ciencia-vitae()```, ai-ciencia-vitae(), ai-icon("ciencia-vitae"),
```typst #ai-ciencia-vitae-square()```, ai-ciencia-vitae-square(), ai-icon("ciencia-vitae-square"),
```typst #ai-clarivate()```, ai-clarivate(), ai-icon("clarivate"),
```typst #ai-clarivate-square()```, ai-clarivate-square(), ai-icon("clarivate-square"),
```typst #ai-closed-access()```, ai-closed-access(), ai-icon("closed-access"),
```typst #ai-closed-access-square()```, ai-closed-access-square(), ai-icon("closed-access-square"),
```typst #ai-conversation()```, ai-conversation(), ai-icon("conversation"),
```typst #ai-conversation-square()```, ai-conversation-square(), ai-icon("conversation-square"),
```typst #ai-coursera()```, ai-coursera(), ai-icon("coursera"),
```typst #ai-coursera-square()```, ai-coursera-square(), ai-icon("coursera-square"),
```typst #ai-crossref()```, ai-crossref(), ai-icon("crossref"),
```typst #ai-crossref-square()```, ai-crossref-square(), ai-icon("crossref-square"),
```typst #ai-cv()```, ai-cv(), ai-icon("cv"),
```typst #ai-cv-square()```, ai-cv-square(), ai-icon("cv-square"),
```typst #ai-datacite()```, ai-datacite(), ai-icon("datacite"),
```typst #ai-datacite-square()```, ai-datacite-square(), ai-icon("datacite-square"),
```typst #ai-dataverse()```, ai-dataverse(), ai-icon("dataverse"),
```typst #ai-dataverse-square()```, ai-dataverse-square(), ai-icon("dataverse-square"),
```typst #ai-dblp()```, ai-dblp(), ai-icon("dblp"),
```typst #ai-dblp-square()```, ai-dblp-square(), ai-icon("dblp-square"),
```typst #ai-depsy()```, ai-depsy(), ai-icon("depsy"),
```typst #ai-depsy-square()```, ai-depsy-square(), ai-icon("depsy-square"),
```typst #ai-doi()```, ai-doi(), ai-icon("doi"),
```typst #ai-doi-square()```, ai-doi-square(), ai-icon("doi-square"),
```typst #ai-dryad()```, ai-dryad(), ai-icon("dryad"),
```typst #ai-dryad-square()```, ai-dryad-square(), ai-icon("dryad-square"),
```typst #ai-elsevier()```, ai-elsevier(), ai-icon("elsevier"),
```typst #ai-elsevier-square()```, ai-elsevier-square(), ai-icon("elsevier-square"),
```typst #ai-figshare()```, ai-figshare(), ai-icon("figshare"),
```typst #ai-figshare-square()```, ai-figshare-square(), ai-icon("figshare-square"),
```typst #ai-google-scholar()```, ai-google-scholar(), ai-icon("google-scholar"),
```typst #ai-google-scholar-square()```, ai-google-scholar-square(), ai-icon("google-scholar-square"),
```typst #ai-hal()```, ai-hal(), ai-icon("hal"),
```typst #ai-hal-square()```, ai-hal-square(), ai-icon("hal-square"),
```typst #ai-hypothesis()```, ai-hypothesis(), ai-icon("hypothesis"),
```typst #ai-hypothesis-square()```, ai-hypothesis-square(), ai-icon("hypothesis-square"),
```typst #ai-ideas-repec()```, ai-ideas-repec(), ai-icon("ideas-repec"),
```typst #ai-ideas-repec-square()```, ai-ideas-repec-square(), ai-icon("ideas-repec-square"),
```typst #ai-ieee()```, ai-ieee(), ai-icon("ieee"),
```typst #ai-ieee-square()```, ai-ieee-square(), ai-icon("ieee-square"),
```typst #ai-impactstory()```, ai-impactstory(), ai-icon("impactstory"),
```typst #ai-impactstory-square()```, ai-impactstory-square(), ai-icon("impactstory-square"),
```typst #ai-inaturalist()```, ai-inaturalist(), ai-icon("inaturalist"),
```typst #ai-inaturalist-square()```, ai-inaturalist-square(), ai-icon("inaturalist-square"),
```typst #ai-inpn()```, ai-inpn(), ai-icon("inpn"),
```typst #ai-inpn-square()```, ai-inpn-square(), ai-icon("inpn-square"),
```typst #ai-inspire()```, ai-inspire(), ai-icon("inspire"),
```typst #ai-inspire-square()```, ai-inspire-square(), ai-icon("inspire-square"),
```typst #ai-isidore()```, ai-isidore(), ai-icon("isidore"),
```typst #ai-isidore-square()```, ai-isidore-square(), ai-icon("isidore-square"),
```typst #ai-isni()```, ai-isni(), ai-icon("isni"),
```typst #ai-isni-square()```, ai-isni-square(), ai-icon("isni-square"),
```typst #ai-jstor()```, ai-jstor(), ai-icon("jstor"),
```typst #ai-jstor-square()```, ai-jstor-square(), ai-icon("jstor-square"),
```typst #ai-lattes()```, ai-lattes(), ai-icon("lattes"),
```typst #ai-lattes-square()```, ai-lattes-square(), ai-icon("lattes-square"),
```typst #ai-mathoverflow()```, ai-mathoverflow(), ai-icon("mathoverflow"),
```typst #ai-mathoverflow-square()```, ai-mathoverflow-square(), ai-icon("mathoverflow-square"),
```typst #ai-mendeley()```, ai-mendeley(), ai-icon("mendeley"),
```typst #ai-mendeley-square()```, ai-mendeley-square(), ai-icon("mendeley-square"),
```typst #ai-moodle()```, ai-moodle(), ai-icon("moodle"),
```typst #ai-moodle-square()```, ai-moodle-square(), ai-icon("moodle-square"),
```typst #ai-mtmt()```, ai-mtmt(), ai-icon("mtmt"),
```typst #ai-mtmt-square()```, ai-mtmt-square(), ai-icon("mtmt-square"),
```typst #ai-nakala()```, ai-nakala(), ai-icon("nakala"),
```typst #ai-nakala-square()```, ai-nakala-square(), ai-icon("nakala-square"),
```typst #ai-obp()```, ai-obp(), ai-icon("obp"),
```typst #ai-obp-square()```, ai-obp-square(), ai-icon("obp-square"),
```typst #ai-open-access()```, ai-open-access(), ai-icon("open-access"),
```typst #ai-open-access-square()```, ai-open-access-square(), ai-icon("open-access-square"),
```typst #ai-open-data()```, ai-open-data(), ai-icon("open-data"),
```typst #ai-open-data-square()```, ai-open-data-square(), ai-icon("open-data-square"),
```typst #ai-open-materials()```, ai-open-materials(), ai-icon("open-materials"),
```typst #ai-open-materials-square()```, ai-open-materials-square(), ai-icon("open-materials-square"),
```typst #ai-openedition()```, ai-openedition(), ai-icon("openedition"),
```typst #ai-openedition-square()```, ai-openedition-square(), ai-icon("openedition-square"),
```typst #ai-orcid()```, ai-orcid(), ai-icon("orcid"),
```typst #ai-orcid-square()```, ai-orcid-square(), ai-icon("orcid-square"),
```typst #ai-osf()```, ai-osf(), ai-icon("osf"),
```typst #ai-osf-square()```, ai-osf-square(), ai-icon("osf-square"),
```typst #ai-overleaf()```, ai-overleaf(), ai-icon("overleaf"),
```typst #ai-overleaf-square()```, ai-overleaf-square(), ai-icon("overleaf-square"),
```typst #ai-philpapers()```, ai-philpapers(), ai-icon("philpapers"),
```typst #ai-philpapers-square()```, ai-philpapers-square(), ai-icon("philpapers-square"),
```typst #ai-piazza()```, ai-piazza(), ai-icon("piazza"),
```typst #ai-piazza-square()```, ai-piazza-square(), ai-icon("piazza-square"),
```typst #ai-preregistered()```, ai-preregistered(), ai-icon("preregistered"),
```typst #ai-preregistered-square()```, ai-preregistered-square(), ai-icon("preregistered-square"),
```typst #ai-protocols()```, ai-protocols(), ai-icon("protocols"),
```typst #ai-protocols-square()```, ai-protocols-square(), ai-icon("protocols-square"),
```typst #ai-psyarxiv()```, ai-psyarxiv(), ai-icon("psyarxiv"),
```typst #ai-psyarxiv-square()```, ai-psyarxiv-square(), ai-icon("psyarxiv-square"),
```typst #ai-publons()```, ai-publons(), ai-icon("publons"),
```typst #ai-publons-square()```, ai-publons-square(), ai-icon("publons-square"),
```typst #ai-pubmed()```, ai-pubmed(), ai-icon("pubmed"),
```typst #ai-pubmed-square()```, ai-pubmed-square(), ai-icon("pubmed-square"),
```typst #ai-pubpeer()```, ai-pubpeer(), ai-icon("pubpeer"),
```typst #ai-pubpeer-square()```, ai-pubpeer-square(), ai-icon("pubpeer-square"),
```typst #ai-researcherid()```, ai-researcherid(), ai-icon("researcherid"),
```typst #ai-researcherid-square()```, ai-researcherid-square(), ai-icon("researcherid-square"),
```typst #ai-researchgate()```, ai-researchgate(), ai-icon("researchgate"),
```typst #ai-researchgate-square()```, ai-researchgate-square(), ai-icon("researchgate-square"),
```typst #ai-ror()```, ai-ror(), ai-icon("ror"),
```typst #ai-ror-square()```, ai-ror-square(), ai-icon("ror-square"),
```typst #ai-sci-hub()```, ai-sci-hub(), ai-icon("sci-hub"),
```typst #ai-sci-hub-square()```, ai-sci-hub-square(), ai-icon("sci-hub-square"),
```typst #ai-scirate()```, ai-scirate(), ai-icon("scirate"),
```typst #ai-scirate-square()```, ai-scirate-square(), ai-icon("scirate-square"),
```typst #ai-scopus()```, ai-scopus(), ai-icon("scopus"),
```typst #ai-scopus-square()```, ai-scopus-square(), ai-icon("scopus-square"),
```typst #ai-semantic-scholar()```, ai-semantic-scholar(), ai-icon("semantic-scholar"),
```typst #ai-semantic-scholar-square()```, ai-semantic-scholar-square(), ai-icon("semantic-scholar-square"),
```typst #ai-springer()```, ai-springer(), ai-icon("springer"),
```typst #ai-springer-square()```, ai-springer-square(), ai-icon("springer-square"),
```typst #ai-ssrn()```, ai-ssrn(), ai-icon("ssrn"),
```typst #ai-ssrn-square()```, ai-ssrn-square(), ai-icon("ssrn-square"),
```typst #ai-stackoverflow()```, ai-stackoverflow(), ai-icon("stackoverflow"),
```typst #ai-stackoverflow-square()```, ai-stackoverflow-square(), ai-icon("stackoverflow-square"),
```typst #ai-viaf()```, ai-viaf(), ai-icon("viaf"),
```typst #ai-viaf-square()```, ai-viaf-square(), ai-icon("viaf-square"),
```typst #ai-wiley()```, ai-wiley(), ai-icon("wiley"),
```typst #ai-wiley-square()```, ai-wiley-square(), ai-icon("wiley-square"),
```typst #ai-zenodo()```, ai-zenodo(), ai-icon("zenodo"),
```typst #ai-zotero()```, ai-zotero(), ai-icon("zotero"),
```typst #ai-zotero-square()```, ai-zotero-square(), ai-icon("zotero-square"),
)
|
https://github.com/r8vnhill/apunte-bibliotecas-de-software | https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/Unit1/NullSafety.typ | typst |
== Null-Safety
=== El Problema de los Punteros Nulos
Los punteros o referencias nulas han sido denominados "el error de mil millones de dólares" por <NAME>, quien introdujo el concepto de valores nulos. Este problema ocurre cuando una variable que se
espera que contenga una referencia a un objeto en realidad contiene un valor nulo, lo que lleva a
errores en tiempo de ejecución cuando se intenta acceder a métodos o propiedades de dicho objeto.
=== Motivación
El manejo inadecuado de valores nulos puede causar una serie de errores en tiempo de ejecución que
son difíciles de detectar y corregir, especialmente en grandes bases de código. Estos errores pueden
comprometer la robustez y la seguridad de las aplicaciones. Por lo tanto, la gestión eficaz de los
valores nulos es un aspecto crítico del diseño del software.
=== Enfoques en Diferentes Lenguajes
- *Java*: Tradicionalmente, Java ha permitido referencias nulas y lxs desarrolladores deben chequear
explícitamente si una variable es nula antes de usarla. Esto puede llevar a mucho código de
validación redundante y a veces se pasa por alto, resultando en `NullPointerException`.
- *C\#*: Introduce el concepto de tipos anulables y no anulables. Los tipos de referencia son no
anulables por defecto, pero pueden ser declarados como anulables con un signo de interrogación
(`?`) después del tipo.
- *Scala*: Utiliza el concepto de `Option` para manejar valores nulos de manera segura. Un `Option`
puede contener un valor (`Some`) o no contener nada (`None`), lo que obliga a los desarrolladores a
manejar explícitamente ambos casos.
El problema con los approach de otros lenguajes como Scala es que todos los valores pueden ser nulos, lo que no garantiza la seguridad en tiempo de ejecución. Por ejemplo, una aplicación en Scala podría
contener la siguiente línea de código:
```scala
var option: Option[String] = None
```
Esto impondrá la restricción de que para trabajar con `option`, se debe manejar explícitamente el caso en que no contenga un valor. Pero hay un malentendido común en torno a este enfoque: aunque `Option` es una forma segura de manejar valores nulos, no garantiza que los valores no sean nulos. En otras palabras, `Option` no elimina la posibilidad de `NullPointerException`, sino que la traslada a un nivel superior de abstracción.
```scala
var option: Option[String] = null
```
En este caso, `option` es nulo, lo que significa que el problema de los valores nulos no se ha resuelto, sino que se ha trasladado a la abstracción de `Option`. Por lo tanto, aunque `Option` es una mejora con respecto a los punteros nulos tradicionales, no es una solución completa al problema de los valores nulos.
Para mejorar y clarificar la sección sobre cómo Kotlin maneja la nulabilidad, es crucial enfocar la redacción para que sea precisa, concisa y directamente informativa. Aquí te ofrezco una versión revisada de tu texto que corrige algunos errores tipográficos y mejora la claridad del mensaje:
=== Solución en Kotlin: Seguridad de Tipos frente a Nulos
Kotlin introduce un sistema de tipos que distingue claramente entre referencias que pueden ser nulas
y aquellas que no pueden serlo. Esto evita los errores comunes de `NullPointerException` que son
frecuentes en muchos otros lenguajes de programación.
==== Tipos no nullables y nullables
En Kotlin, las variables son no nulables por defecto. Esto significa que no puedes asignar `null` a
una variable a menos que se declare explícitamente como nullable. Para declarar una variable
nullable, añade `?` al tipo de la variable.
```kotlin
var a: String = "Definitivamente no nulo"
var b: String? = "Posiblemente nulo"
a = null // Error de compilación: tipo no nulable
b = null // Permitido: tipo nulable
```
En el ejemplo anterior:
- `a` es una variable de tipo `String`, que no puede ser nula. Intentar asignar `null` resulta en un
error de compilación.
- `b` es una variable de tipo `String?`, que puede ser nula. Kotlin permite asignar `null` a este
tipo sin problema.
==== Inferencia de tipos y nulabilidad
Kotlin también soporta la inferencia de tipos, lo que permite omitir la declaración explícita del
tipo cuando este puede ser inferido del contexto. Sin embargo, la inferencia de tipos no cambia las
reglas de nulabilidad:
```kotlin
var c = "Hola" // Tipo inferido como String, no nullable
c = null // Error de compilación: `c` es inferido como no nullable
```
En este caso:
- `c` es automáticamente inferido como `String` debido a la asignación inicial y, por defecto, no admite `null`.
==== Llamadas Seguras en Kotlin
En Kotlin, el manejo de variables que pueden ser nulas es fundamental debido al sistema de tipos
diseñado para prevenir `NullPointerExceptions`. El compilador de Kotlin obliga a lxs desarrolladores
a tratar las nulidades de manera explícita, asegurando que los accesos a variables nullables se
manejen adecuadamente antes de su uso.
*Comprobación de Nulos Obligatoria:*
Para acceder a una propiedad o método de un objeto que podría ser nulo, Kotlin *no permite*
simplemente hacerlo sin verificar si el objeto no es nulo. Si se intenta, el código no compilará,
lo que obliga a manejar estas situaciones para garantizar la seguridad del programa:
```kotlin
val a: String? = TODO()
if (a != null) {
println(a.length) // Acceso seguro porque se ha comprobado que 'a' no es nulo.
} else {
println("a es nulo")
}
```
En este código:
- `a` es una variable que puede ser nula (`String?`).
- `TODO()` es una instrucción que significa "voy a implementar esto más tarde", es útil para
ejemplos, pero no debe usarse en producción ya que siempre arrojará un error.
- Se utiliza una instrucción `if` para comprobar explícitamente que `a` no es nulo antes de acceder
a su propiedad `length`.
- Este enfoque asegura que no se lanzará un `NullPointerException`.
*Sintaxis de Llamadas Seguras*
Para simplificar el manejo de nulos, Kotlin ofrece el operador de llamada segura (`?.`). Este
operador permite realizar una operación sobre un objeto solo si no es nulo, de lo contrario devuelve
`null`, evitando así el error en tiempo de ejecución:
```kotlin
println(a?.length) // Evalúa a 'null' y no hace nada si 'a' es nulo.
```
Este fragmento de código:
- Evalúa `a?.length`: si `a` no es nulo, devuelve la longitud; si `a` es nulo, devuelve `null`.
- `println` imprimirá el resultado, que será `null` si `a` es nulo.
*Operador Elvis en Kotlin*
El operador Elvis (`?:`) en Kotlin es una herramienta eficiente para manejar valores nulos en
expresiones. Funciona evaluando la primera parte de la expresión (a la izquierda del operador) y, si
el resultado no es nulo, lo retorna directamente. Si es nulo, evalúa y retorna la segunda parte de
la expresión (a la derecha del operador).
El operador Elvis permite proporcionar un valor por defecto para expresiones que puedan resultar en
nulo, reduciendo así la necesidad de bloques condicionales explícitos en el código. La expresión a
la derecha del operador solo se evalúa si la expresión de la izquierda es nula, lo que lo hace
eficiente en términos de rendimiento.
```kotlin
val a: String? = TODO()
val l = a?.length ?: -1
```
En este ejemplo:
- `a?.length` intenta obtener la longitud de `a`. Si que `a` es nulo, esta parte de la expresión
también evaluaría a nulo.
- `?: -1` se activaría debido a que el resultado de la primera parte es nulo, y por lo tanto, el
operador Elvis retorna `-1`.
Este patrón es especialmente útil cuando se necesita un valor por defecto para evitar valores nulos
en el flujo de un programa.
_Detalles Importantes:_
- *Evaluación de Cortocircuito*: El operador Elvis realiza una evaluación de cortocircuito similar
a los operadores lógicos en muchos lenguajes de programación. Esto significa que si la parte
izquierda de la expresión es no nula, la parte derecha no se evalúa en absoluto.
- *Uso en Cadenas de Llamadas Seguras*: El operador Elvis es particularmente útil en combinación
con llamadas seguras (`?.`), permitiendo manejar cadenas de métodos o propiedades que podrían ser
nulas de una manera muy concisa y legible.
#line(length: 100%)
*Ejercicio: Procesamiento de Temperaturas de Ciudades*
Desarrolla un programa que maneje y procese información sobre temperaturas de diferentes ciudades,
que pueden o no estar disponibles (null).
1. *Datos de Entrada*:
- Define un diccionario (`Map<String, Int?>`) donde cada clave es el nombre de una ciudad y cada
valor asociado es la temperatura registrada en esa ciudad, que puede ser nula si no se ha
registrado correctamente.
2. *Procesamiento de Datos*:
- Itera sobre el diccionario usando un bucle. Durante la iteración, utiliza llamadas seguras
para verificar si las temperaturas son nulas.
3. *Salida del Programa*:
- Imprime el nombre de cada ciudad junto con su temperatura. Si la temperatura es nula, imprime
el mensaje: `Temperatura no disponible.`
#line(length: 100%) |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/quill/0.2.0/src/utility.typ | typst | Apache License 2.0 |
#let if-none(a, b) = { if a != none { a } else { b } }
#let is-gate(item) = { type(item) == "dictionary" and "gate-type" in item }
#let is-circuit-drawable(item) = { is-gate(item) or type(item) in ("string", "content") }
#let is-circuit-meta-instruction(item) = { type(item) == "dictionary" and "qc-instr" in item }
// Get content from a gate or plain content item
#let get-content(item, draw-params) = {
if is-gate(item) {
if item.draw-function != none {
let func = item.draw-function
return func(item, draw-params)
}
} else { return item }
}
// Get size hint for a gate or plain content item
#let get-size-hint(item, draw-params) = {
if is-gate(item) {
let func = item.size-hint
return func(item, draw-params)
}
measure(item, draw-params.styles)
}
|
https://github.com/taooceros/typst-sync-packages | https://raw.githubusercontent.com/taooceros/typst-sync-packages/main/packages/local/apa/0.1.0/lib.typ | typst | Apache License 2.0 | #let apa(title: [], authors: (), institution: [], course: none, professor: [], body, title-abbr: [], section: none) = {
set document(author: authors, title: title)
set page(numbering: "1", number-align: center, margin: 1in, paper: "us-letter", header: align(left, text(gray.darken(50%), title-abbr)))
set text(font: "<NAME>", lang: "en", weight: 300, size: 12pt)
set heading(numbering: "1.1")
set block(below: 2em, above: 2em)
set par(leading: 2em, first-line-indent: 2em, justify: false, linebreaks: "optimized")
align(center + horizon, {
block(text(weight: "bold", title))
v(3em)
pad(
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center, author)),
),
)
institution
if (course != none) {
[course, section]
}
professor
datetime.today().display("[month repr:long] [day], [year]")
v(15em)
})
pagebreak(weak: true)
body
} |
https://github.com/rikhuijzer/phd-thesis | https://raw.githubusercontent.com/rikhuijzer/phd-thesis/main/functions.typ | typst | The Unlicense | #let only(values) = {
assert(values.len() == 1, message: "Expected an array of length 1")
values.first()
}
#let title() = "Predicting Dropout in Special Forces Selection"
#let textcite(
label,
supplement: none,
) = {
cite(
label,
supplement: supplement,
form: "prose",
)
}
// Parenthetical citation without surrounding braces.
// Thanks to https://github.com/typst/typst/issues/1139#issuecomment-2002940931.
#let parencite(
label
) = context {
// I probably can fix the not-showing-et-al bug but I need to figure out what cite calls.
[#cite(label, form: "author"), #cite(label, form:"year")]
}
#let avoid_indent() = context [
#v(-0.5cm)
\
]
// Ensure that the next page starts on the right.
#let pagebreak_to_right() = context [
#pagebreak()
#if calc.even(only(counter(page).get())) [
#pagebreak()
]
]
#let chapter(
title,
label: none,
abstract: none
) = context {
let based_on = if label != none [
#set text(size: 9pt)
_This chapter is based on:_ #v(0pt) \
#set text(size: 8pt)
#label
] else [
]
let abstract_text = if label != none [
=== Abstract
#abstract
] else [
]
let chapter_selector = selector(
heading.where(level: 1)
).before(here())
let chapter_num = only(counter(chapter_selector).get()) + 1
[
#pagebreak()
#show heading.where(level: 1): it => [
#set text(0pt)
]
// This heading is shown in the Table of Contents,
// but hidden from the chapter page.
#par(justify: false)[
= #title
#if chapter_num in range(2, 6) [
#text([CHAPTER #chapter_num], style: "italic", size: 12pt) \
]
\
#text(title, weight: "bold", size: 16pt) \
#if label != none [
\
#based_on
\
]
]
// Basically nested if is an and.
#if abstract != none [
#if label != none [
#abstract_text
#pagebreak()
]
]
]
}
#let header(
current_heading
) = context {
let num = only(counter(page).get())
let is_left_page = calc.even(num)
set text(size: 9pt)
set text(fill: gray)
if is_left_page [
#upper(title())
] else [
#h(1fr)
#upper(current_heading)
]
}
#let bib() = {
set par(
first-line-indent: 0em,
justify: false,
)
[= Bibliography]
set text(size: 7pt)
bibliography("references.bib", title: none, style: "apa.csl")
}
#let note(
txt
) = {
assert(type(txt) == content, message: "Expected content type")
let elems = txt.children
if elems.last() == [ ] {
elems.pop()
}
let last_child = elems.last()
let last_txt = last_child.text.trim(regex("\n| "))
assert(last_txt.ends-with("."), message: "Note did not end with a dot")
set text(size: 8pt, top-edge: 0.7em)
set align(left)
[_Note._ #txt #linebreak()]
}
|
https://github.com/MALossov/YunMo_Doc | https://raw.githubusercontent.com/MALossov/YunMo_Doc/main/template/utils.typ | typst | Apache License 2.0 | #import "font.typ": *
// -----------------
// zhnumbers 工具函数
// @param: num, level 1 的章节数字
// @return: zhnum, num 对应的汉语数字
// -----------------
// 2023/4/11 update log:
// - 使用 `at` 进行索引,抛弃了恐怖的语法
// - 扩展了支持的数字范围,更新到[0, 10]
#let zhnumbers(num) = {
("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十").at(int(num))
}
// -----------------
// textbf 工具函数
// @param: it, 要加粗的文本
// @return: text, 加粗的文本
// -----------------
// 2023/4/11 update log:
// - 粗体字
#let textbf(it) = [
#set text(weight: "semibold")
#it
]
// -----------------
// textit 工具函数
// @param: it, 要斜体的文本
// @return: text, 斜体的文本
// -----------------
// 2023/4/11 update log:
// - 斜体字
#let textit(it) = [
#set text(style: "italic")
#it
] |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/game-theoryst/0.1.0/src/utils/styling_utils.typ | typst | Apache License 2.0 | #import table: cell
#import "table_utils.typ": blank-cells
#import "programming_utils.typ": if-else
// Helper function to format player 1's name
// Default color is red
// Default rspn (`row-span`) is for a 3x3 game
#let p1(name, color: red, rspn: 3) = {
cell(
inset: (right: 1em),
rowspan: rspn,
text(
fill: color,
weight: "semibold",
name
)
)
}
// Helper function to format player 1's name
// Default color is blue
// Default cspn (`column-span`) is for a 3x3 game
#let p2(name, color: blue, cspn: 3) = {
table.header(
blank-cells(),
cell(
inset: (bottom: 0.66em),
colspan: cspn,
text(
fill: color,
weight: "semibold",
name
)
)
)
}
// Utility for styling mixed parameters
#let mixd(color: "e64173", delims: ([\[], [\]]), spaces: false, body) = {
let spc = if-else(spaces, [ ], [])
set text(fill: rgb(color))
if body != [] [#delims.at(0)#spc#body#spc#delims.at(1)]
} |
https://github.com/uben0/tree-sitter-typst | https://raw.githubusercontent.com/uben0/tree-sitter-typst/master/DOC.md | markdown | MIT License | # Implementation documentation
## Tricky Typst
List of tests exposing particular behaviors from Typst
- Test `positive/320`: indent takes in account comments, but redent is done at item, term or heading token.
- Tests `positive/328` and `positive/329`: math function don't work with symbol.
- Test `positive/330`: Comment block don't need closing end.
## FIXME
- [ ] Test `fixme/011`: Embedded code causes a segfault
- With new version of Tree Sitter or Helix, this bug seems to be fixed
- [X] ~Test `fixme/014`: Right square bracket exits from all containers~
- [X] ~Test `fixme/012`: Matching square brackets in text are paired~
- [X] ~Test `fixme/013`: Point ending a ref is not part of the ref~
- [X] ~Test `fixme/010`: Math shorthand and letter can applied~
- [X] ~Test `fixme/009`: Indentation and comments~
- [X] ~Test `fixme/001`: Group termination in math~
- [X] ~Test `fixme/002`: Import precedence over list~
- [X] ~Test `fixme/008`: Condition if set statement~
- [X] ~Test `fixme/007`: Trailing comments before `else`~
- [X] ~Test `fixme/003`: Spaces in method notation~
- [X] ~Test `fixme/004`: Leading space not recognized~
- [X] ~Test `fixme/005`: Inlined code absorbs new line~
Failing tests are found in [`corpus/fixme.scm`](https://github.com/uben0/tree-sitter-typst/blob/master/corpus/fixme.scm).
## Optimization with extras
When searching ways to optimize the parser and simplify the grammar, I thought about using the *extras* feature for spaces and comments (and line breaks as well). At the end, it significantly reduced parser size. The only problem arises with function calls and, in inline code, field access. They must be directly joined (no space nor comment in between). The use of the *immediate* feature won't solve the problem as it only takes in acount inline regex (which would be ok with spaces but not comments, as they have to appear in output tree).
The solution is to rely on external scanner when parsing spaces or comments. Lets call a "pre-immediate" token, a token susceptible to be followed by immediate token. When a pre-immediate token is parsed, it sets a flag to `true`, and when a space or comment is parsed, it resets the flag to `false` (this flag is stored in scanner's state as a boolean).
This way when a token has to be immediate, an external token can be required and will only match if flag is `true`. It means, any pre-immediate token have to be preceded by a token that will set to `true` the flag.
# Scanner
## Containers
The scanner uses a stack of "containers" as internal states in order to simplify the parsing of some nodes like `emph`, `strong` and `content`. At any moment, the scanner knows what are the containing nodes. For instance:
```typst
* _ #[Hello *World*] _ *
```
Here, when the scanner will be called at the beginning of "World", the container stack will be `stron/emph/content/strong`. When a '*' is encountered while the top of the stack is `strong`, it will be interpreted as the end of this container. If the top of the stack was `emph`, it would be the start of a `strong` container, and it would be pushed on the stack.
It is mandatory to use the external scanner for the containers because of indentation.
## Indentation
Three distinct token are dedicated to indentation:
- `indent`: When the following line start further than the current one
- `dedent`: When the following line start at a column previously set as indentation column
- `redent`: When the following line start at the same column as current one, or before, but further than the previous indentation.
The concept of redent can be seen here:
```typst
- 1
- 2
- 3
- 4
```
Which have the same hierarchy as:
```typst
- 1
- 2
- 3
- 4
```
## Character class
Five character classes are defined in the external scanner:
- space (`is_sp`)
- line break (`is_lb`)
- xid start (`is_id_start`)
- xid continue (`is_id_continue`)
- word part (`is_word_part`)
The three functions `is_id_start`, `is_id_continue` and `is_word_part` are implemented as binary search.
The character list is based on the Unicode database which can be found here: https://www.unicode.org/Public/UCD/latest/ucd/
A utility is used to produce those tables: https://github.com/uben0/unicode-table
## Barrier
The `heading`, `item` and `term` nodes are technically delimited contexts, but because thay behave similarly, they have the same external token as container, which is `barrier`.
|
https://github.com/morrisfeist/cvgen | https://raw.githubusercontent.com/morrisfeist/cvgen/master/README.md | markdown | MIT License | A PDF generator for CVs using typst
<img src="docs/cv.png" alt="Example generated pdf"/>
## Usage
```bash
# Download JSON file into working directory
curl https://raw.githubusercontent.com/morrisfeist/cvgen/master/docs/cv.json --output cv.json
# Edit JSON file with your editor of choice
nano/vim/emacs/code/… cv.json
# Create `cv.pdf` in working directory
nix run github:morrisfeist/cvgen -- --file cv.json
```
Alternativly to continuously work on it while reviewing changes:
```bash
# Download JSON file into working directory
curl https://raw.githubusercontent.com/morrisfeist/cvgen/master/docs/cv.json --output cv.json
# Create `cv.pdf` in working directory
nix run github:morrisfeist/cvgen -- --watch --file cv.json
# Open pdf-viewer that reloads the document when it is updated
# e.g.
zathura cv.pdf
# Edit JSON file with your editor of choice
nano/vim/emacs/code/… cv.json
```
## Acknowledgements
The layout was inspired by [jankapunkt/latexcv](https://github.com/jankapunkt/latexcv/tree/master/sidebarleft).
|
https://github.com/kurk070ff/typst-flake-template | https://raw.githubusercontent.com/kurk070ff/typst-flake-template/master/README.md | markdown | # Typst template
This is a template for creating documents written in typst for the nix package manager
Usage:
```sh
$> nix flake init -t github:kurk070ff/typst-flake-template # To init in an already existing directory
$> nix flake new -t github:kurk070ff/typst-flake-template <folder-name> # To create a new directory
```
|
|
https://github.com/isaacholt100/isaacholt | https://raw.githubusercontent.com/isaacholt100/isaacholt/main/public/maths-notes/4-cambridge%3A-part-III/combinatorics/combinatorics.typ | typst | MIT License | #import "../../template.typ": *
#show: doc => template(doc, hidden: (), slides: false)
= Set systems
== Chains and antichains
#note[
The ideas in combinatorics often occur in the proofs, so it is advisable to learn the techniques used in proofs, rather than just learning the results and not their proofs.
]
#definition[
Let $X$ be a set. A *set system* on $X$ (also called a *family of subsets of $X$*) is a collection $cal(A) subset.eq powset(X)$.
]
#notation[
$X^((r)) := {A subset.eq X: |A| = r}$ denotes the family of subsets of $X$ of size $r$.
]
#remark[
Usually, we take $X = [n] = {1, ..., n}$, so $|X^((r))| = binom(n, r)$.
]
#notation[
For brevity, we write e.g. $[4]^((2)) = {12, 13, 14, 23, 24, 34}$.
]
#definition[
We can visualise $powset(A)$ as a graph by joining nodes $A in powset(X)$ and $B in powset(X)$ if $|A Delta B| = 1$, i.e. if $A = B union {i}$ for some $i in.not B$, or vice versa.
This graph is the *discrete cube* $Q_n$.
Alternatively, we can view $Q_n$ as an $n$-dimensional unit cube ${0, 1}^n$ by identifying e.g. ${1, 3} subset.eq [5]$ with $10100$ (i.e. identify $A$ with $bb(1)_A$, the characteri stic/indicator function of $A$).
]<def:discrete-cube>
#definition[
$cal(A) subset.eq powset(X)$ is a *chain* if $forall A, B in cal(A)$, $A subset.eq B$ or $B subset.eq A$.
]<def:chain>
#example[
- $cal(A) = {23, 1235, 123567}$ is a chain.
- $cal(A) = {emptyset, 1, 12, ..., [n]} subset.eq powset([n])$ is a chain.
]
#definition[
$cal(A) subset.eq powset(X)$ is an *antichain* if $forall A != B in cal(A)$, $A subset.eq.not B$.
]<def:antichain>
#example[
- $cal(A) = {23, 137}$ is an antichain.
- $cal(A) = {1, ..., n} subset.eq powset([n])$ is an antichain.
- More generally, $cal(A) = X^((r))$ is an antichain for any $r$.
]
#proposition[
A chain and an antichain can meet at most once.
]
#proofhints[
Trivial.
]
#proof[
By definition.
]
#proposition[
A chain $cal(A) subset.eq powset([n])$ can have at most $n + 1$ elements.
]
#proofhints[
Trivial.
]
#proof[
For each $0 <= r <= n$, $cal(A)$ can contain at most $1$ $r$-set (set of size $r$).
]
#theorem(name: "Sperner's Lemma")[
Let $cal(A) subset.eq powset(X)$ be an antichain. Then $|cal(A)| <= binom(n, floor(n\/2))$, i.e. the maximum size of an antichain is achieved by the set of $X^((floor(n\/2)))$.
]<thm:sperners-lemma>
#proofhints[
- Let $r < n/2$.
- Let $G$ be bipartite subgraph of $Q_n$ spanned by $X^((r)) union X^((r + 1))$.
- By considering an expression and upper bound for number of $S$-$Gamma(S)$ edges in $G$ for each $S subset.eq X^((r))$, show that there is a matching from $X^((r))$ to $X^((r + 1))$.
- Reason that this induces a matching from $X^((r))$ to $X^((r - 1))$ for each $r > n/2$.
- Reason that joining these matchings together, together with length $1$ chains of subsets of $X^((floor(n\/2)))$ not included in a matching, result in a partition of $powset(X)$ into $binom(n, floor(n\/2))$ chains, and conclude result from here.
]
#proof[
- We use the idea: from "a chain meets each layer in $<=1$ points, because a layer is an antichain", we try to decompose the cube into chains.
- We partition $powset(X)$ into $binom(n, floor(n\/2))$ chains, so each subset of $X$ appears exactly once in one chain. Then we are done (since to form an antichain, we can pick at most one element from each chain).
- To achieve this, it is sufficient to find:
- For each $r < n/2$, a matching from $X^((r))$ to $X^((r + 1))$ (a matching is a set of disjoint edges, one for each point in $X^((r))$).
- For each $r > n/2$, a matching from $X^((r))$ to $X^((r - 1))$.
- Then put these matchings together to form a set of chains, each passing through $X^((floor(n\/2)))$. If a subset $X^((floor(n\/2)))$ has a chain passing through it, then this chain is unique. The subsets with no chain passing through form their own one-element chain.
- By taking complements, it is enough to construct the matchings just for $r < n/2$ (since a matching from $X^((r))$ to $X^((r + 1))$ induces a matching from $X^((n - r - 1))$ to $X^((n - r))$: there is a correspondence between $X^((r))$ and $X^((n - r))$ by taking complements, and taking complements reverse inclusion, so edges in the induced matching are guaranteed to exist).
- Let $G$ be the (bipartite) subgraph of $Q_n$ spanned by $X^((r)) union X^((r + 1))$.
- For any $S subset.eq X^((r))$, the number of $S$-$Gamma(S)$ edges in $G$ is $|S|(n - r)$ (counting from below) since there are $n - r$ ways to add an element.
- This number is $<= |Gamma(S)| (r + 1)$ (counting from above), since $r + 1$ ways to remove an element.
- Hence $|Gamma(S)| >= (|S| (n - r))/(r + 1) >= |S|$ as $r < n/2$.
- So by Hall's theorem, since there is a matching from $S$ to $Gamma(S)$, there is a matching from $X^((r))$ to $X^((r + 1))$.
]
#remark[
The proof above doesn't tell us when we have equality in Sperner's Lemma.
]
#definition[
For $cal(A) subset.eq X^((r))$ ($1 <= r <= n$), the *shadow* of $cal(A)$ is the set of subsets which can be obtained by removing one element from a subset in $cal(A)$: $
partial cal(A) = partial^- cal(A) := {B in X^((r - 1)): B subset.eq cal(A) "for some" A in cal(A)}.
$
]<def:shadow>
#example[
Let $cal(A) = {123, 124, 134, 137} in [7]^((3))$. Then $partial cal(A) = {12, 13, 23, 14, 24, 34, 17, 37}$.
]
#proposition(name: "Local LYM")[
Let $cal(A) subset.eq X^((r))$, $1 <= r <= n$. Then $
(|partial cal(A)|)/binom(n, r - 1) >= (|cal(A)|)/binom(n, r).
$ i.e. the proportion of the level occupied by $partial cal(A)$ is at least the proportion of the level occupied by $cal(A)$.
]<prop:local-lym>
#proofhints[
Find equation and upper bound for number of $cal(A)$-$partial cal(A)$ edges in $Q_n$.
]
#proof[
- The number of $cal(A)$-$partial cal(A)$ edges in $Q_n$ is $|A|r$ (counting from above, since we can remove any of $r$ elements from $|A|$ sets) and is $<= |partial cal(A)| (n - r + 1)$ (since adding one of the $n - r + 1$ elements not in $A in partial cal(A)$ to $A$ may not result in a subset of $cal(A)$).
- So $(|partial cal(A)|)/(|cal(A)|) >= r/(n - r + 1) = binom(n, r - 1)\/binom(n, r)$.
]
#remark[
For equality in Local LYM, we must have that $forall A in cal(A)$, $forall i in A$, $forall j in.not A$, we must have $(A - {i}) union {j} in cal(A)$, i.e. $cal(A) = emptyset$ or $X^((r))$ for some $r$.
]
#notation[
Write $cal(A)_r$ for $cal(A) sect X^((r))$.
]
#theorem(name: "LYM Inequality")[
Let $cal(A) subset.eq powset(X)$ be an antichain. Then $
sum_(r = 0)^n (|cal(A) sect X^((r))|)/binom(n, r) <= 1.
$
]<thm:lym-inequality>
#proofhints[
- Method 1: show the result for the sum $sum_(r = k)^n$ by induction, starting with $k = n$. Use local LYM, and that $partial cal(A)_n$ and $cal(A)_(n - 1)$ are disjoint (and analogous results for lower levels).
- Method 2: let $cal(C)$ be uniformly random maximal chain, find an expression for $Pr(cal(C) "meets" cal(A))$.
- Method 3: determine number of maximal chains in $X$, determine number of maximal chains passing through a fixed $r$-set, deduce maximal number of chains passing through $cal(A)$.
]
#proof[
- Method 1: "bubble down with local LYM".
- We trivially have that $cal(A)_n \/ binom(n, n) <= 1$.
- $partial cal(A)_n$ and $cal(A)_(n - 1)$ are disjoint, as $cal(A)$ is an antichain.
- So $ (|partial cal(A)_n|)/binom(n, n - 1) + (|cal(A)_(n - 1)|)/binom(n, n - 1) = (|partial cal(A)_n union cal(A)_(n - 1)|)/binom(n, n - 1) <= 1. $
- So by local LYM, $ (|cal(A)_n|)/binom(n, n) + (|cal(A)_(n - 1)|)/binom(n, n - 1) <= 1. $
- Now, $partial (partial A_n union A_(n - 1))$ and $cal(A)_(n - 2)$ are disjoint, as $cal(A)$ is an antichain.
- So $ (|partial(partial cal(A)_n union cal(A)_(n - 1))|)/binom(n, n - 2) + (|cal(A)_(n - 2)|)/binom(n, n - 2) <= 1. $
- So by local LYM, $ (|partial A_n union cal(A)_(n - 1)|)/binom(n, n - 1) + (|cal(A)_(n - 2)|)/binom(n, n - 2) <= 1. $
- So $ (|cal(A)_n|)/binom(n, n) + (|cal(A)_(n - 1)|)/binom(n, n - 1) + (|cal(A)_(n - 2)|)/binom(n, n - 2) <= 1. $
- Continuing inductively, we obtain the result.
- Method 2:
- Choose uniformly at random a maximal chain $cal(C)$ (i.e. $C_0 subset.neq C_1 subset.eq dots.c subset.neq C_n$ with $abs(C_r) = r$ for all $r$).
- For any $r$-set $A$, $Pr(A in cal(C)) = 1\/binom(n, r)$, since all $r$-sets are equally likely.
- So $Pr(cal(C) "meets" cal(A)_r) = abs(cal(A)_r)\/binom(n, r)$, since events are disjoint.
- So $Pr(cal(C) "meets" cal(A)) = sum_(r = 0)^n abs(cal(A)_r)\/binom(n, r) <= 1$ since events are disjoint (since $cal(A)$ is an antichain).
- Method 3: equivalently, the number of maximal chains is $n!$, and the number through any fixed $r$-set is $r! (n - r)!$, so $sum_r abs(cal(A)_r) r! (n - r)! <= n!$.
]
#remark[
To have equality in LYM, we must have equality in each use of local LYM in proof method 1. In this case, the maximum $r$ with $cal(A)_r != emptyset$ has $cal(A)_r = X^((r))$. So equality holds iff $cal(A) = X^((r))$ for some $r$. Hence equality in Sperner's Lemma holds iff $cal(A) = X^((floor(n\/2)))$ or $cal(A) = X^((ceil(n\/2)))$.
]
== Two total orders on $X^((r))$
#definition[
Let $A != B$ be $r$-sets, $A = a_1 ... a_r$, $B = b_1 ... b_r$ (where $a_1 < dots.c < a_n$, $b_1 < dots.c < b_n$). $A < B$ in the *lexicographic (lex)* ordering if for some $j$, we have $a_i = b_i$ for all $i < j$, and $a_j < b_j$.
]<def:lex-order>
#example[
The elements of $[4]^((2))$ in lexicographic order are $12, 13, 14, 23, 24, 34$. The elements of $[6]^((3))$ in lexicographic order are $123, 124, 125, 126, 134, 135, 136, 145, 146, 156, 234, 235, 236, 245, 246, 256, 345, 346, 356, 456$.
]
#definition[
Let $A != B$ be $r$-sets, $A = a_1 ... a_r$, $B = b_1 ... b_r$ (where $a_1 < dots.c < a_n$, $b_1 < dots.c < b_n$). $A < B$ in the *colexicographic (colex)* order if for some $j$, we have $a_i = b_i$ for all $i > j$, and $a_j < b_j$. "avoid large elements".
]<def:colex-order>
#example[
The elements of $[4]^((2))$ in colex order are $12, 13, 23, 14, 24, 34$. The elements of $[6]^((3))$ are $123, 124, 134, 234, 125, 135, 235, 145, 245, 345, 126, 136, 236, 146, 246, 346, 156, 256, 356, 456$.
]
#remark[
Lex and colex are both total orders. Note that in colex, $[n - 1]^((r))$ is an initial segment of $[n]^((r))$ (this does not hold for lex). So we can view colex as an enumeration of $NN^((r))$.
]
#remark[
$A < B$ in colex iff $A^c < B^c$ in lex with ground set order reversed.
]
#remark[
We want to show that if $cal(A) subset.eq X^((r))$ and $cal(C) subset.eq X^((r))$ is the initial segment of colex with $abs(cal(C)) = abs(cal(A))$, then $abs(partial cal(C)) <= abs(partial cal(A))$. In particular, if $abs(cal(A)) = binom(k, r)$, then $abs(partial cal(A)) >= binom(k, r - 1)$.
]
== Compressions
#remark[
We want to transform $cal(A) subset.eq X^((r))$ into some $cal(A)' subset.eq X^((r))$ such that:
- $abs(cal(A)') = abs(cal(A))$,
- $abs(partial cal(A)') <= abs(partial cal(A))$.
Ideally, we want a family of such "compressions" $cal(A) -> cal(A)' -> ... -> cal(B)$ such that either $cal(B) = cal(C)$, or $cal(B)$ is similar enough to $cal(C)$ that we can directly check that $abs(partial cal(B)) >= abs(partial cal(C))$.
]
== Shadows
#remark[
By Local LYM, we know that $abs(partial cal(A)) >= abs(cal(A)) r\/(n - r + 1)$. Equality is rare (only for $cal(A) = X^((r))$ for $0 <= r <= n$). What happens in between, i.e., given $abs(cal(A))$, how should we choose $cal(A)$ to minimise $abs(partial A)$?
You should be able to convince yourself that if $abs(cal(A)) = binom(k, r)$, then we should take $cal(A) = [k]^((r))$. If $binom(k, r) < abs(cal(A)) < binom(k + 1, r)$, then convince yourself that we should take some $[k]^((r))$ plus some $r$-sets in $[k + 1]^((r))$.
E.g. for $cal(A) subset.eq X^((r))$ with $abs(cal(A)) = binom(8, 3) + binom(4, 2)$, take $cal(A) = [8]^((3)) union \{9 union B: B in [4]^((2))\}$.
]
= Isoperimetric inequalities
= Intersecting families |
https://github.com/ayoubelmhamdi/typst-phd-AI-Medical | https://raw.githubusercontent.com/ayoubelmhamdi/typst-phd-AI-Medical/master/chapters/ch04-art.typ | typst | MIT License | #import "../functions.typ": heading_center, images, italic,linkb
#let finchapiter = text(size: 24pt, fill:rgb("#1E045B"),[■])
/*
*
* ARTICLE 04
*
*/
= DETECTING LUNG CANCER NODULES.
== Introduction and Related Work
CT Scan ...
Automatic brain tumor segmentation directly from CT scan represent a challenging task involving a plethora disciplines covering pathology and radiology [38].
In fact, there are many issues associated with nodule pulmonary cancer, segmentation may be of any size, may have a variety of shapes, may appear at any location, and may appear in different image intensities[6].
Some tumors also deform other structures and appear together with edema that changes intensity properties of the nearby region [25].
For many human experts, manual segmentation is a difficult and time consuming task, this is the reason why there is an effort in the automated this process [46].
There are many possible applications of an automated method, it can be used for surgical planning, treatment planning, and vascular analysis.
(...other metodes...)
Other methods are based on statistical pattern recognition techniques, for instance the approach designed by researchers in [30], validated against meningiomas and low-grade gliomas.
(... some introduction to wat i we do in next chapters ...)
The aim of this models is to classify CT scan image as benign or affected by lung cancer.
= Method.
== Discussion.
Neural Networks are exploited in the method proposed in [27] to classify brain CTs: they achieve an accuracy equal to 96.33 %.
A deep learning-based method is proposed in [36], where .... we segment the MRIs and then they extract a set of features using ... .
The deep neural network designed is composed by 7 hidden layers.
... convolutional neural networks composed by 7 hidden layers, obtaining an accuracy equal to 0.86 in brain cancer grade detection.
Preliminary experiments on high-grade cancer patients provided by the LUNA16 dataset confirm the effectiveness of the proposed approach in nodules lung cancer segmentation.
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/themes/dewdrop.typ | typst | // This theme is inspired by https://github.com/zbowang/BeamerTheme
// The typst version was written by https://github.com/OrangeX4
#import "../utils/utils.typ"
#import "../utils/states.typ"
#let slide(
self: none,
subsection: none,
title: none,
footer: auto,
..args,
) = {
self.page-args = self.page-args + (
fill: self.colors.neutral-lightest,
)
if footer != auto {
self.m-footer = footer
}
(self.methods.touying-slide)(
..args.named(),
self: self,
subsection: subsection,
title: title,
setting: body => {
set text(fill: self.colors.neutral-darkest)
show heading: set text(fill: self.colors.primary)
show: args.named().at("setting", default: body => body)
if self.auto-heading and subsection != none {
heading(level: 1, subsection)
}
if self.auto-heading and title != none {
heading(level: 2, title)
}
body
},
..args.pos(),
)
}
#let title-slide(
self: none,
extra: none,
..args,
) = {
self = utils.empty-page(self)
let info = self.info + args.named()
let content = {
set text(fill: self.colors.neutral-darkest)
set align(center + horizon)
block(width: 100%, inset: 3em, {
block(
fill: self.colors.neutral-light,
inset: 1em,
width: 100%,
radius: 0.2em,
text(size: 1.3em, fill: self.colors.primary, text(weight: "medium", info.title))
+ (if info.subtitle != none {
linebreak()
text(size: 0.9em, fill: self.colors.primary, info.subtitle)
})
)
set text(size: .8em)
if info.author != none {
block(spacing: 1em, info.author)
}
v(1em)
if info.date != none {
block(spacing: 1em, if type(info.date) == datetime { info.date.display(self.datetime-format) } else { info.date })
}
set text(size: .8em)
if info.institution != none {
block(spacing: 1em, info.institution)
}
if extra != none {
block(spacing: 1em, extra)
}
})
}
(self.methods.touying-slide)(self: self, repeat: none, content)
}
#let focus-slide(self: none, body) = {
self = utils.empty-page(self)
self.page-args = self.page-args + (
fill: self.colors.primary,
margin: 2em,
)
set text(fill: self.colors.neutral-lightest, size: 1.5em)
(self.methods.touying-slide)(self: self, repeat: none, align(horizon + center, body))
}
#let new-section-slide(self: none, section) = {
(self.methods.slide)(self: self, section: section, heading(level: 2, self.outline-title) + parbreak() + (self.methods.touying-outline)(self: self))
}
#let d-outline(self: none, enum-args: (:), list-args: (:), cover: true) = states.touying-progress-with-sections(dict => {
let (current-sections, final-sections) = dict
current-sections = current-sections.filter(section => section.loc != none)
final-sections = final-sections.filter(section => section.loc != none)
let current-index = current-sections.len() - 1
let d-cover(i, body) = if i != current-index and cover {
(self.methods.d-cover)(self: self, body)
} else {
body
}
set enum(..enum-args)
set list(..enum-args)
set text(fill: self.colors.primary)
for (i, section) in final-sections.enumerate() {
d-cover(i, {
enum.item(i + 1, [#link(section.loc, section.title)<touying-link>] + if section.children.filter(it => it.kind != "slide").len() > 0 {
let subsections = section.children.filter(it => it.kind != "slide")
set text(fill: self.colors.neutral-dark, size: 0.9em)
list(
..subsections.map(subsection => [#link(subsection.loc, subsection.title)<touying-link>])
)
})
})
parbreak()
}
})
#let d-sidebar(self: none) = states.touying-progress-with-sections(dict => {
let (current-sections, final-sections) = dict
current-sections = current-sections
.filter(section => section.loc != none)
.map(section => (section, section.children))
.flatten()
.filter(item => item.kind != "slide")
final-sections = final-sections
.filter(section => section.loc != none)
.map(section => (section, section.children))
.flatten()
.filter(item => item.kind != "slide")
let current-index = current-sections.len() - 1
show: block.with(width: self.d-sidebar.width, inset: (top: 4em, x: 1em))
set align(left)
set par(justify: false)
set text(size: 0.9em)
for (i, section) in final-sections.enumerate() {
if section.kind == "section" {
set text(fill: if i != current-index { self.colors.primary.lighten(self.d-alpha) } else { self.colors.primary })
[#link(section.loc, utils.section-short-title(section.title))<touying-link>]
} else {
set text(fill: if i != current-index { self.colors.neutral-dark.lighten(self.d-alpha) } else { self.colors.neutral-dark }, size: 0.9em)
[#link(section.loc, utils.section-short-title(h(.3em) + section.title))<touying-link>]
}
parbreak()
}
})
#let d-mini-slides(self: none) = states.touying-progress-with-sections(dict => {
let (current-sections, final-sections) = dict
current-sections = current-sections.filter(section => section.loc != none)
final-sections = final-sections.filter(section => section.loc != none)
let current-i = current-sections.len() - 1
let cols = ()
let current-count = 0
for (i, section) in current-sections.enumerate() {
if self.d-mini-slides.section {
for slide in section.children.filter(it => it.kind == "slide") {
current-count += 1
}
}
for subsection in section.children.filter(it => it.kind != "slide") {
for slide in subsection.children {
current-count += 1
}
}
}
let final-count = 0
for (i, section) in final-sections.enumerate() {
let primary-color = if i != current-i { self.colors.primary.lighten(self.d-alpha) } else { self.colors.primary }
cols.push({
set align(left)
set text(fill: primary-color)
[#link(section.loc, utils.section-short-title(section.title))<touying-link>]
linebreak()
if self.d-mini-slides.section {
for slide in section.children.filter(it => it.kind == "slide") {
final-count += 1
if i == current-i and final-count == current-count {
[#link(slide.loc, sym.circle.filled)<touying-link>]
} else {
[#link(slide.loc, sym.circle)<touying-link>]
}
}
}
if self.d-mini-slides.section and self.d-mini-slides.subsection {
linebreak()
}
for subsection in section.children.filter(it => it.kind != "slide") {
for slide in subsection.children {
final-count += 1
if i == current-i and final-count == current-count {
[#link(slide.loc, sym.circle.filled)<touying-link>]
} else {
[#link(slide.loc, sym.circle)<touying-link>]
}
}
if self.d-mini-slides.subsection {
linebreak()
}
}
})
}
set align(top)
show: block.with(inset: (top: .5em, x: 2em))
show linebreak: it => it + v(-1em)
set text(size: .7em)
grid(columns: cols.map(_ => auto).intersperse(1fr), ..cols.intersperse([]))
})
#let slides(self: none, title-slide: true, outline-slide: true, slide-level: 2, ..args) = {
if title-slide {
(self.methods.title-slide)(self: self)
}
if outline-slide {
(self.methods.slide)(self: self, heading(level: 2, self.outline-title) + parbreak() + (self.methods.touying-outline)(self: self, cover: false))
}
(self.methods.touying-slides)(self: self, slide-level: slide-level, ..args)
}
#let register(
aspect-ratio: "16-9",
navigation: "sidebar",
sidebar: (width: 10em),
mini-slides: (height: 4em, x: 2em, section: false, subsection: true),
footer: [],
footer-right: states.slide-counter.display() + " / " + states.last-slide-number,
primary: rgb("#0c4842"),
alpha: 70%,
self,
) = {
assert(navigation in ("sidebar", "mini-slides", none), message: "navigation must be one of sidebar, mini-slides, none")
// color theme
self = (self.methods.colors)(
self: self,
neutral-darkest: rgb("#000000"),
neutral-dark: rgb("#202020"),
neutral-light: rgb("#f3f3f3"),
neutral-lightest: rgb("#ffffff"),
primary: primary,
)
// save the variables for later use
self.d-navigation = navigation
self.d-sidebar = sidebar
self.d-mini-slides = mini-slides
self.d-footer = footer
self.d-footer-right = footer-right
self.d-alpha = alpha
self.auto-heading = true
self.outline-title = [Outline]
// set page
let header(self) = {
if self.d-navigation == "sidebar" {
place(right + top, (self.methods.d-sidebar)(self: self))
} else if self.d-navigation == "mini-slides" {
(self.methods.d-mini-slides)(self: self)
}
}
let footer(self) = {
set text(size: 0.8em)
set align(bottom)
show: pad.with(.5em)
text(fill: self.colors.neutral-darkest.lighten(40%), utils.call-or-display(self, self.d-footer))
h(1fr)
text(fill: self.colors.neutral-darkest.lighten(20%), utils.call-or-display(self, self.d-footer-right))
}
self.page-args = self.page-args + (
paper: "presentation-" + aspect-ratio,
fill: self.colors.neutral-lightest,
header: header,
footer: footer,
) + if navigation == "sidebar" {(
margin: (top: 2em, bottom: 1em, x: 0em),
)} else if navigation == "mini-slides" {(
margin: (top: mini-slides.height, bottom: 2em, x: 0em),
)} else {(
margin: (top: 2em, bottom: 2em, x: 0em),
)}
self.padding = (x: if navigation == "sidebar" { sidebar.width } else { mini-slides.x }, y: 0em)
// register methods
self.methods.slide = slide
self.methods.title-slide = title-slide
self.methods.focus-slide = focus-slide
self.methods.new-section-slide = new-section-slide
self.methods.touying-new-section-slide = new-section-slide
self.methods.slides = slides
self.methods.d-cover = (self: none, body) => {
utils.cover-with-rect(fill: utils.update-alpha(
constructor: rgb, self.page-args.fill, self.d-alpha), body)
}
self.methods.touying-outline = d-outline
self.methods.d-outline = d-outline
self.methods.d-sidebar = d-sidebar
self.methods.d-mini-slides = d-mini-slides
self.methods.alert = (self: none, it) => text(fill: self.colors.primary, it)
self.methods.init = (self: none, body) => {
set text(size: 20pt)
set par(justify: true)
show heading: set block(below: 1em)
body
}
self
}
|
|
https://github.com/EstebanMunoz/typst-template-informe | https://raw.githubusercontent.com/EstebanMunoz/typst-template-informe/main/conf.typ | typst | MIT No Attribution | #import "title-page.typ": title-page
#import "custom-outline.typ": custom-outline
#import "@preview/codly:1.0.0": *
#import "@preview/subpar:0.1.1"
#let conf(
include-title-page: true,
title: none,
subject: none,
students: (),
teachers: (),
auxiliaries: (),
assistants: (),
lab-assistants: (),
semester: none,
due-date: none,
place: none,
university: none,
faculty: none,
department: none,
logo: none,
course-code: none,
course-name: none,
doc
) = {
// Función que entrega el heading que debe ir en el header
let get-heading-for-header() = context {
let headings = query(
selector(heading.where(level: 1))
).filter(it => it.location().page() <= here().page())
return if headings.len() > 0 {
headings.last().body
}
}
// Seteo general del documento
set document(title: title, author: students)
set page(
"us-letter",
margin: (top: 3.37cm, bottom: 3.07cm, right: 2.54cm, left: 2.54cm),
header: [#stack(
dir: ttb,
spacing: 4.5pt,
[#smallcaps(title) #h(1fr) #emph(get-heading-for-header())],
line(length: 100%, stroke: 0.4pt)
)],
footer: [#stack(
dir: ttb,
spacing: 4.5pt,
line(length: 100%, stroke: 0.4pt),
[#emph([#course-code #course-name]) #h(1fr) #context counter(page).display(here().page-numbering())]
)],
numbering: "1"
)
set par(leading: 0.55em, justify: true)
set heading(numbering: "1.")
set text(size: 11pt, font: "New Computer Modern", lang: "es")
set raw(syntaxes: "template/assets/syntaxes/Arduino.sublime-syntax")
show raw: set text(size: 11pt, font: "New Computer Modern Mono")
show bibliography: set par(justify: false)
set bibliography(style: "institute-of-electrical-and-electronics-engineers")
// Introduce la portada
if include-title-page {
title-page(
title: title,
subject: subject,
students: students,
teachers: teachers,
auxiliaries: auxiliaries,
assistants: assistants,
lab-assistants: lab-assistants,
semester: semester,
due-date: due-date,
place: place,
university: university,
faculty: faculty,
department: department,
logo: logo
)
}
// Resize de títulos y subtítulos
let font-sizes = (17.28pt, 14.4pt, 12pt)
show heading: it => block(above: 1.4em, below: 1em)[
#let new-size = font-sizes.at(it.level - 1, default: 11pt)
#set text(size: new-size)
#if it.numbering == none {
it.body
} else [
#context counter(it.func()).display() #h(10pt) #it.body
]
]
// Modifica apariencia de índices
show outline: it => custom-outline(title: it.title, target: it.target)
// Modifica apariencia de tablas
show table.cell.where(y: 0): strong
set table(
stroke: (_, y) => (
left: 0pt,
right: 0pt,
top: if y == 1 { 1pt } else { 0pt },
bottom: 1pt
),
inset: (x, y) => if y == 0 { 8pt } else { 5pt }
)
// Usa el paquete Codly para modificar la apariencia de códigos
show figure.where(kind: raw): set figure(supplement: "Código")
let icon(codepoint) = {
box(
height: 0.8em,
baseline: 0.05em,
image(codepoint)
)
h(0.1em)
}
show: codly-init.with()
codly(languages: (
python: (
name: "Python",
icon: icon("template/assets/logos/python.svg"),
color: rgb("#FFC331")
),
javascript: (
name: "JavaScript",
icon: icon("template/assets/logos/javascript.svg"),
color: rgb("#F7DF1E")
),
rust: (
name: "Rust",
icon: icon("template/assets/logos/rust.svg"),
color: rgb("#CE412B")
),
arduino: (
name: "Arduino",
icon: icon("template/assets/logos/arduino.svg"),
color: rgb("#00878F")
)
))
// Figuras pueden ser contenidas en múltiples páginas
show figure: set block(breakable: true)
// Comienzo del documento
doc
}
// Crea función para subfigures
#let subfigures = subpar.grid.with(
gap: 1em,
numbering-sub-ref: "1.a",
)
// Misc: configuraciones extra
#let months = ("January": "Enero", "February": "Febrero", "March": "Marzo", "April": "Abril", "May": "Mayo", "June": "Junio", "July": "Julio", "August": "Agosto", "September": "Septiembre", "October": "Octubre", "November": "Noviembre", "December": "Diciembre")
#let month = datetime.today().display("[month repr:long]")
#let today = datetime.today().display("[day] de [month repr:long] de [year]").replace(month, months.at(month))
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/互联网原理与技术/作业/template.typ | typst | The Unlicense | #let 字号 = (
初号: 42pt,
小初: 36pt,
一号: 26pt,
小一: 24pt,
二号: 22pt,
小二: 18pt,
三号: 16pt,
小三: 15pt,
四号: 14pt,
中四: 13pt,
小四: 12pt,
五号: 10.5pt,
小五: 9pt,
六号: 7.5pt,
小六: 6.5pt,
七号: 5.5pt,
小七: 5pt,
)
#let 字体 = (
仿宋: ("Times New Roman", "FangSong"),
宋体: ("Times New Roman", "SimSun"),
黑体: ("Times New Roman", "SimHei"),
楷体: ("Times New Roman", "KaiTi"),
代码: ("New Computer Modern Mono", "Times New Roman", "SimSun"),
)
#let answer(body) = {
set par(justify: true,first-line-indent: 2em)
body
}
#let project(
title: "",
authors: (),
body
) = {
set document(author: authors, title: title)
set page(numbering: "1", number-align: center, margin: 0.7in)
set text(font: 字体.宋体, size: 字号.小四, lang: "zh")
// heading,一级标题换页,首行居中
show heading: set text(font: 字体.黑体)
set heading(numbering: "1.1")
show heading: it => {
if it.level == 1 {
text(font: 字体.黑体, size: 字号.四号, it)
}
else if it.level == 2 {
text(font: 字体.黑体, size: 字号.小四, it)
}
else if it.level == 3 {
text(font: 字体.黑体, size: 字号.五号, it)
}
}
// figure(image)
show figure: it => [
#set align(center)
#if not it.has("kind") {
it
} else if it.kind == image {
it.body
[
#set text(font: 字体.宋体, size: 字号.五号, weight: "extrabold")
#h(1em)
#it.caption
]
} else if it.kind == code {
[
#set text(font: 字体.宋体, size: 字号.五号, weight: "bold")
#h(1em)
#it.caption
]
it.body
}
]
align(center)[
#block(text(font: 字体.黑体, size: 字号.二号, weight: "bold", title))
]
body
}
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/signature/user.typ | typst | Apache License 2.0 | #let f(u, v) = u + v;
#(/* ident after */ f);
|
https://github.com/timon-schelling/abi-research-paper-rewrite-with-typst | https://raw.githubusercontent.com/timon-schelling/abi-research-paper-rewrite-with-typst/main/src/template.typ | typst | #let project(
title: "",
authors: (),
date: none,
bib: none,
bib-title: none,
numbering-skip-outline: true,
body,
) = {
set document(author: authors, title: title)
set page(numbering: if numbering-skip-outline { none } else { "1" })
set text(font: "Linux Libertine", lang: "de")
set heading(numbering: "1.1")
text(1.1em, date)
v(1.2em, weak: true)
text(2em, weight: 700, title)
// Author information.
pad(
top: 0.7em,
right: 20%,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(start, strong(author))),
),
)
pagebreak()
// Table of contents.
outline(depth: 5, indent: true)
pagebreak()
// Page numbering.
set page(numbering: "1")
if numbering-skip-outline {
counter(page).update(1)
}
// Main body.
set par(justify: true)
body
// Display the bibliography, if any is given.
if bib != none {
pagebreak()
show bibliography: set text(8.3pt)
show bibliography: pad.with(x: 0.5pt)
show bibliography: set heading(numbering: "1.1")
[
= #bib-title
]
bibliography(bib, title: none)
}
}
#let regular_polygon(
radius: 10pt,
sides: 4,
inner: false,
fill: none,
stroke: black + 1pt,
) = {
let halfstep = calc.pi / sides
let step = 2 * halfstep
if inner {
radius = radius / calc.cos(halfstep)
}
let side = calc.tan(halfstep) * radius
let calc-x(n) = (calc.cos((step * n) - halfstep + (calc.pi/2)) * radius)
let calc-y(n) = (calc.sin((step * n) - halfstep + (calc.pi/2)) * radius)
let offset-x = 0 * radius
let offset-y = 0 * radius
for n in range(sides) {
let x = calc-x(n)
let y = calc-y(n)
if x > offset-x {
offset-x = x
}
if y > offset-y {
offset-y = y
}
}
let calc-vert(n) = {
let x = (calc-x(n) + offset-x)
let y = (calc-y(n) + offset-y)
((x, y),)
}
let vertices = for n in range(sides) {
calc-vert(n)
}
polygon(
fill: fill,
stroke: stroke,
..vertices
)
}
#let help_lines(
width: 220pt,
height: 220pt,
x-start: 10pt,
y-start: 10pt,
x-spacing: 20pt,
y-spacing: 20pt,
stroke: (paint: gray.lighten(20%), dash: "densely-dashed", thickness: 0.5pt)
) = {
let x-lines = calc.ceil((width - x-start) / x-spacing)
let y-lines = calc.ceil((height - y-start) / y-spacing)
rect(width: width, height: height, inset: 0pt, stroke: none)[
#for n in range(x-lines) {
place(top + left, line(start: ((n * x-spacing) + x-start, 0%), length: height, angle: 90deg, stroke: stroke))
}
#for n in range(y-lines) {
place(top + left, line(start: (0%, (n * y-spacing) + y-start), length: height, stroke: stroke))
}
]
}
#let axis(
length: 100%,
size: 2pt,
fill: black,
stroke: black,
angle: 0deg
) = rotate(angle + 90deg, rect(width: size, height: length, inset: 0pt, stroke: none)[
#line(length: 100%, start: (50%, 0%), angle: 90deg, stroke: stroke)
#place(top + center, regular_polygon(sides: 3, radius: size, fill: fill, stroke: stroke))
])
#let axes(
width: 100%,
height: 100%,
size: 2pt,
fill: black,
stroke: black
) = rect(width: width, height: height, inset: 0pt, stroke: none)[
#place(center + horizon, axis(length: width, size: size, fill: fill, stroke: stroke))
#place(center + horizon, axis(length: height, size: size, fill: fill, stroke: stroke, angle: -90deg))
]
#let arc(start: 0deg, end: 90deg, radius: 100%/2, segments: 10) = {
let bezier_arc(start: (x: 100, y: 0), end: (x: 200, y: 100), center: (x: 100, y: 100)) = {
let point_minus(a, b) = {
(x: a.x - b.x, y: a.y - b.y)
}
let point_mirror(a) = {
(x: -a.x, y: -a.y)
}
let a = point_minus(start, center)
let b = point_minus(end, center)
let q1 = a.x * a.x + a.y * a.y
let q2 = q1 + a.x * b.x + a.y * b.y
let k2 = (4.0 / 3.0) * (calc.sqrt(2.0 * q1 * q2) - q2) / ((a.x * b.y) - (a.y * b.x))
let control_1 = (x: center.x + a.x - k2 * a.y, y: center.y + a.y + k2 * a.x)
let control_2 = (x: center.x + b.x + k2 * b.y, y: center.y + b.y - k2 * b.x)
control_1 = point_minus(control_1, start)
control_2 = point_minus(control_2, end)
control_1 = point_mirror(control_1)
(
((start.x, start.y), (control_1.x, control_1.y)),
((end.x, end.y), (control_2.x, control_2.y))
)
}
let start = start - 180deg
let end = end - 180deg
let segment = (end - start) / segments
let segs = for n in range(segments) {
let a = (x: - (calc.sin(start + (n * segment))), y: calc.cos(start + (n * segment)))
let b = (x: - (calc.sin(start + ((n + 1) * segment))), y: calc.cos(start + ((n + 1) * segment)))
bezier_arc(start: a, end: b, center: (x: 0, y: 0))
}
let ret = ()
for (i, e) in segs.enumerate() {
if calc.rem(i, 2) == 0 {
ret.push(e)
}
}
ret.push(segs.last())
ret.map(
((a, b)) => {
let (ax, ay) = a
let (cx, cy) = b
((ax * radius, ay * radius), (cx * radius, cy * radius))
}
)
}
|
|
https://github.com/atareao/fondos-productivos | https://raw.githubusercontent.com/atareao/fondos-productivos/master/src/paquetes-linux.typ | typst | MIT License | #set page(
"presentation-16-9",
fill: black,
margin: 0.5cm)
#set text(size: 12pt, fill: white)
= Gestión de paquetes en Linux
#columns(3, gutter: 12pt)[
== Instalar desde repositorio
- `snap install <paquete>`
- `flatpak install [remote] <paquete>`
- `apt install <paquete>`
- `yum install <paquete>`
- `dnf install <paquete>`
- `pkg install <paquete>`
- `apt-get install <paquete>`
- `pacman -S <paquete>`
- `pip install <paquete>`
- `zypper install <paquete>`
== Instalar desde archivo
- `flatpak install <paquete.flatpakref>`
- `dpkg -i [package.deb]`
- `yum install [package.rpm]`
- `dnf install [package.rpm]`
- `pkg add [package.txz]`
- `pacman -U [package.tar.gz]`
- `pip install [/path/to/package]`
== Desinstalar
- `snap remove [packageName]`
- `apt-get remove [packageName]`
- `apt remove [packageName]`
- `dnf erase [packageName]`
- `pkg delete [packageName]`
- `pacman -R [packageName]`
- `pip uninstall [packageName]`
- `zypper rm [packageName]`
== Buscar un paquete
- `snap find [query]`
- `flatpak search [query]`
- `apt-cache search [query]`
- `apt search [query]`
- `yum search [query]`
- `dnf search [query]`
- `pkg search [query]`
- `pacman -Ss [query]`
- `pip search [query]`
- `zypper search [packageName]`
== Ver información de un paquete
- `snap info [packageName]`
- `apt-cache show [packageName]`
- `apt show [packageName]`
- `dpkg -s [packageName]`
- `yum info [packageName]`
- `dnf info [packageName]`
- `pkg info [packageName]`
- `pacman -Si [packageName]`
- `pip show [packageName]`
== Actualizar la lista de paquetes
- `apt-get update`
- `apt update`
- `yum check-update`
- `dnf check-update`
- `pkg update`
- `pacman -S`
- `zypper refresh`
== Actualizar los paquetes instalados
- `snap refresh`
- `flatpak update`
- `apt-get upgrade`
- `apt upgrade`
- `yum update`
- `dnf upgrade`
- `pkg upgrade`
- `pacman -Syu`
- `pip install [packageName] --upgrade`
- `zypper update`
== Añadir un repositorio
- `add-apt-repository ppa:[userName]/[ppaName]`
- `add-apt-repository deb [url] [derivative]`
- `yum-config-manager --add-repo [url]`
- `dnf config-manager --add-repo [url]`
- `zypper addrepo [url] [alias]`
] |
https://github.com/GYPpro/ACM_res | https://raw.githubusercontent.com/GYPpro/ACM_res/main/C_printDoc.typ | typst | #import "@preview/codelst:2.0.1": sourcecode
// Display inline code in a box
#set text(font:("Times New Roman","Source Han Serif SC"))
#show raw.where(block: false): box.with(
fill: luma(230),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
#show raw: set text(
font: ("consolas", "Source Han Serif SC")
)
#set page(
// flipped: true,
// background: [#image("background.png")]
paper: "a4",
)
#set text(
font:("Times New Roman","Source Han Serif SC"),
style:"normal",
weight: "regular",
size: 13pt,
)
#show math.equation:set text(font:("New Computer Modern Math","Source Han Serif SC"))
#let nxtIdx(name) = box[ #counter(name).step()#counter(name).display()]
#set math.equation(numbering: "(1)")
#outline(depth: 2)
#set page(
paper:"a4",
number-align: right,
margin: (x:2cm,y:2.5cm),
header: [
#box(baseline:5pt)[#set text(
size: 11pt,
)
#align(
left+bottom,
[
#smallcaps[Templetes]
#h(1fr)#text("Github GYPpro/Acm_res",fill:rgb("#898989"));
]
)]
#line(start: (0pt,-10pt),end:(483pt,-10pt))
],
numbering: "1/1"
)
= #smallcaps[Basic]
== `bitset.h`
#sourcecode[```cpp
#include<bitset>
int n;
auto bin = bitset<32>(n);
cout << bin;
//输出二进制位
cout << bin.to_ullong();
//输出十进制
bin[1] = 1
//随机访问
bin = !bin ^ (bin & bin | bitset<32>(1))
//位运算
bin != bin
//比较运算符
bin.count()
//1的数量
bin.test(i)
//随机访问,类似std::vector::pos()
bin.any()
//有一位1就true
bin.none()
//全0就返回true
bin.all()
//全1就返回true
bin.flip()
//翻转全部
bin.flip(i)
//a[i] = !a[i]
bin._Find_first()
//第一个1的下标
bin._Find_next(i)
//从下标n往后第一个1的下标
```]
#pagebreak()
== `pbds.h`
#sourcecode[```cpp
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
using ord_set = tree<int, null_type, less<int>, rb_tree_tag,
tree_order_statistics_node_update>;
using ord_mset = tree<int, null_type, less_equal<int>, rb_tree_tag,
tree_order_statistics_node_update>;
//find_by_order
//order_of_key
```]
#pagebreak()
= #smallcaps[Ds]
== `bst.h`
#sourcecode[```cpp
const int N=1e5+100;
struct node{
int s[2];
int v,p,cnt,sz;
void init(int p1,int v1){
p=p1;v=v1;
cnt=sz=1;
}
}tr[N];
int root=0,idx=0;
void pushup(int x){
tr[x].sz=tr[x].cnt+tr[tr[x].s[1]].sz+tr[tr[x].s[0]].sz;
}
void rotate(int x){
int y=tr[x].p;
int z=tr[y].p;
int k=tr[y].s[1]==x;
tr[y].s[k]=tr[x].s[k^1];
tr[tr[x].s[k^1]].p=y;
tr[z].s[tr[z].s[1]==y]=x;
tr[x].p=z;
tr[y].p=x;
tr[x].s[k^1]=y;
pushup(y);pushup(x);
}
void splay(int x,int k){s
while(tr[x].p!=k){
int y=tr[x].p;
int z=tr[y].p;
if(z!=k) (tr[y].s[0]==x)^(tr[z].s[0]==y) ? rotate(x) : rotate(y);
rotate(x);
}
if(k==0) root=x;
}
void find(int v){
int x=root;
while(tr[x].v!=v && tr[x].s[v>tr[x].v] ) x=tr[x].s[v>tr[x].v];
splay(x,0);
}
int get_pre(int v){
find(v);
int x=root;
if(tr[x].v<v) return x;
x=tr[x].s[0];
while(tr[x].s[1]) x=tr[x].s[1];
splay(x,0);
return x;
}
int get_suc(int v){
find(v);
int x=root;
if(tr[x].v>v) return x;
x=tr[x].s[1];
while(tr[x].s[0]) x=tr[x].s[0];
splay(x,0);
return x;
}
void del(int v){
int pre=get_pre(v);
int suc=get_suc(v);
splay(pre,0);splay(suc,pre);
int d=tr[suc].s[0];
if(tr[d].cnt>1){
tr[d].cnt--;splay(d,0);
}
else{
tr[suc].s[0]=0;splay(suc,0);
}
}
void insert(int v){
int x=root;
int p=0;
while(x && tr[x].v!=v){
p=x;x=tr[x].s[v>tr[x].v];
}
if(x) tr[x].cnt++;
else{
x=++idx;
tr[p].s[v>tr[p].v]=x;
tr[x].init(p,v);
}
splay(x,0);
}
int get_rank(int v){
insert(v);
int res=tr[tr[root].s[0]].sz;
del(v);
return res;
}
int get_val(int k){
int x=root;
while(1){
int y=tr[x].s[0];
if(tr[x].cnt+tr[y].sz<k){
k-=tr[y].sz+tr[x].cnt;
x=tr[x].s[1];
}
else{
if(tr[y].sz>=k) x=tr[x].s[0];
else break;
}
}
splay(x,0);
return tr[x].v;
}
```]
#pagebreak()
== `dsu.h`
#sourcecode[```cpp
class DSU {
std::vector<int> f, siz;
public:
DSU() {}
DSU(int n) {
init(n);
}
void init(int n) {
f.resize(n);
for(int i = 0;i < n;i ++) f[i] = i;
siz.assign(n, 1);
}
int find(int x) {
while (x != f[x]) {
x = f[x] = f[f[x]];
}
return x;
}
bool same(int x, int y) {
return find(x) == find(y);
}
bool merge(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return false;
}
siz[x] += siz[y];
f[y] = x;
return true;
}
int size(int x) {
return siz[find(x)];
}
};
```]
#pagebreak()
== `segTree_add.h`
#sourcecode[```cpp
// AC 带懒惰标记线段树
template <class TYPE_NAME>
class lazyTree
{
/*
* TYPE_NAME需要支持:+ += != 和自定义的合并运算符
* 实现了懒惰标记,仅支持区间批量增加
* 区间批量减需要TYPE_NAME支持-,且有-a = 0 - a
* 额外处理了一个单点修改为对应值的函数,非原生实现,其复杂度为 4logn
* 不提供在线
* 不提供持久化
*/
private:
vector<TYPE_NAME> d;
vector<TYPE_NAME> a;
vector<TYPE_NAME> b;
int n;
const TYPE_NAME INI = 0; // 不会影响合并运算的初始值,如max取INF,min取0,mti取1
void subbuild(int s, int t, int p)
{
if (s == t)
{
d[p] = a[s];
return;
}
int m = s + ((t - s) >> 1); // (s+t)/2
subbuild(s, m, p * 2);
subbuild(m + 1, t, p * 2 + 1);
d[p] = d[p * 2] + d[p * 2 + 1];
// 合并运算符 ↑
}
TYPE_NAME subGetSum(int l, int r, int s, int t, int p)
{
if (l <= s && t <= r)
return d[p];
int m = s + ((t - s) >> 1);
if (b[p] != 0)
{
d[p * 2] += b[p] * (m - s + 1); // 合并运算符的高阶运算 此处运算为应用懒惰标记
d[p * 2 + 1] += b[p] * (t - m); // 合并运算符的高阶运算 此处运算为应用懒惰标记
b[p * 2] += b[p]; // 下传标记,无需修改
b[p * 2 + 1] += b[p]; // 下传标记,无需修改
b[p] = 0;
}
TYPE_NAME ansl = INI;
TYPE_NAME ansr = INI;
if (l <= m)
ansl = subGetSum(l, r, s, m, p * 2);
if (r > m)
ansr = subGetSum(l, r, m + 1, t, p * 2 + 1);
return ansl + ansr;
// 合并运算符↑
}
void subUpdate(int l, int r, TYPE_NAME c, int s, int t, int p)
{
if (l <= s && t <= r)
{
d[p] += (t - s + 1) * c; // 合并运算符的高阶运算 此处运算为修改整匹配区间值
b[p] += c; // 记录懒惰标记,无需修改
return;
}
int m = s + ((t - s) >> 1);
if (b[p] != 0 && s != t)
{
d[p * 2] += b[p] * (m - s + 1); // 合并运算符的高阶运算 此处运算为应用懒惰标记
d[p * 2 + 1] += b[p] * (t - m); // 合并运算符的高阶运算 此处运算为应用懒惰标记
b[p * 2] += b[p]; // 下传标记,无需修改
b[p * 2 + 1] += b[p]; // 下传标记,无需修改
b[p] = 0;
}
if (l <= m)
subUpdate(l, r, c, s, m, p * 2);
if (r > m)
subUpdate(l, r, c, m + 1, t, p * 2 + 1);
d[p] = d[p * 2] + d[p * 2 + 1];
// 合并运算符 ↑
}
public:
lazyTree(TYPE_NAME _n)
{
n = _n;
d.resize(4 * n + 5);
a.resize(4 * n + 5);
b.resize(4 * n + 5);
}
void build(vector<TYPE_NAME> _a)
{
a = _a;
subbuild(1, n, 1);
}
TYPE_NAME getsum(int l, int r)
{
return subGetSum(l, r, 1, n, 1);
}
void update(int l, int r, TYPE_NAME c) // 修改区间
{
subUpdate(l, r, c, 1, n, 1);
}
void update(int idx, TYPE_NAME tar)
{ // 修改单点,未测试
TYPE_NAME tmp = getsum(idx, idx);
tar -= tmp;
subUpdate(idx, idx, tar, 1, n, 1);
}
};
```]
#pagebreak()
== `segTree_add_setto.h`
#sourcecode[```cpp
template <typename T>
class SegTreeLazyRangeSet {
vector<T> tree, lazy;
vector<T> *arr;
vector<bool> ifLazy;
int n, root, n4, end;
void maintain(int cl, int cr, int p) {
int cm = cl + (cr - cl) / 2;
if (cl != cr && ifLazy[p]) {
lazy[p * 2] = lazy[p],ifLazy[p*2] = 1;
lazy[p * 2 + 1] = lazy[p],ifLazy[p*2+1] = 1;
tree[p * 2] = lazy[p] * (cm - cl + 1);
tree[p * 2 + 1] = lazy[p] * (cr - cm);
lazy[p] = 0;
ifLazy[p] = 0;
}
}
T range_sum(int l, int r, int cl, int cr, int p) {
if (l <= cl && cr <= r) return tree[p];
int m = cl + (cr - cl) / 2;
T sum = 0;
maintain(cl, cr, p);
if (l <= m) sum += range_sum(l, r, cl, m, p * 2);
if (r > m) sum += range_sum(l, r, m + 1, cr, p * 2 + 1);
return sum;
}
void range_set(int l, int r, T val, int cl, int cr, int p) {
if (l <= cl && cr <= r) {
lazy[p] = val;
ifLazy[p] = 1;
tree[p] = (cr - cl + 1) * val;
return;
}
int m = cl + (cr - cl) / 2;
maintain(cl, cr, p);
if (l <= m) range_set(l, r, val, cl, m, p * 2);
if (r > m) range_set(l, r, val, m + 1, cr, p * 2 + 1);
tree[p] = tree[p * 2] + tree[p * 2 + 1];
}
void build(int s, int t, int p) {
if (s == t) {
tree[p] = (*arr)[s];
return;
}
int m = s + (t - s) / 2;
build(s, m, p * 2);
build(m + 1, t, p * 2 + 1);
tree[p] = tree[p * 2] + tree[p * 2 + 1];
}
public:
explicit SegTreeLazyRangeSet<T>(vector<T> v) {
n = v.size();
n4 = n * 4;
tree = vector<T>(n4, 0);
lazy = vector<T>(n4, 0);
ifLazy = vector<bool>(n4,0);
arr = &v;
end = n - 1;
root = 1;
build(0, end, 1);
arr = nullptr;
}
void show(int p, int depth = 0) {
if (p > n4 || tree[p] == 0) return;
show(p * 2, depth + 1);
for (int i = 0; i < depth; ++i) putchar('\t');
printf("%d:%d\n", tree[p], lazy[p]);
show(p * 2 + 1, depth + 1);
}
T range_sum(int l, int r) { return range_sum(l, r, 0, end, root); }
void range_set(int l, int r, T val) { range_set(l, r, val, 0, end, root); }
};
```]
#pagebreak()
== `segTree_mul_add.h`
#sourcecode[```cpp
/*
三种操作:(模数为mod)
1.区间乘val
2.区间加val
3.区间和
*/
#define int long long
#define lc p<<1
#define rc p<<1|1
const int N=1e5+10;
int mod=1e9+7;
struct node{
int l,r,sum,mul,add;
}tr[4*N];
vector<int> a(N);
void pushup(int p){
tr[p].sum=tr[lc].sum+tr[rc].sum;
tr[p].sum%=mod;
}
void build(int p,int l,int r){
tr[p].l=l;tr[p].r=r;
tr[p].mul=1;tr[p].add=0;
if(l==r){
tr[p].sum=a[l];
return;
}
int m=l+r>>1;
build(lc,l,m);
build(rc,m+1,r);
pushup(p);
}
void pushdown(int p){
tr[lc].sum=(tr[lc].sum*tr[p].mul+tr[p].add*(tr[lc].r-tr[lc].l+1))%mod;
tr[rc].sum=(tr[rc].sum*tr[p].mul+tr[p].add*(tr[rc].r-tr[rc].l+1))%mod;
tr[lc].mul=tr[lc].mul*tr[p].mul%mod;
tr[rc].mul=tr[rc].mul*tr[p].mul%mod;
tr[lc].add=(tr[lc].add*tr[p].mul+tr[p].add)%mod;
tr[rc].add=(tr[rc].add*tr[p].mul+tr[p].add)%mod;
tr[p].mul=1;tr[p].add=0;
}
void update_mul(int p,int l,int r,int val){
if(l<=tr[p].l&&tr[p].r<=r){
tr[p].sum=tr[p].sum*val%mod;
tr[p].mul=tr[p].mul*val%mod;
tr[p].add=tr[p].add*val%mod;
return;
}
pushdown(p);
int m=tr[p].l+tr[p].r>>1;
if(l<=m) update_mul(lc,l,r,val);
if(m<r) update_mul(rc,l,r,val);
pushup(p);
return;
}
void update_add(int p,int l,int r,int val){
if(l<=tr[p].l&&tr[p].r<=r){
tr[p].add=(tr[p].add+val)%mod;
tr[p].sum=(tr[p].sum+val*(tr[p].r-tr[p].l+1))%mod;
return;
}
pushdown(p);
int m=tr[p].l+tr[p].r>>1;
if(l<=m) update_add(lc,l,r,val);
if(m<r) update_add(rc,l,r,val);
pushup(p);
return;
}
int query(int p,int l,int r){
if(l<=tr[p].l&&tr[p].r<=r) return tr[p].sum;
pushdown(p);
int m=tr[p].l+tr[p].r>>1;
int sum=0;
if(l<=m) sum+=query(lc,l,r);
if(m<r) sum+=query(rc,l,r);
return sum%mod;
}
void solve(){
int n,m;
cin>>n>>m>>mod;
for(int i=1;i<=n;i++) cin>>a[i];
build(1,1,n);
while(m--){
int op;
cin>>op;
if(op==1){
int x,y,val;
cin>>x>>y>>val;
update_mul(1,x,y,val);
}
else if(op==2){
int x,y,val;
cin>>x>>y>>val;
update_add(1,x,y,val);
}
else{
int x,y;
cin>>x>>y;
cout<<query(1,x,y)<<"\n";
}
}
return;
}
```]
#pagebreak()
== `segTree_MX_MI.h`
#sourcecode[```cpp
//AC MJ的MIN/MAX树
template<class Info>
struct SegmentTree {
int n;
std::vector<Info> info;
SegmentTree() : n(0) {}
SegmentTree(int n_, Info v_ = Info()) {
init(n_, v_);
}
template<class T>
SegmentTree(std::vector<T> init_) {
init(init_);
}
void init(int n_, Info v_ = Info()) {
init(std::vector(n_, v_));
}
template<class T>
void init(std::vector<T> init_) {
n = init_.size();
info.assign(4 << std::__lg(n), Info());
std::function<void(int, int, int)> build = [&](int p, int l, int r) {
if (r - l == 1) {
info[p] = init_[l];
return;
}
int m = (l + r) / 2;
build(2 * p, l, m);
build(2 * p + 1, m, r);
pull(p);
};
build(1, 0, n);
}
void pull(int p) {
info[p] = info[2 * p] + info[2 * p + 1];
}
void modify(int p, int l, int r, int x, const Info &v) {
if (r - l == 1) {
info[p] = v;
return;
}
int m = (l + r) / 2;
if (x < m) {
modify(2 * p, l, m, x, v);
} else {
modify(2 * p + 1, m, r, x, v);
}
pull(p);
}
void modify(int p, const Info &v) {
modify(1, 0, n, p, v);
}
Info rangeQuery(int p, int l, int r, int x, int y) {
if (l >= y || r <= x) {
return Info();
}
if (l >= x && r <= y) {
return info[p];
}
int m = (l + r) / 2;
return rangeQuery(2 * p, l, m, x, y) + rangeQuery(2 * p + 1, m, r, x, y);
}
Info rangeQuery(int l, int r) {
return rangeQuery(1, 0, n, l, r);
}
template<class F>
int findFirst(int p, int l, int r, int x, int y, F &&pred) {
if (l >= y || r <= x) {
return -1;
}
if (l >= x && r <= y && !pred(info[p])) {
return -1;
}
if (r - l == 1) {
return l;
}
int m = (l + r) / 2;
int res = findFirst(2 * p, l, m, x, y, pred);
if (res == -1) {
res = findFirst(2 * p + 1, m, r, x, y, pred);
}
return res;
}
template<class F>
int findFirst(int l, int r, F &&pred) {
return findFirst(1, 0, n, l, r, pred);
}
template<class F>
int findLast(int p, int l, int r, int x, int y, F &&pred) {
if (l >= y || r <= x) {
return -1;
}
if (l >= x && r <= y && !pred(info[p])) {
return -1;
}
if (r - l == 1) {
return l;
}
int m = (l + r) / 2;
int res = findLast(2 * p + 1, m, r, x, y, pred);
if (res == -1) {
res = findLast(2 * p, l, m, x, y, pred);
}
return res;
}
template<class F>
int findLast(int l, int r, F &&pred) {
return findLast(1, 0, n, l, r, pred);
}
};
const int inf = 1E9;
struct Info
{
int mn {inf}, mnId, mx {-inf}, mxId;
} ;
Info operator+(Info a, Info b)
{
if (a.mn > b.mn)
a.mn = b.mn, a.mnId = b.mnId;
if (a.mx < b.mx)
a.mx = b.mx, a.mxId = b.mxId;
return a;
}
```]
#pagebreak()
== `ST.h`
#sourcecode[```cpp
class SparseTable
{
using func_type = function<int(const int &, const int &)>;
vector<vector<int>> ST;
int len;
vector<int> preLog;
func_type op;
static int default_func(const int &t1, const int &t2) { return max(t1, t2); }
public:
void build(const vector<int> &v, func_type _func = default_func)
{
op = _func;
len = v.size();
int l1 = ceil(log2(len)) + 1;
ST.assign(len, vector<int>(l1, 0));
for (int i = 0; i < len; ++i)
{
ST[i][0] = v[i];
}
for (int j = 1; j < l1; ++j)
{
int pj = (1 << (j - 1));
for (int i = 0; i + pj < len; ++i)
{
ST[i][j] = op(ST[i][j - 1], ST[i + (1 << (j - 1))][j - 1]);
}
}
preLog.resize(len + 1);
lop(i, 1, len + 1) preLog[i] = floor(log2(i));
}
int getsum(int l, int r)
{
if (r < l)
return 0;
l = max(0, l), r = min(len - 1, r);
if (r == 0)
return 0;
int lt = r - l + 1;
int q = preLog[lt];
return op(ST[l][q], ST[r - (1 << q) + 1][q]);
}
};
```]
#pagebreak()
== `twoDimPrfxSum.h`
#sourcecode[```cpp
class prfx_2{
public:
vector<vector<int>> mtx;
int n,m;
public:
prfx_2(vector<vector<int>> _mtx){init(_mtx);};
prfx_2() { };
void init(vector<vector<int>> _mtx)
{
n = _mtx.size();
m = _mtx[0].size();
mtx.resize(n+1);
for(auto &x:mtx) x.resize(m+1);
lop(i,1,n+1)
lop(j,1,m+1)
mtx[i][j] = mtx[i-1][j] + mtx[i][j-1] - mtx[i-1][j-1] + _mtx[i-1][j-1];
}
int getsum(int x1,int y1,int x2,int y2)
{
x1 ++,x2 ++,y1 ++,y2 ++;
return mtx[x2][y2] - mtx[x1-1][y2] - mtx[x2][y1-1] + mtx[x1-1][y1-1];
}
int getsum(pii d1,pii d2)
{
auto [x1,y1] = d1;
auto [x2,y2] = d2;
x1 ++,x2 ++,y1 ++,y2 ++;
return mtx[x2][y2] - mtx[x1-1][y2] - mtx[x2][y1-1] + mtx[x1-1][y1-1];
}
vector<int> & operator[](std::size_t i)
{
return mtx[i];
}
};
class conj_diff_2{
vector<vector<int>> mtx;
vector<vector<int>> prf;
int n,m;
public:
conj_diff_2(int _n,int _m)
{
n = _n+1,m = _m+1;
vector<vector<int>> initmp(n,vector<int> (m,0));
init(initmp);
}
conj_diff_2(vector<vector<int>> _mtx)
{
this->init(_mtx);
}
conj_diff_2(){ }
void init(vector<vector<int>> _mtx)
{
n = _mtx.size();
m = _mtx[0].size();
mtx.resize(n+2);
for(auto &x:mtx) x.resize(m+2);
prf.resize(n+2);
for(auto &x:prf) x.resize(m+2);
lop(i,1,n+1)
lop(j,1,m+1)
prf[i][j] = _mtx[i-1][j-1];
}
void modify(int x1,int y1,int x2,int y2,int k)
{
x1 ++,x2 ++,y1 ++,y2 ++;
mtx[x1][y1] += k;
mtx[x2+1][y1] -= k,mtx[x1][y2+1] -= k;
mtx[x2+1][y2+1] += k;
}
void modify(pii d1,pii d2,int k)
{
this->modify(d1.fi,d1.se,d2.fi,d2.se,k);
}
vector<vector<int>> cacu()
{
auto res = prfx_2(mtx);
vector<vector<int>> rst(n,vector<int>(m));
lop(i,1,n+1)
lop(j,1,m+1)
rst[i-1][j-1] = prf[i][j] + res[i+1][j+1];
return rst;
}
vector<int> & operator[](std::size_t i)
{
return mtx[i];
}
};
```]
#pagebreak()
= #smallcaps[Geo]
== `3_Dim.h`
#sourcecode[```cpp
using ld = long double;
struct Point3
{
ld x, y, z;
Point3(ld x_ = 0, ld y_ = 0, ld z_ = 0) : x(x_), y(y_), z(z_) {}
Point3 &operator+=(Point3 p) &
{
return x += p.x, y += p.y, z += p.z, *this;
}
Point3 &operator-=(Point3 p) &
{
return x -= p.x, y -= p.y, z -= p.z, *this;
}
Point3 &operator*=(Point3 p) &
{
return x *= p.x, y *= p.y, z *= p.z, *this;
}
Point3 &operator*=(ld t) &
{
return x *= t, y *= t, z *= t, *this;
}
Point3 &operator/=(ld t) &
{
return x /= t, y /= t, z /= t, *this;
}
friend Point3 operator+(Point3 a, Point3 b) { return a += b; }
friend Point3 operator-(Point3 a, Point3 b) { return a -= b; }
friend Point3 operator*(Point3 a, Point3 b) { return a *= b; }
friend Point3 operator*(Point3 a, ld b) { return a *= b; }
friend Point3 operator*(ld a, Point3 b) { return b *= a; }
friend Point3 operator/(Point3 a, ld b) { return a /= b; }
friend auto &operator>>(istream &is, Point3 &p)
{
return is >> p.x >> p.y >> p.z;
}
friend auto &operator<<(ostream &os, Point3 p)
{
return os << "(" << p.x << ", " << p.y << ", " << p.z << ")";
}
};
using P3 = Point3;
struct Line3
{
Point3 a, b;
};
using L3 = Line3;
struct Plane
{
Point3 u, v, w;
};
ld len(P3 p)
{ // 原点到当前点的距离计算
return sqrt(p.x * p.x + p.y * p.y + p.z * p.z);
}
P3 crossEx(P3 a, P3 b)
{ // 叉乘
P3 ans;
ans.x = a.y * b.z - a.z * b.y;
ans.y = a.z * b.x - a.x * b.z;
ans.z = a.x * b.y - a.y * b.x;
return ans;
}
ld cross(P3 a, P3 b)
{
return len(crossEx(a, b));
}
ld dot(P3 a, P3 b)
{ // 点乘
return a.x * b.x + a.y * b.y + a.z * b.z;
}
P3 getVec(Plane s)
{ // 获取平面法向量
return crossEx(s.u - s.v, s.v - s.w);
}
ld dis(P3 a, P3 b)
{ // 三维欧几里得距离公式
ld val = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z);
return sqrt(val);
}
P3 standardize(P3 vec)
{ // 将三维向量转换为单位向量
return vec / len(vec);
}
bool onLine(P3 p1, P3 p2, P3 p3)
{ // 三点是否共线
return sign(cross(p1 - p2, p3 - p2)) == 0;
}
bool onLine(Plane s)
{
return onLine(s.u, s.v, s.w);
}
bool onPlane(P3 p1, P3 p2, P3 p3, P3 p4)
{ // 四点是否共面
ld val = dot(getVec({p1, p2, p3}), p4 - p1);
return sign(val) == 0;
}
bool pointOnSegment(P3 p, L3 l)
{
return sign(cross(p - l.a, p - l.b)) == 0 && min(l.a.x, l.b.x) <= p.x &&
p.x <= max(l.a.x, l.b.x) && min(l.a.y, l.b.y) <= p.y && p.y <= max(l.a.y, l.b.y) &&
min(l.a.z, l.b.z) <= p.z && p.z <= max(l.a.z, l.b.z);
}
bool pointOnSegmentEx(P3 p, L3 l)
{ // pointOnSegment去除端点版
return sign(cross(p - l.a, p - l.b)) == 0 && min(l.a.x, l.b.x) < p.x &&
p.x < max(l.a.x, l.b.x) && min(l.a.y, l.b.y) < p.y && p.y < max(l.a.y, l.b.y) &&
min(l.a.z, l.b.z) < p.z && p.z < max(l.a.z, l.b.z);
}
bool pointOnSegmentSide(P3 p1, P3 p2, L3 l)
{
if (!onPlane(p1, p2, l.a, l.b))
{ // 特判不共面
return 0;
}
ld val = dot(crossEx(l.a - l.b, p1 - l.b), crossEx(l.a - l.b, p2 - l.b));
return sign(val) == 1;
}
bool pointOnPlaneSide(P3 p1, P3 p2, Plane s)
{
ld val = dot(getVec(s), p1 - s.u) * dot(getVec(s), p2 - s.u);
return sign(val) == 1;
}
bool lineParallel(L3 l1, L3 l2)
{ // 平行
return sign(cross(l1.a - l1.b, l2.a - l2.b)) == 0;
}
bool lineVertical(L3 l1, L3 l2)
{ // 垂直
return sign(dot(l1.a - l1.b, l2.a - l2.b)) == 0;
}
```]
#pagebreak()
== `Cood_Convert.h`
#sourcecode[```cpp
using p = pair<int,int>;
```]
#pagebreak()
== `Distance.typ`
=== 曼哈顿距离
$ d(A,B) = |x_1 - x_2| + |y_1 - y_2| $
=== 欧几里得距离
$ d(A,B) = sqrt((x_1 - x_2)^2 + (y_1 - y_2)^2) $
=== 切比雪夫距离
$ d(A,B) = max(|x_1 - x_2|, |y_1 - y_2|) $
=== 闵可夫斯基距离
$ d(A,B) = (|x_1 - x_2|^p + |y_1 - y_2|^p)^{1/p} $
=== 曼哈顿转切比雪夫
对于直角坐标中的$A(x_1,y_1),B(x_2,y_2)$
其曼哈顿距离
$ d(A,B) = max(|(x_1+y_1) - (x_2+y_2)|,|(x_1-y_1)-(x_2-y_2|)) $
即为点$A'(x_1+y_1,x_1-y_1),B'(x_2+y_2,x_2-y_2)$的切比雪夫距离。
同理,其切比雪夫距离
$ d(A,B) = max(|(x_1+y_1)/2-(x_2+y_2)/2| + |(x_1-y_1)/2-(x_2-y_2)/2|) $
即为点$A'((x_1+y_1)/2,(x_1-y_1)/2),B'((x_2+y_2)/2, (x_2-y_2)/2)$的曼哈顿距离。
综上:
$
"曼哈顿距离" & =>"切比雪夫距离:" \
(x,y) & => (x+y,x-y) \
"切比雪夫距离"&=>"曼哈顿距离:"\
(x,y) &=> ((x+y)/2,(x-y)/2) $
#pagebreak()
== `Rotating_Calipers.h`
#sourcecode[```cpp
//Rotating_Calipers
template<typename VALUE_TYPE>
class Rotating_Calipers
{
public:
using pv = pair<VALUE_TYPE, VALUE_TYPE>;
using vec_pv = vector<pair<VALUE_TYPE, VALUE_TYPE>>;
vec_pv p;
static VALUE_TYPE cross(pv p1, pv p2, pv p0)
{
pv t1 = {p1.fi - p0.fi, p1.se - p0.se},
t2 = {p2.fi - p0.fi, p2.se - p0.se};
return t1.fi * t2.se - t1.se * t2.fi;
}
static VALUE_TYPE dis(const pv &p1,const pv &p2){
return (p1.fi - p2.fi) * (p1.fi - p2.fi) + (p1.se - p2.se) * (p1.se - p2.se);
};
public:
Rotating_Calipers() {}
Rotating_Calipers(vec_pv _A) {
build(_A);
}
void build(const vec_pv & _A) {
p = ConvexHull(_A);
}
static vec_pv ConvexHull(vec_pv A, VALUE_TYPE flag = 1)
{
int n = A.size();
if (n <= 2) return A;
vec_pv ans(n * 2);
sort(A.begin(), A.end(),
[](pv a,pv b) -> bool {
if(fabs(a.fi - b.fi) < 1e-10)
return a.se < b.se;
else return a.fi < b.fi;} );
int now = -1;
for (int i = 0; i < n; i++)
{ // 维护下凸包
while (now > 0 && cross(A[i], ans[now], ans[now - 1]) < flag) now--;
ans[++now] = A[i];
}
int pre = now;
for (int i = n - 2; i >= 0; i--)
{ // 维护上凸包
while (now > pre && cross(A[i], ans[now], ans[now - 1]) < flag) now--;
ans[++now] = A[i];
}
ans.resize(now);
return ans;
}
VALUE_TYPE getDiameter() {
int j = 1;
VALUE_TYPE ans = 0;
int m = p.size();
p.push_back(p[0]);
for(int i = 0;i < m;i ++)
{
while( cross(p[i+1],p[j],p[i]) > cross(p[i+1],p[j+1],p[i]) ) j = (j+1)%m;
ans = max(ans, max( dis(p[i],p[j]) , dis(p[i+1],p[j]) ) );
}
p.pop_back();
return ans;
}
VALUE_TYPE getPerimeter() {
VALUE_TYPE sum = 0;
p.pb(p[0]);
for(int i = 0;i < (int)p.size() - 1;i ++)
{
sum += sqrtl(dis(p[i],p[i+1]));
}
p.pop_back();
return sum;
}
};
```]
#pagebreak()
== `segIntersection.h`
#sourcecode[```cpp
using pii = pair<int, int>
#define fi first
#define se second
const long double EPS = 1e-9;
template <class T>
int sign(T x)
{
if (-EPS < x && x < EPS)
return 0;
return x < 0 ? -1 : 1;
}
// 叉乘
template <class T>
T cross(pair<T, T> a, pair<T, T> b)
{
return a.fi * b.se - a.se * b.fi;
}
// 二维快速跨立实验
template <class T>
bool segIntersection(pair<T, T> l1, pair<T, T> l2)
{
auto [s1, e1] = l1;
auto [s2, e2] = l2;
auto A = max(s1.fi, e1.fi), AA = min(s1.fi, e1.fi);
auto B = max(s1.se, e1.se), BB = min(s1.se, e1.se);
auto C = max(s2.fi, e2.fi), CC = min(s2.fi, e2.fi);
auto D = max(s2.se, e2.se), DD = min(s2.se, e2.se);
return A >= CC && B >= DD && C >= AA && D >= BB &&
sign(cross(s1, s2, e1) * cross(s1, e1, e2)) == 1 &&
sign(cross(s2, s1, e2) * cross(s2, e2, e1)) == 1;
}
//三维线段交点,需要P3封装,不相交返回{0,{}}
pair<bool, P3> lineIntersection(L3 l1, L3 l2)
{
if (!onPlane(l1.a, l1.b, l2.a, l2.b) || lineParallel(l1, l2))
{
return {0, {}};
}
auto [s1, e1] = l1;
auto [s2, e2] = l2;
ld val = 0;
if (!onPlane(l1.a, l1.b, {0, 0, 0}, {0, 0, 1}))
{
val = ((s1.x - s2.x) * (s2.y - e2.y) - (s1.y - s2.y) * (s2.x - e2.x)) /
((s1.x - e1.x) * (s2.y - e2.y) - (s1.y - e1.y) * (s2.x - e2.x));
}
else if (!onPlane(l1.a, l1.b, {0, 0, 0}, {0, 1, 0}))
{
val = ((s1.x - s2.x) * (s2.z - e2.z) - (s1.z - s2.z) * (s2.x - e2.x)) /
((s1.x - e1.x) * (s2.z - e2.z) - (s1.z - e1.z) * (s2.x - e2.x));
}
else
{
val = ((s1.y - s2.y) * (s2.z - e2.z) - (s1.z - s2.z) * (s2.y - e2.y)) /
((s1.y - e1.y) * (s2.z - e2.z) - (s1.z - e1.z) * (s2.y - e2.y));
}
return {1, s1 + (e1 - s1) * val};
}
```]
#pagebreak()
= #smallcaps[Graph]
== #smallcaps[Flow]
=== `max_Flow_print.h`
#sourcecode[```cpp
class maxFlow//AC
{
private:
class edge
{
public:
ll int nxt, cap, flow;
pair<int, int> revNodeIdx;
public:
edge(int _nxt, int _cap)
{
nxt = _nxt,cap = _cap,flow = 0;
}
void setRevIdx(int _i, int _j) { revNodeIdx = {_i,_j}; }
};
vector<vector<edge>> edgeList;
vector<int> dep,fir;
ll int maxFlowAns;
int T, S;
public:
maxFlow(int _n)
{
maxFlowAns = 0;
S = 1;
T = _n;
edgeList.resize(_n + 1);
dep.resize(_n + 1);
fir.resize(_n+1);
}
void resetTS(int _T, int _S) { T = _T,S = _S; }
void addedge(int _u, int _v, int _w)
{
edgeList[_u].push_back(edge(_v, _w));
edgeList[_v].push_back(edge(_u, 0));
edgeList[_u][edgeList[_u].size() - 1].setRevIdx(_v, edgeList[_v].size() - 1);
edgeList[_v][edgeList[_v].size() - 1].setRevIdx(_u, edgeList[_u].size() - 1);
}
bool bfs()
{
queue<int> que;
for (auto x = dep.begin(); x != dep.end(); x++) (*x) = 0;
dep[S] = 1;
que.push(S);
while (que.size())
{
ll int at = que.front();
que.pop();
for (int i = 0; i < edgeList[at].size(); i++)
{
auto tar = edgeList[at][i];
if ((!dep[tar.nxt]) && (tar.flow < tar.cap))
{
dep[tar.nxt] = dep[at] + 1;
que.push(tar.nxt);
}
}
}
return dep[T];
}
ll int dfs(int at, ll int flow)
{
if ((at == T) || (!flow))
return flow; // 到了或者没了
ll int ret = 0; // 本节点最大流
for (int &i = fir[at]; i < edgeList[at].size(); i++)
{
auto tar = edgeList[at][i]; // 目前遍历的边
int tlFlow = 0; // 目前边的最大流
if (dep[at] == dep[tar.nxt] - 1) // 遍历到的边为合法边
{
tlFlow = dfs(tar.nxt, min((ll)tar.cap - tar.flow, flow - ret));
if (!tlFlow)
continue; // 若最大流为0,什么都不做
ret += tlFlow; // 本节点最大流累加
edgeList[at][i].flow += tlFlow; // 本节点实时流量
edgeList[tar.revNodeIdx.first][tar.revNodeIdx.second].flow -= tlFlow; // 反向边流量
if (ret == flow)
return ret; // 充满了就不继续扫了
}
}
return ret;
}
ll int dinic()
{
if (maxFlowAns)
return maxFlowAns;
while (bfs())
{
for(auto x = fir.begin();x != fir.end();x ++) (*x) = 0;
maxFlowAns += dfs(S, INT_MAX);
}
return maxFlowAns;
}
};
```]
#pagebreak()
=== `min_Cost.h`
#sourcecode[```cpp
const int INF = 0x3f3f3f3f
class PD//AC
{
public:
class edge
{
public:
int v, f, c, next;
edge(int _v,int _f,int _c,int _next)
{
v = _v,f = _f,c = _c,next = _next;
}
edge() { }
} ;
void vecset(int value,vector<int> &arr)
{
for(int i = 0;i < arr.size();i ++) arr[i] = value;
return;
}
class node
{
public:
int v, e;
} ;
class mypair
{
public:
int dis, id;
bool operator<(const mypair &a) const { return dis > a.dis; }
mypair(int d, int x)
{
dis = d;
id = x;
}
};
vector<int> head,dis,vis,h;
vector<edge> e;
vector<node> p;
int n, m, s, t, cnt = 1, maxf, minc;
PD(int _n,int _m,int _s,int _t)
{
n = _n, m = _m,s = _s,t = _t;
maxf = 0, minc = 0;
head.resize(n+2), dis.resize(n+2),vis.resize(n+2);
e.resize(2);
h.resize(n+2), p.resize(m+2);
}
void addedge(int u, int v, int f, int c)
{
e.push_back(edge(v,f,c,head[u]));
head[u] = e.size()-1;
e.push_back(edge(u,0,-c,head[v]));
head[v] = e.size()-1;
}
bool dijkstra()
{
priority_queue<mypair> q;
vecset(INF,dis);
vecset(0,vis);
dis[s] = 0;
q.push(mypair(0, s));
while (!q.empty())
{
int u = q.top().id;
q.pop();
if (vis[u])
continue;
vis[u] = 1;
for (int i = head[u]; i; i = e[i].next)
{
int v = e[i].v, nc = e[i].c + h[u] - h[v];
if (e[i].f && dis[v] > dis[u] + nc)
{
dis[v] = dis[u] + nc;
p[v].v = u;
p[v].e = i;
if (!vis[v])
q.push(mypair(dis[v], v));
}
}
}
return dis[t] != INF;
}
void spfa()
{
queue<int> q;
vecset(63,h);
h[s] = 0, vis[s] = 1;
q.push(s);
while (!q.empty())
{
int u = q.front();
q.pop();
vis[u] = 0;
for (int i = head[u]; i; i = e[i].next)
{
int v = e[i].v;
if (e[i].f && h[v] > h[u] + e[i].c)
{
h[v] = h[u] + e[i].c;
if (!vis[v])
{
vis[v] = 1;
q.push(v);
}
}
}
}
}
int pd()
{
spfa();
while (dijkstra())
{
int minf = INF;
for (int i = 1; i <= n; i++)
h[i] += dis[i];
for (int i = t; i != s; i = p[i].v)
minf = min(minf, e[p[i].e].f);
for (int i = t; i != s; i = p[i].v)
{
e[p[i].e].f -= minf;
e[p[i].e ^ 1].f += minf;
}
maxf += minf;
minc += minf * h[t];
}
return 0;
}
pair<int,int> get()
{
return {maxf,minc};
}
};
```]
#pagebreak()
== #smallcaps[Path]
=== `SCSP.h`
#sourcecode[```cpp
// Sides Change Shortest Path
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll inf=1e18;
#define N 200505
#define mod 1000000007
//换边最短路
int n,m,qu;
struct Original_edge{int u,v;ll len;}OE[N];
struct tabl{int to,id;ll len;};
struct node{int id; ll len; bool operator < (const node &x) const {return x.len<len;}};
vector<tabl> edge[N<<1];
priority_queue<node> q;
int lstvis[N]={0},l[N]={0},r[N]={0},ind[N]={0},vis[N];
ll t[N<<4]={0};
ll disT[N],disN[N];
bool on_path[N];
int path_cnt=0;
void dj(int p,ll dis[],int f)
{
for(int i=1;i<=n;i++)
{
vis[i]=0;
dis[i]=inf;
}
dis[p]=0;
q.push((node){p,0});
while(!q.empty())
{
node temp=q.top();
q.pop();
int u=temp.id;
ll w=temp.len;
if(vis[u])continue;
vis[u]++;
dis[u]=w;
for(auto re:edge[u])
{
int v=re.to;
int id=re.id;
ll tw=re.len;
if(dis[v]<=w+tw)continue;
dis[v]=w+tw;
lstvis[v]=id; //记前驱
q.push((node){v,w+tw});
if(f==1&&!on_path[v])l[v]=l[u]; //记住前后缀
if(f==2&&!on_path[v])r[v]=r[u];
}
}
}
void trace()
{
int u=1;
on_path[u]=true;
l[u]=r[u]=0;
for(int i=1;u!=n;i++)
{
int e_id=lstvis[u]; //取前驱
ind[e_id]=i; //做标记
u^=OE[e_id].u^OE[e_id].v; //取前点
on_path[u]=true; //做标记
l[u]=r[u]=i; //做标记
path_cnt++; //路长
}
}
void build(int le,int ri,int p)
{
t[p]=inf;
if(le==ri)return;
int mid=(le+ri)>>1,lef=(p<<1),rig=lef|1;
build(le,mid,lef);
build(mid+1,ri,rig);
}
void update(int L,int R,int x,int y,int p,ll k)
{
if(x>y)return;
if(x<=L&&R<=y)
{
t[p]=min(t[p],k);
return;
}
int mid=(L+R)>>1,lef=(p<<1),rig=lef|1;
if(x<=mid)update(L,mid,x,y,lef,k);
if(y>mid)update(mid+1,R,x,y,rig,k);
}
ll query(int L,int R,int x,int y,int p)
{
ll ans=t[p];
if(L==R)
{
return ans;
}
int mid=(L+R)>>1,lef=(p<<1),rig=lef|1;
if(y<=mid)ans=min(ans,query(L,mid,x,y,lef));
else ans=min(ans,query(mid+1,R,x,y,rig));
return ans;
}
void solve()
{
memset(on_path,false,sizeof(on_path));
cin>>n>>m>>qu;
for(int i=1;i<=m;i++)
{
int u,v;
ll w;
cin>>u>>v>>w;
OE[i].u=u;
OE[i].v=v;
OE[i].len=w;
edge[u].push_back({v,i,w});
edge[v].push_back({u,i,w});
}
dj(n,disN,0);
trace();
dj(1,disT,1);
dj(n,disN,2);
build(1,path_cnt,1);
for(int i=1;i<=m;i++)
{
int u=OE[i].u,v=OE[i].v;
ll w=OE[i].len;
if(ind[i])continue;
update(1,path_cnt,l[u]+1,r[v],1,disT[u]+w+disN[v]);
update(1,path_cnt,l[v]+1,r[u],1,disT[v]+w+disN[u]);
}
while(qu--)
{
int ti;
ll ch;
ll ans;
cin>>ti>>ch;
if(ind[ti])
{
ans=disT[n]-OE[ti].len+ch;
if(ch>OE[ti].len)
{
ans=min(ans,query(1,path_cnt,ind[ti],ind[ti],1));
}
}
else
{
ans=disT[n];
if(OE[ti].len>ch)
{
int u=OE[ti].u,v=OE[ti].v;
ans=min(ans,min(disT[u]+ch+disN[v],disT[v]+ch+disN[u]));
}
}
cout<<ans<<"\n";
}
}
```]
#pagebreak()
=== `SPFA+SLE.h`
#sourcecode[```cpp
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int inf =1e9+7;
////////////////////
struct p3008 //链式前向星
{
int to;
int nex;
int v;
}a[300000];
int head[25006]={0},cnt=0;
int dis[25006]={0}; //距离
void add(int u,int v,int w)
{
a[++cnt].nex=head[u];
a[cnt].to=v;
a[cnt].v=w;
head[u]=cnt;
}
/////////////////////////////////
//SPFA,但是双端队列优化
//小的放队头,大的放队尾
void spfa(int t,int s)
{
for(int i=1;i<=t;i++)dis[i]=inf; //初始化距离
deque<int> q;
vector<int> vis(t+1),cou(t+1);
q.push_front(s); //起点入队
dis[s]=0; //起点初始化
vis[s]++;
while(!q.empty())
{
int u=q.front(); //取出队头
q.pop_front();
cou[u]++;
if(cou[u]>t)return; //遍历次数过大,出现负环
for(int i=head[u];i;i=a[i].nex) //遍历儿子
{
int v=a[i].to;
int w=a[i].v;
if(dis[v]>dis[u]+w) //可松弛
{
dis[v]=dis[u]+w; //松弛操作
if(!vis[v])
{
if(q.empty())q.push_back(v); //特判!队空则随便入队
else if(dis[q.front()]>=dis[v])q.push_front(v); //小的放队头
else q.push_back(v); //大的放队尾
vis[v]++;
}
}
}
vis[u]--; //取消入队标记
}
}
void solve()
{
int t,r,p,s;
cin>>t>>r>>p>>s;
for(int i=1;i<=r;i++)
{
int u,v;
int w;
cin>>u>>v>>w;
add(u,v,w);
add(v,u,w);
}
for(int i=1;i<=p;i++)
{
int u,v;
int w;
cin>>u>>v>>w;
add(u,v,w);
}
spfa(t,s); //建好边调用即可,t是点数,s是起点
for(int i=1;i<=t;i++)
{
if(dis[i]>=inf)cout<<"NO PATH\n";
else cout<<dis[i]<<"\n";
}
}
```]
#pagebreak()
=== `SPFA.h`
#sourcecode[```cpp
#include<bits/stdc++.h>
using namespace std;
#define ll long long
/////////////////////////////////////
struct p4779SPFA //链式前向星
{
int to;
int nex;
ll w;
}star[550000];
int head[100005]={0},cnt=0;
void add(int u,int v,ll w)
{
star[++cnt].to=v;
star[cnt].nex=head[u];
star[cnt].w=w;
head[u]=cnt;
}
///////////////////////////////
//SPFA,一款暴力的最短路算法
//常用于网络流、判负环、带负边的最短路
//暴力版的dj,每次松弛都让未入队的点入队,直到无法松弛为止
int n,m,s;
ll dis[100005]={0}; //距离
int times[100005]={0}; //遍历次数
bool vis[100005]; //入队情况
void SPFA()
{
memset(vis, 0 ,sizeof(vis)); //清空vis
for(int i=1;i<=n;i++)dis[i]=2147483647; //距离初始化为无穷大
dis[s]=0; //起点归零
queue<int> q; //队列
q.push(s);
while(!q.empty())
{
int temp=q.front();
q.pop();
times[temp]++;
vis[temp]=false; //出队判定
if(times[temp]>2+n) //判负环 ,遍历次数过多说明出现了负环
{
times[s]=n+10; //做标记
break;
}
for(int i=head[temp];i;i=star[i].nex) //遍历儿子
{
int v=star[i].to;
if(dis[v]>dis[temp]+star[i].w) //可松弛
{
dis[v]=dis[temp]+star[i].w;//松弛
if(!vis[v]) //未入队则入队
{
q.push(v);
vis[v]=true;
}
}
}
}
}
void solve()
{
//spfa用于求最短路
cin>>n>>m>>s;
for(int i=1;i<=m;i++)
{
int u,v;
ll w;
cin>>u>>v>>w;
add(u,v,w);
}
SPFA();//建边后调用即可
if(times[s]>n) //找负环
{
cout<<"minus circle!\n";
return;
}
for(int i=1;i<=n;i++)cout<<dis[i]<<" ";
cout<<"\n";
}
```]
#pagebreak()
== #smallcaps[Tree]
=== `hld.h`
#sourcecode[```cpp
void dfs1(int o) {
son[o] = -1;
siz[o] = 1;
for (int j = h[o]; j; j = nxt[j])
if (!dep[p[j]]) {
dep[p[j]] = dep[o] + 1;
fa[p[j]] = o;
dfs1(p[j]);
siz[o] += siz[p[j]];
if (son[o] == -1 || siz[p[j]] > siz[son[o]]) son[o] = p[j];
}
}
void dfs2(int o, int t) {
top[o] = t;
cnt++;
dfn[o] = cnt;
rnk[cnt] = o;
if (son[o] == -1) return;
dfs2(son[o], t); // 优先对重儿子进行 DFS,可以保证同一条重链上的点 DFS 序连续
for (int j = h[o]; j; j = nxt[j])
if (p[j] != son[o] && p[j] != fa[o]) dfs2(p[j], p[j]);
}
int lca(int u, int v) {
while (top[u] != top[v]) {
if (dep[top[u]] > dep[top[v]])
u = fa[top[u]];
else
v = fa[top[v]];
}
return dep[u] > dep[v] ? v : u;
}
// st 是线段树结构体
int querymax(int x, int y) {
int ret = -inf, fx = top[x], fy = top[y];
while (fx != fy) {
if (dep[fx] >= dep[fy])
ret = max(ret, st.query1(1, 1, n, dfn[fx], dfn[x])), x = fa[fx];
else
ret = max(ret, st.query1(1, 1, n, dfn[fy], dfn[y])), y = fa[fy];
fx = top[x];
fy = top[y];
}
if (dfn[x] < dfn[y])
ret = max(ret, st.query1(1, 1, n, dfn[x], dfn[y]));
else
ret = max(ret, st.query1(1, 1, n, dfn[y], dfn[x]));
return ret;
}
```]
#pagebreak()
=== `lca.h`
#sourcecode[```cpp
class LCA{
public:
vector<vector<pii>> cnj;
vector<int> lg,dep;
vector<array<int,32>> fa,wei;
int n;
LCA(int _n) {
n = _n;
cnj.resize(n+1);
lg.resize(n+1),fa.resize(n+1),dep.resize(n+1),wei.resize(n+1);
for(int i = 1; i <= n; i ++)
lg[i] = lg[i-1] + (1 << lg[i-1] == i);
}
void addEdge(int u,int v,int w) {
cnj[u].push_back({v,w});
cnj[v].push_back({u,w});
}
void build(int rt = 1) {
using itf = function<void(int,int)>;
itf dfs = [&](int p,int f) -> void {
fa[p][0] = f,dep[p] = dep[f] + 1;
// wei[p][0] = 0;
for(int i = 1;i <= lg[dep[p]];i ++) fa[p][i] = fa[fa[p][i-1]][i-1];
for(int i = 1;i <= lg[dep[p]];i ++) wei[p][i] = max(wei[p][i-1],wei[fa[p][i-1]][i-1]);
for(auto [x,w]:cnj[p]) if(x == f) continue;
else wei[x][0] = w,dfs(x,p);
};
dfs(rt,0);
}
int get(int x,int y) {
if(dep[x] < dep[y]) swap(x,y);
while(dep[x] > dep[y]) x = fa[x][lg[dep[x] - dep[y]] - 1];
if(x == y) return x;
for(int k = lg[dep[x]]-1;k >= 0;k --) if(fa[x][k] != fa[y][k]) x = fa[x][k],y = fa[y][k];
return fa[x][0];
}
int getmaxw(int x,int y) {
int curmx = 0;
if(dep[x] < dep[y]) swap(x,y);
while(dep[x] > dep[y]) curmx = max(curmx,wei[x][lg[dep[x] - dep[y]] - 1]), x = fa[x][lg[dep[x] - dep[y]] - 1];
if(x == y) return curmx;
for(int k = lg[dep[x]]-1;k >= 0;k --)
if(fa[x][k] != fa[y][k])
curmx = max(curmx,wei[x][k]),x = fa[x][k],
curmx = max(curmx,wei[y][k]),y = fa[y][k];
return max({curmx,wei[x][0],wei[y][0]});
}
};
```]
#pagebreak()
= #smallcaps[Math]
== #smallcaps[Number_theory]
=== `basic.h`
#sourcecode[```cpp
__builtin_ffsll(x)
// 返回 x 的二进制末尾最后一个 1 的位置
__builtin_clzll(x)
// 返回 x 的二进制的前导 0 的个数。
__builtin_ctzll(x)
// 返回 x 的二进制末尾连续 0 的个数。
__builtin_clrsbll(x)
// 当 x 的符号位为 0 时返回 x 的二进制的前导 0 的个数减一,否则返回 x 的二进制的前导 1 的个数减一。
__builtin_popcountll(x)
// 返回 x 的二进制中 1 的个数。
__builtin_parity(x)
// 判断 x 的二进制中 1 的个数的奇偶性。
int binpow(int x, int y)
{
int res = 1;
while (y > 0)
{
if (y & 1)
res = res * x % mod;
x = x * x % mod;
y >>= 1;
}
return res;
}
void exgcd(int a, int b, int& x, int& y) {
if (b == 0) {
x = 1, y = 0;
return;
}
exgcd(b, a % b, y, x);
y -= a / b * x;
}
binpow(x,mod-2)
```]
#pagebreak()
=== `Comb.h`
#sourcecode[```cpp
const int N = 1e6;
const int mod = 1e9+7;
int binpow(int x, int y)
{
int ans = 1;
while (y)
{
if (y & 1) ans = ans * x % mod;
x = x * x % mod;
y >>= 1;
}
return ans;
}
vector<int> fac(N), inv(N);
void init()
{
fac[0] = inv[0] = 1;
for (int i = 1; i < N; i++) fac[i] = fac[i - 1] * i % mod;
inv[N - 1] = binpow(fac[N - 1], mod - 2);
for (int i = N - 2; i >= 1; i--)
{
inv[i] = inv[i + 1] * (i + 1) % mod;
}
}
auto C = [&](int x, int y) -> int
{
return (fac[x] * inv[y] % mod) * inv[x - y] % mod;
};
```]
#pagebreak()
=== `CRT.h`
#sourcecode[```cpp
int CRT(vector<int> &r, vector<int> &a)
{ // % r === a
int n = a.size();
__int128 k = 1, ans = 0;
for (int i = 0; i < n; i++) k *= r[i];
for (int i = 0; i < n; i++)
{
__int128 m = k / r[i];
int b, y;
exgcd(m, r[i], b, y); // b * m mod r[i] = 1
ans = (ans + a[i] * m * b % k) % k;
}
return (ans % k + k) % k;
}
int mul(int a, int b, int m) {
return (__int128)a * b % m;
}
int exgcd (int a,int b,int &x,int &y) {
if (b == 0) { x = 1, y = 0; return a; }
int g = exgcd(b, a % b, x, y), tp = x;
x = y, y = tp - a / b * y;
return g;
};
int EXCRT(vector<int> &a,vector<int> &r) { // % r == a
int x, y, k;
int n = r.size();
int M = a[0], ans = r[0];
for (int i = 1; i < n; ++ i) {
int ca = M, cb = a[i], cc = (r[i] - ans % cb + cb) % cb;
int gcd = exgcd(ca, cb, x, y), bg = cb / gcd;
if (cc % gcd != 0) return -1;
x = mul(x, cc / gcd, bg);
ans += x * M;
M *= bg;
ans = (ans % M + M) % M;
}
return (ans % M + M) % M;
}
```]
#pagebreak()
=== `Eular_phi.h`
#sourcecode[```cpp
int euler_phi(int n) {
int ans = n;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) {
ans = ans / i * (i - 1);
while (n % i == 0) n /= i;
}
if (n > 1) ans = ans / n * (n - 1);
return ans;
}
```]
#pagebreak()
=== `Eular_sieve.h`
#sourcecode[```cpp
vector<int> init(int n)
{
vector<int> pri;
vector<bool> vis(n, 0);
for (int i = 2; i <= n; i++)
{
if (!vis[i])
pri.push_back(i);
for (int j = 0; j < pri.size(); j++)
{
if (i * pri[j] > n)
break;
vis[pri[j] * i] = 1;
if (i % pri[j] == 0)
break;
}
}
return pri;
}
```]
#pagebreak()
=== `factor_pr.h`
#sourcecode[```cpp
#define int long long
#define pii pair<int, int>
const int INF = 1145141919810LL;
using namespace std;
class Pollard_Rho
{
private:
vector<int> B;
int mul(int a, int b, int m)
{
int r = a * b - m * (int)(1.L / m * a * b);
return r - m * (r >= m) + m * (r < 0);
}
int mypow(int a, int b, int m)
{
int res = 1 % m;
for (; b; b >>= 1, a = mul(a, a, m))
{
if (b & 1)
{
res = mul(res, a, m);
}
}
return res;
}
bool MR(int n)
{
if (n <= 1)
return 0;
for (int p : B)
{
if (n == p)
return 1;
if (n % p == 0)
return 0;
}
int m = (n - 1) >> __builtin_ctz(n - 1);
for (int p : B)
{
int t = m, a = mypow(p, m, n);
while (t != n - 1 && a != 1 && a != n - 1)
{
a = mul(a, a, n);
t *= 2;
}
if (a != n - 1 && t % 2 == 0)
return 0;
}
return 1;
}
inline const int getfecsum(int _n)
{
int sum = 0;
while (_n)
{
sum += _n % 10;
_n /= 10;
}
return sum;
};
int PR(int n)
{
for (int p : B)
{
if (n % p == 0)
return p;
}
auto f = [&](int x) -> int
{
x = mul(x, x, n) + 1;
return x >= n ? x - n : x;
};
int x = 0, y = 0, tot = 0, p = 1, q, g;
for (int i = 0; (i & 255) || (g = gcd(p, n)) == 1; i++, x = f(x), y = f(f(y)))
{
if (x == y)
{
x = tot++;
y = f(x);
}
q = mul(p, abs(x - y), n);
if (q)
p = q;
}
return g;
}
vector<int> fac(int n)
{
// if(n == 0)
// #define pb emplace_back
if (n <= 1)
return {};
if (MR(n))
return {n};
int d = PR(n);
auto v1 = fac(d), v2 = fac(n / d);
auto i1 = v1.begin(), i2 = v2.begin();
vector<int> ans;
while (i1 != v1.end() || i2 != v2.end())
{
if (i1 == v1.end())
{
ans.pb(*i2++);
}
else if (i2 == v2.end())
{
ans.pb(*i1++);
}
else
{
if (*i1 < *i2)
{
ans.pb(*i1++);
}
else
{
ans.pb(*i2++);
}
}
}
return ans;
}
public:
Pollard_Rho(){
B = {2, 3, 5, 7, 11, 13, 17, 19, 23};
}
vector<pii> fac_Comp(int n)
{
auto srt = fac(n);
map<int, int> cnt;
for (auto x : srt)
cnt[x]++;
vector<pii> rt;
for (auto x : cnt)
rt.push_back(x);
return rt;
}
vector<int> fac_pri(int n)
{
return fac(n);
}
vector<int> fac_all(int n)
{
vector<pii> rt = fac_Comp(n);
vector<int> v;
function<void(int, int)> dfs = [&](int id, int x)
{
if (id == rt.size())
{
v.push_back(x);
return;
}
for(int i = 0;i <= rt[id].se;i ++)
{
dfs(id + 1, x * (mypow(rt[id].fi, i, INF)));
}
};
dfs(0, 1);
return v;
}
};
```]
#pagebreak()
== #smallcaps[Other]
=== `Frac.h`
#sourcecode[```cpp
template<class T>
struct Frac {
T num;
T den;
Frac(T num_, T den_) : num(num_), den(den_) {
if (den < 0) {
den = -den;
num = -num;
}
}
Frac() : Frac(0, 1) {}
Frac(T num_) : Frac(num_, 1) {}
explicit operator double() const {
return 1. * num / den;
}
Frac &operator+=(const Frac &rhs) {
num = num * rhs.den + rhs.num * den;
den *= rhs.den;
return *this;
}
Frac &operator-=(const Frac &rhs) {
num = num * rhs.den - rhs.num * den;
den *= rhs.den;
return *this;
}
Frac &operator*=(const Frac &rhs) {
num *= rhs.num;
den *= rhs.den;
return *this;
}
Frac &operator/=(const Frac &rhs) {
num *= rhs.den;
den *= rhs.num;
if (den < 0) {
num = -num;
den = -den;
}
return *this;
}
friend Frac operator+(Frac lhs, const Frac &rhs) {
return lhs += rhs;
}
friend Frac operator-(Frac lhs, const Frac &rhs) {
return lhs -= rhs;
}
friend Frac operator*(Frac lhs, const Frac &rhs) {
return lhs *= rhs;
}
friend Frac operator/(Frac lhs, const Frac &rhs) {
return lhs /= rhs;
}
friend Frac operator-(const Frac &a) {
return Frac(-a.num, a.den);
}
friend bool operator==(const Frac &lhs, const Frac &rhs) {
return lhs.num * rhs.den == rhs.num * lhs.den;
}
friend bool operator!=(const Frac &lhs, const Frac &rhs) {
return lhs.num * rhs.den != rhs.num * lhs.den;
}
friend bool operator<(const Frac &lhs, const Frac &rhs) {
return lhs.num * rhs.den < rhs.num * lhs.den;
}
friend bool operator>(const Frac &lhs, const Frac &rhs) {
return lhs.num * rhs.den > rhs.num * lhs.den;
}
friend bool operator<=(const Frac &lhs, const Frac &rhs) {
return lhs.num * rhs.den <= rhs.num * lhs.den;
}
friend bool operator>=(const Frac &lhs, const Frac &rhs) {
return lhs.num * rhs.den >= rhs.num * lhs.den;
}
friend std::ostream &operator<<(std::ostream &os, Frac x) {
T g = std::gcd(x.num, x.den);
if (x.den == g) {
return os << x.num / g;
} else {
return os << x.num / g << "/" << x.den / g;
}
}
};
using F = Frac<int>;
```]
#pagebreak()
= #smallcaps[String]
== `AC_automaton.h`
#sourcecode[```cpp
struct ACAutomaton
{
static constexpr int N = 1e6 + 10;
int ch[N][26], fail[N], cntNodes;
int cnt[N];
ACAutomaton()
{
cntNodes = 1;
}
void insert(string s)
{
int u = 1;
for (auto c : s)
{
int &v = ch[u][c - 'a'];
if (!v)
v = ++cntNodes;
u = v;
}
cnt[u]++;
}
void build()
{
fill(ch[0], ch[0] + 26, 1);
queue<int> q;
q.push(1);
while (!q.empty())
{
int u = q.front();
q.pop();
for (int i = 0; i < 26; i++)
{
int &v = ch[u][i];
if (!v)
v = ch[fail[u]][i];
else
{
fail[v] = ch[fail[u]][i];
q.push(v);
}
}
}
}
LL query(string t)
{
LL ans = 0;
int u = 1;
for (auto c : t)
{
u = ch[u][c - 'a'];
for (int v = u; v && ~cnt[v]; v = fail[v])
{
ans += cnt[v];
cnt[v] = -1;
}
}
return ans;
}
};
```]
#pagebreak()
== `compress_print.h`
#sourcecode[```cpp
const int N = 1 << 21;
static const int mod1 = 1E9 + 7, base1 = 127;
static const int mod2 = 1E9 + 9, base2 = 131;
vector<int> val1;
vector<int> val2;
void init(int n = N)
{
val1.resize(n + 1), val2.resize(n + 2);
val1[0] = 1, val2[0] = 1;
for (int i = 1; i <= n; i++)
{
val1[i] = val1[i - 1] * base1 % mod1;
val2[i] = val2[i - 1] * base2 % mod2;
}
}
string compress(vector<string> in)
{ // 前后缀压缩
vector<int> h1{1};
vector<int> h2{1};
string ans = "#";
for (auto s : in)
{
s = "#" + s;
int st = 0;
int chk1 = 0;
int chk2 = 0;
for (int j = 1; j < s.size() && j < ans.size(); j++)
{
chk1 = (chk1 * base1 % mod1 + s[j]) % mod1;
chk2 = (chk2 * base2 % mod2 + s[j]) % mod2;
if ((h1.back() == (h1[ans.size() - 1 - j] * val1[j] % mod1+ chk1) % mod1) &&
(h2.back() == (h2[ans.size() - 1 - j] * val2[j] % mod2+ chk2) % mod2) )
st = j;
}
for (int j = st + 1; j < s.size(); j++)
{
ans += s[j];
h1.push_back((h1.back() * base1 % mod1 + s[j]) % mod1);
h2.push_back((h2.back() * base2 % mod2 + s[j]) % mod2);
}
}
return ans.substr(1);
}
```]
#pagebreak()
== `get_occr.h`
#sourcecode[```cpp
#include <template_overAll.h>
/*
* 找到某一堆短字符串在长字符串中的出现位置
* dira=1为最早出现的后端点下标 dira=0为最晚出现的前端点下标
* 源字符串s长度为|s|,查找字符串列表中所有字符串长度和为|_s|
* 则时间复杂度为O(max(|_s|log(|_s|),|s|))
*/
class get_occr
{
private:
string s;
public:
get_occr(string _s) { s = _s; }
vector<int> locate(vector<string> _s,bool dira = 1)
{
int n = _s.size();
vector<int> occr(n,-1);
map<char,vector<pair<int,int>>> gncing;
if(dira == 1)
{
for(int i = 0;i < n;i++)
gncing[_s[i][0]].push_back({i,0});
for(int i = 0;i < s.size();i ++)
{
vector<pair<int,int>> gnctmp = gncing[s[i]];
gncing[s[i]].clear();
for(int j = 0;j < gnctmp.size();j ++)
{
if(gnctmp[j].se+1 < _s[gnctmp[j].fi].size())
gncing[_s[gnctmp[j].fi][gnctmp[j].se+1]].push_back({gnctmp[j].fi,gnctmp[j].se+1});
else occr[gnctmp[j].fi] = i;
}
}
} else {
for(int i = 0;i < n;i++) gncing[_s[i][_s[i].size()-1]].push_back({i,_s[i].size()-1});
for(int i= s.size()-1;i >=0;i --)
{
vector<pair<int,int>> gnctmp = gncing[s[i]];
gncing[s[i]].clear();
for(int j = 0;j < gnctmp.size();j ++)
{
if(gnctmp[j].se -1 >= 0)
gncing[_s[gnctmp[j].fi][gnctmp[j].se-1]].push_back({gnctmp[j].fi,gnctmp[j].se-1});
else occr[gnctmp[j].fi] = i;
}
}
}
return occr;
}
};
```]
#pagebreak()
== `hash_print.h`
#sourcecode[```cpp
#define int long long
const int N = 1 << 21;
static const int mod1 = 1E9 + 7, base1 = 127;
static const int mod2 = 1E9 + 9, base2 = 131;
vector<int> val1;
vector<int> val2;
using puv = pair<int,int>;
void init(int n = N)
{
val1.resize(n + 1), val2.resize(n + 2);
val1[0] = 1, val2[0] = 1;
for (int i = 1; i <= n; i++)
{
val1[i] = val1[i - 1] * base1 % mod1;
val2[i] = val2[i - 1] * base2 % mod2;
}
}
class hstring
{
public:
vector<int> h1;
vector<int> h2;
string s;
hstring(string s_) : s(s_), h1{0}, h2{0}
{
build();
}
void build()
{
for (auto it : s)
{
h1.push_back((h1.back() * base1 % mod1 + it) % mod1);
h2.push_back((h2.back() * base2 % mod2 + it) % mod2);
}
}
puv get()
{ // 输出整串的哈希值
return {h1.back(), h2.back()};
}
puv substring(int l, int r)
{ // 输出子串的哈希值
if (l > r) swap(l, r);
int ans1 = (mod1 + h1[r + 1] - h1[l] * val1[r - l + 1] % mod1) % mod1;
int ans2 = (mod2 + h2[r + 1] - h2[l] * val2[r - l + 1] % mod2) % mod2;
return {ans1, ans2};
}
puv modify(int idx, char x)
{ //修改 idx 位为 x
int n = s.size() - 1;
int ans1 = (h1.back() + val1[n - idx] * (x - s[idx]) % mod1) % mod1;
int ans2 = (h2.back() + val2[n - idx] * (x - s[idx]) % mod2) % mod2;
return {ans1, ans2};
}
};
```]
#pagebreak()
== `KMP.h`
#sourcecode[```cpp
#include <template_overAll.h>
class KMP
{
private:
string s;
string inis;
public:
vector<int> pi;
KMP(string _s)
{
s = _s;
inis = s;
}
void prefix_function()
{
pi.clear();
int n = (int)s.length();
pi.resize(n);
for (int i = 1; i < n; i++)
{
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return;
}
vector<int> find_occr(string p)
{
s = inis;
s = p + "#" + s;
prefix_function();
vector<int> v;
for (int i = p.size() + 1; i < s.size(); i++)
if (pi[i] == p.size())
v.push_back(i - 2 * p.size());
return v;
}
};
```]
#pagebreak()
== `trie_Tree.h`
#sourcecode[```cpp
#include <template_overAll.h>
class Trie//AC
{
public:
vector<map<char, int>> t;
int root = 0;
Trie()
{
t.resize(1);
}
void addedge(string _s)
{
int pvidx = root;
_s.push_back('-');
for (int i = 0; i < _s.size(); i++)
{
if (t[pvidx].find(_s[i]) != t[pvidx].end())
{
pvidx = t[pvidx][_s[i]];
}
else
{
t[pvidx][_s[i]] = t.size();
t.push_back(map<char, int>());
pvidx = t[pvidx][_s[i]];
}
}
}
bool ifcmp(string &s)
{
int pvidx = root;
for(int i = 0;i < s.size();i ++)
{
if(t[pvidx].find(s[i]) != t[pvidx].end()) pvidx = t[pvidx][s[i]];
else return 0;
}
return t[pvidx].find('-') != t[pvidx].end();
}
};
```]
#pagebreak()
|
|
https://github.com/dadn-dream-home/documents | https://raw.githubusercontent.com/dadn-dream-home/documents/main/README.md | markdown | # Documents
Source code for the final report.
## Requirement
- Deno =~ 1.34.2
- Draw.io CLI =~ 21.3.7
- Inkscape =~ 1.0.1
- Typst =~ 0.5.0
## Build
After modifying `*.drawio` files, run
```sh
$ deno task generate-svg
```
To watch and build the `main.pdf`:
```sh
$ deno task typst
```
|
|
https://github.com/MattiaOldani/Informatica-Teorica | https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/calcolabilità/11_problemi_decisione.typ | typst | #import "../alias.typ": *
#import "@preview/lemmify:0.1.5": *
#let (theorem, lemma, corollary, remark, proposition, example, proof, rules: thm-rules) = default-theorems(
"thm-group",
lang: "it",
)
#show: thm-rules
#show thm-selector("thm-group", subgroup: "theorem"): it => block(
it,
stroke: red + 1pt,
inset: 1em,
breakable: true,
)
#show thm-selector("thm-group", subgroup: "proof"): it => block(
it,
stroke: green + 1pt,
inset: 1em,
breakable: true,
)
= Problemi di decisione
Un *problema di decisione* è una domanda cui devo decidere se rispondere _SI_ o _NO_.
I problemi di decisione sono costituiti da tre elementi principali:
- *nome*: il nome del problema;
- *istanza*: dominio degli oggetti che verranno considerati;
- *domanda*: proprietà che gli oggetti del dominio possono soddisfare o meno. Dato un oggetto del dominio, devo rispondere _SI_ se soddisfa la proprietà, _NO_ altrimenti. In altre parole, è la *specifica* del problema di decisione.
Diamo ora una definizione più formale:
- *nome* $Pi$;
- *istanza* $x in D$ input;
- *domanda* $p(x)$ proprietà che $x in D$ può soddisfare o meno.
Se, per esempio, mi viene chiesto _"questo polinomio ha uno zero?"_ non devo dire _quale_ zero ha, ma solo _se lo ha_ o meno. Non devo esibire una *struttura* come risultato (cosa che avviene nei problemi di ricerca o di ottimizzazione), ma solo una risposta _SI/NO_.
== Esempi
Vediamo qualche esempio di problemi di decisione noti. L'assegnamento di un valore a $x in D$ genera un'*istanza particolare* del problema:
1. *Parità*
- Nome: Parità.
- Istanza: $n in NN$.
- Domanda: $n$ è pari?
2. *Equazione diofantea*
- Nome: Equazione Diofantea.
- Istanza: $a,b,c in NN^+$.
- Domanda: $exists x,y in ZZ bar.v a x + b y = c$?
Questa domanda nei reali avrebbe poco senso, perché ci sarebbero infiniti punti che soddisfano l'equazione della retta. Considerando punti interi, invece, ha più senso in quanto niente garantisce che la retta ne abbia.
Ad esempio, per $a=3$, $b=4$ e $c=5$ rispondo _SI_, visto che la proprietà vale per $x = -1$ e $y = 2$.
Il nome di queste equazioni deriva dal matematico Diofanto, che per primo le trattò nel contesto dell'aritmetica di, appunto, Diofanto.
3. *Fermat*
- Nome: Ultimo Teorema di Fermat.
- Istanza: $n in NN^+$.
- Domanda: $exists x,y,z in NN^+ bar.v x^n + y^n = z^n$?
Questo problema è, in un certo senso, riconducibile al precedente.
Per $n = 1$ rispondo _SI_: è facile trovare tre numeri tali che $x + y = z$, ne ho infiniti.
Per $n = 2$ rispondo _SI_, i numeri nella forma $x^2 + y^2 = z^2$ rappresentano le *terne pitagoriche*.
Per $n gt.eq 3$ rispondo _NO_, è stato dimostrato da Eulero.
Questo problema è rimasto irrisolto per circa 400 anni, fino a quando nel 1994 viene dimostrato il *teorema di Andrew-Wiles* (dall'omonimo matematico), come banale conseguenza di una dimostrazione sulla modularità delle curve ellittiche.
Si dice che il primo a risolvere questo problema sia stato Fermat, giurista che nel tempo libero giocava con la matematica, tanto da meritarsi il nome di _principe dei dilettanti_, lo dimostra il fatto che questo teorema non ha nessuna conseguenza pratica, è totalmente "inutile".
4. *Raggiungibilità*
- Nome: Raggiungibilità.
- Istanza: grafo $G = ({1,dots,n}, E)$.
- Domanda: $exists pi$ cammino dal nodo $1$ al nodo $n$?
5. *Circuito hamiltoniano*
- Nome: Circuito Hamiltoniano.
- Istanza: grafo $G = (V,E)$.
- Domanda: $exists gamma$ circuito hamiltoniano nel grafo $G$?
Un *circuito hamiltoniano* è un circuito che coinvolge ogni nodo una e una sola volta.
6. *Circuito euleriano*
- Nome: Circuito Euleriano.
- Istanza: grafo $G = (V,E)$.
- Domanda: $exists gamma$ circuito euleriano nel grafo $G$?
Un *circuito euleriano* è un circuito che coinvolge ogni arco una e una sola volta. Questo quesito ha dato via alla teoria dei grafi.
== Decidibilità
Sia $Pi$ problema di decisione con istanza $x in D$ e domanda $p(x)$. $Pi$ è *decidibile* se e solo se esiste un programma $P_Pi$ tale che
#v(12pt)
#figure(
image("assets/decidibilità.svg", width: 50%),
)
#v(12pt)
Allo stesso modo, possiamo associare a $Pi$ la sua *funzione soluzione*: $ Phi_Pi : D arrow.long {0,1} $ tale che $ Phi_Pi (x) = cases(1 & "se" p(x), 0 quad & "se" not p(x)) quad . $
Questa funzione deve essere programmabile e deve terminare sempre, ma allora $Phi_Pi in cal(T)$.
I due approcci per definire la decidibilità sono equivalenti:
- il programma $P_Pi$ calcola $Phi_Pi$, quindi $Phi_Pi in cal(T)$;
- se $Phi_Pi in cal(T)$ allora esiste un programma che la calcola e che ha il comportamento di $P_Pi$.
Quindi, definire la decidibilità partendo da un programma o da una funzione ricorsiva parziale, è indifferente: una definizione implica l'altra.
Possiamo sfruttare questa cosa per sviluppare due tecniche di risoluzione del problema Decidibilità:
+ esibiamo un algoritmo di soluzione $P_Pi$ (anche inefficiente, basta che esista);
+ mostriamo che $Phi_Pi$ è ricorsiva totale.
== Applicazione agli esempi
1. *Parità*
$ Phi_("PR") (n) = 1 overset(-,.) (n mod 2) in cal(T). $
2. *Equazione diofantea*
$ Phi_("ED") (a,b,c) = 1 overset(-,.) (c mod "mcd"(a,b)) in cal(T). $
3. *Fermat*
$ Phi_F (n) = 1 overset(-,.) (n overset(-,.) 2) in cal(T). $
4. *Raggiungibilità*
\ Sia $M_G in {0,1}^(n times n)$ matrice di adiacenza tale che $M_G [i,j] = 1$ se e solo se $(i,j) in E$. Inoltre, $M_G^k$ ha un 1 nella cella $[i,j]$ sse esiste un cammino lungo $k$ da $i$ a $j$.
$ Phi_R (G) = (or.big_(k=0)^n M_G^k)[1,n] in cal(T). $
5. *Circuito hamiltoniano*
\ Dovendo visitare ogni nodo una e una sola volta, il circuito genera una permutazione dei vertici in $V$. L'algoritmo di soluzione deve:
+ generare l'insieme $P$ di tutte le permutazioni di $V$;
+ data la permutazione $p_i in P$, se è un circuito hamiltoniano rispondo _SI_;
+ se nessuna permutazione $p_i$ è un circuito hamiltoniano rispondo _NO_.
L'algoritmo è inefficiente perché ci mette un tempo $O(n!)$, vista la natura combinatoria del problema, ma sicuramente questo problema è decidibile.
6. *Circuito euleriano*
#theorem(
name: "Teorema di Eulero (1936)",
numbering: none,
)[
Un grafo $G = (V,E)$ contiene un circuito euleriano se e solo se ogni vertice in $G$ ha grado pari.
]
Grazie a questo risultato, l'algoritmo di risoluzione deve solo verificare se il grado di ogni vertice in $V$ è pari, quindi anche questo problema è decidibile.
== Problemi indecidibili
_Ma esistono dei *problemi indecidibili*?_
// Lo lascerò
#align(center)[
#block(
fill: rgb("#9FFFFF"),
inset: 8pt,
radius: 4pt,
[*PEFFORZA*],
)
]
Se esistono programmi che non so scrivere allora esistono problemi per i quali non riesco a scrivere dei programmi che li risolvano.
=== Problema dell'arresto ristretto
Il *problema dell'arresto ristretto* per un programma $P$ è un esempio di problema indecidibile.
Fissato $P$ un programma, il problema è il seguente:
- Nome: $arresto(P)$.
- Istanza: $x in NN$.
- Domanda: $phi_P (x) arrow.b$?
In altre parole, ci chiediamo se il programma $P$ termina su input $x$. La risposta dipende ovviamente dal programma $P$, che può essere decidibile o non decidibile.
Ad esempio, se $ P_1 equiv & "input"(x) \ & x := x + 1; \ & "output"(x) $ allora la funzione $ Phi_(arresto(P_1)) (x) = 1 in cal(T) $ ci dice quando il problema $P_1$ termina o meno (_sempre_).
Se invece $ P_2 equiv & "input"(x) \ & "if" (x mod 2 eq.not 0) \ & quad "while" (1 > 0); \ & "output"(x) $ allora la funzione $ Phi_(arresto(P_2)) (x) = 1 overset(-,.) (x mod 2) in cal(T) $ ci dice quando il problema $P_2$ termina o meno.
Abbiamo quindi trovato due funzioni $Phi_(arresto(P)) in cal(T)$ che ci dicono quando i programmi $P_1$ e $P_2$ terminano o meno, _ma è sempre possibile?_
Prendiamo ora $ ristretto equiv & "input"(x) \ & z := U(x,x); \ & "output"(z), $ con $U$ interprete universale tale che $ phi_U (x,n) = phi_n (x). $ Vale allora $ phi_(ristretto) (x) = phi_U (x,x) = phi_x (x). $
Abbiamo, quindi, un programma $x$ che lavora su un altro programma (_se stesso_). Questo non è strano: compilatori, debugger, interpreti sono programmi che lavorano su programmi.
Come prima mi chiedo se $phi_x$ su input $x$ termina. A differenza di prima, ora il programma $P$ non è fissato e dipende dall'input, essendo $x$ sia input che programma.
#theorem(numbering: none)[
Dato $ ristretto equiv & "input"(x) \ & z := U(x,x); \ & "output"(z), $ $arresto(ristretto)$ è indecidibile.
]
#proof[
\ Per assurdo assumiamo $arresto(ristretto)$ decidibile. Dunque esiste $ Phi_(arresto(ristretto)) (x) = cases(1 & "se" phi_ristretto (x) = phi_x (x) arrow.b, 0 quad & "se" phi_(ristretto) (x) = phi_x (x) arrow.t) quad in cal(T) $ calcolabile da un programma che termina sempre. Visto che $Phi_(ristretto) in cal(T)$, anche la funzione $ f(x) = cases(0 & "se" Phi_(arresto(ristretto)) (x) = 0 equiv phi_x (x) arrow.t, phi_x (x) + 1 quad & "se" Phi_(arresto(ristretto)) (x) = 1 equiv phi_x (x) arrow.b) $ è ricorsiva totale. Infatti, il programma $ A equiv & "input"(x) \ & "if" (Phi_(arresto(ristretto) (x)) == 0) \ & quad "output"(0) \ & "else" \ & quad "output"(U(x,x) + 1) $ calcola esattamente la funzione $f(x)$.
Sia $alpha in NN$ la codifica del programma $A$, allora $phi_alpha = f$. Valutiamo $phi_alpha$ in $alpha$: $ phi_alpha (alpha) = cases(0 & "se" phi_alpha (alpha) arrow.t, phi_alpha (alpha) + 1 quad & "se" phi_alpha (alpha) arrow.b) quad . $
Tale funzione non può esistere, infatti:
- nel primo caso ho $phi_alpha (alpha) = 0$ se non termino, ma è una contraddizione perché $A in cal(T)$;
- nel secondo caso ho $phi_alpha (alpha) = phi_alpha (alpha) + 1$ se termino, ma è una contraddizione perché questa relazione non vale per nessun naturale.
Siamo ad un *assurdo*, quindi concludiamo che $arresto(ristretto)$ deve essere *indecidibile*.
]
=== Problema dell'arresto
La versione generale del problema dell'arresto ristretto è il *problema dell'arresto*, posto nel 1936 da Al<NAME>.
#theorem(numbering: none)[
Dati $x,y in NN$ rispettivamente un dato e un programma, il problema dell'arresto AR con domanda $phi_y (x) arrow.b$ è indecidibile.
]
#proof[
\ Assumiamo per assurdo che AR sia decidibile, ma allora esiste un programma $P_("AR") (x,y)$ che lo risolve, quindi restituisce:
- 1 se $phi_y (x) arrow.b$;
- 0 altrimenti.
Il seguente programma decide AR: $ P equiv & "input"(x,y) \ & "output"(P_("AR") (x,x)) quad . $
Il risultato precedente dimostra che questo problema è indecidibile, quindi non possono esistere programmi per la soluzione di AR. Siamo ancora ad un *assurdo*, quindi AR è *indecidibile*.
]
|
|
https://github.com/jamesrswift/musicaux | https://raw.githubusercontent.com/jamesrswift/musicaux/main/src/symbols.typ | typst | #let symbols = symbol(
("stave", "𝄚"),
("stave.single", "𝄖"),
("bar", "𝄀"),
("bar.double", "𝄁"),
("bar.double.bold", "𝄂"),
("bar.double.bold.reverse", "𝄃"),
("bar.dotted", "𝄄"),
("clef", "𝄞"),
("clef.treble", "𝄞"),
("clef.treble.upper-octave", "𝄟"),
("clef.treble.lower-octave", "𝄠"),
("clef.bass", "𝄢"),
("clef.bass.upper-octave", "𝄣"),
("clef.bass.lower-octave", "𝄤"),
("flat", "♭"),
("sharp", "♯"),
("time", "𝄴"),
("time.common", "𝄴"),
("time.cut", "𝄵"),
("time.number.two", ""),
("note", "𝅗"),
("note.semibreve", "𝅗"),
("note.minim", "𝅗𝅥"),
("note.crotchet", "𝅘𝅥"),
("note.quaver", "𝅘𝅥𝅮"),
("crescendo", "𝆒"),
("decrescendo", "𝆓"),
("tie", "⁀"),
//("tie", sym.paren.t),
("pedal", "𝆮"),
("pedal.release", "𝆯"),
("brace", "𝄔"),
("bracket", "𝄕")
) |
|
https://github.com/Dylan-Padilla/typst-examples | https://raw.githubusercontent.com/Dylan-Padilla/typst-examples/main/main-text.typ | typst | #align(center, text(17pt)[
*Beyond Microsoft*
])
#align(center)[
<NAME> \
Arizona State University \
#link("<EMAIL>")
]
#set par(
justify: true,
)
= Introduction
"Free Software" means software that respects users' freedom and community. Roughly, it means that the users have the freedom to run, copy, distribute, study, and improve the software. Thus, "free software" is a matter of liberty, not price. To understand the concept, please watch the series of YouTube shorts that the ASN Graduate Council is making. We hope you enjoy them.
#align(center)[
#image("imgs/ASN_logo.png")
*Figure 1: Caption here ...*
]
|
|
https://github.com/Origami404/kaoyan-shuxueyi | https://raw.githubusercontent.com/Origami404/kaoyan-shuxueyi/main/微积分/08-空间解析几何.typ | typst | #import "../template.typ": sectionline, gray_table, colored
#let vi = $bold(i)$
#let vj = $bold(j)$
#let vk = $bold(k)$
#let vx = $bold(x)$
#let vp = $bold(p)$
#let prl = $\/\/$
#let cross = $times$
#let clr(exp) = text(fill: red)[$#exp$]
= 空间解析几何
== 基本元素
=== 向量运算
- 注意叉积的反交换和自乘零
- 注意混合积的轮换不变性, 反交换性和自乘零
- 叉积的计算可以用三阶行列式算, 也可以记住 "23-31-12"
- $(clr(a_2 b_3) - a_3 b_2) vi + (clr(a_3 b_1) - a_1 b_3) vj + (clr(a_1 b_2) - a_2 b_1) vk$
=== 平面
*点法式*: 平面上的两个点组成的向量和法向量垂直
$
(vx - vx_0) dot vp = 0
quad quad quad
A(x - x_0) + B(y - y_0) + C(z - z_0) = 0
$
*三点式*: 平面上一个点和其他三个点组成的三个向量张成的平行体体积为 $0$
$
[(vx-vx_0) (vx-vx_1) (vx-vx_2)] = 0
quad quad quad
mat(delim: "|",
x - x_0, y - y_0, z - z_0;
x - x_1, y - y_1, z - z_1;
x - x_2, y - y_2, z - z_2
) = 0
$
*一般式*:
$
A x + B y + C z + D = 0
$
=== 直线
*点向式*: 两个点的方向和方向向量的方向相同
$
(vx - vx_0) prl vp
quad quad quad
(x - x_0) / A = (y - y_0) / B = (z - z_0) / C
$
*两点式*: 另外一个点和两个点组成的两个向量平行
$
(vx - vx_0) prl (vx - vx_1)
quad quad quad
(x - x_0) / (x - x_1) = (y - y_0) / (y - y_1) = (z - z_0) / (z - z_z)
$
注意此时有 $vp = vx_0 - vx_1$
*一般式*: 两个平面相交
$
cases(
A_1 x + B_1 y + C_1 z + D_1 = 0,
A_2 x + B_2 y + C_2 z + D_2 = 0,
)
$
#pagebreak()
== 基本元素之间关系
*点与点之间共线或共面*: 存在非零系数, 线性组合得零
*直线 平行/垂直 直线*: 方向向量 平行/垂直, 注意排除重合
*直线 平行/垂直 平面*: 方向向量 垂直/平行 法向量, 注意关系是*反*过来的, 并且要排除重合
*平面 平行 平面*: 法向量平行, 注意排除重合
*点到直线距离*: 叉积求出平行四边形面积, 除以底得到高
$
d = (vp cross (vx - vx_0)) / (||vp||)
$
*点到平面距离*: 和平面上的点组成的向量到法向量方向的投影长度
$
d = "Prj"_vp (vx - vx_0) = ((vx - vx_0) dot vp) / (||vp||)
$
== 常见求法
#set list(marker: ([★], [⤥], [›]))
- 尽量减少待定系数, 方向/法 向量可以用垂直关系叉积求的尽量叉积求
=== 旋转面
对任意曲线, 从它的参数方程形式可以求出它绕某个坐标轴旋转得到的曲面. 以 $z$ 轴为例, 此时的关键是曲线上任意一点到 $z$ 轴距离不变, 由此可以得到曲面方程:
$
x^2 + y^2 = x^2(t) + y^2(t)
$
其中 $t$ 用 $t = z^(-1)(z)$ 代替, 即可得到方程.
特别地, 对于在过坐标轴平面上的曲线, 如 $x O z$ 上的曲线, 可以直接通过一般式求出曲面方程:
$
cases(f(x, z) = 0, y = 0) quad => quad f(sqrt(x^2+y^2), z) = 0
$
原理是原先曲线中的 $x$ 就是代表到 $z$ 轴的距离, 旋转后用新的到 $z$ 轴距离替换掉变量 $x$ 即可.
旋转体的体积可以参考一元积分中的内容.
=== 投影
从曲线的一般式可以求出它到坐标平面上的投影柱面和投影曲线:
$
cases(
F_1(x, y, z) = 0,
F_2(x, y, z) = 0,
) quad => quad phi(x, y) = 0
$
例如求曲线投影到 $x O y$ 上, 只需要联立两方程消 $z$ 即可得到投影柱面. 投影柱面和平面方程联立即可得到投影曲线.
特别地, 直线到平面上的投影可以通过直线方向向量和平面法向量叉积求得一个过直线且垂直于平面的平面, 然后此二平面相交即可得到投影直线. 当然, 也可以用方向向量求出它在平面法向量上的垂直分量, 并上直线和平面的交点直接得到投影直线的点法式.
#pagebreak()
|
|
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/PianoDiProgetto/sections/PreventivoSprint/DodicesimoSprint.typ | typst | MIT License | #import "../../const.typ": Re_cost, Am_cost, An_cost, Ve_cost, Pr_cost, Pt_cost
#import "../../functions.typ": prospettoOrario, prospettoEconomico, glossary
==== Dodicesimo preventivo
*Inizio*: Venerdì 08/03/2024
*Fine*: Giovedì 14/03/2024
#prospettoOrario(sprintNumber: "12")
#prospettoEconomico(sprintNumber: "12") |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz-plot/0.1.0/src/chart/barcol-common.typ | typst | Apache License 2.0 | // Valid bar- and columnchart modes
#let barchart-modes = (
"basic", "clustered", "stacked", "stacked100"
)
// Functions for max value calculation
#let barchart-max-value-fn = (
basic: (data, value-key) => {
calc.max(0, ..data.map(t => t.at(value-key)))
},
clustered: (data, value-key) => {
calc.max(0, ..data.map(t => calc.max(
..value-key.map(k => t.at(k)))))
},
stacked: (data, value-key) => {
calc.max(0, ..data.map(t =>
value-key.map(k => t.at(k)).sum()))
},
stacked100: (..) => {
100
}
)
// Functions for min value calculation
#let barchart-min-value-fn = (
basic: (data, value-key) => {
calc.min(0, ..data.map(t => t.at(value-key)))
},
clustered: (data, value-key) => {
calc.min(0, ..data.map(t => calc.max(
..value-key.map(k => t.at(k)))))
},
stacked: (data, value-key) => {
calc.min(0, ..data.map(t =>
value-key.map(k => t.at(k)).sum()))
},
stacked100: (..) => {
0
}
)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-square_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Default square.
#box(square())
#box(square[hey!])
|
https://github.com/dainbow/MatGos | https://raw.githubusercontent.com/dainbow/MatGos/master/themes/31.typ | typst | #import "../conf.typ": *
= Простейшая задача вариационного исчисления. Необходимые условия локального экстремума.
#note[
Вспомнин $C$-нормы:
#eq[
$forall k in NN union {0} : space norm(f)_(C^k [a, b]) = sum_(i = 0)^k max_(x in [a, b]) abs(f^((i)) (x))$
]
]
#definition[
Пусть $(X, rho)$ -- метрическое пространство, $M subset X$.
Отображение $F : M -> RR$ называется *функционалом* с областью определения $M$.
]
Пусть $F(x, y, p)$ -- непрерывно дифференцируемая функция на $[a, b] times RR^2$.
В этом билете будем рассматривать функционал
#eq[
$J(y) = integral_a^b F(x, y, y') dif x; quad y(a) = A, y(b) = B$
]
Определённый на множестве
#eq[
$M := {y(x) in C^1 [a, b] | y(a) = a, y(b) = b}$
]
#definition[
Функция $hat(y)(x) in M$ называется *слабым локальным минимумом* (максимумом)
функционала $J$, если
#eq[
$exists epsilon > 0 : forall y(x) in M : space norm(hat(y) - y)_(C^1 [a, b]) < epsilon : space J(y) >= (<=) space J(hat(y))$
]
]
#definition[
Задача на отыскание слабого локального экстремума функционала $J$ называется
*простейшей вариационной задачей* или *задачей с закреплёнными концами*.
]
#definition[
Выражение $dif / (dif alpha) J(y + alpha nu)|_(alpha = 0)$, где $eta in C^1 [a, b]$ называется
*первой вариацией* функционала $J(y)$ на функции $y(x)$ и обозначается $partial J[y, eta(x)]$
]
#theorem[
Если $hat(y)(x) in M$ является решением простейшей вариационной задачи, то
#eq[
$forall eta(x) in C^1 [a, b] : space partial J[hat(y), eta(x)] = 0$
]
]
#proof[
Пусть, БОО, $hat(y)$ -- слабый локальный минимум $J(y)$. Тогда
#eq[
$exists epsilon > 0 : forall y(x) in M : norm(hat(y) - y)_(C^1 [a, b]) : space J(y) >= J(hat(y))$
]
Зафиксировав $eta(x)$, подберём $alpha_0 : norm(alpha_0 eta)_(C^1 [a, b]) < epsilon$.
Тогда
#eq[
$forall alpha : abs(alpha) < alpha_0 : space norm(alpha eta)_(C^1 [a, b]) < epsilon$
]
Рассмотрим числовую функцию $Phi(alpha) := J(hat(y) + alpha eta)$. Так как $hat(y)$ -- слабый
локальный экстремум $J(y)$, то $0$ -- локальный минимум функции $Phi$.
Получается, что $Phi'(0) = 0$ по необходимуму условию минимума числовой функции,
это и означает, что
#eq[
$forall eta in C^1 [a, b] : space partial J[hat(y), eta(x)] = 0$
]
]
#theorem(
"<NAME> / основная лемма вариационного исчисления",
)[
Если $f(x) in C[a, b]$ и
#eq[
$forall eta(x) in C^1 [a,b] : space integral_a^b f(x) eta(x) dif x = 0$
]
то $f(x) equiv 0$ на $[a, b]$.
]
#proof[
Пусть это не так, тогда БОО $exists x_0 : f(x_0) > 0$.
Из-за непрерывности $f$ следует, что
#eq[
$exists epsilon > 0 : space forall x in (x_0 - epsilon, x_0 + epsilon) : f(x) > 0$
]
Тогда выберем $eta_0$, как гладкую положительную шапочку на даннном интервале,
которая гладко спускается к нулю.
Получим что
#eq[
$integral_a^b f(x) eta_0 (x) dif x = integral_(x_0 - epsilon)^(x_0 + epsilon) f(x) eta_0 (x) dif x > 0$
]
Противоречие
]
#theorem[
Пусть $F(x, y, p)$ -- дважды непрерывно дифференцируемая функция $forall (x, y, p) in [a, b] times RR^2$.
Если непрерывно дифференцируемая функция $hat(y)$ является решением простейшей
вариационной задачи для $J$, то эта функция удовлетворяет уравнению Эйлера на $[a, b]$:
#eq[
$(partial F) / (partial y) - dif / (dif x) ((partial F) / (partial y')) equiv 0$
]
]
#proof[
Распишем первую вариацию:
#eq[
$partial J[y, eta(x)] = [dif / (dif alpha) integral_a^b F(x, y + alpha eta, y' + alpha eta')]|_(alpha = 0) = \
[integral_a^b ((partial F (x, y + alpha eta, y' + alpha eta')) / (partial y) eta + (partial F (x, y + alpha eta, y' + alpha eta')) / (partial y') eta') dif x ]|_(alpha = 0) = \
integral_a^b ((partial F(x, y, y')) / (partial y) eta + (partial F(x, y, y')) / (partial y') eta') dif x$
]
Проинтегрируем одно из подыинтегральных слагаемых по частям:
#eq[
$integral_a^b (partial F(x, y, y')) / (partial y') eta' dif x = (partial F(x, y, y')) / (partial y') eta|_a^b - integral_a^b dif / (dif x) ((partial F(x, y, y')) / (partial y')) eta dif x$
]
Первое слагаемое равно нулю в силу ограничений на допустимое приращение $eta$.
Тогда
#eq[
$partial J[y, eta(x)] = integral_a^b ((partial F(x, y, y')) / (partial y) - dif / (dif x) ((partial F(x, y, y')) / (partial y')))eta dif x$
]
Так как $y$ -- локальный экстремум, то по предыдущему необходимому условию
#eq[
$forall eta in C^1 [a, b] : space partial J [y, eta(x)] = 0$
]
Теперь по лемме Лагранжа получим требуемое.
] |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/list_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
- Top-level indent
- is fine.
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-text-08.typ | typst | Other | // Test absolute path in layout phase.
#show "GRAPH": image("test/assets/files/graph.png")
The GRAPH has nodes.
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/048%20-%20Dominaria%20United/009_Shards%20of%20Nightmares.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Shards of Nightmares",
set_name: "Dominaria United",
story_date: datetime(day: 17, month: 08, year: 2022),
author: "<NAME>",
doc
)
<NAME> pressed her hand against the wall of her cabin and felt the #emph[Weatherlight] 's soft warmth pulsing through its wooden hull. At least here it was still ordinary. At least here she couldn't see what she'd turned the great skyship into. At least here she didn't imagine the spirit of Captain Sisay judging her.
#emph[It'll be alright. Everything just needs to hold together for a little while longer.]
"—all come apart," Tiana was saying. When Shanna didn't respond, the artificer's angelic radiance flared. "Captain, are you listening?"
"Sure, I am," Shanna said. "Things are hard on everyone right now, Tiana. The #emph[Weatherlight] included."
"The #emph[Weatherlight] wasn't meant to take this kind of strain," Tiana said. "Nothing was. All this Phyrexian garbage, it's corrosive. The crew can barely stay ahead of it. The ship's hurting, Captain. I can feel it."
"Without all this Phyrexian garbage, we'd have been shot down five times already. The Coalition needs us, and this disguise lets us fly right over Sheoldred's territory."
#figure(image("009_Shards of Nightmares/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"The Coalition needs a ship that isn't wrecked!" Tiana's eyes flared with all the righteous fury of an angel pushed to the wall. "I've had to put off repairs to the powerstone motivator, and I can see fatigue cracks in the moderator rods—"
A screech like nothing Shanna had heard sliced through the air, chopping the rest of Tiana's words into ribbons, and the #emph[Weatherlight] rumbled and lurched to one side. She shared a surprised look with Tiana for an instant before they dashed out of her cabin. When the Phyrexian garbage failed, it was up to them—and everyone else—to succeed.
"What have we got?" Shanna shouted as she ran into the cockpit. The helmsman, Botono, was on the floor with a puddle of blood under his head, and <NAME> had taken the ship's wheel. Outside, the setting sun painted the clouds like fire.
"Bone dragon, I think!" Raff turned the wheel hard, and the #emph[Weatherlight] swung into a heavy tilt. "It came from behind. I haven't had a good look at it yet. But if it can knock us around like that by yelling, I don't want to see what its claws might do."
"Then get us some altitude." Shanna braced herself against a railing. #emph[It had all been going so smoothly!] "Whatever it is, we'll show it our claws."
Another screech slammed against the #emph[Weatherlight] 's hull, and in it, Shanna could hear the dragon's fury that the skyship hadn't had the decency to go down without a fight. Ulaten and Anyxni, two of the newer cockpit crew, carried Botono away as the skyship levelled out. With luck, he'd make it, and with a lot of luck, they'd only need that luck for him.
"There it is, up ahead!" shouted Velena at the weapons podium. "Serra's grace, just #emph[look] at that!"
She pointed to a creature that looked less like a dragon than an assembly of bones flying in close formation. Only its wings were whole, with fibrous red membranes that reminded Shanna too much of the #emph[Weatherlight] 's own disguised wings. It spat crimson lances that shimmered with magical energy toward the #emph[Weatherlight] , and only Raff's quick reaction at the wheel kept the skyship from being speared.
"Velena, why don't you show that monster some of Serra's grace?" Shanna scowled at the dragon, as if her own fury could knock it out of the sky. "Powerbolt barrage, as focused as you can make it."
"My pleasure, Captain!"
#figure(image("009_Shards of Nightmares/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
A musical hum reverberated through the #emph[Weatherlight] 's structure, deepening until it erupted into a crescendo of green bolts that sprayed out toward the dragon. Or, at least, where the dragon had been. It rolled and weaved in exactly the way bones shouldn't be able to, and their bolts pierced nothing but clouds.
"That's not going to work," Shanna said. "Raff, get us closer."
"I'll try to keep us out of claw range, but I can't promise anything." Raff slammed a palm against the wheel. "I #emph[knew] I should've gone with the southern route instead."
"We're here now," Shanna said. There was no telling which route would've been safer, or if any of them were. Dominaria wasn't the place it had been only a couple of years ago, when the winds had been clean and the skies peaceful. These days, everything smelled of Phyrexian invaders.
"I guess we are," Raff said as the #emph[Weatherlight] wheeled to keep the dragon ahead. As it righted itself, the dragon spat another brace of crimson lances. "Damn, hang on!"
Raff threw the #emph[Weatherlight] into a hard dodge. It wasn't enough to keep one of the lances from tearing a hole in the starboard wing with immolating heat and a pyrotechnic roar. From the intensity of the impact, it was clear Tiana would be getting her wish for serious repairs after all, so long as they survived the next few minutes.
"It's left itself open! This is it!" Velena shouted. "Firing!"
Another barrage of powerbolts erupted from the #emph[Weatherlight] 's cannons, and this time, the skeletal dragon was far too close to evade. A few went wide and others splashed against the dragon's ribcage and tail, but the rest of them sliced true into one of its wings, severing it with a snapping crack. The dragon howled and plummeted out of the sky. Whatever magic had brought it out of its grave wasn't enough to keep it in the air with only a single wing.
Shanna allowed herself an instant of satisfaction at the crew. They were all living up to Sisay's example.
"Captain, whatever you're doing, we've got to land now!" Tiana's voice thundered out of the speech tube. "If you don't put us on the ground, gravity will!"
Raff didn't wait to throw the #emph[Weatherlight] into a sharp descent, and Shanna didn't blame him. It'd be an awful thing to shoot down a reanimated dragon only to fall out of the sky.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"You don't want to know how close we came to falling out of the sky," Tiana said. "So don't ask."
Shanna gathered a handful of dirt and squeezed her fist until her knuckles were the color of sunrise. In these last dregs of daylight, this stretch of Otaria, where the open plains gave way to rocky foothills, looked less like a refuge and more like a threat. Even Arvad, standing next to her, looked unsettled by it.
"Then I won't tempt fate," Arvad said. "That we're alive is satisfactory."
"It could've been a lot worse," Raff said, pointing north where the twilight weight of a mountain range was only just visible. "We could've come down in Pardia. That would've been fun, right?"
"We can talk about how fun it would've been once we're at a safe port," Shanna said. "Tiana, how long until we can take off?"
The artificer-angel whistled like a broken kettle. "That's the problem. We can't. Half the moderator rods are cracked. If we try to spin up the powerstone in those conditions, #emph[bang] , no more #emph[Weatherlight] ."
"What about replacements? Spare parts?"
"The half that aren't broken #emph[are] the spare parts," Tiana said. "I can't make new ones with what we've got."
"That can't be it." Shanna sweated from the feeling of Sisay, Jhoira, Ilsa Braven, all the former #emph[Weatherlight] captains judging her from afar and beyond. "You're saying we're stuck here? Grounded?"
For a moment, no one spoke. The idea of losing the #emph[Weatherlight] was a knife in all their backs. All their sacrifices, all those close escapes, all to end up here, like this?
"Maybe not," Raff said as he stared at the mountains. "As long as I'm right."
Shanna spun to face him. "Then for all our sakes, you'd better be right. What have you got?"
"I think that dragon was guarding something," Raff said. "Something with a lot of magic, and not too far from here. I'm not sure what, exactly, but from the emanations I'm sensing, it might be something Tiana could use to fix the damage."
"Might is better than can't," Shanna said. "Let's check it out."
"Are~ do you mean me, too?" Tiana's wings curled around her. "You want me to leave the #emph[Weatherlight] like this?"
"You said it yourself, you can't make new ones here," Shanna said. "If whatever Raff's picked up is something you can work with, you should be there. Arvad will keep things under control while we're gone."
"The captain's right," Arvad said. "Go on. The #emph[Weatherlight] will be fine without you for a little while."
"Okay," Tiana said. "Alright. Yes. Better that I be there, just in case. Wouldn't want you to waste all that time carrying back something I couldn't use anyway, right?" She smiled, but it didn't erase the concern in her eyes.
"Right! It'll all be fine," Raff said with a hollow chuckle. "Not a problem at all."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"On closer inspection," Shanna said, "this could be a problem."
Nestled amid the low hills, where nature howled and skittered and a cool breeze carried no trace of Phyrexian invaders, a cloudy dome of oily black smoke crackled and roiled. Raff raised one finger and sniffed the air, while Shanna threw a rock at it. The rock slammed hard and fell to the ground with singe marks where it had hit.
#figure(image("009_Shards of Nightmares/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"This never came up at the Tolarian Academy, but I might be able to deal with it anyway," Raff said. After a moment's thought and concentration, he summoned a blaze of magic and hurled it at the dome. It disappeared without even a fizzle, an ember in an ocean.
"Hmm." He kneeled and scratched the ground with a stick. "Shanna, you've got that magical immunity. Maybe it's as simple as you walking through."
"Or as simple as vaporizing her when she touches it," Tiana said. "Magic like this is something to be respected, not challenged. Definitely not with the captain's life."
"No one's getting vaporized," Shanna said. Least of all herself. "Let's think about this. There's got to be another way through."
As Shanna studied the dome, looking for any hint of a plan on its roiling surface, she felt an unfamiliar twinge. Not the sensation she got when magic nullified itself against her, but a mirrored version of it with a sour taste rising on her tongue. Raff looked ill at ease as well.
"You feel that, Raff? Phyrexian?"
"If it is, they're getting creative," Raff said. "Maybe we should give this some distance."
Before they could take more than a few steps back, a low and fast crack like miniature thunder bolted out, followed by the muffled roar of distant wind and what sounded like a mountain-sized horn backed by the whole world groaning. It only got louder as a howling blackness shot through with lightning manifested next to the dome, and as Shanna went for her sword, a tornado of rainbow and darkness emerged and solidified into a figure.
Human-like, maybe, but certainly not human. Humans didn't tend to be swathed in a dozen twisting braids that could just as easily be hair or shadow, with too many clawed hands reaching out of the tumult and a body ending in only the suggestion of feet. All that hinted at ordinariness were the goggles on the figure's head.
Shanna tightened her grip.
"Well, well, well, it's you and you and you already!" The braided stranger pointed at Shanna, Raff, and Tiana in turn and laughed. "You're lucky you didn't listen to him, you know. It would've vaporized you, and you'd have deserved it. Didn't your parents tell you not to play with deadly magic?"
"Whoever you are, stay back!" Raff raised his hand as patterns of magical light gathered around it. The shadow-stranger laughed, and with a gesture, the lights snuffed out like candles.
"My name~ that'd be telling. You can call me Braids," she said. "You don't need to impress me. You three, you didn't get yourselves killed up there. That's good enough."
"Are you saying that dragon was your work, Braids?" Shanna took one step forward. "That you brought my ship down?"
"Oh, please, if it was mine, you'd have never survived to crash," Braids said. "Blame the Phyrexians. Their war construct tore the roof off its hoardgrave, and it got just a #emph[little] irritated. That wonderful, glittery, indefatigable construct. So full of potential, and also fiery death! That's why I had to hide it behind there, to deal with it."
Shanna traded a look with the others. Raff looked like the air had turned lemon-sour, but Tiana's wings were fully extended, and her eyes were full of confidence.
"If there's a construct in there, it's definitely got the parts I need," Tiana said. "We're on an urgent mission. My skyship's been grounded. I need to fix it."
"Oh, I know, it was all very exciting when all that snapping happened!" Three shadowy claws emerged from Braids's dark aura and clacked sharp nails together. "Snap, snap, snap. So exciting that I lost a bit of control! Which is very exciting, when you think of it like that. But now you and you and you are here, and so I think we can help each other!"
Shanna pursed her lips and lowered her sword. Whatever Braids was and wherever she'd floated in from, she hadn't tried to kill them yet. If the #emph[Weatherlight] stayed grounded, the Phyrexians certainly would. "What do you have in mind?"
"It's so very simple, even you three should be able to manage it," Braids said. "I help you get inside the barricade, and you help me kill me."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"Why can't important things ever be behind locked doors?" Raff said as the three of them and Braids stood in front of the roiling, smoking barrier. "You'd be surprised how easy it is to pick locks."
Shanna steeled herself by thinking of everyone who was counting on her, back at the #emph[Weatherlight] and out in the world. Of course, it couldn't have been as easy as a simple magical barrier that Raff could dispel with the right preparations. No, it had to be some monstrosity from beyond who'd shattered herself into pieces. She didn't pretend to understand how that chaotic magic worked, how Braids could split herself into two separate beings when even something as simple as a worm couldn't, or why a being like Braids needed Shanna's help to swallow a wayward copy of herself. Magic rarely made sense to her, and Braids made even less sense than magic.
"Let me guess, they keep you around to ask the foolish questions." Braids threw a handful of dirt at the barrier and smiled as the clump sizzled into steam. "Think about it too hard and you'll crack your brain like an egg. Such a great noise that'd make. All you need to know is that I need to reabsorb that version of myself. See? So simple even simpletons like you can comprehend."
Shanna squeezed her sword's hilt and saved her frustration. Dealing with Braids's shard wouldn't be "killing," really, but it didn't sound like the easiest thing either way. As long as it got the #emph[Weatherlight] off the ground and her crew to safety, it would be worth it.
"I suppose it wouldn't keep you out either way," Tiana said. "You don't look like the sort that'd be slowed down by a lock."
"Why protect yourself with rusty machines when screaming nightmares can do the job even better?" Braids laughed at that with hollow barks that set Shanna on edge. "My shard-self had the same idea. Lucky for all of us, I have a little bit of experience with nightmares."
While Braids went to the cloud, Shanna looked back at Tiana. She'd wrapped her wings around her and looked like she'd just awakened from a blood-chilling dream. What kind of nightmares did angels reckon with?
"It'll work out," Tiana said. "Serra's grace is with us."
"I hope that's all we need," Shanna said. "Alright, let's get to it."
"That's right, you and you and you, all the more chance that at least one of you will survive the way through!" Braids gave them a smile loaded with an uncomfortable number of teeth. "You'll all walk your paths alone until you reach the other side, and don't get lost. You can't just wake up in there when you find trouble."
"I'd have felt a lot better if you'd said 'if,' instead," Raff said.
"You think you're going to navigate a storm of screaming nightmares and get through unscathed?" Braids's laughter was loud enough to awaken dead war machines. "You'll be lucky to not come out gibbering. Exciting, isn't it?"
It wasn't the first word that Shanna thought of, or even the thirty-seventh. Besides, her true terror—losing the #emph[Weatherlight] and losing the war—was already in front of her. She couldn't imagine anything in a nightmare that would be worse than the reality she was staring down.
Half a dozen shadowy tendrils unfolded from Braids, swayed for a moment like branches in the wind, and lanced into the barrier like predators striking prey. The barrier hissed like water dropped onto a hot pan, and it screamed with a battlefield's agony. Waves of dread crashed against Shanna, Raff was covering his ears and whispering something she couldn't hear, and Tiana kneeled as if it would wash her away.
After a moment, the noise and tumult ceased. Four gaps had opened in the barrier, smooth sided and narrow. Braids smiled with rainbow teeth.
"There you are, a corridor for everyone and all the lovely nightmares you could ever hope to meet," Braids said. "Don't anyone try to follow someone in. I mean, I really want to see if sharing nightmares makes your brains dribble out your nose, but there'll be time for that later. You'll need to deal with my shard-self first."
Shanna kneeled, grabbed a handful of soil, and wiped it between her palms. The more connections she had to the world outside, where nightmares only occasionally came true, the better off she'd be at saving the #emph[Weatherlight] and her crew. Failing at that was the only real nightmare.
"Raff, Tiana, I'd better see you both on the other side," Shanna said. "We've still got plenty to do."
Up close, the barrier was a gibbering storm that felt impossible. Shanna took a deep breath and stepped through the gap that Braids had made for her.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
It started with darkness deeper than sleep, deep enough to mock the concept of light. Shanna made her way forward because there was no going back. She couldn't turn around any more than she could step back into the past, and neither direction appealed to her.
Between blinks, the corridor transformed from that unlightable darkness to the #emph[Weatherlight] 's familiar passages. It wasn't a surprise Shanna would find nightmares here, in the hub of her besieged life.
Another blink, and she was no longer alone. Centuries-dead Sisay stood before her, half flesh and half bone, wreathed in smoky shadow and carrying the same sword Shanna wielded. Sisay's own sword. The most regular reminder of her ancestor's deeds, and of the example Shanna was driven to exceed.
"Foolish legacy," Sisay said with a smirk that dissolved into a dead rictus as it crossed her face. "What do you think you're doing?"
"What I have to." This wasn't her ancestor and didn't deserve respect. "Get out of my way."
"Why, so you can further poison my memory? I gave you the power and the dream of the #emph[Weatherlight] , and look what you've done with it."
Sisay stabbed at the bulkhead, and oil mixed with clotted blood poured forth. More holes tore themselves open, and tentacles made of Phyrexian detritus whipped out. Everywhere they touched the #emph[Weatherlight] 's wood turned livid and rotten, polluted by Phyrexian corpse-poison.
"I'm fighting to save the world," Shanna said. "Just like the real Sisay did."
"The difference is that she was successful." Sisay stabbed the wood again, and the false #emph[Weatherlight] screamed. "When she lost the #emph[Weatherlight] , it was the price for destroying Yawgmoth and saving the world. You're losing it for the grand and noble cause of smuggling trinkets from here to there. Are you too scared to confront the invaders, legacy? Or are you a waste of her blood? Do you at least have the courage to show me that you can fight at all?"
Shanna scowled at the mocking nightmare, and in an instant, the tip of her sword was at Sisay's throat. The nightmare only smiled, her teeth jagged and cold. It would be so easy to slash the neck of the thing that tore her ancestor's face to ribbons, to slice it into nothing and bury it.
The same way she'd buried all her other fears. The same way she'd forced Tiana to swallow her own worries when she'd come to her before the battle. The same way the land would reclaim the #emph[Weatherlight] if the crew couldn't get it back in the air.
Shanna pressed the tip of her sword into the nightmare's neck. Instead of blood, gray smoke whispered out.
"It's not just my courage that matters," Shanna said. "It's everyone's. We're stronger together. If you understood anything about Sisay, you'd understand that."
"But right now, you're alone." The nightmare-wearing half of Sisay's face tore into a predator's grin. "Your friends can't help you. Face it, without you around to help them, they're probably dead already."
Nightmare-Sisay's jaw unhinged like a snake, and in her throat's darkness, Shanna saw awful things. Raff cut in half on a bed of entrails, Tiana's skin hanging loose next to her polished skeleton, the #emph[Weatherlight] 's crew corrupted into Phyrexian monstrosities with oil for eyes and twisted metal tentacles wrapped in barbed wire, and through it all screaming, screaming, screaming.
"No!" Shanna roared with a dragon's fury. "#emph[NO!] "
There was no artistry to Shanna's assault, only brutality. She struck at the nightmare-Sisay again and again, slashing and thrusting with her sword and her screams, severing bones and piercing clouds of smoke until there was nothing left of the nightmare. Nothing that her eyes could see, at least.
The false #emph[Weatherlight] dissolved around her, and the shadowed corridor reasserted itself. This time, the darkness wasn't complete. Her sword shone bright enough to light the way.
"We're in this together," Shanna whispered, and she charged ahead, unyielding.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
By Shanna's reckoning, she'd been walking down the corridor for half an hour after dispelling the nightmare-Sisay with no hint of the world beyond. Despite the darkness, she wasn't afraid. If she died here, she'd die on her feet while trying to save her crew. What better end could a captain ask for?
The corridor ended with the abruptness of sudden death. Between blinks, it evaporated, leaving her on solid, familiar dirt under a roiling cloud shot through with lightning. Below her, the ground bowed into a mud-bottomed crater where the half-sunken hulk of a Phyrexian war machine shrieked like an unoiled hinge as it tried and failed to free itself.
It was more nightmarish than anything she'd seen in the corridor.
"Captain!" Shanna whirled to find Tiana nearby, alive and unruffled. "I'm so thankful you're alright."
"What about Raff? Did you see him?"
"No, I was alone in there, and I'm thankful for that, too." Tiana shuddered. "Some things shouldn't be shared. But I'm sure he'll be—"
Without a flash of light, a thunderclap, or roar, Raff wasn't there one instant and was the next. He appeared close enough to Tiana to make her yelp with surprise, and Raff in turn fell to the ground, gasping for breath.
"He's being, alright." Shanna offered Raff her hand. "Come on. Are you okay?"
"Okay? I thought I'd never get out of there!" Raff said as he hauled himself up. "I was walking for hours and never getting anywhere."
"Hours?" Tiana furrowed her brow. "It was minutes for me."
"It sounds like time was a bit unmoored in there," Shanna said. "Here's hoping it hasn't been years outside."
Before they could gather themselves any further, the air filled with a thrumming tune that started like a military march only to detour into warped playfulness. Shadows gathered from across the barrier's inside and congealed into a single form. It looked like Braids but faded and wrong, like a distorted shadow that had been burned onto a wall and then slithered off it.
Shanna stood firm as it approached. The shard of Braids, the thing she'd been sent in to kill. It had to be.
"Now that's a disappointment," Shard-Braids said with a voice that drilled. "Those nightmares should've made powder out of your fool brains. I must be out of practice."
"I'm an illusionist," Raff said. "I'm used to dealing with things that aren't real."
"Yes, well, I'm as real as death," Shard-Braids said. "And that's what you'll get if you don't leave now. Don't think it's a kindness. I'm itching to see if you survive the way back out."
A storm of shadows slithered out from the barrier's walls, and Shanna tensed herself. She could only hope that they'd be as easy to defeat as the nightmare-Sisay. Rather than pouncing to attack, the wisps of darkness coalesced into the original Braids's grasping, rainbow-and-shadow form.
"There you are~ or there I am, is it?" Braids chuckled. "Did you really think you could hide? Stop being foolish and come back to me, or I'll break you."
"What did she promise you three?" Shard-Braids sounded desperate, like a dream that knew it was a figment. "Don't be ridiculous, she's using you!"
"We don't have time for this," Shanna said. "Figure things out!"
"No, I won't!" Shard-Braids screamed, and the barrier rumbled and flashed with lightning. "If you're here with her, then I'll just have to kill you all!"
Shard-Braids pointed at Shanna with four flickering, shadowy hands. Nested cubes simultaneously black and transparent erupted from her fingers and hurled themselves at Shanna, only to spatter against the faint golden light of Shanna's magical immunity: Sisay's most enduring gift to her descendants.
Before the light had settled, Shanna charged and cleaved the space where Shard-Braids had been an instant before. Now she was behind her, with a palm against Raff's head. He was frozen mid-spellcast, his face twisted in terror.
"You're easier to play than gutstrings," Shard-Braids said. "And you thought you'd seen all the nightmares I had to offer."
Shanna charged again, and Shard-Braids only smiled like someone who knew the situation was entirely under control. That smile lasted until Tiana struck from the opposite direction, her open palm blazing with angelic power. One touch was enough to make Shard-Braids scream, but not enough to keep her from twisting around to spray a beam of darkness at Tiana's face.
It never made it. Raff's unfinished spell knitted itself together and crashed into the beam with a storm of mutual annihilation, while Raff dodged out of Shard-Braids's reach. He gave Shanna all the opening she needed to skewer Shard-Braids on the tip of her sword.
Shanna found more resistance than mere shadow. Her sword blazed with fire and ice, fear and pleasure, and in Shard-Braids's scream, Shanna heard lingering nightmares. As Shanna jerked her sword back, the original Braids descended from above with a predator's smile. Braids's teeth gave way to a swirling void of a throat as her jaw first yawned wide then tore open with the eagerness of poorly stitched clothes, like an earthquake fissure, like an avalanche that buried the shard whole. With a sizzling screech, the barrier fell away and the stars gazed down on them.
"Was~ was that it?" Shanna blinked in surprise. "It was that simple?"
"Oh, no," Braids said. "I was holding her back. You and you and you'd have been ugly corpses by now otherwise. Especially you."
"That's, well~" Raff fell to the ground in a heap. "Tiana, you don't know how lucky you are not having to worry about sleep, or nightmares!"
"I wondered if I was missing out," Tiana said. "I don't think I will for a while. I think~ I need to start gathering parts."
For a long moment, nobody spoke. The world's silence was a balm that lasted until Braids shattered it with applause.
"Now then, now then, if you want to lie down here and die, I'm happy to help you along, but if you still want my help with your ship, you should really get organized! I promise I won't even kill anyone, even when they really deserve it. I mean, look at how I haven't killed any of you yet!"
"That's encouraging," Shanna said, sheathing her sword. "Come on. Let's gather those parts and get out of here."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Shanna walked behind everyone else as they traced the path back to the #emph[Weatherlight] . Aside from not wanting to be between Tiana and her skyship, she wanted to keep a close eye on Braids. Not that it would matter, given everything she'd seen, but vigilance was always preferable to the alternative.
"You really wouldn't rather fly, Tiana?" Raff asked. "I'm sure you'd have everything ready once we caught up."
"I would." Tiana unfurled her wings for a moment, then tucked them back again around the armful of parts she'd scavenged from the dead construct. "But I wouldn't want to leave you alone, either. Or risk dropping anything on your head."
"Alone with a mystery like me, you mean?" Smoky snake heads unfolded from Braids's shadowed aura with hissing laughter. "I'm so touched, angel. I mean it. Come on, touch me and find out what happens!"
"Nobody's touching anyone," Shanna said.
"Yes, yes, it's going to be so exciting!" Braids said. "The sort of exciting where you make sure you said goodbye to your loved ones first. You #emph[did] all say goodbye before you started winging around the world, right? I'd be tickled to make some extra visits if not~"
"All we need is to get back in the air again," Shanna said. She thought of her loved ones every time the #emph[Weatherlight] struck a blow against the Phyrexian invaders. "That's all that matters for now."
"The sooner, the better." Tiana put one hand to her head. "I don't know what it is, but I'm getting a terrible headache."
As they passed a bowed-over tree that Shanna remembered being not too far from the #emph[Weatherlight] 's crash site, a pair of bobbing lights appeared around a curve in the trail. Shanna grasped her sword's hilt, and when she recognized Velena's voice shouting, her grip only tightened.
"Captain!" Velena was accompanied by Arvad and Elmegraun from the #emph[Weatherlight] 's engine room, and they all looked ragged and wrecked. "Thank Serra we found you! It's awful!"
"What happened?"
"The #emph[Weatherlight] , it's—"
Arvad shouted before she could finish. "Too late, get down!"
A flurry of sickly green powerbolts rained down, digging craters and setting trees alight. There was no time to scatter. Shanna threw herself to the ground, singed from a near miss. Velena and Elmegraun weren't so lucky and melted into puddles an instant before Raff finished casting a protection spell. Arvad grunted with pain, but the sort of grunt that told Shanna he was still in the game.
Braids howled with laughter. "Wouldn't you know, just like wax, except wax never screams like that!"
Shanna had no words for any of it as she helped Arvad to his feet. The #emph[Weatherlight] loomed above them, and a glance was enough to know it wasn't the #emph[Weatherlight] anymore. Its spike-studded hull was knotted like burned muscle, and cables like intestines hung dribbling with viscera that said the #emph[Weatherlight] she knew was dead.
"Arvad, what happened?"
"Some problem in the engine room," Arvad said. "A malfunction that spiralled on and on. What matters is the #emph[Weatherlight] 's turned against us."
In a distant recess of her mind, Shanna heard Tiana say, #emph[I told you so. ] She wasn't going to dwell on that, not when only one thing mattered.
"Tiana, can you bring it down?"
"Bring it down?" Braids gasped with mock outrage. "This is a better show than anything I could've hoped for."
"If I can get the powerstone, that should do it." Tiana's eyes burned with resolve that made her tears shine.
"Then let's go." She grabbed Tiana tight and gave her a pleading look. #emph[I'm so sorry.]
Though the #emph[Weatherlight] fired more volleys as Tiana and Shanna ascended, its attacks went wide, as if still getting used to being a monstrosity, and it couldn't keep them from its rancid hull. Though slick with Phyrexian corruption, Tiana had no trouble carving a hatch open.
"I think I'm going to be sick," Shanna said. Instead of the soothing wood she remembered, the #emph[Weatherlight] 's interior was overgrown with mossy flesh, eyes wreathed in teeth, and jagged spines, more than one of which had speared a crew member's arm or heart or head. "How did this happen so fast?"
"It was happening for weeks," Tiana said in a low monotone. "Some things start slow, and finish all at once."
In the engine room, raw meat had grown around the machine frames, with the exposed Thran metal skeleton here turned black and acid burned. The powerstone, still in its cradle, was the only source of light and the only uncorrupted thing. Slimefoot clung to it, its cap singed and trailing hyphae.
Three razored tentacles growing from the meat stabbed and snapped at Slimefoot until Shanna drew their attention. All three were impaled in heads that Shanna recognized, and which recognized her.
Botono, the helmsman Raff had replaced in the storm of battle. Ulaten, who'd always had a joke to pierce the most stressful situations. Anyxni, with a spirit that never gave up. Shanna had never seen defeat in their eyes before now.
"Captain~" they groaned and wheezed. "You left us to die~"
The head-tentacles whipped forth, and before Shanna could dodge or slash them away, they licked her neck worse than acid and fire combined. It was betrayal distilled into a poison.
That shard of Braids hadn't had any idea what real nightmares were.
"I'm sorry I wasn't there when you needed me." Shanna dodged another strike as her sword bit through the tentacle wearing Ulaten's head. It wept black oil instead of blood. "I know it hurts. Let me end it."
"You killed us~" They spoke sharper than swords.
"The Phyrexians killed you," Shanna said. "Don't think I'll forget."
Shanna felt the razor's pain the way she saw through frosted glass: only the vaguest impressions were there. She'd have time for pain later. One thrust, and Botono's death was final; another, and Anyxni's spirit disappeared like desert rain.
There was no triumph to it. The only triumph in nightmares was waking up from them. Shanna and Tiana traded a long, wordless gaze that said everything necessary and worked to free the powerstone from its cradle. It was warm to the touch, and still full of possibilities.
"Slimefoot, are you okay?" Shanna didn't expect an answer from the thallid, but the way it shivered and took a step forward told her what she needed to know. "Come on, let's get out of here."
"And how," Tiana said. "This wreck won't stay flying much longer."
There was no resistance on the way back to the hatch. Shanna hoped it was thanks to some remnant of the #emph[Weatherlight] 's spirit fighting on. Tiana paused at the edge, her hand pressed against the corrupted bulkhead, fighting back tears.
"First the Great Machine, and now this," Tiana whispered. "What kind of angel am I?"
"One who's going to keep on going, to make sure it doesn't end like this," Shanna pressed her hand to Tiana's shoulder. "Right?"
Tiana squeezed Shanna and Slimefoot close and leapt out of the hatch. As they fell, the #emph[Weatherlight] with its transformed hull and veiny wings shuddered, turned away, and flew off.
It was a defeat, but it wasn't the end.
|
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/cetz-manual.typ | typst | Apache License 2.0 | #import "doc/util.typ": *
#import "doc/example.typ": example
#import "doc/style.typ" as doc-style
#import "src/lib.typ": *
#import "src/styles.typ"
#import "src/anchor.typ" as anchor_
#import "@preview/tidy:0.2.0"
// Usage:
// ```example
// /* canvas drawing code */
// ```
#show raw.where(lang: "example"): example
#show raw.where(lang: "example-vertical"): example.with(vertical: true)
#make-title()
#set terms(indent: 1em)
#set par(justify: true)
#set heading(numbering: (..num) => if num.pos().len() < 4 {
numbering("1.1", ..num)
})
#show link: set text(blue)
// Outline
#{
show heading: none
columns(2, outline(indent: true, depth: 3))
pagebreak(weak: true)
}
#set page(numbering: "1/1", header: align(right)[CeTZ])
= Introduction
This package provides a way to draw onto a canvas using a similar API to #link("https://processing.org/")[Processing] but with relative coordinates and anchors from #link("https://tikz.dev/")[Ti#[_k_]Z]. You also won't have to worry about accidentally drawing over other content as the canvas will automatically resize. And remember: up is positive!
The name CeTZ is a recursive acronym for "CeTZ, ein Typst Zeichenpaket" (german for "CeTZ, a Typst drawing package").
= Usage
This is the minimal starting point:
#pad(left: 1em)[```typ
#import "@preview/cetz:0.2.1"
#cetz.canvas({
import cetz.draw: *
...
})
```]
Note that draw functions are imported inside the scope of the `canvas` block. This is recommended as some draw functions override Typst's function's such as `line`.
#show raw.where(block: false): it => if it.text.starts-with("<") and it.text.ends-with(">") {
set text(1.2em)
doc-style.show-type(it.text.slice(1, -1))
} else {
it
}
== CeTZ Unique Argument Types
Many CeTZ functions expect data in certain formats which we will call types. Note that these are actually made up of Typst primitives.
/ `<coordinate>`: Any coordinate system. See coordinate-systems.
/ `<number>`: Any of `<float>`, `<integer>` or `<length>`.
/ `<style>`: Named arguments (or a dictionary if used for a single argument) of style key-values.
/ `<context>`: A CeTZ context object that holds internal state.
/ `<vector>`: A three element array of `<float>`s
== Anchors <anchors>
You can refer to a position relative to an element by using its anchors. Anchors come in several different variations but can all be used in two different ways.
The first is by using the `anchor` argument on an element. When given, the element will be translated such that the given anchor will be where the given position is. This is supported by all elements that have the `anchor` argument.
```example
// Draw a circle and place its "west" anchor at the origin.
circle((0,0), anchor: "west")
// Draw a smaller red circle at the origin.
fill(red)
stroke(none)
circle((0,0), radius: 0.3)
```
The second is by using anchor coordinates. You must first give the element a name by passing a string to its `name` argument, you can then use its anchors to place other elements, see @coordinate-anchor for more usage. Note this is only available for elements that have a `name` argument.
```example
// Name the circle
circle((0,0), name: "circle")
// Draw a smaller red circle at "circle"'s east anchor
fill(red)
stroke(none)
circle("circle.east", radius: 0.3)
```
Note that all anchors are transformed along with the element.
=== Named
Named anchors are normally unique to the type of element, such as a bezier curve's control points. Other anchor variants specify their own named anchors that are available to all elements that support the anchor variant.
All elements also have a "default" named anchor, it always refers to another anchor on the element.
=== Border
A border anchor refers to a point on the element's border where a ray is cast from the element's center at a given angle and hits the border.
They are given as angles where `0deg` is towards the right and `90deg` is up.
Border anchors also specify named compass directions such as "north", "north-east", etc. Border anchors also spefcify a "center" named anchor which is where the ray cast originates from.
```example-vertical
circle((0, 0), name: "circle", radius: 1)
set-style(content: (frame: "rect", stroke: none, fill: white, padding: .1))
content((name: "circle", anchor: 0deg), [0deg], anchor: "west")
content((name: "circle", anchor: 160deg), [160deg], anchor: "south-east")
content("circle.north", [North], anchor: "south")
content("circle.south-east", [South East], anchor: "north-west")
content("circle.south-west", [South West], anchor: "north-east")
```
=== Path
A path anchor refers to a point along the path of an element. They can be given as either a `<number>` for an absolute distance along the path, or a `<ratio>` for a relative distance along the path.
Path anchors also specify three anchors "start", "mid" and "end".
```example-vertical
line((0,0), (10, 1), name: "line")
set-style(content: (frame: "rect", stroke: none, fill: white, padding: .1))
content("line.start", [0%, 0, "start"], anchor: "east")
content("line.mid", [50%, "mid"])
content("line.end", [100%, "end"], anchor: "west")
content((name: "line", anchor: 75%), [75%])
content((name: "line", anchor: 50pt), [50pt])
```
= Draw Function Reference
== Canvas
#doc-style.parse-show-module("/src/canvas.typ")
== Styling <styling>
You can style draw elements by passing the relevant named arguments to their draw functions. All elements that draw something have stroke and fill styling unless said otherwise.
#doc-style.show-parameter-block("fill", ("color", "none"), default: none, [How to fill the drawn element.])
#doc-style.show-parameter-block("stroke", ("none", "auto", "length", "color", "dictionary", "stroke"), default: black + 1pt, [How to stroke the border or the path of the draw element. See Typst's line documentation for more details: https://typst.app/docs/reference/visualize/line/#parameters-stroke])
```example
// Draws a red circle with a blue border
circle((0, 0), fill: red, stroke: blue)
// Draws a green line
line((0, 0), (1, 1), stroke: green)
```
Instead of having to specify the same styling for each time you want to draw an element, you can use the `set-style()` function to change the style for all elements after it. You can still pass styling to a draw function to override what has been set with `set-style()`. You can also use the `fill()` and `stroke()` functions as a shorthand to set the fill and stroke respectively.
```example
// Draws an empty square with a black border
rect((-1, -1), (1, 1))
// Sets the global style to have a fill of red and a stroke of blue
set-style(stroke: blue, fill: red)
circle((0,0))
// Draws a green line despite the global stroke is blue
line((), (1,1), stroke: green)
```
When using a dictionary for a style, it is important to note that they update each other instead of overriding the entire option like a non-dictionary value would do. For example, if the stroke is set to `(paint: red, thickness: 5pt)` and you pass `(paint: blue)`, the stroke would become `(paint: blue, thickness: 5pt)`.
```example
// Sets the stroke to red with a thickness of 5pt
set-style(stroke: (paint: red, thickness: 5pt))
// Draws a line with the global stroke
line((0,0), (1,0))
// Draws a blue line with a thickness of 5pt because dictionaries update the style
line((0,0), (1,1), stroke: (paint: blue))
// Draws a yellow line with a thickness of 1pt because other values override the style
line((0,0), (0,1), stroke: yellow)
```
You can also specify styling for each type of element. Note that dictionary values will still update with its global value, the full hierarchy is `function > element type > global`. When the value of a style is `auto`, it will become exactly its parent style.
```example
set-style(
// Global fill and stroke
fill: green,
stroke: (thickness: 5pt),
// Stroke and fill for only rectangles
rect: (stroke: (dash: "dashed"), fill: blue),
)
rect((0,0), (1,1))
circle((0.5, -1.5))
rect((0,-3), (1, -4), stroke: (thickness: 1pt))
```
```example
// Its a nice drawing okay
set-style(
rect: (
fill: red,
stroke: none
),
line: (
fill: blue,
stroke: (dash: "dashed")
),
)
rect((0,0), (1,1))
line((0, -1.5), (0.5, -0.5), (1, -1.5), close: true)
circle((0.5, -2.5), radius: 0.5, fill: green)
```
=== Marks <styling-mark>
Marks are arrow tips that can be added to the end of path based elements that support the `mark` style key, or can be directly drawn by using the `mark` draw function. Marks are specified by giving there names as strings and have several options to customise them. You can give an array of names to have multiple marks in a row, dictionaries can also be used in the array for per mark styling.
#figure(table(
columns: 3,
[*Name*], [*Shorthand*], [*Shape*],
..(for (name, item) in cetz.mark-shapes.marks {
let name-to-mnemonic = (:)
for (name, item) in cetz.mark-shapes.mnemonics {
let list = name-to-mnemonic.at(item.at(0), default: ())
list += (raw(name) + if item.at(1) { " (reversed)" },)
name-to-mnemonic.insert(item.at(0), list)
}
(
raw(name),
name-to-mnemonic.at(name, default: ([],)).join([, ]),
cetz.canvas(cetz.draw.line((), (1, 0), mark: (end: name)))
)
})
), caption: [Mark symbols])
```example
let c = ((rel: (0, -1)), (rel: (2, 0), update: false)) // Coordinates to draw the line, it is not necessary to understand this for this example.
// No marks
line((), (rel: (1, 0), update: false))
// Draws a triangle mark at both ends of the line.
set-style(mark: (symbol: ">"))
line(..c)
// Overrides the end mark to be a diamond but the start is still a triangle.
set-style(mark: (end: "<>"))
line(..c)
// Draws two triangle marks at both ends but the first mark of end is still a diamond.
set-style(mark: (symbol: (">", ">")))
line(..c)
// Sets the stroke of first mark in the sequence to red but the end mark overrides it to be blue.
set-style(mark: (symbol: ((symbol: ">", stroke: red), ">"), end: (stroke: blue)))
line(..c)
```
#doc-style.show-parameter-block("symbol", ("none", "string", "array", "dictionary"), [This option sets the mark to draw when using the `mark` draw function, or applies styling to both mark ends of path based elements. The mark's name or shorthand can be given, multiple marks can be drawn by passing an array of names or shorthands. When `none` no marks will be drawn. A style `dictionary` can be given instead of a `string` to override styling for that particular mark, just make sure to still give the mark name using the `symbol` key otherwise nothing will be drawn!. ])
#doc-style.show-parameter-block("start", ("none", "string", "array", "dictionary"), [This option sets the mark to draw at the start of a path based element. It will override all options of the `symbol` key and will not effect marks drawn using the `mark` draw function.])
#doc-style.show-parameter-block("end", ("none", "string", "array", "dictionary"), [This option sets the mark to draw at the end of a path based element. It will override all options of the `symbol` key and will not effect marks drawn using the `mark` draw function.])
#doc-style.show-parameter-block("length", "number", [The size of the mark in the direction it is pointing.], default: 0.2cm)
#doc-style.show-parameter-block("width", "number", [The size of the mark along the normal of its direction.], default: 0.15cm)
#doc-style.show-parameter-block("inset", "number", [It specifies a distance by which something inside the arrow tip is set inwards; for the Stealth arrow tip it is the distance by which the back angle is moved inwards.], default: 0.05cm)
#doc-style.show-parameter-block("scale", "float", [A factor that is applied to the mark's length, width and inset.], default: 1)
#doc-style.show-parameter-block("sep", "number", [The distance between multiple marks along their path.], default: 0.1cm)
#doc-style.show-parameter-block("flex", "boolean", [Only applicable when marks are used on curves such as bezier and hobby. If true, the mark will point along the secant of the curve. If false, the tangent at the marks tip is used.], default: true)
#doc-style.show-parameter-block("position-samples", "integer", [Only applicable when marks are used on curves such as bezier and hobby. The maximum number of samples to use for calculating curve positions. A higher number gives better results but may slow down compilation.], default: 30)
#doc-style.show-parameter-block("pos", ("number", "ratio"), [Overrides the mark's position along a path. A number will move it an absolute distance, while a ratio will be a distance relative to the length of the path. Note that this may be removed in the future in preference of a different method.])
#doc-style.show-parameter-block("offset", ("number", "ratio"), [Like `pos` but it moves the position of the mark instead of overriding it.])
#doc-style.show-parameter-block("slant", "ratio", [How much to slant the mark relative to the axis of the arrow. 0% means no slant 100% slants at 45 degrees], default: 0%)
#doc-style.show-parameter-block("harpoon", "boolean", [When true only the top half of the mark is drawn.], default: false)
#doc-style.show-parameter-block("flip", "boolean", [When true the mark is flipped along its axis.], default: false)
#doc-style.show-parameter-block("reverse", "boolean", [Reverses the direction of the mark.], default: false)
#doc-style.show-parameter-block("xy-up", "vector", [The direction which is "up" for use when drawing 2D marks.], default: (0, 0, 1))
#doc-style.show-parameter-block("z-up", "vector", [The direction which is "up" for use when drawing 3D marks.], default: (0, 1, 0))
#doc-style.show-parameter-block("shorten-to", ("integer", "auto", "none"), [Which mark to shorten the path to when multiple marks are given. `auto` will shorten to the last mark, `none` will shorten to the first mark (effectively disabling path shortening). An integer can be given to select the mark's index.])
#doc-style.show-parameter-block("transform-shape", "bool", [When false marks will not be streched/affected by the current transformation, marks will be placed after the path is transformed.], default: true)
#pagebreak()
== Shapes
#doc-style.parse-show-module("/src/draw/shapes.typ")
#pagebreak()
== Grouping
#doc-style.parse-show-module("/src/draw/grouping.typ")
#pagebreak()
== Transformations
All transformation functions push a transformation matrix onto the current transform stack. To apply transformations scoped use a `group(...)` object.
Transformation matrices get multiplied in the following order:
$ M_"world" = M_"world" dot M_"local" $
#doc-style.parse-show-module("/src/draw/transformations.typ")
= Coordinate Systems <coordinate-systems>
A _coordinate_ is a position on the canvas on which the picture is drawn. They take the form of dictionaries and the following sub-sections define the key value pairs for each system. Some systems have a more implicit form as an array of values and `CeTZ` attempts to infer the system based on the element types.
== XYZ <coordinate-xyz>
Defines a point `x` units right, `y` units upward, and `z` units away.
#doc-style.show-parameter-block("x", "number", default: 0, [The number of units in the `x` direction.])
#doc-style.show-parameter-block("y", "number", default: 0, [The number of units in the `y` direction.])
#doc-style.show-parameter-block("z", "number", default: 0, [The number of units in the `z` direction.])
The implicit form can be given as an array of two or three `<number>`s, as in `(x,y)` and `(x,y,z)`.
```example
line((0,0), (x: 1))
line((0,0), (y: 1))
line((0,0), (z: 1))
// Implicit form
line((0, -2), (1, -2))
line((0, -2), (0, -1, 0))
line((0, -2), (0, -2, 1))
```
== Previous <previous>
Use this to reference the position of the previous coordinate passed to a draw function. This will never reference the position of a coordinate used in to define another coordinate. It takes the form of an empty array `()`. The previous position initially will be `(0, 0, 0)`.
```example
line((0,0), (1, 1))
// Draws a circle at (1,1)
circle(())
```
== Relative <coordinate-relative>
Places the given coordinate relative to the previous coordinate. Or in other words, for the given coordinate, the previous coordinate will be used as the origin. Another coordinate can be given to act as the previous coordinate instead.
#doc-style.show-parameter-block("rel", "coordinate", "The coordinate to be place relative to the previous coordinate.", show-default: false)
#doc-style.show-parameter-block("update", "boolean", default: true, "When false the previous position will not be updated.")
#doc-style.show-parameter-block("to", "coordinate", default: (), "The coordinate to treat as the previous coordinate.")
In the example below, the red circle is placed one unit below the blue circle. If the blue circle was to be moved to a different position, the red circle will move with the blue circle to stay one unit below.
```example
circle((0, 0), stroke: blue)
circle((rel: (0, -1)), stroke: red)
```
== Polar
Defines a point that is `radius` distance away from the origin at the given `angle`.
#doc-style.show-parameter-block("angle", "angle", [The angle of the coordinate. An angle of `0deg` is to the right, a degree of `90deg` is upward. See https://typst.app/docs/reference/layout/angle/ for details.], show-default: false)
#doc-style.show-parameter-block("radius", ("number", "tuple<number>"), [The distance from the origin. An array can be given, in the form `(x, y)` to define the `x` and `y` radii of an ellipse instead of a circle.], show-default: false)
```example
line((0,0), (angle: 30deg, radius: 1cm))
```
The implicit form is an array of the angle then the radius `(angle, radius)` or `(angle, (x, y))`.
```example
line((0,0), (30deg, 1), (60deg, 1),
(90deg, 1), (120deg, 1), (150deg, 1), (180deg, 1))
```
== Barycentric
In the barycentric coordinate system a point is expressed as the linear combination of multiple vectors. The idea is that you specify vectors $v_1$, $v_2$ ..., $v_n$ and numbers $alpha_1$, $alpha_2$, ..., $alpha_n$. Then the barycentric coordinate specified by these vectors and numbers is $ (alpha_1 v_1 + alpha_2 v_1 + dots.c + alpha_n v_n)/(alpha_1 + alpha_2 + dots.c + alpha_n) $
#doc-style.show-parameter-block("bary", "dictionary", [A dictionary where the key is a named element and the value is a `<float>`. The `center` anchor of the named element is used as $v$ and the value is used as $a$.], show-default: false)
```example
circle((90deg, 3), radius: 0, name: "content")
circle((210deg, 3), radius: 0, name: "structure")
circle((-30deg, 3), radius: 0, name: "form")
for (c, a) in (
("content", "south"),
("structure", "north"),
("form", "north")
) {
content(c, align(center, c + [\ oriented]), padding: .1, anchor: a)
}
stroke(gray + 1.2pt)
line("content", "structure", "form", close: true)
for (c, s, f, cont) in (
(0.5, 0.1, 1, "PostScript"),
(1, 0, 0.4, "DVI"),
(0.5, 0.5, 1, "PDF"),
(0, 0.25, 1, "CSS"),
(0.5, 1, 0, "XML"),
(0.5, 1, 0.4, "HTML"),
(1, 0.2, 0.8, "LaTeX"),
(1, 0.6, 0.8, "TeX"),
(0.8, 0.8, 1, "Word"),
(1, 0.05, 0.05, "ASCII")
) {
content((bary: (content: c, structure: s, form: f)),
cont, fill: rgb(50, 50, 255, 100), stroke: none, frame: "circle")
}
```
== Anchor <coordinate-anchor>
Defines a point relative to a named element using anchors, see @anchors.
#doc-style.show-parameter-block("name", "string", [The name of the element that you wish to use to specify a coordinate.], show-default: false)
#doc-style.show-parameter-block("anchor", ("number", "angle", "string", "ratio", "none"), [The anchor of the element. Strings are named anchors, angles are border anchors and numbers and ratios are path anchors. If not given the default anchor will be used, on most elements this is `center` but it can be different.])
You can also use implicit syntax of a dot separated string in the form `"name.anchor"`
for named anchors.
```example
line((0,0), (3,2), name: "line")
circle("line.end", name: "circle")
rect("line.start", "circle.east")
```
Note, that not all elements provide border or path anchors!
```example
circle((0,0), name: "circle")
// Anchor at 30 degree
content((name: "circle", anchor: 30deg), box(fill: white, $ 30 degree $))
// Anchor at 30% of the path length
content((name: "circle", anchor: 30%), box(fill: white, $ 30 % $))
// Anchor at 3.14 of the path
content((name: "circle", anchor: 3.14), box(fill: white, $ p = 3.14 $))
```
== Tangent
This system allows you to compute the point that lies tangent to a shape. In detail, consider an element and a point. Now draw a straight line from the point so that it "touches" the element (more formally, so that it is _tangent_ to this element). The point where the line touches the shape is the point referred to by this coordinate system.
#doc-style.show-parameter-block("element", "string", [The name of the element on whose border the tangent should lie.], show-default: false)
#doc-style.show-parameter-block(show-default: false, "point", "coordinate", [The point through which the tangent should go.])
#doc-style.show-parameter-block(show-default: false, "solution", "integer", [Which solution should be used if there are more than one.])
A special algorithm is needed in order to compute the tangent for a given shape. Currently it does this by assuming the distance between the center and top anchor (See @anchors) is the radius of a circle.
```example
grid((0,0), (3,2), help-lines: true)
circle((3,2), name: "a", radius: 2pt)
circle((1,1), name: "c", radius: 0.75)
content("c", $ c $, anchor: "north-east", padding: .1)
stroke(red)
line("a", (element: "c", point: "a", solution: 1),
"c", (element: "c", point: "a", solution: 2),
close: true)
```
== Perpendicular
Can be used to find the intersection of a vertical line going through a point $p$ and a horizontal line going through some other point $q$.
#doc-style.show-parameter-block(show-default: false, "horizontal", "coordinate", [The coordinate through which the horizontal line passes.])
#doc-style.show-parameter-block(show-default: false, "vertical", "coordinate", [The coordinate through which the vertical line passes.])
You can use the implicit syntax of `(horizontal, "-|", vertical)` or `(vertical, "|-", horizontal)`
```example
set-style(content: (padding: .05))
content((30deg, 1), $ p_1 $, name: "p1")
content((75deg, 1), $ p_2 $, name: "p2")
line((-0.2, 0), (1.2, 0), name: "xline")
content("xline.end", $ q_1 $, anchor: "west")
line((2, -0.2), (2, 1.2), name: "yline")
content("yline.end", $ q_2 $, anchor: "south")
line("p1.south-east", (horizontal: (), vertical: "xline.end"))
line("p2.south-east", ((), "|-", "xline.end")) // Short form
line("p1.south-east", (vertical: (), horizontal: "yline.end"))
line("p2.south-east", ((), "-|", "yline.end")) // Short form
```
== Interpolation <coordinate-lerp>
Use this to linearly interpolate between two coordinates `a` and `b` with a given distance `number`. If `number` is a `<number>` the position will be at the absolute distance away from `a` towards `b`, a `<ratio>` can be given instead to be the relative distance between `a` and `b`.
An angle can also be given for the general meaning: "First consider the line from `a` to `b`. Then rotate this line by `angle` around point `a`. Then the two endpoints of this line will be `a` and some point `c`. Use this point `c` for the subsequent computation."
#doc-style.show-parameter-block(show-default: false, "a", "coordinate", [The coordinate to interpolate from.])
#doc-style.show-parameter-block(show-default: false, "b", "coordinate", [The coordinate to interpolate to.])
#doc-style.show-parameter-block(show-default: false, "number", ("ratio", "number"), [
The distance between `a` and `b`. A ratio will be the relative distance between the two points, a number will be the absolute distance between the two points.
])
#doc-style.show-parameter-block("angle", "angle", [Angle between $arrow("AB")$ and $arrow("AP")$, where $P$ is the resulting coordinate. This can be used to get the _normal_ for a tangent between two points.], default: 0deg)
Can be used implicitly as an array in the form `(a, number, b)` or `(a, number, angle, b)`.
```example
grid((0,0), (3,3), help-lines: true)
line((0,0), (2,2), name: "a")
for i in (0%, 20%, 50%, 80%, 100%, 125%) { /* Relative distance */
content(("a.start", i, "a.end"),
box(fill: white, inset: 1pt, [#i]))
}
line((1,0), (3,2), name: "b")
for i in (0, 0.5, 1, 2) { /* Absolute distance */
content(("b.start", i, "b.end"),
box(fill: white, inset: 1pt, text(red, [#i])))
}
```
```example
grid((0,0), (3,3), help-lines: true)
line((1,0), (3,2))
line((1,0), ((1, 0), 1, 10deg, (3,2)))
fill(red)
stroke(none)
circle(((1, 0), 50%, 10deg, (3, 2)), radius: 2pt)
```
```example
grid((0,0), (4,4), help-lines: true)
fill(black)
stroke(none)
let n = 16
for i in range(0, n+1) {
circle(((2,2), i / 8, i * 22.5deg, (3,2)), radius: 2pt)
}
```
You can even chain them together!
```example
grid((0,0), (3, 2), help-lines: true)
line((0,0), (3,2))
stroke(red)
line(((0,0), 0.3, (3,2)), (3,0))
fill(red)
stroke(none)
circle(
( // a
(((0, 0), .3, (3, 2))),
0.7,
(3,0)
),
radius: 2pt
)
```
```example
grid((0,0), (3, 2), help-lines: true)
line((1,0), (3,2))
for (l, c) in ((0cm, "0cm"), (1cm, "1cm"), (15mm, "15mm")) {
content(((1,0), l, (3,2)), box(fill: white, $ #c $))
}
```
Interpolation coordinates can be used to get the _normal_ on a tangent:
```example
let (a, b) = ((0,0), (3,2))
line(a, b)
// Get normal for tangent from a to () with distance .5, at a
circle(a, radius: .1, fill: black)
line((a, .7, b), (a: (), b: a, number: .5, angle: 90deg), stroke: red)
```
== Function
An array where the first element is a function and the rest are coordinates will cause the function to be called with the resolved coordinates. The resolved coordinates have the same format as the implicit form of the 3-D XYZ coordinate system, @coordinate-xyz.
The example below shows how to use this system to create an offset from an anchor, however this could easily be replaced with a relative coordinate with the `to` argument set, @coordinate-relative.
```example
circle((0, 0), name: "c")
fill(red)
circle((v => cetz.vector.add(v, (0, -1)), "c.west"), radius: 0.3)
```
#pagebreak()
= Libraries
== Tree
The tree library allows the drawing diagrams with simple tree layout algorithms
#doc-style.parse-show-module("/src/lib/tree.typ")
== Plot
The library `plot` of CeTZ allows plotting data.
=== Types
Types commonly used by function of the `plot` library:
- #doc-style.show-type("domain"): Tuple representing a functions domain as closed interval.
Example domains are: `(0, 1)` for $[0, 1]$ or
`(-calc.pi, calc.pi)` for $[-pi, pi]$.
- #doc-style.show-type("axes"): Tuple of axis names. Plotting functions taking an `axes` tuple
will use those axes as their `x` and `y` axis for plotting.
To rotate a plot, you can simply swap its axes, for example `("y", "x")`.
- #doc-style.show-type("mark"): Plots feature their own set of marks. The following mark symbols are
available:
```example-vertical
let marks = ("+", "x", "-", "|", "o", "square", "triangle")
cetz.plot.plot(size: (14, 1), x-min: 0, x-max: marks.len() + 1,
x-ticks: marks.enumerate().map(((i, s)) => (i+1, raw(s))),
x-tick-step: none, y-tick-step: none,
x-label: none, y-label: none,
{
for (i, s) in marks.enumerate() {
cetz.plot.add(((i + 1, 0),), mark: s, mark-style: (stroke: blue, fill: white), mark-size: .5)
}
})
```
#doc-style.parse-show-module("/src/lib/plot.typ")
=== Legends <plot-legends>
A legend for a plot will be drawn if at least one set of data with a label that is not `none` is given.
The following anchors are available when placing a legend on a plot:
- `legend.north`
- `legend.south`
- `legend.east`
- `legend.west`
- `legend.north-east`
- `legend.north-west`
- `legend.south-east`
- `legend.south-west`
- `legend.inner-north`
- `legend.inner-south`
- `legend.inner-east`
- `legend.inner-west`
- `legend.inner-north-east`
- `legend.inner-north-west`
- `legend.inner-south-east`
- `legend.inner-south-west`
```example
import cetz.plot
plot.plot(
size: (3,2),
x-tick-step: none,
y-tick-step: none,
legend: "legend.north", {
plot.add(
((-1, -1), (1, 1)),
mark: "o",
label: $ f(x) $
)
})
```
==== Styling
*Root:* `legend`
===== Keys
#doc-style.show-parameter-block("orientation", ("direction"), default: ttb, [
The direction the legend items get laid out to.
])
#doc-style.show-parameter-block("default-position", ("string", "coordinate"), default: "legend.north-east", [
The default position the legend gets placed at.
])
#doc-style.show-parameter-block("layer", ("number"), default: 1, [
The layer index the legend gets drawn at, see on-layer.
])
#doc-style.show-parameter-block("fill", ("paint"), default: rgb(255,255,255,200), [
The legends frame background color.
])
#doc-style.show-parameter-block("stroke", ("stroke"), default: black, [
The legends frame stroke style.
])
#doc-style.show-parameter-block("padding", ("float"), default: .1, [
The legends frame padding, that is the distance added between its items and its frame.
])
#doc-style.show-parameter-block("offset", ("tuple"), default: (0,0), [
An offset tuple (x and y coordinates) to add to the legends position.
])
#doc-style.show-parameter-block("spacing", ("number"), default: .1, [
The spacing between the legend position and its frame.
])
#doc-style.show-parameter-block("item.spacing", ("number"), default: .05, [
The spacing between two legend items in canvas units.
])
#doc-style.show-parameter-block("item.preview.width", ("number"), default: .75, [
The width of a legend items preview picture, a small preview of the graph the legend item belongs to.
])
#doc-style.show-parameter-block("item.preview.height", ("number"), default: .3, [
The height of a legend items preview picture.
])
#doc-style.show-parameter-block("item.preview.margin", ("number"), default: .1, [
Margin between the preview picture and the item label.
])
#doc-style.parse-show-module("/src/lib/plot/line.typ")
#doc-style.parse-show-module("/src/lib/plot/contour.typ")
#doc-style.parse-show-module("/src/lib/plot/boxwhisker.typ")
#doc-style.parse-show-module("/src/lib/plot/bar.typ")
#doc-style.parse-show-module("/src/lib/plot/annotation.typ")
#doc-style.parse-show-module("/src/lib/plot/sample.typ")
=== Examples
```example
import cetz.plot
plot.plot(size: (3,2), x-tick-step: calc.pi, y-tick-step: 1,
x-format: v => $#{v/calc.pi} pi$, {
plot.add(domain: (0, 4*calc.pi), calc.sin,
samples: 15, line: "hvh", style: (mark: (stroke: blue)))
plot.add(domain: (0, 4*calc.pi), calc.sin)
})
```
```example
import cetz.plot
import cetz.palette
// Let ticks point outwards by giving them negative length
set-style(axes: (tick: (length: -.2, minor-length: -.1)))
// Plot something
plot.plot(size: (3,3), x-tick-step: 1, x-minor-tick-step: .2,
y-tick-step: 1, y-minor-tick-step: .2, {
let z(x, y) = {
(1 - x/2 + calc.pow(x,5) + calc.pow(y,3)) * calc.exp(-(x*x) - (y*y))
}
plot.add-contour(x-domain: (-2, 3), y-domain: (-3, 3),
z, z: (.1, .4, .7), fill: true)
})
```
=== Styling <plot.style>
The following style keys can be used (in addition to the standard keys)
to style plot axes. Individual axes can be styled differently by
using their axis name as key below the `axes` root.
```typc
set-style(axes: ( /* Style for all axes */ ))
set-style(axes: (bottom: ( /* Style axis "bottom" */)))
```
Axis names to be used for styling:
- School-Book and Left style:
- `x`: X-Axis
- `y`: Y-Axis
- Scientific style:
- `left`: Y-Axis
- `right`: Y2-Axis
- `bottom`: X-Axis
- `top`: X2-Axis
#doc-style.parse-show-module("/src/lib/axes.typ")
==== Default `scientific` Style
#raw(repr(axes.default-style-scientific))
==== Default `school-book` Style
#raw(repr(axes.default-style-schoolbook))
== Chart
With the `chart` library it is easy to draw charts.
#doc-style.parse-show-module("/src/lib/chart/barchart.typ")
#doc-style.parse-show-module("/src/lib/chart/columnchart.typ")
#doc-style.parse-show-module("/src/lib/chart/piechart.typ")
#doc-style.parse-show-module("/src/lib/chart/boxwhisker.typ")
=== Examples -- Bar Chart <barchart-examples>
```example-vertical
import cetz.chart
// Left - Basic
let data = (("A", 10), ("B", 20), ("C", 13))
group(name: "a", {
chart.barchart(size: (4, 3), data)
})
// Center - Clustered
let data = (("A", 10, 12, 22), ("B", 20, 1, 7), ("C", 13, 8, 9))
group(name: "b", anchor: "south-west", {
anchor("default", "a.south-east")
chart.barchart(size: (4, 3), mode: "clustered", value-key: (1,2,3), data)
})
// Right - Stacked
let data = (("A", 10, 12, 22), ("B", 20, 1, 7), ("C", 13, 8, 9))
group(name: "c", anchor: "south-west", {
anchor("default", "b.south-east")
chart.barchart(size: (4, 3), mode: "stacked", value-key: (1,2,3), data)
})
```
=== Examples -- Column Chart <columnchart-examples>
==== Basic, Clustered and Stacked
```example-vertical
import cetz.chart
// Left - Basic
let data = (("A", 10), ("B", 20), ("C", 13))
group(name: "a", {
chart.columnchart(size: (4, 3), data)
})
// Center - Clustered
let data = (("A", 10, 12, 22), ("B", 20, 1, 7), ("C", 13, 8, 9))
group(name: "b", anchor: "south-west", {
anchor("default", "a.south-east")
chart.columnchart(size: (4, 3), mode: "clustered", value-key: (1,2,3), data)
})
// Right - Stacked
let data = (("A", 10, 12, 22), ("B", 20, 1, 7), ("C", 13, 8, 9))
group(name: "c", anchor: "south-west", {
anchor("default", "b.south-east")
chart.columnchart(size: (4, 3), mode: "stacked", value-key: (1,2,3), data)
})
```
=== Styling
Charts share their axis system with plots and therefore can be
styled the same way, see @plot.style.
==== Default `barchart` Style
#raw(repr(chart.barchart-default-style))
==== Default `columnchart` Style
#raw(repr(chart.columnchart-default-style))
==== Default `boxwhisker` Style
#raw(repr(chart.boxwhisker-default-style))
==== Default `piechart` Style
#raw(repr(chart.piechart-default-style))
== Palette <palette>
A palette is a function of the form `index => style` that takes an
index, that can be any integer and returns a canvas style dictionary.
If passed the string `"len"` it must return the length of its unique
styles. An example use for palette functions is the `plot` library, which
can use palettes to apply different styles per plot.
The palette library provides some predefined palettes.
#doc-style.parse-show-module("/src/lib/palette.typ")
#let show-palette(p) = box({
let p = p.with(stroke: true)
canvas(length: 1em, {
import cetz.draw: *
for i in range(0, p("len")) {
if calc.rem(i, 10) == 0 { move-to((rel: (0, -.5))) }
rect((), (rel: (1,.5)), name: "r", ..p(i))
move-to("r.south-east")
}
})
})
=== List of predefined palettes
#columns(2, [
- `gray` #show-palette(palette.gray)
- `red` #show-palette(palette.red)
- `orange` #show-palette(palette.orange)
- `light-green` #show-palette(palette.light-green)
- `dark-green` #show-palette(palette.dark-green)
- `turquoise` #show-palette(palette.turquoise)
- `cyan` #show-palette(palette.cyan)
- `blue` #show-palette(palette.blue)
- `indigo` #show-palette(palette.indigo)
- `purple` #show-palette(palette.purple)
- `magenta` #show-palette(palette.magenta)
- `pink` #show-palette(palette.pink)
- `rainbow` #show-palette(palette.rainbow)
- `tango-light` #show-palette(palette.tango-light)
- `tango` #show-palette(palette.tango)
- `tango-dark` #show-palette(palette.tango-dark)
])
== Angle <angle>
The `angle` function of the angle module allows drawing angles with an optional label.
#doc-style.parse-show-module("/src/lib/angle.typ")
==== Default `angle` Style
#raw(repr(angle.default-style))
== Decorations <decorations>
Various pre-made shapes and path modifications.
=== Braces
#doc-style.parse-show-module("/src/lib/decorations/brace.typ")
=== Path Decorations
Path decorations are elements that accept a path as input and generate
one or more shapes that follow that path.
All path decoration functions support the following style keys:
#def-arg("start", [`<ratio>` or `<length>`], default: 0%,
[Absolute or relative start of the decoration on the path.])
#def-arg("stop", [`<ratio>` or `<length>`], default: 100%,
[Absolute or relative end of the decoration on the path.])
#def-arg("rest", [`<string>`], default: "LINE",
[If set to `"LINE"`, generate lines between the paths start/end and
the decorations start/end if the path is _not closed_.])
#def-arg("width", [`<number>`], default: 1,
[Width or thickness of the decoration.])
#def-arg("segments", [`<int>`], default: 10,
[Number of repetitions/phases to generate.
This key is ignored if `segment-length` is set != `none`.])
#def-arg("segment-length", [`none` or `<number>`], default: none,
[Length of one repetition/phase of the decoration.])
#def-arg("align", [`"START"`, `"MID"`, `"END"`], default: "START",
[Alignment of the decoration on the path _if `segment-length` is set_ and
the decoration does not fill up the full range between start and stop.])
#doc-style.parse-show-module("/src/lib/decorations/path.typ")
==== Styling
===== Default `brace` Style
#decorations.brace-default-style
===== Default `flat-brace` Style
#decorations.flat-brace-default-style
= Advanced Functions
== Coordinate
#doc-style.parse-show-module("/src/coordinate.typ")
== Styles
#doc-style.parse-show-module("/src/styles.typ")
=== Default Style <default-style>
This is a dump of the style dictionary every canvas gets initialized with.
It contains all supported keys for all elements.
#[
#set text(size: 8pt)
#columns(raw(repr(styles.default), lang: "typc"))
]
= Creating Custom Elements <custom-elements>
The simplest way to create custom, reusable elements is to return them
as a group. In this example we will implement a function `my-star(center)`
that draws a star with `n` corners and a style specified inner and outer
radius.
```example
let my-star(center, name: none, ..style) = {
group(name: name, ctx => {
// Define a default style
let def-style = (n: 5, inner-radius: .5, radius: 1)
// Resolve the current style ("star")
let style = cetz.styles.resolve(ctx.style, merge: style.named(),
base: def-style, root: "star")
// Compute the corner coordinates
let corners = range(0, style.n * 2).map(i => {
let a = 90deg + i * 360deg / (style.n * 2)
let r = if calc.rem(i, 2) == 0 { style.radius } else { style.inner-radius }
// Output a center relative coordinate
(rel: (calc.cos(a) * r, calc.sin(a) * r, 0), to: center)
})
line(..corners, ..style, close: true)
})
}
// Call the element
my-star((0,0))
my-star((0,3), n: 10)
set-style(star: (fill: yellow)) // set-style works, too!
my-star((0,6), inner-radius: .3)
```
= Internals
== Context
The state of the canvas is encoded in its context dictionary. Elements or other
draw calls may return a modified context to the canvas to change its
state, e.g. modifying the transformating matrix, adding a group or setting a style.
The context can be manually retrieved and modified using the `get-ctx` and `set-ctx`
functions.
== Elements
Each CeTZ element (`line`, `bezier`, `circle`, ...) returns an array of
functions for drawing to the canvas. Such function takes the canvas'
context and must return an dictionary of the following keys:
- `ctx` (required): The (modified) canvas context object
- `drawables`: List of drawables to render to the canvas
- `anchors`: A function of the form `(<anchor-identifier>) => <vector>`
- `name`: The elements name
An element that does only modify the context could be implemented like the
following:
```example
let my-element() = {
(ctx => {
// Do something with ctx ...
(ctx: ctx)
},)
}
// Call the element
my-element()
```
For drawing, elements must not use Typst native drawing functions, but
output CeTZ paths. The `drawable` module provides functions for path
creation (`path(..)`), the `path-util` module provides utilities for path
segment creation. For demonstration, we will recreate the custmom element
`my-star` from @custom-elements:
```example
import cetz.drawable: path
import cetz.vector
let my-star(center, ..style) = {
(ctx => {
// Define a default style
let def-style = (n: 5, inner-radius: .5, radius: 1, stroke: auto, fill: auto)
// Resolve center to a vector
let (ctx, center) = cetz.coordinate.resolve(ctx, center)
// Resolve the current style ("star")
let style = cetz.styles.resolve(ctx.style, merge: style.named(),
base: def-style, root: "star")
// Compute the corner coordinates
let corners = range(0, style.n * 2).map(i => {
let a = 90deg + i * 360deg / (style.n * 2)
let r = if calc.rem(i, 2) == 0 { style.radius } else { style.inner-radius }
vector.add(center, (calc.cos(a) * r, calc.sin(a) * r, 0))
})
// Build a path through all three coordinates
let path = cetz.drawable.path((cetz.path-util.line-segment(corners),),
stroke: style.stroke, fill: style.fill, close: true)
(ctx: ctx,
drawables: cetz.drawable.apply-transform(ctx.transform, path),
)
},)
}
// Call the element
my-star((0,0))
my-star((0,3), n: 10)
my-star((0,6), inner-radius: .3, fill: yellow)
```
Using custom elements instead of groups (as in @custom-elements) makes sense
when doing advanced computations or even applying modifications to passed in
elements.
/*
= Vector, Matrix and Complex Types
#doc-style.parse-show-module("/src/vector.typ")
#doc-style.parse-show-module("/src/matrix.typ")
#doc-style.parse-show-module("/src/complex.typ")
*/
|
https://github.com/pluttan/typst-g7.32-2017 | https://raw.githubusercontent.com/pluttan/typst-g7.32-2017/main/gost7.32-2017/styles/heading.typ | typst | MIT License | #import "../g7.32-2017.config.typ":config
#let style_heading(content) = {
set heading(numbering: config.heading.numbering)
show heading.where(level:1): it => {
if (config.heading.l1.pagebreak){pagebreak()}
set text(config.heading.l1.size, hyphenate: false)
if (config.heading.l1.upper){
upper[#align(config.heading.l1.align)[#it]]
} else {
align(config.heading.l1.align)[#it]
}
par(text(size: config.heading.l1.indent, h(0.0em)))
}
show heading.where(level:2): it => {
if (config.heading.l2.pagebreak){pagebreak()}
set text(config.heading.l2.size, hyphenate: false)
if (config.heading.l2.upper){
upper[#align(config.heading.l2.align)[#it]]
} else {
align(config.heading.l2.align)[#it]
}
par(text(size: config.heading.l2.indent, h(0.0em)))
}
show heading.where(level:3): it => {
if (config.heading.l3.pagebreak){pagebreak()}
set text(config.heading.l3.size, hyphenate: false)
if (config.heading.l3.upper){
upper[#align(config.heading.l3.align)[#it]]
} else {
align(config.heading.l3.align)[#it]
}
par(text(size: config.heading.l3.indent, h(0.0em)))
}
content
} |
https://github.com/Arsenii324/matap-p2 | https://raw.githubusercontent.com/Arsenii324/matap-p2/main/t-repo/lecture4.typ | typst | #import "macros.typ" : *
= Лекция
== Функциональные ряды и последовательности
=== Определение функционального ряда
Пусть есть функции $f_n (x) = sumin u_i (x), u_i : EE -> RR, EE subset.eq RR $
Если $forall x in EE " " exists limits(lim)_(n -> infinity) f_n (x) = f(x),$ тогда $limits(lim)_(n -> infinity) f_n (x) = f(x) = sumii u_i (x)$ - сумма функционального ряда.
=== Определение поточечной сходимости
*Пусть:*
a) $EE subset.eq RR$
b) $f_n : EE -> RR " "(forall n in NN)$
*Тогда:*
Функциональная последовательность ${f_n}^infinity_(n=1)$ сходится поточечно к функции $f : EE -> RR$, если $forall x in EE, exists limits(lim)_(n arrow infinity) f_n (x) = f(x)$.
Обозначение: $f_n -> f$.
=== Определение равномерной сходимости
*Пусть:*
a) $EE subset.eq RR$
b) $f_n : EE -> RR " "(forall n in NN)$
*Тогда:*
Функциональная последовательность ${f_n}^infinity_(n=1)$ сходится равномерно к фунции $f : EE -> RR$ на $EE$, если $forall epsilon > 0 " " exists N : forall n >= N " " forall x in EE ==> abs(f_n (x) - f(x)) < epsilon$.
Обозначение: $f_n arrows f$.
=== Определение сходимости функциональных рядов
*Пусть:*
a) $EE subset.eq RR$
b) $u_i : EE -> RR " " (forall i in NN)$
c) $f_n (x) = sumin u_i (x) " " forall n in N$
*Тогда:*
1) Функциональный ряд сходится поточечно к функции $f : EE -> RR$, если $f_n arrow f$.
2) Функциональный ряд сходится равномерно к функции $f : EE -> RR "на" EE$, если $f_n arrows f$.
=== Критерий Коши равномерной сходимости
$(f_n arrows f) <==> (forall epsilon > 0 " " exists N : forall n, m : n >= N " " forall x in EE --> abs(f_(n+m) (x) - f_n (x)) < epsilon)$.
=== Теорема о почленном переходе к пределу
*Пусть:*
a) $EE subset.eq RR$
b) а - конечная предельная точка множества $EE$
c) $u_k : EE -> RR " " forall k in NN$
d) $exists limits(lim)_(x -> a) u_k (x) = c_k in RR$
e) $f_n arrows f$, где $f_n (x) = limits(sum)_(k = 1)^n u_k (x) " " forall n in NN$
*Тогда:*
$limits(lim)_(x -> a) f(x) = limits(lim)_(x -> a) limits(sum)_(k = 1)^infinity u_k (x) = limits(sum)_(k = 1)^infinity limits(lim)_(x -> a) u_k (x) = limits(sum)_(k = 1)^infinity c_k$
1) Ряд $c_k$ сходится.
2) $limits(sum)_(k = 1)^infinity c_k = limits(lim)_(x -> a) f(x)$
*Proof:*
1) По кр. Коши равномерной сходимости:
$(f_n arrows f) ==> (forall epsilon > 0 " " exists N : forall n, m : n >= N " " forall x in EE --> abs(f_(n+m) (x) - f_n (x)) < epsilon) ==> abs(limits(sum)_(k = n + 1)^(n+m) u_k (x)) < epsilon$.
При $x -> a ==> abs(limits(sum)_(k = n + 1)^(n+m) c_k) <= epsilon ==> "ряд" c_k "сходится по кр. Коши".$
2) Пусть $limits(sum)_(k = 1)^infinity c_k = C in RR$
$limits(lim)_(x -> a) f(x) = C$ - хотим доказать.
$forall epsilon > 0 " " exists delta : abs(x - a) < delta --> abs(f(x) - C) < epsilon$.
$abs(f(x) - C) = abs(f(x) - f_N (x) + f_N (x) - C_N + C_N - C) <= abs(f(x) - f_N (x)) + abs(f_N (x) - C_N) + abs(C_N - C)$
- Для $abs(f(x) - f_N (x))$ найдется такое $N_1$, что $forall x in EE: abs(f(x) - f_N (x)) < epsilon/3$ по равномерной сходисти.
- Для $abs(C_N - C)$ найдется такое $N_2$, что $forall x in EE: abs(C_N - C) < epsilon/3$ по сходимости ряда $c_k$.
Чтобы это выполнялось одновременно $N = max{N_1, N_2}$
- Для $abs(f_N (x) - C_N)$ $:$
$f_N (x) = limits(sum)_(k = 1)^N u_k (x) underbrace(-->, x -> a) limits(sum)_(k = 1)^N c_k = C_N ==> $ найдется такое $delta : abs(x - a) < delta => abs(f_N (x) - C_N) < epsilon/3$
Тогда $abs(f(x) - C) < epsilon ==> limits(lim)_(x -> a) f(x) = C$.
=== Теорема о непрерывности для равномерно сходящегося ряда
*Пусть:*
a) $EE subset.eq RR$
b) $u_k : EE -> RR$
c) $f_n (x) = limits(sum)_(k = 1)^n u_k (x)$
d) $u_k in C(EE)$ - непрерывная
e) $f_n arrows f$
*Тогда:*
$f in C(EE)$
*Proof:*
Достаточно доказать, что f непрерывна в любой точке $a in EE$, т.е. нужно доказать, что $limits(lim)_(x -> a) f(x) = f(a), forall a in EE$.
Если $a - "изолированная точка множества" EE$, то равенство очевидно.
Если $a - "предельная точка множества" EE$, то:
$exists limits(lim)_(x -> a) u_k (x) = u_k (a) = c_k$. Тогда по теореме о почленном переходе к пределу $limits(lim)_(x -> a) f(x) = limits(sum)_(k = 1)^infinity u_k (a) = f(a)$
== Критерии равномерной сходимости
=== lim-sup критерий
*Пусть:*
a) $EE subset.eq RR$
b) $f_n : EE -> RR, " " forall n in NN$
c) $f_n = limits(sum)_(k = 1)^n u_k : EE -> RR$
*Тогда:*
$(f_n arrows f) <==> (limits(lim)_(n arrow infinity) limits(sup)_(x in EE) abs(f_n (x) - f(x)) = 0) $
*Proof:*
По определению равномерной сходимости:
$forall epsilon > 0 " " exists N : forall n >= N " " underbracket(forall x in EE --> abs(f(x) - f_n (x)) < epsilon, limits(sup)_(x in EE) abs(f(x) - f_n (x)) <= epsilon)$.
Тогда по определению предела последовательности имеем: $limits(lim)_(n arrow infinity) limits(sup)_(x in EE) abs(f_n (x) - f(x)) = 0$
=== <NAME> равномерной сходимости
$(f_n arrows f) <==> (forall epsilon > 0 " " exists N : forall n, m : n >= N " " forall x in EE --> abs(f_(n+m) (x) - f_n (x)) < epsilon)$.
=== <NAME> равномерной сходимости
*Пусть:*
a) $EE subset.eq RR$
b) $u_k : EE -> RR$
c) $forall n in NN " " forall x in EE --> abs(u_k (x)) <= a_k$
d) $limits(sum)_(k = 1)^infinity a_k$ сходится.
*Тогда:*
$limits(sum)_(k = 1)^infinity u_k (x) arrows u(x)$
\
=== <NAME>/Дирехле
*Пусть:*
#table(
columns: (50%, 50%),
inset: 10pt,
align: center,
[*Дирихле*], [*Абель*],
[$exists M > 0 : forall n in NN, forall x in E\
abs(limits(sum)_(k=1)^(n) a_k (x)) <= M$], [$limits(sum)_(n=1)^(infinity) a_n (x) "- сходится равномерно."$],
[$b_k (x) arrows 0$], [$exists M > 0 : forall n, forall x\
abs(b_n (x)) <= M$],
[${b_n (x)} arrow.tr$ или ${b_n (x)} arrow.br$], [${b_n} arrow.tr$ или ${b_n} arrow.br$]
)
*Тогда:*
$limits(sum)_(n=1)^(infinity) a_n b_n "- сходится равномерно."$
== Почленное интегрирование/дифференцирование
=== Теорема о почленном интегрировании
*Пусть:*
a) $I = [a, b] subset RR$
b) $u_k : I -> RR$
c) $f_n (x) = limits(sum)_(k = 1)^n u_k (x)$
d) $u_k in R(I)$ (интегрируемая по Риману)
e) $f_n arrows f$
*Тогда:*
1) $f in R(I)$
2) $limits(integral)_a^b f(x) d x = limits(sum)_(k = 1)^infinity limits(integral)_a^b u_k (x) d x$
*Proof:*
1) $f in R(I) underbrace(<==>, "кр. Дарбу") forall epsilon > 0 " " exists lambda : forall T : d(T) <= lambda --> limits(sum)_T limits(w)_(I_i) (f) dot abs(I_i) < epsilon$
- $d(T)$ - диаметр разбиения ($max abs(I_i)$)
- $limits(w)_(I_i) = limits(sup)_(x in I_i) (f) - limits(inf)_(x in I_i) (f)$ - колебание $f$ на отрезке $I_i$.
- Суммирование ведется по всем отрезкам разбиения T
Выбираем N по данному $epsilon > 0$.
(1) - $forall epsilon > 0 " " exists N : forall x in I -> abs(f(x) - f_N (x)) < epsilon/(4 (b - a)) ==> f_N (x) - epsilon/(4 (b - a)) <= f(x) <= f_N (x) + epsilon/(4 (b - a)), forall x in I$
Для любого подотрезка $tilde(I) subset.eq I$ имеем:
(2) - $underbrace(w(f) = sup(f) - inf(f), "по определению") <= underbrace((sup(f_N) + epsilon/(4 (b - a))) - (inf(f_N) - epsilon/(4 (b - a))), "из неравенства (1) и т.к." inf f_N <= f_N <= sup f_N) <= underbrace(w(f_N) + epsilon/(2 (b - a)), "по определению" w(f_N))$
Дальше, пользуясь критерием Дарбу, для заданного $epsilon$ и выбранного $N$ мы выбираем $lambda$:
$f_N in R(I) ==> forall epsilon > 0 " " exists lambda : d(T) < lambda -> limits(sum)_T limits(w)_I_i (f_N) dot abs(I_i) < epsilon/2$
$limits(sum)_T limits(w)_I_i (f) dot abs(I_i) <= underbrace(limits(sum)_T (limits(w)_I_i (f_N) + epsilon/(2 (b - a)) ) dot abs(I_i), "т.к. нер-во (2) верно для " forall" подотрезка") = underbrace(limits(sum)_T limits(w)_I_i (f_N) abs(I_i), "в силу (3) меньше" epsilon/2) + epsilon/(2 (b - a)) underbrace(limits(sum)_T abs(I_i), b-a) <= epsilon/2 + epsilon/2 = epsilon$
2) Положим $phi_n = f - f_n$. Ясно, что $phi in R(I)$ (сумма конечного числа интегрируемых интегрируема, а $f in R(I)$ доказали в 1 пункте).
Достаточно доказать, что $limits(integral)_a^b phi_n (x) d x underbrace(-->, n -> infinity) 0$
Т.к. $f_n arrows f$, то $exists N : forall n > N, forall x in I " " abs(f_n - f) < epsilon/ (b - a)$
$abs(limits(integral)_a^b phi_n (x) d x) <= limits(integral)_a^b abs(phi_n (x)) d x = limits(integral)_a^b abs(f_n - f) d x <= limits(integral)_a^b epsilon/(b-a) d x = epsilon$
=== Теорема о почленном дифференцировании
*Пусть:*
a) $I = [a, b] subset RR$
b) $u_k : I -> RR$
c) $f_n (x) = limits(sum)_(k = 1)^n u_k (x)$
d) $u_k in D(I)$, (дифференцируемая)
e) $exists c in I : limits(sum)_(k = 1)^infinity u_k (c) = L in RR$, (есть хоть одна точка, где ряд сходится)
f) $f'_n arrows g$, (сходится равномерно к чему-то)
*Тогда:*
1) $f_n arrows f$
2) $f'(x) = g(x) = (limits(sum)_(k = 1)^infinity u_k)'$
*Proof:*
1) Прежде всего покажем, что $forall y in I$:
$limits(sum)_(k = 1)^infinity (u_k (x) - u_k (y)) / (x - y) , x in underbrace(I \\ {y}, EE) -> $ ряд сходится на $EE$.
Т.е. по кр. Коши показать, что $forall epsilon > 0 " " exists N : forall n > N, " " forall m in NN, " " forall x in I -> abs(limits(sum)_(k = n)^(n+m) (u_k (x) - u_k (y)) / (x - y) ) < epsilon$
Т.к. $f'_n arrows g ==> forall epsilon > 0 " " exists N : forall n > N, " " forall m in NN, " " forall x in I -> abs(f'_(n+m) (x) - f'_n (x)) < epsilon$
$abs(f'_(n+m) (x) - f'_n (x)) = abs(limits(sum)_(k = n + 1)^(n+m) u'_k (x)) = abs(h'(x)) < epsilon$
$abs(limits(sum)_(k = n)^(n+m) (u_k (x) - u_k (y)) / (x - y) ) = abs(( limits(sum)_(k = n)^(n+m) u_k (x) " "- limits(sum)_(k = n)^(n+m)u_k (y)) \/ (x - y)) = abs((h(x) - h(y))/(x-y)) = |"т. Лагранжа о среднем"| =\ abs(((h'(t))(x-y))/(x-y)) = abs(h'(t)), "где " x<t<y.$
Знаем, что $abs(h'(x)) < epsilon ==> abs(h'(t)) < epsilon ==> limits(sum)_(k = 1)^infinity (u_k (x) - u_k (y)) / (x - y)$ сходится равномерно.
Возьмем $y = c$:
$limits(sum)_(k = 1)^infinity (u_k (x) - u_k (c)) / (x - c)$ - сходится равномерно на $I \\ {c}$
(x - c) - ограниченная функция, а домножение на ограниченную функцию не влияет на сходимость. Тогда:
$limits(sum)_(k = 1)^infinity (u_k (x) - u_k (c))$ - сходится равномерно на $I \\ {c}$
$limits(sum)_(k = 1)^infinity (u_k (x) - u_k (c)) = limits(sum)_(k = 1)^infinity u_k (x) - underbrace(limits(sum)_(k = 1)^infinity u_k (c), "const") => limits(sum)_(k = 1)^infinity u_k (x) "сх. равномерно на " I \\ {c}$
Ряд сходится равномерно на ${c}$ и на I \\ {c} => ряд сходится равномерно на $I$, т.к. если ряд сходится на множествах, то он будет сходиться и на их объединении (достаточно в критерии Коши выбрать $N = max{N_1, ..., N_k}$).
2) Доказали, что $limits(sum)_(k = 1)^infinity u_k (x) = f(x)$.
$limits(sum)_(k = n)^(n+m) (u_k (x) - u_k (y)) / (x - y) = (f(x) - f(y))/(x - y)$
Пусть:
a) $E = I \\ {y}$
b) y - конечная предельная точка $E$
c) $limits(lim)_(x->y) (u_k (x) - u_k (y)) / (x - y) = u'_k (y)$
d) $limits(sum)_(k = 1)^(infinity) (u_k (x) - u_k (y)) / (x - y) arrows (f(x) - f(y))/(x - y)$
Выполнены все условия теоремы о почленном переходе к пределу $==>$
$ ==> limits(sum)_(k = 1)^(infinity) u'_k (y) = limits(lim)_(x->y) (f(x) - f(y))/(x - y) = f'(y)$.
=== Теорема Вейерштрасса о равномерном приближении
*Пусть:*
a)$f in C^m [a,b]$
*Тогда:*
$forall epsilon > 0 " " exists p in RR[x] : " " forall k in {0 .. m }, forall x in [a, b] --> abs(f^((k)) (x) - p^((k)) (x)) < epsilon$
|
|
https://github.com/jamesrswift/dining-table | https://raw.githubusercontent.com/jamesrswift/dining-table/main/src/validation.typ | typst | The Unlicense | #import "deps.typ": *
#let columns-schema = z.array(
z.dictionary((:
key: z.any(),
header: z.content(optional: true),
display: z.function(optional: true),
fill: z.color(optional: true),
align: z.alignment(default: start),
gutter: z.length(optional: true),
width: z.any(optional: true),
)) + (:
handle-descendents: (self, it, ctx: z.z-ctx(), scope: ()) => {
if (it.len() == 0 and self.optional) {
return none
}
// Check `it` if strict
if (ctx.strict == true) {
for (key, value) in it {
if (key not in self.dictionary-schema) {
return (self.fail-validation)(
self,
it,
ctx: ctx,
scope: scope,
message: "Unknown key `" + key + "` in dictionary",
)
}
}
}
if "children" in it {
it.children = z.parse(
it.children,
z.array(
self,
z.coerce.array
),
ctx: ctx
)
}
for (key, schema) in self.dictionary-schema {
let entry = (
schema.validate
)(
schema,
it.at(key, default: none), // implicitly handles missing entries
ctx: ctx,
scope: (..scope, str(key))
)
if (entry != none or ctx.remove-optional-none == false) {
it.insert(key, entry)
}
}
return it
},
)
)
|
https://github.com/almarzn/portfolio | https://raw.githubusercontent.com/almarzn/portfolio/main/templates/typst/main.typ | typst | // @font-face(url=https://fonts.google.com/download?family=Lexend)
// @font-face(dir=.template/fonts/)
#import "@preview/fontawesome:0.1.0": *
#import ".template/title.typ": title
#import ".template/competencies.typ": competencies
#import ".template/about.typ": about-section
#import ".template/education.typ": education
#import ".template/presentation.typ": presentation-section
#import ".template/experiences.typ": experience-block
#import ".template/shared/flex.typ": *
#import ".template/styles.typ"
#let content = yaml("data.json")
#styles.default[
#block(inset: (x: 24pt), flex(
gap: 32pt,
{
block(
inset: (x: 24pt, top: 48pt),
title(
profile: (
name: content.profile.name,
title: content.profile.title,
tagline: [#content.profile.experience d'XP -- Dispo #content.profile.availability]
)
)
)
styles.margin-large()[
#set par(justify: true)
#presentation-section(content.presentation, content.links)
]
styles.margin-large()[
#styles.section-heading(fa-list-check(baseline: -1pt), [Compétences])
]
styles.margin-small(
competencies(content.skills)
)
styles.margin-large()[
#styles.section-heading(fa-user-graduate(baseline: -2pt), [Formation])
]
styles.margin-large()[
#education(content.education)
]
})
)
#for experience in content.experiences [
#set page(header: [
#place(
top + right,
dx: 25pt,
dy: 34pt,
image(".template/logo/maxds-logo-light.svg", height: 200pt)
)
], margin: (top: 12pt))
#pagebreak(weak: true)
#block(
inset: (top: 48pt),
flex(gap: 24pt)[
#styles.margin-large()[
#styles.section-heading(fa-briefcase(baseline: -1pt), [Expériences])
]
#styles.margin-xlarge()[
#experience-block(experience)
]
]
)
]
] |
|
https://github.com/JacentyI1/Interpersonal-Communication | https://raw.githubusercontent.com/JacentyI1/Interpersonal-Communication/main/README.md | markdown | The Unlicense | ### [Presentation](https://1drv.ms/p/s!ApPlUecbgSQIyTGZdQ94JTFu_qO9)
# Subject: IC
Interpersonal Communication
## Presentation date & topic
10.04 - Trends and challenges for interpersonal communication in the next decade.
## Script
[script.md](assets/script.md)
## Grade
- attendance
- commitment (+ attendance) 40%
- poroject 60% : 12/14pts
## Materials & references
N/A
## General notes
- expected punctuality
- when sick, notify immediately (or within a resonable time frame)
### Form
Oral presentation in teams (every team member should present some part of the researched topic).
### Estimated presentation time
- estimated time: 7min (per person/ in general?)
### Presentation evaluation form
- #### Content and organization [0-2] 2
Ability to explore the topic in an extended, organized, clear and logical way.
- #### Accuracy [0-2] 2
Control of structures including tenses, prepositions, register, linkers, grammar, etc.
- #### Fluency [0-2] 2
Speed and rhythm, choice of structures, clarity
- #### Pronunciation [0-2] 1
Stress timing, rhythm and intonation patterns, linking of phrases.
- #### Vocabulary [0-2] 2
Variety and correctness of vocabulary in the communicative context
- #### Body language [0-2] 1
Eye contact, gestures, stance & posture, movement
- #### Visual aids [0-2] 2
Number, design, relevance, use
# Additional information
Some assets provided in the `assets` folder belong to [Poznań University of Technology]("https://put.poznan.pl"). Mainly the two provided logos and the font.
If you do not want to install the provided font to typeset `Team_project_framework.typ` please use this flag: `--font-path ./assets`. Alternatively you can set `TYPST_FONT_PATHS=./assets` as an enviromnet variable. It is provided inside `.env`.
> Locally, Typst uses your installed system fonts. In addition, you can use the --font-path argument or TYPST_FONT_PATHS environment variable to add directories that should be scanned for fonts.
|
https://github.com/genericusername3/structogrammer | https://raw.githubusercontent.com/genericusername3/structogrammer/master/example.typ | typst | MIT License | #import "structogrammer/main.typ": structogram
#set page(width: auto, height: auto, margin: 4pt, fill: rgb("0000"))
#set text(lang: "de")
// #set text(font: "IBM Plex Mono")
#structogram(
title: "method_title()",
(
// Regular chaining
(
"do this first",
"then this",
),
// Conditionals
(
If: "condition",
Then: "do this",
Else: "or this",
),
(
If: "condition",
Then: "or this",
),
(
If: "condition",
Else: "or this",
),
// While loops
(
While: "condition",
Do: "repeat this"
),
(
Do: "repeat this",
While: "condition",
),
// For loops
(
For: "element",
In: "container",
Do: "repeat this",
),
(
For: "i = 0",
To: "6",
Do: "repeat this",
),
(
For: "<?>",
Do: "repeat this",
),
// Nesting
(
For: "element",
In: "container",
Do: (
If: "condition",
Then: (
"A",
(
While: "true",
Do: "do something"
)
)
)
),
// Call
(Call: "method Name"),
// Break
(Break: "target"),
// Normal block again
"block",
),
) |
https://github.com/freefrancisco/typst-resume | https://raw.githubusercontent.com/freefrancisco/typst-resume/main/resumetemplate.typ | typst | #let cv(author: "", contacts: (), body) = {
set document(author: author, title: author)
set text(font: "Linux Libertine", lang: "en")
show heading: it => [
#pad(bottom: -10pt, [#smallcaps(it.body)])
#line(length: 100%, stroke: 1pt)
]
// Author
align(center)[
#block(text(weight: 700, 1.75em, author))
]
// Contact information.
pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
align(center)[
#grid(
columns: 4,
gutter: 1em,
..contacts
)
],
)
// Main body.
set par(justify: true)
pad(left: -1pt, right: -10pt, body)
// body
}
#let icon(name, baseline: 1.5pt) = {
box(
baseline: baseline,
height: 10pt,
image(name)
)
}
#let exp(company, title, location, time, details) = {
pad(
bottom: -1pt,
grid(
columns: (auto, 1fr),
align(left)[
*#company* \
#emph[#title]
],
align(right)[
#location \
#time
]
)
)
pad(top: -5pt, bottom: -1pt, details)
}
|
|
https://github.com/kdog3682/2024-typst | https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/layout.typ | typst | #import "base-utils.typ": *
#let flex(..sink) = {
let opts = sink.named()
let padding = opts.at("padding", default: none)
// pads the arg inside of fn:prepare
let debug = opts.at("debug", default: none)
// draws a red rectangle around the arg
// uses a block wrapper around the final payload
let wrapper(value) = {
let width = opts.at("width", default: none)
let margin = opts.at("margin", default: 10pt)
let block-attrs = (:)
if margin != none {
block-attrs.insert("above", margin)
block-attrs.insert("below", margin)
}
if width != none {
block-attrs.insert("width", resolve-pt(width))
}
if has-value(block-attrs) {
return block(..block-attrs, value)
}
return value
}
let prepare(arg) = {
if debug != none {
arg = rect(stroke: red, arg)
}
if padding != none {
arg = pad(padding, arg)
}
return arg
}
let args = sink.pos().map(prepare)
let columns = args.len()
let top-attrs = (
columns: columns,
)
let justify-content = opts.at("justify-content", default: none)
if justify-content != none {
let (
justify,
container,
attrs,
) = justify-ref.at(justify-content)
let payload = container(..attrs, ..top-attrs, ..map(args, justify))
return wrapper(payload)
}
// we prepare the args with padding because
// prose almost always needs padding
// place all the paddings in one place
let table-attrs = (
stroke: (
paint: black,
thickness: 0.5pt,
dash: "dotted",
),
// stroke: none,
row-gutter: auto,
rows: auto,
column-gutter: auto,
align: auto,
)
let block-attrs = (
below: 0pt,
above: 0pt,
fill: yellow.lighten(90%),
radius: 5pt,
inset: 5pt,
width: 400pt, // the width does control it
height: auto,
outset: 0pt,
)
block(..block-attrs, table(..table-attrs, columns: columns, ..args))
}
#let flex-1(..sink) = {
// layout-util
let args = sink.pos()
let flat(arg) = {
if is-array(arg) {
arg.join()
} else {
arg
}
}
let flattened = args.map(flat)
let length = len(flattened)
// let spacer = h(0.5fr) // has a purpose ...
let spacer = h(1fr)
return table(columns: (1fr,) * flattened.len(), align: align-apart.with(length: length), stroke: none, ..flattened)
return flattened.join(spacer)
}
|
|
https://github.com/floriandejonckheere/utu-thesis | https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/proposal/template.typ | typst | #let template(
// Document title
title: "",
// Document subtitle
subtitle: "",
// List of authors
authors: (),
// Date of publication
date: none,
// Institution logo (SVG)
logo-file: none,
// Bibliography
bibliography-file: none,
// Abstract
abstract: [],
// Document contents
body,
) = {
// Basic properties
set document(author: authors.map(a => a.name), title: title)
set page(numbering: "1", number-align: center, margin: 7em)
set par(leading: 1.1em, justify: true)
set bibliography(full: true, style: "apa", title: [References])
show par: set block(spacing: 2em)
show heading: set block(above: 1.4em, below: 1.5em)
// Title page
v(0.6fr)
if logo-file != none {
align(right, image(logo-file, width: 40%))
}
v(9.6fr)
text(1.1em, date)
v(1.2em, weak: true)
text(2em, weight: 700, title)
linebreak()
text(1em, subtitle)
// Author
pad(
top: 0.7em, right: 20%, grid(
columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..authors.map(author => align(start)[
*#author.name* \
#link("mailto:" + author.email)[#author.email]
]),
),
)
v(2.4fr)
pagebreak()
// Abstract
v(1fr)
align(
left,
)[
#set par(justify: true)
#heading(outlined: false, numbering: none, text(0.85em, smallcaps[Abstract]))
#abstract
]
v(1.618fr)
pagebreak()
// Main document
set par(justify: true)
show raw: set text(font: "New Computer Modern Mono")
show par: set block(spacing: 0.55em)
show heading: set block(above: 1.4em, below: 1em)
body
// Bibliography
show bibliography: pad.with(x: 0.5pt)
set par(first-line-indent: 0em)
bibliography(bibliography-file)
} |
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/experiment/weeks/week10.typ | typst | #import "../../utils.typ": *
#section("From distribution to reality")
The idea is, if we do one specific experiment multiple times, then we get
multiple results, aka multiple medians and multiple variances.
#align(
center,
[#image("../../Screenshots/2023_11_24_07_06_13.png", width: 100%)],
)
#subsection("Law1")
#set text(16pt)
Law 1: If we have some experiments with n data points as *samples* from them ->
{x1,x2,x3,...,xn}:\
sample median: $E[X] = mu = overline(x) = 1/n sum^n_(i=1)x_i$\
#text(teal)[The sum of random variables is again a random variable!]\
#text(
teal,
)[The value of this sum is the same as the expected result of the base
quantity(grundgesamtheit)]\
When considering each element of the sample as a possible value of the random
variable $X_i$ then we can also consider this formula:\
sample median: $overline(X) = 1/n sum^n_(i=1)X_i$\
Variance: $sigma^2_overline(X) = (sigma^2)/n$
#text(
teal,
)[The bigger n, the smaller the variance of the sample -> makes sense more probes
means less extreme values. -> E.g. the variance will be closer and closer to the
variance of the base quantity(grundgesamtheit)]
legend:
- $mu$: Poisson number
- E[X]: Sample median
- $sigma^2$: Variance
#set text(11pt)
Example:
#align(
center,
[#image("../../Screenshots/2023_11_24_07_28_05.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_07_28_16.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_07_28_34.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_07_28_47.png", width: 100%)],
)
#subsection("Law2")
#set text(16pt)
If law1 is given -> X is distributed in a normal fashion, then *the sample probe
is also distributed in a normal fashion*:\
$E[X] = mu$ and $sigma_x = sigma_mu/root(2, n)$
Legend:
- $sigma_x$: standard deviation of the random samples
- $sigma_mu$: standard deviation of the base quantity
- $mu$: median of base quantity
- $E[X]$: median of samples
- $overline(X)$: random variable of the sample
- n: amount of samples
#set text(11pt)
Examples:
#align(
center,
[#image("../../Screenshots/2023_11_24_07_40_35.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_07_40_50.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_07_41_01.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_07_41_40.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_07_41_53.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_07_42_05.png", width: 100%)],
)
#subsection("T-Distribution or accurate sampletheory")
- used for samples with count below 30 -> normal distribution is bad for this ->
too general!
- in the examples above -> for n 5 and 25 -> t would have been better!
#set text(16pt)
- r: Freedom value -> how many parameters can be chosen
#text(
teal,
)[We don't need the formula, just make sure to remember the stuff on the bottom
right]
#align(
center,
[#image("../../Screenshots/2023_11_24_07_52_47.png", width: 100%)],
)
#text(
red,
)[See the formula, calculate t just like the Z value in the normal distribution
example] \
- *p: error value -> 0.1 means 10%!!*
#align(
center,
[#image("../../Screenshots/2023_11_24_07_54_36.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_08_02_08.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_08_08_36.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_08_00_39.png", width: 100%)],
)
#set text(11pt)
#subsection("Chi-Square-Distribution")
- only 1 parameter -> which must be a natural number.
- this parameter is the freedom value r
- used for test distributions..
- test of variances
- (is just an approximation?)
- derivation of the normal distributions
- requires *independent random variables* and *a normal distribution of these
variables*
- Chi-square is the *sum of all variables squared*
- Y(function) = $X^2_1 +X^2_2+X^2_3 +X^2_4 +X^2_r$
#align(
center,
[#image("../../Screenshots/2023_11_24_08_09_56.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_08_10_10.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_08_10_22.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_08_10_38.png", width: 100%)],
)
|
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2007/MS-02.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (1 - 32)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[1], [WANG Hao], [CHN], [3006],
[2], [MA Lin], [CHN], [2878],
[3], [BOLL Timo], [GER], [2855],
[4], [WANG Liqin], [CHN], [2813],
[5], [SAMSONOV Vladimir], [BLR], [2783],
[6], [HAO Shuai], [CHN], [2775],
[7], [OH Sangeun], [KOR], [2736],
[8], [<NAME>], [AUT], [2717],
[9], [HOU Yingchao], [CHN], [2686],
[10], [CHEN Qi], [CHN], [2643],
[11], [RYU Seungmin], [KOR], [2601],
[12], [LI Ching], [HKG], [2568],
[13], [JOO Saehyuk], [KOR], [2540],
[14], [MA Long], [CHN], [2539],
[15], [CHEUNG Yuk], [HKG], [2510],
[16], [KO Lai Chak], [HKG], [2484],
[17], [SMIRNOV Alexey], [RUS], [2482],
[18], [LEE Jungwoo], [KOR], [2474],
[19], [CHUANG Chih-Yuan], [TPE], [2471],
[20], [KONG Linghui], [CHN], [2423],
[21], [CHEN Weixing], [AUT], [2417],
[22], [WALDNER Jan-Ove], [SWE], [2403],
[23], [<NAME>], [ROU], [2396],
[24], [<NAME>], [GRE], [2387],
[25], [<NAME>], [JPN], [2385],
[26], [<NAME>], [BEL], [2383],
[27], [<NAME>], [DEN], [2382],
[28], [YANG Zi], [SGP], [2378],
[29], [<NAME>], [ESP], [2378],
[30], [<NAME>], [CZE], [2374],
[31], [<NAME>], [FRA], [2350],
[32], [<NAME>], [SWE], [2349],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (33 - 64)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[33], [KARAKASEVIC Aleksandar], [SRB], [2344],
[34], [<NAME>], [CRO], [2328],
[35], [LIM Jaehyun], [KOR], [2327],
[36], [#text(gray, "<NAME>")], [BUL], [2321],
[37], [CHANG Yen-Shu], [TPE], [2313],
[38], [MIZUTANI Jun], [JPN], [2306],
[39], [BLASZCZYK Lucjan], [POL], [2303],
[40], [<NAME>], [AUT], [2303],
[41], [YANG Min], [ITA], [2296],
[42], [<NAME>], [CHN], [2292],
[43], [<NAME>], [SGP], [2292],
[44], [<NAME>], [SLO], [2288],
[45], [<NAME>], [FRA], [2279],
[46], [<NAME>], [NED], [2277],
[47], [<NAME>], [KOR], [2274],
[48], [<NAME>], [KOR], [2273],
[49], [<NAME>], [JPN], [2265],
[50], [<NAME>], [CHN], [2264],
[51], [#text(gray, "<NAME>")], [CHN], [2260],
[52], [<NAME>], [BEL], [2257],
[53], [<NAME>], [KOR], [2252],
[54], [KUZMIN Fedor], [RUS], [2244],
[55], [<NAME>], [GER], [2243],
[56], [CHTCHETININE Evgueni], [BLR], [2238],
[57], [BENTSEN Allan], [DEN], [2237],
[58], [SHMYREV Maxim], [RUS], [2234],
[59], [<NAME>], [PRK], [2234],
[60], [<NAME>], [DOM], [2230],
[61], [MAZUNOV Dmitry], [RUS], [2224],
[62], [LEGOUT Christophe], [FRA], [2224],
[63], [OVTCHAROV Dimitrij], [GER], [2224],
[64], [TAKAKIWA Taku], [JPN], [2218],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (65 - 96)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[65], [#text(gray, "JIANG Weizhong")], [CRO], [2218],
[66], [CHIANG Hung-Chieh], [TPE], [2216],
[67], [GIONIS Panagiotis], [GRE], [2207],
[68], [<NAME>], [SWE], [2206],
[69], [<NAME>], [GER], [2204],
[70], [<NAME>], [PRK], [2203],
[71], [<NAME>], [GER], [2196],
[72], [<NAME>], [DEN], [2190],
[73], [JIANG Tianyi], [HKG], [2186],
[74], [<NAME>], [SVK], [2183],
[75], [<NAME>], [KOR], [2181],
[76], [<NAME>], [SVK], [2168],
[77], [CHIANG Peng-Lung], [TPE], [2166],
[78], [WOSIK Torben], [GER], [2166],
[79], [TAN Ruiwu], [CRO], [2165],
[80], [<NAME>], [NGR], [2163],
[81], [TOSIC Roko], [CRO], [2163],
[82], [#text(gray, "GUO Keli")], [CHN], [2162],
[83], [KISHIKAWA Seiya], [JPN], [2161],
[84], [<NAME>], [ITA], [2161],
[85], [<NAME>], [POL], [2159],
[86], [#text(gray, "<NAME>")], [CHN], [2159],
[87], [<NAME>], [POR], [2155],
[88], [<NAME>], [CZE], [2153],
[89], [#text(gray, "<NAME>")], [SWE], [2152],
[90], [<NAME>], [SWE], [2148],
[91], [<NAME>], [CZE], [2148],
[92], [<NAME>], [SRB], [2146],
[93], [<NAME>], [BRA], [2146],
[94], [<NAME>], [ITA], [2142],
[95], [<NAME>], [CAN], [2137],
[96], [ROSSKOPF Jorg], [GER], [2131],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (97 - 128)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[97], [WANG Wei], [ESP], [2130],
[98], [MATSUMOTO Cazuo], [BRA], [2124],
[99], [<NAME>], [ESP], [2123],
[100], [ACHANTA <NAME>], [IND], [2122],
[101], [WANG Zengyi], [POL], [2120],
[102], [GRIGOREV Artur], [RUS], [2118],
[103], [BA<NAME>], [GER], [2118],
[104], [DIDUKH Oleksandr], [UKR], [2118],
[105], [<NAME>], [GER], [2117],
[106], [<NAME>], [POR], [2112],
[107], [<NAME>], [HKG], [2112],
[108], [<NAME>], [SVK], [2110],
[109], [<NAME>], [HKG], [2105],
[110], [#text(gray, "LENGEROV Kostadin")], [AUT], [2103],
[111], [<NAME>], [CZE], [2097],
[112], [<NAME>], [HUN], [2095],
[113], [SVENSSON Robert], [SWE], [2093],
[114], [<NAME>], [HUN], [2091],
[115], [<NAME>], [ROU], [2090],
[116], [OLEJNIK Martin], [CZE], [2089],
[117], [<NAME>], [CZE], [2086],
[118], [<NAME>], [ARG], [2086],
[119], [ZWICKL Daniel], [HUN], [2085],
[120], [URBANEK Jan], [CZE], [2077],
[121], [<NAME>], [GER], [2077],
[122], [ANDRIANOV Sergei], [RUS], [2073],
[123], [KUSINSKI Marcin], [POL], [2062],
[124], [<NAME>], [HUN], [2060],
[125], [WU Chih-Chi], [TPE], [2058],
[126], [<NAME>], [FRA], [2055],
[127], [<NAME>], [ESP], [2052],
[128], [<NAME>], [RUS], [2051],
)
) |
|
https://github.com/BreakingLead/note | https://raw.githubusercontent.com/BreakingLead/note/main/School/古诗文.typ | typst | #set text(font: "LXGW WenKai Mono", size: 1.05em)
#show heading.where(level: 1): it => {
set align(center)
set text(font:"LXGW Fasmart Gothic", size: 1.7em)
it
}
#show heading.where(level: 2): it => {
set text(1.2em)
set align(center)
block()
it
}
#show enum: it => {
set text(font: "SimSun",size:0.75em)
it
}
#let kai(x) = box(stroke: black,inset:0.1em,text(font: "STKaiti", size: 0.8em,x))
#let ba = kai("必修上")
#let bb = kai("必修下")
#let bc = kai("选必上")
#let bd = kai("选必中")
#let be = kai("选必下")
#set page(
numbering: "-1-",
margin: 2cm,
)
#page[
#align(center)[
#text(
font: "LXGW WenKai",
size: 64pt,
)[
高
中
背
诵
全
集
]
]
]
#pagebreak()
#outline(
title: "目录",
indent: 2em,
fill: line(length: 100%, stroke: gradient.linear(..color.map.rainbow))
)
#text(font: "LXGW Fasmart Gothic")[
整理者:Lead (西北工业大学附属中学 A12 2026)
本书大部分是由脚本从人教版语文书PDF自动生成的,未经仔细校对,若有错误,请不吝指出!
关注Lead谢谢喵
// Count: #context query(heading.where(level: 2)).len()
Contact me:
- #link("https://space.bilibili.com/34258013")
- #link("https://www.zhihu.com/people/ggmyfriendxd")
- #link("https://github.com/BreakingLead/")
- 闲聊群:909765699
请随意转载!请转给你的老师同学!
]
```markdown
Changelog:
1.0.0 2024-03-25
```
#pagebreak()
= 必修上
#columns[
== 短歌行 曹操
对酒当歌,人生几何!譬如朝露,去日苦多。\
慨当以慷,忧思难忘。何以解忧?唯有杜康。\
青青子衿,悠悠我心。但为君故,沉吟至今。\
呦呦鹿鸣,食野之苹。我有嘉宾,鼓瑟吹笙。\
明明如月,何时可掇?忧从中来,不可断绝。\
越陌度阡,枉用相存。契阔谈讌,心念旧恩。\
月明星稀,乌鹊南飞。绕树三匝,何枝可依?\
山不厌高,海不厌深。周公吐哺,天下归心。\
+ 〔对酒当歌〕面对着酒与歌,即饮酒听歌。当,也 是“对”的意思。
+ 〔几何〕多少。
+ 〔去日苦多〕可悲的是逝去的日子太多了。这是慨 叹人生短暂。
+ 〔慨当以慷〕即“慷慨”。这里指宴会上的歌声激越 不平。当以,没有实义。
+ 〔杜康〕相传是最早造酒的人。这里代指酒。
+ 〔青青子衿(jīn),悠悠我心〕语出《诗经·郑风·子衿》,原写姑娘思念情人,这里用来形容渴望得到 贤才。子,对对方的尊称。青衿,指代周代读书人 青色交领的服装。衿,衣服的交领。悠悠,长远的 样子,形容思虑连绵不断。
+ 〔沉吟〕沉思吟味。这里指思念和倾慕贤人。
+ 〔呦呦鹿鸣,食野之苹。我有嘉宾,鼓瑟吹笙〕语 出《诗经·小雅·鹿鸣》。苹,艾蒿。《鹿鸣》是宴 客的诗,这里用来表达招纳贤才的热情。
+ 〔掇〕拾取,摘取。一说同“辍”,停止。
+ 〔越陌度阡〕穿过纵横交错的小路。陌,东西向的 田间小路。阡,南北向的田间小路。
+ 〔枉用相存〕屈驾来访。枉,这里是枉驾的意思。 用,以。存,问候、探望。
+ 〔契阔谈讌(yàn)〕久别重逢,欢饮畅谈。契阔, 聚散,这里指久别重逢。讌,同“宴”。
+ 〔三匝(zā)〕三周。匝,周、圈。
+ 〔山不厌高,海不厌深〕这里是仿用《管子·形势解》中的话:“海不辞水,故能成其大;山不辞土石,故能成其高;明主不厌人,故能成其众。”意思 是表示希望尽可能多地接纳人才。厌,满足。
+ 〔周公吐哺(bǔ)〕《史记·鲁周公世家》记载,周 公广纳贤才,正吃饭时,听到门外有士子求见,来 不及咽下嘴里的食物,把食物一吐就赶紧去接见。 这里借用这个典故,表示自己像周公一样热切殷勤 地接待贤才。吐哺,吐出嘴里的食物。
== 琵琶行并序 白居易
#text(font: "FangSong")[元和十年,予左迁九江郡司马。明年秋,送客湓浦口,闻舟中夜弹琵琶者,听其音,铮铮然有京都声。问其人,本长安倡女,尝学琵琶于穆、曹二善才,年长色衰,委身为贾人妇。遂命酒,使快弹数曲。曲罢悯然,自叙少小时欢乐事,今漂沦憔悴,转徙于江湖间。予出官二年,恬然自安,感斯人言,是夕始觉有迁谪意。因为长句,歌以赠之,凡六百一十六言,命曰《琵琶行》。]
浔阳江头夜送客,枫叶荻花秋瑟瑟。\
主人下马客在船,举酒欲饮无管弦。\
醉不成欢惨将别,别时茫茫江浸月。\
忽闻水上琵琶声,主人忘归客不发。\
寻声暗问弹者谁,琵琶声停欲语迟。\
移船相近邀相见,添酒回灯重开宴。\
千呼万唤始出来,犹抱琵琶半遮面。\
转轴拨弦三两声,未成曲调先有情。\
弦弦掩抑声声思,似诉平生不得志。\
低眉信手续续弹,说尽心中无限事。\
轻拢慢捻抹复挑,初为《霓裳》后《六幺》。\
大弦嘈嘈如急雨,小弦切切如私语。\
嘈嘈切切错杂弹,大珠小珠落玉盘。\
间关莺语花底滑,幽咽泉流冰下难。\
冰泉冷涩弦凝绝,凝绝不通声暂歇。\
别有幽愁暗恨生,此时无声胜有声。\
银瓶乍破水浆迸,铁骑突出刀枪鸣。\
曲终收拨当心画,四弦一声如裂帛。\
东船西舫悄无言,唯见江心秋月白。\
沉吟放拨插弦中,整顿衣裳起敛容。\
自言本是京城女,家在虾蟆陵下住。\
十三学得琵琶成,名属教坊第一部。\
曲罢曾教善才服,妆成每被秋娘妒。\
五陵年少争缠头,一曲红绡不知数。\
钿头银篦击节碎,血色罗裙翻酒污。\
今年欢笑复明年,秋月春风等闲度。\
弟走从军阿姨死,暮去朝来颜色故。\
门前冷落鞍马稀,老大嫁作商人妇。\
商人重利轻别离,前月浮梁买茶去。\
去来江口守空船,绕船月明江水寒。\
夜深忽梦少年事,梦啼妆泪红阑干。\
我闻琵琶已叹息,又闻此语重唧唧。\
同是天涯沦落人,相逢何必曾相识!\
我从去年辞帝京,谪居卧病浔阳城。\
浔阳地僻无音乐,终岁不闻丝竹声。\
住近湓江地低湿,黄芦苦竹绕宅生。\
其间旦暮闻何物?杜鹃啼血猿哀鸣。\
春江花朝秋月夜,往往取酒还独倾。\
岂无山歌与村笛,呕哑嘲哳难为听。\
今夜闻君琵琶语,如听仙乐耳暂明。\
莫辞更坐弹一曲,为君翻作《琵琶行》。
感我此言良久立,却坐促弦弦转急。\
凄凄不似向前声,满座重闻皆掩泣。\
座中泣下谁最多?江州司马青衫湿。\
+ 选自《白居易集笺校》卷十二(上海古籍出版社1988年版)。行,古诗的一种体裁。
+ 〔元和十年〕公元815年。元和,唐宪宗的年号(806—820)。
+ 〔左迁〕贬官、降职的委婉说法。白居易因越职上书言事,触怒当朝权贵,被贬为江州司马。
+ 〔九江郡〕设于隋代,唐代称为江州或浔阳郡,治所在今江西九江。
+ 〔司马〕州刺史的副职。
+ 〔湓(pén)浦口〕湓江流入长江的地方,在今九江西。湓浦,又叫湓江,源出江西瑞昌清湓山。
+ 〔京都声〕指唐代京城长安流行的乐曲声调。
+ 〔倡(chāng)女〕歌女。
+ 〔善才〕当时对技艺高超的乐师的称呼。
+ 〔委身〕托身。这里是嫁人的意思。
+ 〔贾(gǔ)人〕商人。
+ 〔命酒〕叫人摆酒。
+ 〔快〕畅快。
+ 〔悯然〕忧郁的样子。
+ 〔漂沦〕漂泊流落。
+ 〔出官〕京官贬黜往地方任职。
+ 〔恬然〕宁静安适的样子。
+ 〔迁谪〕官吏因罪降职并流放。
+ 〔为〕创作。
+ 〔长句〕指七言诗。唐代的习惯说法。
+ 〔江头〕江边。
+ 〔荻(dí)〕多年生草本植物,形状像芦苇,生长在水边。
+ 〔瑟瑟〕形容微风吹动的声音。
+ 〔主人〕白居易自指。
+ 〔管弦〕指音乐。管,箫、笛之类的管乐。弦,琴、瑟、琵琶之类的弦乐。
+ 〔暗问〕低声询问。
+ 〔欲语迟〕将要回答,又有些迟疑。
+ 〔回灯〕重新掌灯。一说“移灯”。
+ 〔转轴拨弦〕拧转弦轴,拨动弦丝。这里指调弦校音。
+ 〔掩抑〕声音低沉。
+ 〔思〕深长的情思
+ 〔信手〕随手。
+ 〔续续〕连续。
+ 〔轻拢慢捻抹(mò)复挑(tiǎo)〕轻轻地拢,慢慢地捻,一会儿抹,一会儿挑。拢,扣弦。捻,揉弦。抹,顺手下拨。挑,反手回拨。
+ 〔《霓裳(cháng)》〕即《霓裳羽衣曲》,唐代乐曲名,相传为唐玄宗所制。
+ 〔《六幺(yāo)》〕即《六幺令》,唐代乐曲名。
+ 〔大弦〕指琵琶四根弦中的粗弦。
+ 〔嘈嘈〕形容声音沉重舒长。
+ 〔小弦〕指琵琶上的细弦。
+ 〔切切〕形容声音轻细急促。
+ 〔大珠小珠落玉盘〕分别比喻乐声的重浊和清脆。一说,形容声音的清脆圆润。
+ 〔间(jiàn)关莺语花底滑〕像黄莺在花下啼叫一样婉转流利。间关,形容鸟鸣婉转。
+ 〔幽咽泉流冰下难〕像幽咽的泉水在冰下艰难流过。幽咽,形容乐声梗塞不畅。难,艰难,形容乐声滞塞难通。
+ 〔冰泉冷涩弦凝绝〕像冰下的泉水又冷又涩不能畅流,弦似乎凝结不动了。这是形容弦声愈来愈低沉,以至停顿。
+ 〔银瓶乍破水浆迸,铁骑突出刀枪鸣〕像银瓶突然破裂,水浆迸射一样;像铁骑突然冲出,刀枪齐鸣一般。这是形容琵琶声在沉咽、暂歇后,忽然又爆发出激越、雄壮的乐音。
+ 〔曲终收拨当心画〕乐曲终了,用拨子在琵琶的中间部位划过四弦。这是弹奏琵琶到一曲结束时的常用手法。拨,拨子,弹奏弦乐的用具。
+ 〔四弦一声〕四根弦同时发声。
+ 〔敛容〕显出端庄的脸色。
+ 〔虾(há)蟆陵〕地名,在长安城东南。
+ 〔教坊〕古时管理宫廷音乐的官署。专管雅乐以外的音乐、舞蹈、百戏的教习、排练、演出等事务。
+ 〔第一部〕第一队,是教坊中最优秀的一队。部,量词,计量歌舞队、乐队。
+ 〔秋娘〕唐代歌伎常用的名字。这里是对善歌貌美歌伎的通称。
+ 〔五陵年少〕指京城富家豪族子弟。五陵,汉代五个皇帝(高、惠、景、武、昭)的陵墓,在长安附近,富家豪族多聚居在这一带。
+ 〔缠头〕古代对歌伎舞女打赏用的锦帛。
+ 〔绡(xiāo)〕轻薄的生丝织品。泛指轻美的丝织品。
+ 〔钿(diàn)头银篦(bì)〕上端镶着花钿的银质发篦。钿,用金银等制成的花形首饰。
+ 〔击节碎〕(随着音乐)打拍子时敲碎了。节,节拍。
+ 〔翻酒污〕(因为)泼翻了酒被沾污。
+ 〔等闲〕平常,随随便便。
+ 〔颜色故〕容貌衰老。故,旧、老。
+ 〔老大〕年纪大了。
+ 〔浮梁〕地名,在今江西景德镇北。
+ 〔去来〕走了以后。来,语气助词。
+ 〔梦啼妆泪红阑干〕从梦中哭醒,搽了胭脂粉的脸上流满了一道道红色的泪痕。妆,这里指脸上的胭脂粉。
+ 〔唧唧〕叹息。
+ 〔杜鹃啼血〕传说杜鹃鸟啼叫时,嘴里会淌出血来。这是形容杜鹃啼声的悲切。
+ 〔独倾〕独自饮酒。
+ 〔呕哑(ōuyā)嘲哳(zhāozhā)〕指声音嘈杂刺耳。
+ 〔暂〕忽然,一下子。
+ 〔更〕再。
+ 〔翻作〕写作。翻,按曲调写作歌词。
+ 〔却坐〕回到(原处)坐下。却,退回。
+ 〔促弦〕把琴弦拧紧。促,紧、迫。
+ 〔转〕更加,越发。
+ 〔向前〕以前。
+ 〔掩泣〕掩面哭泣。下面“泣下”的“泣”指眼泪。
+ 〔青衫〕青色单衣。唐代官职低的服色为青。
== 归园田居(其一) 陶渊明
少无适俗韵,性本爱丘山。\
误落尘网中,一去三十年。\
羁鸟恋旧林,池鱼思故渊。\
开荒南野际,守拙归园田。\
方宅十余亩,草屋八九间。\
榆柳荫后檐,桃李罗堂前。\
暧暧远人村,依依墟里烟。\
狗吠深巷中,鸡鸣桑树颠。\
户庭无尘杂,虚室有余闲。\
久在樊笼里,复得返自然。\
+ 〔适俗〕适应世俗。
+ 〔韵〕气质,情致。
+ 〔丘山〕指山林。
+ 〔尘网〕指世俗的种种束缚。
+ 〔一去三十年〕陶渊明大约二十五岁离开少时居所, 直到五十五岁辞去彭泽令方归,所以说“一去三十 年”。或疑当作“十三年”。自开始做官至辞去彭泽 令,前后为十三年。
+ 〔羁鸟〕被关在笼中的鸟。羁,约束。
+ 〔南野〕南面的田野。一作“南亩”,指农田。
+ 〔守拙〕持守愚拙的本性,即不学巧伪,不争名利。
+ 〔方宅十余亩〕宅子四周有十几亩地。方,四周围绕。
+ 〔暧(ài )暧〕迷蒙隐约的样子。
+ 〔依依〕隐约的样子。一说“轻柔的样子”。
+ 〔墟里〕指村落。
+ 〔颠〕顶端。
+ 〔户庭〕门户庭院。
+ 〔尘杂〕指世俗的繁杂琐事。
+ 〔虚室〕静室。
+ 〔余闲〕余暇,空闲。
+ 〔樊笼〕关鸟兽的笼子。这里指束缚本性的俗世。
== 念奴娇 · 赤壁怀古 苏轼
大江东去,浪淘尽,千古风流人物。\
故垒西边,人道是,三国周郎赤壁。\
乱石穿空,惊涛拍岸,卷起千堆雪。江山如画,一时多少豪杰。\
遥想公瑾当年,小乔初嫁了,雄姿英发。\
羽扇纶巾,谈笑间,樯橹灰飞烟灭。\
故国神游,多情应笑我,早生华发。人生如梦,一尊还酹江月。\
+ 选自《东坡乐府笺》卷二(上海古籍出版社2009年 版)。念奴娇,词牌名。这首词作于宋神宗元丰五 年( 1082)。苏轼所游的是黄州(今湖北黄冈)的 赤鼻矶,并非东汉末期赤壁大战处。
+ 〔 大江〕指长江。
+ 〔故垒〕旧时军队营垒的遗迹。
+ 〔 周郎〕即周瑜( 175—210),字公瑾,孙权军中指 挥赤壁大战的将领。二十四岁时即出任要职,军中 皆呼为“周郎”。
+ 〔雄姿英发〕姿容雄伟,英气勃发。
+ 〔 羽扇纶( guān)巾〕(手持)羽扇,(头戴)纶巾。 这是儒者的装束,形容周瑜有儒将风度。纶巾,配 有青丝带的头巾。
+ 〔樯( qiáng)橹〕代指曹操的战船。樯,挂帆的桅 杆。橹,一种摇船的桨。
+ 〔 故国〕指赤壁古战场。
+ 〔 多情应笑我,早生华发〕应笑我多愁善感,过早 地长出花白的头发。
+ 〔尊〕同“樽”,一种盛酒器。这里指酒杯。
+ 〔酹( lèi)〕将酒洒在地上,表示凭吊。
== 永遇乐·京口北固亭怀古 辛弃疾
千古江山,英雄无觅,孙仲谋处。\
舞榭歌台,风流总被,雨打风吹去。\
斜阳草树,寻常巷陌,人道寄奴曾住。\
想当年,金戈铁马,气吞万里如虎。
元嘉草草,封狼居胥,赢得仓皇北顾。\
四十三年,望中犹记,烽火扬州路。\
可堪回首,佛狸祠下,一片神鸦社鼓。\
凭谁问:廉颇老矣,尚能饭否?\
+ 选自《稼轩词编年笺注》卷五(上海古籍出版社1993年版)。永遇乐,词牌名。这首词作于宋宁宗开禧元年(1205)。
+ 〔寄奴曾住〕寄奴是南朝宋武帝刘裕(363—422)的小名。刘裕的祖先移居京口,他在这里起事,晚年推翻东晋做了皇帝。
+ 〔想当年,金戈铁马,气吞万里如虎〕刘裕曾两次率领东晋军队北伐,收复洛阳、长安等地。
+ 〔元嘉草草〕南朝宋文帝刘义隆好大喜功,仓促北伐,遭到重创。元嘉,宋文帝刘义隆的年号(424—453)。草草,轻率。
+ 〔封狼居胥〕汉武帝元狩四年(前119),霍去病远征匈奴,歼敌七万余,封狼居胥山而还。封,登山祭天,以纪功勋。狼居胥,山名,即今蒙古国境内的肯特山。这里用“元嘉北伐”暗示南宋朝廷要汲取历史教训。《宋书·王玄谟传》载刘义隆对殷景仁说:“闻王玄谟陈说,使人有封狼居胥意。”
+ 〔北顾〕败逃中回头北望。
+ 〔四十三年〕作者于宋高宗绍兴三十二年(1162)南归,到写这首词时正好四十三年。
+ 〔烽火扬州路〕扬州一带抗金的烽火。
+ 〔佛(bì)狸祠〕北魏太武帝拓跋焘(408—452)小名“佛狸”。公元450年,他反击刘宋,兵锋南下,在长江北岸瓜步山上建立行宫,后称“佛狸祠”。
+ 〔神鸦〕指在庙里吃祭品的乌鸦。
+ 〔社鼓〕社日祭祀土地神的鼓声。南宋时期,当地老百姓只把佛狸祠当作一般祠庙来祭祀供奉,而不知道它过去曾是北魏皇帝的行宫。
+ 〔廉颇老矣,尚能饭否〕据《史记·廉颇蔺相如列传》,战国时赵国名将廉颇被免职后跑到魏国,后来赵王想重新起用他,派人去探看他的身体状况。廉颇在使者面前吃下饭一斗、肉十斤,披甲上马,以示尚可大用。使者受廉颇仇人郭开的贿赂,回来报告赵王说:“廉将军虽老,尚善饭,然与臣坐,顷之三遗矢矣。”(矢,同“屎”。)赵王以为廉颇已老,遂不召。
== 声声慢 李清照
寻寻觅觅,冷冷清清,凄凄惨惨戚戚。\
乍暖还寒时候,最难将息。\
三杯两盏淡酒,怎敌他、晚来风急!雁过也,正伤心,却是旧时相识。\
满地黄花堆积,憔悴损,如今有谁堪摘?守着窗儿,独自怎生得黑!梧桐更兼细雨,到黄昏、点点滴滴。\
这次第,怎一个愁字了得!\
+ 选自《李清照集校注》卷一(人民文学出版社1979年版)。声声慢,词牌名。北宋末年李清照南渡避乱,不久北宋灭亡,丈夫病死,她只身逃难,境遇悲惨。这首词是作者南渡后晚年的作品。
+ 〔戚戚〕悲愁、哀伤的样子。
+ 〔乍暖还(huán)寒〕忽暖忽冷,天气变化无常。
+ 〔将息〕养息,休息。
+ 〔黄花〕菊花。
+ 〔憔悴损〕枯萎,凋零殆尽。憔悴,凋零、枯萎。损,这里相当于“极”,表示程度很深。
+ 〔堪〕可以,能够。
+ 〔怎生得黑〕怎样挨到天黑。怎生,怎么、怎样。
+ 〔次第〕光景,状况。
+ 〔怎一个愁字了得〕意思是,一个“愁”字怎么能概括得尽呢?
== 劝学 荀子
君子曰: 学不可以已。
青,取之于蓝,而青于蓝;冰,水为之,而寒于水。木直中绳,輮以为轮,其曲中规。虽有槁暴,不复挺者,輮使之然也。故木受绳则直,金就砺则利,君子博学而日参省乎己,则知明而行无过矣。
吾尝终日而思矣,不如须臾之所学也;吾尝跂而望矣,不如登高之博见也。登高而招,臂非加长也,而见者远;顺风而呼,声非加疾也,而闻者彰。假舆马者,非利足也,而致千里;假舟楫者,非能水也,而绝江河。君子性非异也,善假于物也。
积土成山,风雨兴焉;积水成渊,蛟龙生焉;积善成德,而神明自得,圣心备焉。故不积跬步,无以至千里;不积小流,无以成江海。骐骥一跃,不能十步;驽马十驾,功在不舍。锲而舍之,朽木不折;锲而不舍,金石可镂。蚓无爪牙之利,筋骨之强,上食埃土,下饮黄泉,用心一也。蟹六跪而二螯,非蛇鳝之穴无可寄托者,用心躁也。
+ 〔青,取之于蓝〕靛( diàn)青从蓝草中取得。青, 靛青,一种染料。蓝,草名,叶子可提取靛青。
+ 〔青于蓝〕比蓝草颜色深。
+ 〔中( zhòng)绳〕合乎木匠用来取直的墨线。
+ 〔 ( róu)〕同“煣”,用火烘烤木材使之弯曲。
+ 〔规〕圆规。
+ 〔虽有槁暴( gǎopù)〕即使又晒干了。有,同“又”。 槁暴,晒干。槁,枯。暴,晒。
+ 〔挺〕直。
+ 〔受绳〕经过墨线比量。
+ 〔金〕指金属制的刀斧等。
+ 〔就砺〕拿到磨刀石上去磨。就,接近、靠近。砺, 磨刀石。
+ 〔参( cān)省( xǐng)乎己〕对自己检查、省察。 参,检验。省,省察。乎,相当于“于”。
+ 〔知〕同“智”,见识。
+ 〔 跂( qǐ)〕踮起脚后跟。
+ 〔见者远〕意思是远处的人也能看见。
+ 〔疾〕劲疾。
+ 〔彰〕清楚。
+ 〔假〕借助。
+ 〔舆马〕车马。这里指车子。
+ 〔利足〕善于奔走。
+ 〔致〕到达。
+ 〔能水〕善于游水。水,游泳。
+ 〔绝〕横渡。
+ 〔生( xìng)非异〕天性(同一般人)没有差别。 生,同“性”,天性。
+ 〔物〕外物,包括各种客观条件。
+ 〔兴焉〕在这里兴起。兴,起。焉,兼词,相当于 “于此”。下文“生焉”的“焉”同此。
+ 〔神明〕非凡的智慧。
+ 〔圣心〕圣人的心怀。
+ 〔跬( kuǐ)步〕古代称跨出一脚为“跬”,跨出两 脚为“步”。
+ 〔无以〕没有用来……的,无从。
+ 〔骐骥(qíjì)〕骏马。
+ 〔驽马十驾〕劣马拉车走十天。驾,一天的行程。
+ 〔功在不舍〕功效来源于走个不停。舍,停止、止息。
+ 〔锲(qiè)〕刻。
+ 〔镂〕雕刻。
+ 〔埃土〕泥土,尘土。
+ 〔黄泉〕地下的泉水。
+ 〔一〕专一。
+ 〔六跪〕蟹的六条腿。“六”应是“八”。
+ 〔螯〕蟹钳。
+ 〔躁〕浮躁,不专心。
== 师说 韩愈
古之学者必有师。
师者,所以传道受业解惑也。
人非生而知之者,孰能无惑?惑而不从师,其为惑也,终不解矣。
生乎吾前,其闻道也固先乎吾,吾从而师之;生乎吾后,其闻道也亦先乎吾,吾从而师之。
吾师道也,夫庸知其年之先后生于吾乎?是故无贵无贱,无长无少,道之所存,师之所存也。
嗟乎!师道之不传也久矣!欲人之无惑也难矣!古之圣人,其出人也远矣,犹且从师而问焉;今之众人,其下圣人也亦远矣,而耻学于师。
是故圣益圣,愚益愚。
圣人之所以为圣,愚人之所以为愚,其皆出于此乎?爱其子,择师而教之;于其身也,则耻师焉,惑矣。
彼童子之师,授之书而习其句读者,非吾所谓传其道解其惑者也。
句读之不知,惑之不解,或师焉,或不焉,小学而大遗,吾未见其明也。
巫医乐师百工之人,不耻相师。
士大夫之族,曰师曰弟子云者,则群聚而笑之。
问之,则曰:“彼与彼年相若也,道相似也,位卑则足羞,官盛则近谀。
”呜呼!师道之不复,可知矣。
巫医乐师百工之人,君子不齿,今其智乃反不能及,其可怪也欤!
圣人无常师。
孔子师郯子、苌弘、师襄、老聃。
郯子之徒,其贤不及孔子。
孔子曰:三人行,则必有我师。
是故弟子不必不如师,师不必贤于弟子,闻道有先后,术业有专攻,如是而已。
李氏子蟠,年十七,好古文,六艺经传皆通习之,不拘于时,学于余。
余嘉其能行古道,作《师说》以贻之。
+ 选自《韩昌黎文集校注》卷一(上海古籍出版社1986年版)。
+ 〔学者〕求学的人。
+ 〔师者,所以传道受业解惑也〕老师,是依靠他来传授道、教授学业、解除疑惑的人。所以,用来……的、凭它(他)来……的。受,同“授”,传授。
+ 〔生而知之〕生下来就懂得知识和道理。之,指知识和道理。
+ 〔其为惑也〕它们作为疑惑。其,它们,指不跟从老师学习而遗留下的问题。
+ 〔闻〕知道,懂得。
+ 〔从而师之〕跟随他学习,即以他为老师。
+ 〔吾师道也〕我学习的是道。师,学习。
+ 〔夫庸知其年之先后生于吾乎〕哪管他是生在我之前还是生在我之后呢?庸,表示反问语气。
+ 〔无贵无贱〕意思是就从师问道来说,没有贵和贱的区分。
+ 〔道之所存,师之所存也〕道存在的地方,就是老师在的地方。意思是谁懂得道,谁就是自己的老师。
+ 〔师道〕尊师学习的风尚。
+ 〔出人〕超出一般人。
+ 〔犹且〕尚且,还。
+ 〔众人〕一般人。
+ 〔圣益圣,愚益愚〕圣人更加圣明,愚人更加愚昧。益,更加、越发。
+ 〔身〕自己。
+ 〔耻师〕以从师学习为耻。
+ 〔惑〕糊涂。
+ 〔童子〕未成年的男子。
+ 〔授之书而习其句读(dòu)〕教给他书本的文字,(帮助他)学习句读。句读,指断开句子的知识。一句话后面的停顿为句,一句话中间短暂的停顿为读。古书没有标点,所以要学习句读。
+ 〔句读之不知〕不明句读。下文“惑之不解”结构同此。
+ 〔或师焉,或不(fǒu)焉〕有的向老师学习,有的不向老师学习。前一个“或”指代“句读之不知”,后一个“或”指代“惑之不解”。不,同“否”。
+ 〔小学而大遗〕小的方面要学习,大的方面却放弃了。
+ 〔巫医〕古代巫和医不分,故并举。巫主要以祝祷、占卜等为业,也为人治病。
+ 〔乐师〕以演奏音乐为职业的人。
+ 〔百工〕泛指各种工匠。
+ 〔不耻相师〕不以拜别人为师为耻。
+ 〔族〕类。
+ 〔曰师曰弟子云者〕说谁是谁的老师、谁是谁的学生之类的话。云者,如此之类。
+ 〔年相若〕年龄差不多。
+ 〔位卑则足羞,官盛则近谀(yú)〕以地位低者为师,就感到十分耻辱;以官职高者为师,就觉得是近乎谄媚。谀,谄媚奉承。
+ 〔不齿〕不与同列,意思是看不起。齿,并列、排列。
+ 〔乃〕竟。
+ 〔欤(yú)〕语气助词,表示感叹。
+ 〔常师〕固定的老师。
+ 〔郯(tán)子(生卒年不详)〕春秋时郯国(今山东郯城一带)的国君,孔子曾向他请教官职的名称。
+ 〔苌(cháng)弘(生卒年不详)〕周敬王时的大夫,孔子曾向他请教过音乐方面的事情。
+ 〔师襄(生卒年不详)〕春秋时鲁国的乐官,孔子曾跟他学过琴。
+ 〔老聃(dān)〕即老子,孔子曾向他问过礼。
+ 〔郯子之徒〕郯子那些人(指上面说的四个人)。徒,同类的人。
+ 〔贤〕才德优秀。
+ 〔三人行,则必有我师〕语出《论语·述而》。原句是:“三人行,必有我师焉。”
+ 〔不必〕不一定。
+ 〔贤〕超过。
+ 〔术业〕学术技艺。
+ 〔专攻〕专门学习或研究。攻,学习、研究。
+ 〔李氏子蟠〕李家的孩子叫蟠的。即李蟠,唐德宗贞元十九年(803)进士。
+ 〔古文〕指先秦两汉时期的散文,与骈文相对。
+ 〔六艺经传(zhuàn)〕六经的经文和传文。六艺,指《诗》《书》《礼》《乐》《易》《春秋》六种经书,其中《乐》久已失传。传,古代解释经书的著作。
+ 〔通〕全面。
+ 〔不拘于时〕不受时俗的限制。时,时俗,指当时士大夫中耻于从师的不良风气。
+ 〔嘉〕赞许。
+ 〔古道〕指古人从师之道。
+ 〔贻(yí)〕赠送。
== 赤壁赋 苏轼
壬戌之秋,七月既望,苏子与客泛舟游于赤壁之下。清风徐来,水波不兴。举酒属客,诵明月之诗,歌窈窕之章。少焉,月出于东山之上,徘徊于斗牛之间。白露横江,水光接天。纵一苇之所如,凌万顷之茫然。浩浩乎如冯虚御风,而不知其所止;飘飘乎如遗世独立,羽化而登仙。
于是饮酒乐甚,扣舷而歌之。歌曰:“桂棹兮兰桨,击空明兮溯流光。渺渺兮予怀,望美人兮天一方。”客有吹洞箫者,倚歌而和之。其声呜呜然,如怨如慕,如泣如诉,余音袅袅,不绝如缕。舞幽壑之潜蛟,泣孤舟之嫠妇。
苏子愀然,正襟危坐而问客曰:“何为其然也?”客曰:“月明星稀,乌鹊南飞,此非曹孟德之诗乎?西望夏口,东望武昌,山川相缪,郁乎苍苍,此非孟德之困于周郎者乎?方其破荆州,下江陵,顺流而东也,舳舻千里,旌旗蔽空,酾酒临江,横槊赋诗,固一世之雄也,而今安在哉?况吾与子渔樵于江渚之上,侣鱼虾而友麋鹿,驾一叶之扁舟,举匏樽以相属。寄蜉蝣于天地,渺沧海之一粟。哀吾生之须臾,羡长江之无穷。挟飞仙以遨游,抱明月而长终。知不可乎骤得,托遗响于悲风。”
苏子曰:“客亦知夫水与月乎?逝者如斯,而未尝往也;盈虚者如彼,而卒莫消长也。盖将自其变者而观之,则天地曾不能以一瞬;自其不变者而观之,则物与我皆无尽也,而又何羡乎!且夫天地之间,物各有主,苟非吾之所有,虽一毫而莫取。惟江上之清风,与山间之明月,耳得之而为声,目遇之而成色,取之无禁,用之不竭,是造物者之无尽藏也,而吾与子之所共适。”
客喜而笑,洗盏更酌。肴核既尽,杯盘狼藉。相与枕藉乎舟中,不知东方之既白。
+ 选自《苏轼文集》卷一(中华书局1986年版)。宋神宗元丰二年(1079),苏轼被贬为黄州(今湖北黄冈)团练副使。元丰五年(1082)秋冬,苏轼先后两次游览了黄州附近的赤壁,写下两篇赋。本文是第一篇,又称《前赤壁赋》。
+ 〔壬(rén)戌〕宋神宗元丰五年(1082)。
+ 〔既望〕过了望日后的第一天,通常指农历每月十六日。
+ 〔举酒属(zhǔ)客〕举起酒杯,劝客人饮酒。属,劝请。
+ 〔明月之诗〕和下文的“窈窕之章”分指《诗经·陈风·月出》及其诗句。这首诗的第一章有“舒窈纠(jiǎo)兮”的句子,所以称为“窈窕之章”。
+ 〔少焉〕一会儿。
+ 〔斗(dǒu)牛〕斗宿和牛宿,都是星宿名。
+ 〔白露〕指白茫茫的水汽。
+ 〔纵一苇之所如〕任凭小船漂去。纵,放任。一苇,指小船(比喻船很小,像一片苇叶)。语出《诗经·卫风·河广》:“谁谓河广,一苇杭(航)之。”如,往。
+ 〔凌万顷之茫然〕越过那茫茫的江面。凌,越过。万顷,指广阔的江面。茫然,旷远的样子。
+ 〔冯(píng)虚御风〕凌空驾风而行。冯,同“凭”,乘。虚,太空。御,驾。
+ 〔遗世独立,羽化而登仙〕脱离人世,升入仙境。羽化,指飞升成仙。
+ 〔扣舷〕敲着船边,指打着节拍。
+ 〔桂棹兮兰桨〕桂木做的棹,木兰做的桨。
+ 〔击空明兮溯流光〕(桨)划破月光下的清波,(船)在月光浮动的水面上逆流而上。空明,指月光下的清波。流光,江面浮动的月光。
+ 〔渺渺兮予怀〕我心里想得很远。渺渺,悠远的样子。
+ 〔望美人兮天一方〕眺望美人,(美人)却在天的那一边。美人,指所思慕的人。
+ 〔客〕指与苏轼同游的人。
+ 〔洞箫〕管乐器的一种。
+ 〔倚歌〕依照歌曲的声调和节拍。倚,循、依。
+ 〔和(hè)之〕(用箫)随着歌声伴奏。
+ 〔余音袅袅,不绝如缕〕尾声细弱而婉转悠长,如同不断的细丝。袅袅,形容声音婉转悠长。缕,细丝。
+ 〔舞幽壑之潜蛟,泣孤舟之嫠(lí)妇〕意思是,箫声使深谷中的蛟龙听了起舞,使独坐孤舟的寡妇听了落泪。幽壑,深谷。嫠妇,寡妇。
+ 〔危坐〕端坐。
+ 〔何为其然也〕(曲调)为什么这样(悲凉)呢?
+ 〔夏口〕古镇名,在今湖北武昌的西面。
+ 〔武昌〕今湖北鄂州。
+ 〔山川相缪(liáo),郁乎苍苍〕山水环绕,一片苍翠。缪,同“缭”,盘绕、围绕。
+ 〔此〕这地方。
+ 〔困〕受困。指曹操败于赤壁。
+ 〔周郎〕周瑜。
+ 〔方〕当。
+ 〔破荆州〕建安十三年(208),曹操南击荆州,当时荆州刺史刘表已死,刘表的儿子刘琮(cóng)投降曹操。荆州,在今湖北、湖南一带。
+ 〔下江陵〕刘琮投降曹操以后,曹操又在当阳的长坂击败刘备,进兵江陵。下,攻占。江陵,当时为荆州重镇,今属湖北。
+ 〔舳舻(zhúlú)〕船头和船尾的并称,泛指首尾相接的船只。
+ 〔酾(shī)酒临江,横槊(shuò)赋诗〕面对大江斟酒,横执长矛吟诗(曹操所吟的诗就是《短歌行》)。酾酒,斟酒。槊,长矛。
+ 〔渔樵于江渚之上〕在江边捕鱼砍柴。渔樵,捕鱼砍柴。
+ 〔匏(páo)樽〕用葫芦做成的酒器。匏,葫芦的一种。
+ 〔蜉蝣(fúyóu)〕一种小飞虫,夏秋之交生在水边,生存期很短,古人说它朝生暮死。这里用来比喻人生短促。
+ 〔一粟〕一粒米。
+ 〔骤〕一下子,很轻易地。
+ 〔遗响〕余音,指箫声。
+ 〔逝者如斯,而未尝往也;盈虚者如彼,而卒莫消长也〕流去的(水)像这样(不断地流去永不复返),而并没有流去;(月亮)像那样时圆时缺,却终究没有增减的变化。未尝往,意思是江水虽然在不断地奔流,但前者去后者来,始终滔滔不绝,如同没有流去。盈,满。虚,缺。卒,终究。消长,消减和增长。
+ 〔盖将自其变者而观之,则天地曾不能以一瞬〕如果从那变化的一面看,那么天地间万事万物(时刻在变动),连一眨眼的工夫都不停止。将,这里表示假设。
+ 〔物与我皆无尽〕意思是,万物同我们一样都是永恒的。
+ 〔是造物者之无尽藏(zàng)也,而吾与子之所共适〕这是自然界无穷无尽的宝藏,我和你可以共同享受。造物者,原指“天”,就是现在所说的“自然”。无尽藏,出自佛家语的“无尽藏海”(像海之能包罗万物)。适,这里有“享有”的意思。
+ 〔更〕再。
+ 〔肴核〕菜肴和果品。
+ 〔狼籍〕即“狼藉”,凌乱。
+ 〔相与枕藉(jiè)〕互相枕着垫着。
+ 〔既白〕天明。白,明亮。
== 登泰山记 姚鼐
泰山之阳,汶水西流;其阴,济水东流。
阳谷皆入汶,阴谷皆入济。
当其南北分者,古长城也。
最高日观峰,在长城南十五里。
余以乾隆三十九年十二月,自京师乘风雪,历齐河、长清,穿泰山西北谷,越长城之限,至于泰安。
是月丁未,与知府朱孝纯子颍由南麓登。
四十五里,道皆砌石为磴,其级七千有余。
泰山正南面有三谷。
中谷绕泰安城下,郦道元所谓环水也。
余始循以入,道少半,越中岭,复循西谷,遂至其巅。
古时登山,循东谷入,道有天门。
东谷者,古谓之天门溪水,余所不至也。
今所经中岭及山巅,崖限当道者,世皆谓之天门云。
道中迷雾冰滑,磴几不可登。
及既上,苍山负雪,明烛天南。
望晚日照城郭,汶水、徂徕如画,而半山居雾若带然。
戊申晦,五鼓,与子颍坐日观亭,待日出。
大风扬积雪击面。
亭东自足下皆云漫。
稍见云中白若樗蒱数十立者,山也。
极天云一线异色,须臾成五采。
日上,正赤如丹,下有红光动摇承之,或曰,此东海也。
回视日观以西峰,或得日或否,绛皓驳色,而皆若偻。
亭西有岱祠,又有碧霞元君祠。
皇帝行宫在碧霞元君祠东。
是日观道中石刻,自唐显庆以来;其远古刻尽漫失。
僻不当道者,皆不及往。
山多石,少土。
石苍黑色,多平方,少圜ホ。
少杂树,多松,生石罅,皆平顶。
冰雪,无瀑水,无鸟兽音迹。
至日观数里内无树,而雪与人膝齐。
桐城姚鼐记。
+ 选自《惜抱轩诗文集》卷十四(上海古籍出版社1992年版)。姚鼐(1732—1815),字姬传,桐城(今属安徽)人,清代散文家。
+ 〔汶(wèn)水〕发源于山东莱芜东北原山,向西南流经泰安。
+ 〔济(jǐ)水〕发源于河南济源西王屋山,东流到山东入海。
+ 〔阳谷〕山南面山谷中的水。
+ 〔当其南北分者〕在那(阳谷和阴谷)南北分界处的。
+ 〔古长城〕古代的长城,指春秋战国时齐国所筑长城的遗址,古时齐鲁两国以此分界。
+ 〔以〕在。
+ 〔乾隆三十九年〕公元1774年。乾隆,清高宗的年号(1736—1795)。
+ 〔乘〕这里是“冒”的意思。
+ 〔齐河、长清〕清代县名,今属山东。
+ 〔限〕界限。
+ 〔是月丁未〕这个月的丁未日(乾隆三十九年十二月二十八日)。
+ 〔朱孝纯子颍(yǐng)〕朱孝纯,字子颍。当时是泰安府的知府。
+ 〔磴〕石阶。
+ 〔环水〕水名,又名“梳洗河”。郦道元《水经注·汶水》:“又合环水,水出泰山南溪。”
+ 〔循以入〕顺着(中谷)进山。
+ 〔道少半〕路不到一半。
+ 〔中岭〕山名,又名“中溪山”。
+ 〔崖限当道者〕像门槛一样横在路上的山崖。限,门槛。
+ 〔云〕助词,无实义。
+ 〔几(jī)〕几乎。
+ 〔苍山负雪,明烛天南〕青黑色的山上覆盖着白雪,雪反射的光照亮了南面的天空。负,背。烛,照。
+ 〔城郭〕指城市。
+ 〔徂徕(cúlái)〕山名,在泰安城东南。
+ 〔居〕停留。
+ 〔戊申晦〕戊申日月底这一天。晦,农历每月的最后一天。
+ 〔五鼓〕五更。
+ 〔日观亭〕亭名,在日观峰上。
+ 〔漫〕弥漫。
+ 〔稍〕逐渐。
+ 〔樗蒱(chūpú)〕古代的一种博戏,这里指樗蒱所用的掷具,长形而末端尖锐,立起来像山峰。
+ 〔极天〕天边。
+ 〔采〕同“彩”。
+ 〔丹〕朱砂。
+ 〔东海〕泛指东面的海。这里是想象,实际上在泰山顶上并不能看见东海。
+ 〔或得日或否〕有的被日光照着,有的没有被照着。
+ 〔绛皓(hào)驳色〕或红或白,颜色错杂。绛,大红。皓,白。驳,杂。
+ 〔偻〕脊背弯曲的样子。引申为鞠躬的样子。日观峰西面诸峰都比日观峰低,所以说“若偻”。
+ 〔岱祠〕东岳大帝庙。
+ 〔碧霞元君〕传说是东岳大帝的女儿。
+ 〔行宫〕皇帝出外巡行时居住的处所。
+ 〔显庆〕唐高宗的年号(656—661)。
+ 〔漫失〕模糊或缺失。
+ 〔圜〕同“圆”。
== 静女 《诗经·邶风》
静女其姝,俟我于城隅。\
爱而不见,搔首踟蹰。\
静女其娈,贻我彤管。\
彤管有炜,说怿女美。\
自牧归荑,洵美且异。\
匪女之为美,美人之贻。\
+ 〔静女其姝( shū)〕娴静的女子很漂亮。姝,美丽、 漂亮。
+ 〔俟( sì)〕等待。
+ 〔城隅〕城角。一说指城上的角楼。
+ 〔爱〕同“ ( ài)”,隐藏。
+ 〔搔首踟蹰( chíchú)〕以手指挠头,徘徊不进。
+ 〔娈( luán)〕美好。
+ 〔彤管〕红色的管状物。一说指初生时呈红色的管 状的草,即下一章所说的“荑( tí)”。
+ 〔炜( wěi)〕色红而光亮。 + 〔说( yuè)怿( yì)女( rǔ)美〕喜爱你的美丽。说, 同“悦”。 怿,喜悦。女,同“汝”,第二人称代词。 下文的“匪女之为美”的“女”同此。
+ 〔自牧归( kuì)荑〕从远郊归来赠送我初生的茅草。 牧,城邑的远郊。归,同“馈”,赠送。
+ 〔洵美且异〕确实美好而且与众不同。洵,诚然、 实在。
+ 〔匪女之为美〕并非你这荑草美。匪,同“非”,表 示否定判断。
== 涉江采芙蓉 古诗十九首
涉江采芙蓉,兰泽多芳草。\
采之欲遗谁?所思在远道。\
还顾望旧乡,长路漫浩浩。\
同心而离居,忧伤以终老。
+ 〔兰泽〕长着兰草的低湿之地。
+ 〔遗(wèi)〕赠送。
+ 〔以〕连词,表示结果。
#colbreak()
== 虞美人 李煜
春花秋月何时了,往事知多少。
小楼昨夜又东风,故国不堪回首月明中。
雕栏玉砌应犹在,只是朱颜改。
问君能有几多愁,恰似一江春水向东流。
+ 选自《南唐二主词校订》(中华书局2007年版)。虞
+ 人,词牌名。李煜(937—978),字重光,徐州
+ 今属江苏)人,南唐后主,世称李后主。
+ 〔春花秋月〕指季节的更替。
+ 〔往事知多少〕意思是多少往事都难以忘却。
+ 〔故国〕指南唐。
+ 〔雕栏玉砌〕雕饰华美的栏杆与用玉石砌成的台阶,
+ 宫殿建筑。
+ 〔朱颜改〕红润的容颜改变了,指人已憔悴。
+ 〔几多〕多少。
== 鹊桥仙 [宋] 秦观
纤云弄巧,飞星传恨,银汉迢迢暗度。金风玉露一相逢,便胜却人间无数。
柔情似水,佳期如梦,忍顾鹊桥归路。两情若是久长时,又岂在朝朝暮暮。
+ *鹊桥仙*:词牌名,又名“鹊桥仙令”“金风玉露相逢曲”等。双调五十六字,上下片各两仄韵,一韵到底。上下片首两句要求对仗。
+ *纤云*:轻盈的云彩。
+ *弄巧*:指云彩在空中幻化成各种巧妙的花样。
+ *飞星*:流星。一说指牵牛、织女二星。
+ *银汉*:银河。
+ *迢迢*:遥远的样子。
+ *暗度*:悄悄渡过。
+ *金风玉露*:指秋风白露。李商隐《辛未七夕》:“恐是仙家好别离,故教迢递作佳期。由来碧落银河畔,可要金风玉露时。”
+ *忍顾*:怎忍回头看。
+ *朝朝暮暮*:指朝夕相聚。语出宋玉《高唐赋》。
]
#pagebreak()
= 必修下
#columns[
== 登岳阳楼 杜甫
昔闻洞庭水,今上岳阳楼。\
吴楚东南坼,乾坤日夜浮。\
亲朋无一字,老病有孤舟。\
戎马关山北,凭轩涕泗流。\
+ 选自《杜诗详注》卷二十二(中华书局2015年版)。此诗为大历三年(768)岁暮作。这年春天,诗人乘舟由夔州出三峡,岁暮抵达岳阳。
+ ﹝坼(chè)〕分裂。
+ ﹝乾坤〕指日月。
+ ﹝戎马关山北〕指战事起于北部边境地区。当时吐蕃正侵扰陇右、关中一带。戎马,战马,代指战争。关山,在今宁夏南部。
+ ﹝凭轩〕倚窗。
+ ﹝涕泗(sì)〕眼泪鼻涕
== 桂枝香·金陵怀古 王安石
登临送目,正故国晚秋,天气初肃。\
千里澄江似练,翠峰如簇。\
归帆去棹残阳里,背西风,酒旗斜矗。\
彩舟云淡,星河鹭起,画图难足。\
念往昔,繁华竞逐,叹门外楼头,悲恨相续。\
千古凭高对此,谩嗟荣辱。\
六朝旧事随流水,但寒烟衰草凝绿。\
至今商女,时时犹唱,后庭遗曲。\
+ 选自《临川先生文集》卷三十七(《王安石全集》第5册,复旦大学出版社2016年版)。桂枝香,词牌名。
+ ﹝登临送目〕登山临水,放眼远眺。
+ ﹝故国〕故都。这里指金陵。
+ ﹝肃〕肃爽,天高气爽。
+ ﹝簇〕聚集在一起的人或物。一说同“镞”,箭头,形容山峰的尖峭。
+ ﹝星河〕天河。这里指长江。
+ ﹝画图难足〕图画难以完备(地展现)。
+ ﹝繁华竞逐〕即竞逐繁华,争相追逐奢侈豪华生活。
+ ﹝门外楼头〕语出唐杜牧《台城曲》:“门外韩擒虎,楼头张丽华。”指隋军已经兵临城下,陈后主却还在和妃子们寻欢作乐。隋文帝开皇九年(589),隋军大将韩擒虎率兵从朱雀门攻入金陵,俘获了陈后主及其宠妃张丽华等人。门,指朱雀门。楼,指结绮阁,是陈后主特意为张丽华建造的。
+ ﹝悲恨相续〕指各个王朝接连覆亡。
+ ﹝凭高〕登临高处。
+ ﹝谩嗟荣辱〕枉自感叹兴亡的荣耀和耻辱。谩,同“漫”,徒然。
+ ﹝至今商女,时时犹唱,后庭遗曲〕语出唐杜牧《泊秦淮》:“商女不知亡国恨,隔江犹唱后庭花。”后庭遗曲,即陈后主所作《玉树后庭花》,被视为亡国之音。
+ 选自《张孝祥词校笺》卷一(中华书局2010年版)。张孝祥(1132—1170),字安国,号于湖居士,乌江(今安徽和县东北)人,南宋词人。宋孝宗乾道二年(1166),张孝祥因人进谗言而被罢官,由桂林北归,途经洞庭湖时作此词。
== 念奴娇·过洞庭 张孝祥
洞庭青草,近中秋,更无一点风色。\
玉鉴琼田三万顷,着我扁舟一叶。\
素月分辉,明河共影,表里俱澄澈。\
悠然心会,妙处难与君说。\
应念岭海经年,孤光自照,肝肺皆冰雪。\
短发萧骚襟袖冷,稳泛沧浪空阔。\
尽挹西江,细斟北斗,万象为宾客。\
扣舷独啸,不知今夕何夕!\
+ 选自《张孝祥词校笺》卷一(中华书局2010年版)。张孝祥(1132—1170),字安国,号于湖居士,乌江(今安徽和县东北)人,南宋词人。宋孝宗乾道二年(1166),张孝祥因人进谗言而被罢官,由桂林北归,途经洞庭湖时作此词。
+ ﹝青草〕即青草湖,在今湖南岳阳西南,属南洞庭湖。南朝宋盛弘之《荆州记》载:“巴陵南有青草湖,周回数百里,日月出没其中。”
+ ﹝风色〕风。
+ ﹝玉鉴琼田〕形容月光下洞庭湖皎洁的水面。鉴,镜子。
+ ﹝素月分辉,明河共影,表里俱澄澈〕意思是,明月光辉四射,银河与明月一同映入湖水之中,上上下下全都清亮明洁。明河,银河。
+ ﹝悠然心会〕指内心优游自在,与眼前景物相合。
+ ﹝应念岭海经年,孤光自照,肝肺皆冰雪〕意思是,应思量在岭外一年左右的官场生活中,月光本就在照耀陪伴,自己的心胸全部像冰雪一样明洁。岭海,五岭至南海之间的地域,指今两广一带。
+ ﹝萧骚〕稀疏。
+ ﹝挹(yì)〕舀(水)。
+ ﹝西江〕长江。
+ ﹝细斟北斗〕意思是,用天上的北斗舀取长江水细细品酌。北斗,北斗七星,排列成斗勺形,比喻酒器。
+ ﹝不知今夕何夕〕这里是极度赞叹此夜之美好。
#colbreak()
== 游园 汤显祖
【皂罗袍】原来姹紫嫣红开遍,似这般都付与断井颓垣。
良辰美景奈何天,赏心乐事谁家院!朝飞暮卷,云霞翠轩;雨丝风片,烟波画船——锦屏人忒看的这韶光贱!
+ 选自《牡丹亭》(《汤显祖戏曲集》,上海古籍出版社1978年版)。题目是编者加的。汤显祖(1550—1616),字义仍,号若士,临川(今江西抚州)人,明代戏曲作家。代表作有传奇《紫钗记》《牡丹亭》《南柯记》《邯郸记》,合称“玉茗堂(汤显祖居所名)四梦”或“临川四梦”。《牡丹亭》全剧共五十五出,描写了南安太守杜宝的女儿杜丽娘与书生柳梦梅的爱情故事。这段曲词出自第十出《惊梦》。
+ ﹝奈何天〕令人无可奈何的时光。多表示百无聊赖的思绪。
+ ﹝谁家〕哪一家。一说作“什么”解。
+ ﹝朝飞暮卷〕语出唐王勃《滕王阁》:“画栋朝飞南浦云,珠帘暮卷西山雨。”
+ ﹝锦屏人忒(tè)看的这韶光贱〕意思是,我这深闺女子太辜负这美好春光。锦屏人,深闺中人。忒,过于。看的……贱,把……看轻。韶光,美好的时光,多指春光。
]
#line(
length: 100%
)
== 子路、曾皙、冉有、公西华侍坐 《论语》
子路、曾皙、冉有、公西华侍坐。
子曰:“以吾一日长乎尔,毋吾以也。
居则曰:‘不吾知也!’如或知尔,则何以哉?
”子路率尔而对曰:“千乘之国,摄乎大国之间,加之以师旅,因之以饥馑;由也为之,比及三年,可使有勇,且知方也。
夫子哂之。
“求!尔何如?”
对曰:“方六七十,如五六十,求也为之,比及三年,可使足民。
如其礼乐,以俟君子。
“赤!尔何如?”对曰:“非曰能之,愿学焉。宗庙之事,如会同,端章甫,愿为小相焉。
“点!尔何如?”
鼓瑟希,铿尔,舍瑟而作,对曰:“异乎三子者之撰。
子曰:“何伤乎?亦各言其志也。
曰:“莫春者,春服既成,冠者五六人,童子六七人,浴乎沂,风乎舞雩,咏而归。
夫子喟然叹曰:“吾与点也!”
三子者出,曾皙后。曾皙曰:“夫三子者之言何如?”子曰:“亦各言其志也已矣。
曰:“夫子何哂由也?”曰:“为国以礼,其言不让,是故哂之。
“唯求则非邦也与?”
“安见方六七十如五六十而非邦也者?”
“唯赤则非邦也与?”“宗庙会同,非诸侯而何?赤也为之小,孰能为之大?”
+ 选自《论语·先进》(《论语译注》,中华书局1980年版)。题目是编者加的。子路(前542—前480),即仲由,字子路。曾皙(生卒年不详),名点,字子皙,曾参的父亲。冉有(前522—?),即冉求,字子有。公西华(前509—?),复姓公西,名赤,字子华。四人都是孔子的弟子。侍坐,在尊长近旁陪坐。
+ ﹝以吾一日长乎尔,毋吾以也〕意思是,因为我年纪比你们大一点,(你们)不要因我(年长)就不敢说话了。以,因为。后一个“以”同“已”,是“止”的意思。毋,不要。一说本句的意思是,因为我年纪比你们大一点,(老了,)没有人用我了。这里后一个“以”是“用”的意思。
+ ﹝居则曰〕(你们)平日说。居,平日、平时。
+ ﹝不吾知〕即“不知吾”,不了解我。
+ ﹝则何以哉〕那么(你们)打算怎么做呢?
+ ﹝率尔〕急遽而不加考虑的样子。尔,相当于“然”。
+ ﹝千乘(shèng)之国〕有一千辆兵车的诸侯国。在春秋后期,千乘之国是中等国家。乘,古时一车四马为一乘。春秋时,一辆兵车,配甲士三人,步卒七十二人。
+ ﹝摄乎大国之间〕夹在(几个)大国的中间。摄,夹处。
+ ﹝加之以师旅〕有军队来攻打它。师旅,指军队。古时两千五百人为一师,五百人为一旅。
+ ﹝因之以饥馑(jǐn)〕接下来又有饥荒。因,接续。饥馑,泛指饥荒。
+ ﹝为之〕治理这个国家。为,治。
+ ﹝比及〕等到。
+ ﹝方〕合乎礼义的行事准则。
+ ﹝哂(shěn)〕微笑。
+ ﹝方六七十,如五六十〕纵横六七十里或五六十里(的小国)。方,计量面积用语,多用以计量土地,后加表示长度的数词或数量词,表示纵横若干长度的意思。如,或者。下文“如会同”的“如”同。
+ ﹝可使足民〕可以使人民富足。
+ ﹝如其礼乐,以俟君子〕至于礼乐教化,(自己的能力是不够的,)那就得等待君子(来推行了)。这是冉有的谦辞。如,至于。俟,等待。
+ ﹝非曰能之,愿学焉〕不敢说我能胜任,但是愿意在这方面学习。这是公西华的谦辞。能,胜任、能做到。
+ ﹝宗庙之事〕指诸侯祭祀祖先的事。在古代是国家重要的政事。宗庙,天子、诸侯供奉祖宗牌位的处所。
+ ﹝会同〕古代诸侯朝见天子的通称。会,诸侯在非规定时间朝见天子。同,诸侯一起朝见天子。
+ ﹝端章甫〕穿着礼服,戴着礼帽。这是做小相(xiàng)时的穿戴。端,古代的一种礼服。章甫,古代的一种礼帽。端和章甫在这里都用作动词。
+ ﹝相〕诸侯祭祀、会盟或朝见天子时,主持赞礼的司仪官。所谓“小相”,也是公西华的谦辞。
+ ﹝鼓瑟希〕弹奏瑟的声音(渐渐)稀疏,指接近尾声。希,同“稀”,稀疏。
+ ﹝铿(kēng)尔〕铿的一声,指止瑟声。
+ ﹝舍瑟而作〕把瑟放下,站起来。作,起身、站起来。
+ ﹝撰〕才能。这里指为政的才能。一说,讲述、解说。
+ ﹝何伤〕何妨。意思是有什么关系呢。
+ ﹝莫(mù)春〕即暮春,农历三月。莫,同“暮”。
+ ﹝春服既成〕春天的衣服已经穿定了。意思是天气渐暖,不必频繁换衣。
+ ﹝冠(guàn)者〕成年人。古代男子在二十岁时行加冠礼,表示成年。
+ ﹝童子〕少年,未成年的男子。
+ ﹝沂(yí)〕水名,在今山东曲阜南。
+ ﹝风乎舞雩(yú)〕在舞雩台上吹吹风。风,吹风。舞雩,台名,是鲁国求雨的坛,在今曲阜南。雩,求雨的祭祀仪式,伴以乐舞,故称“舞雩”。
+ ﹝咏〕唱歌。
+ ﹝喟(kuì)然〕叹息的样子。喟,叹息。
+ ﹝与〕赞成。
+ ﹝也已矣〕语气助词连用,相当于“罢了”。
+ ﹝为国以礼,其言不让〕治国要用礼,(可是)他(仲由)的话毫不谦逊。
+ ﹝唯求则非邦也与〕难道冉求讲的不是国家的事吗?唯,语气助词,用于句首,无实义。邦,国。也与,语气助词,表示疑问。
+ ﹝安见〕怎见得。
+ ﹝宗庙会同,非诸侯而何〕宗庙祭祀、朝见天子,不是诸侯国的事又是什么呢?意思是,公西赤说的也是国家大事,不过讲得谦虚罢了。
+ ﹝赤也为之小,孰能为之大〕如果公西赤只能给诸侯做一个小相,那么谁能做大相呢?
== 谏太宗十思疏 魏征
臣闻求木之长者,必固其根本;欲流之远者,必浚其泉源;思国之安者,必积其德义。
源不深而望流之远,根不固而求木之长,德不厚而思国之理,臣虽下愚,知其不可,而况于明哲乎!人君当神器之重,居域中之大,将崇极天之峻,永保无疆之休。
不念居安思危,戒奢以俭,德不处其厚,情不胜其欲,斯亦伐根以求木茂,塞源而欲流长者也。
凡百元首,承天景命,莫不殷忧而道著,功成而德衰。
有善始者实繁,能克终者盖寡。
岂取之易而守之难乎?昔取之而有余,今守之而不足,何也?夫在殷忧,必竭诚以待下;既得志,则纵情以傲物。
竭诚则胡越为一体,傲物则骨肉为行路。
虽董之以严刑,振之以威怒,终苟免而不怀仁,貌恭而不心服。
怨不在大,可畏惟人;载舟覆舟,所宜深慎;奔车朽索,其可忽乎!君人者,诚能见可欲则思知足以自戒,将有作则思知止以安人,念高危则思谦冲而自牧,惧满溢则思江海下百川,乐盘游则思三驱以为度,忧懈怠则思慎始而敬终,虑壅蔽则思虚心以纳下,想谗邪则思正身以黜恶,恩所加则思无因喜以谬赏,罚所及则思无因怒而滥刑。
总此十思,弘兹九德,简能而任之,择善而从之,则智者尽其谋,勇者竭其力,仁者播其惠,信者效其忠。
文武争驰,在君无事,可以尽豫游之乐,可以养松、乔之寿,鸣琴垂拱,不言而化。
何必劳神苦思,代下司职,役聪明之耳目,亏无为之大道哉!
+ 选自《贞观政要集校》卷一(中华书局2003年版)。题目是编者加的。魏征(580—643),字玄成,巨鹿(今属河北)人,唐代政治家,以直言敢谏著称。
+ ﹝长(zhǎng)〕生长。这里指长得好。
+ ﹝浚(jùn)〕疏通水道。
+ ﹝德义〕德行和道义。
+ ﹝下愚〕极愚昧无知的人。这里用作谦辞。
+ ﹝明哲〕明智的人。这里指唐太宗。
+ ﹝当神器之重〕掌握帝王的重权。当,主持、掌握。神器,指帝位。
+ ﹝居域中之大〕处在天地间重要的地位上。域中,天地间。语出《老子》第二十五章:“故道大,天大,地大,王亦大。域中有四大,而王居其一焉。”
+ ﹝休〕喜庆,福禄。
+ ﹝戒奢以俭〕戒奢侈,行节俭。
+ ﹝凡百元首〕(历代)所有的帝王。凡百,所有的。
+ ﹝承天景命〕承受上天的重大使命。景,大。
+ ﹝殷忧〕深深忧虑。殷,深。
+ ﹝能克终者盖寡〕能够保持到底的大概很少。盖,表示推断。
+ ﹝傲物〕看不起别人。物,人。
+ ﹝竭诚则胡越为一体,傲物则骨肉为行路〕竭尽诚心,胡越之人也将同心同德;傲视别人,至亲骨肉也会成为不相干的路人。胡越,泛指古代居于我国北方和南方的少数民族。骨肉,指父母兄弟子女等至亲。《史记·鲁仲连邹阳列传》:“故意合则胡越为昆弟,由余、越人蒙是矣;不合,则骨肉出逐不收,朱、象、管、蔡是矣。”
+ ﹝董之以严刑〕用严酷的刑罚督察人民。董,督察。
+ ﹝振〕同“震”,威吓。
+ ﹝终苟免而不怀仁〕最终只是苟且免于刑罚,但是并不会怀念(皇上的)仁德。
+ ﹝怨不在大,可畏惟人〕怨恨不在于大小,可畏惧的是人民(心怀怨恨)。
+ ﹝载舟覆舟〕语出《荀子·王制》:“君者舟也,庶人者水也。水则载舟,水则覆舟。”意思是,人民能拥戴皇帝,也能推翻他的统治。
+ ﹝所宜深慎〕这是应当深切戒慎的。﹝见可欲〕看见(自己)贪图的东西。语出《老子》第三章:“不见可欲,使民心不乱。”下文的“知足”(知道满足)、“知止”(知道适可而止),语出《老子》第四十四章的“知足不辱”与“知止不殆”。
+ ﹝作〕建造,兴建。这里指大兴土木、营建宫殿苑囿一类事情。
+ ﹝念高危则思谦冲而自牧〕想到(君位)高而险,就要不忘谦虚,加强自身的道德修养。谦冲,谦虚。牧,养。语出《周易·谦卦》:“谦谦君子,卑以自牧。”
+ ﹝满溢〕容器中水满而溢出,比喻骄傲自满而听不进不同意见。
+ ﹝江海下百川〕江海居于百川之下(而能容纳百川),比喻有度量,善于听取各方面的意见。下,居于……之下。
+ ﹝盘游〕游乐。这里指田猎。盘,快乐。
+ ﹝三驱〕语出《周易·比卦》:“王用三驱。”田猎时设网三面,留一面不设,指田猎有度,不过分捕杀。
+ ﹝敬〕慎。
+ ﹝虑壅(yōng)蔽〕担心(耳目被)堵塞蒙蔽。
+ ﹝谗邪〕以谗言陷害别人的邪恶之人。
+ ﹝谬赏〕不恰当地奖赏。
+ ﹝弘兹九德〕光大九德的修养。弘,光大。九德,指《尚书·皋陶(yáo)谟》所讲的九种品德。
+ ﹝惠〕仁爱,宽厚。
+ ﹝信者〕诚信的人。
+ ﹝豫游〕出游,游乐。帝王秋天出巡为“豫”,春天出巡为“游”。
+ ﹝松、乔之寿〕像仙人赤松子、王子乔那样的长寿。赤松子、王子乔,都是传说中的仙人。
+ ﹝垂拱〕垂衣拱手,指不亲自处理政务。
== 阿房宫赋 杜牧
六王毕,四海一,蜀山兀,阿房出。
覆压三百余里,隔离天日。
骊山北构而西折,直走咸阳。
二川溶溶,流入宫墙。
五步一楼,十步一阁;廊腰缦回,檐牙高啄;各抱地势,钩心斗角。
盘盘焉,囷囷焉,蜂房水涡,矗不知其几千万落。
长桥卧波,未云何龙?复道行空,不霁何虹?高低冥迷,不知西东。
歌台暖响,春光融融;舞殿冷袖,风雨凄凄。
一日之内,一宫之间,而气候不齐。
妃嫔媵嫱,王子皇孙,辞楼下殿,辇来于秦。
朝歌夜弦,为秦宫人。
明星荧荧,开妆镜也;绿云扰扰,梳晓鬟也;渭流涨腻,弃脂水也;烟斜雾横,焚椒兰也。
雷霆乍惊,宫车过也;辘辘远听,杳不知其所之也。
一肌一容,尽态极妍,缦立远视,而望幸焉。
有不见者,三十六年。
燕赵之收藏,韩魏之经营,齐楚之精英,几世几年,剽掠其人,倚叠如山。
一旦不能有,输来其间。
鼎铛玉石,金块珠砾,弃掷逦迤,秦人视之,亦不甚惜。
嗟乎!一人之心,千万人之心也。
秦爱纷奢,人亦念其家。
奈何取之尽锱铢,用之如泥沙?使负栋之柱,多于南亩之农夫;架梁之椽,多于机上之工女;钉头磷磷,多于在庾之粟粒;瓦缝参差,多于周身之帛缕;直栏横槛,多于九土之城郭;管弦呕哑,多于市人之言语。
使天下之人,不敢言而敢怒。
独夫之心,日益骄固。
戍卒叫,函谷举,楚人一炬,可怜焦土!
呜呼!灭六国者六国也,非秦也;族秦者秦也,非天下也。
嗟乎!使六国各爱其人,则足以拒秦;使秦复爱六国之人,则递三世可至万世而为君,谁得而族灭也?秦人不暇自哀,而后人哀之;后人哀之而不鉴之,亦使后人而复哀后人也。
+ 选自《樊川文集》卷一(《杜牧集系年校注》,中华书局2008年版)。阿房(ēpáng)宫,秦宫殿,遗址在今陕西西安西郊,始建于秦始皇三十五年(前212),到秦亡时尚未完工。本文写于唐敬宗宝历元年(825)。杜牧在《上知己文章启》中说:“宝历大起宫室,广声色,故作《阿房宫赋》。”
+ ﹝六王毕〕六国灭亡了。六王,齐、楚、燕、韩、赵、魏六国的国君,指六国。毕,完结,指为秦国所灭。
+ ﹝一〕统一。
+ ﹝蜀山兀,阿房出〕蜀地的山秃了,阿房宫建成了。兀,光秃。这里形容山上树木已被砍伐殆尽。出,出现,意思是建成。
+ ﹝覆压三百余里〕覆盖三百多里地。形容宫殿楼阁接连不断,占地极广。
+ ﹝隔离天日〕遮蔽天日。这是形容宫殿楼阁的高大。
+ ﹝骊山北构而西折,直走咸阳〕(阿房宫)从骊山北边建起,折而向西,一直通到咸阳(古咸阳在骊山西北)。走,通达。
+ ﹝二川溶溶〕二川,指渭水和樊川。溶溶,河水盛大的样子,一说为缓缓流动的样子。
+ ﹝廊腰缦(màn)回〕走廊萦绕曲折。廊腰,连接高大建筑物的走廊,好像人的腰部,故称。缦,萦绕。回,曲折。
+ ﹝檐牙高啄〕檐牙高耸,如鸟仰首啄物。檐牙,屋檐翘出如牙齿的部分。
+ ﹝各抱地势〕各随地形。这是说楼阁各随地势的高下走向而建。
+ ﹝钩心斗角〕指宫室结构的参差错落,精致工巧。钩心,指各种建筑物都与中心区相连。斗角,指屋角相对,好像兵戈相斗。
+ ﹝盘盘焉,囷(qūn)囷焉,蜂房水涡〕回环曲折,像蜂房,像水涡(一样稠密层叠)。盘盘,盘旋的样子。囷囷,曲折回旋的样子。
+ ﹝矗不知其几千万落〕矗立着,不知它们有几千万座。
+ ﹝长桥卧波,未云何龙〕长桥卧在水上,没有云怎么出现了龙?这是形容长桥似龙。《周易·乾卦》有“云从龙”的话,所以人们认为有龙就应该有云。
+ ﹝复道〕楼阁之间架在空中的通道。因上下都有通道,故称。
+ ﹝冥迷〕分辨不清。
+ ﹝歌台暖响,春光融融〕人们在台上唱歌,歌声响起,好像充满着暖意,如同春光那样和暖。
+ ﹝舞殿冷袖,风雨凄凄〕人们在殿中舞蹈,舞袖飘拂,好像带来寒气,如同风雨交加那样凄冷。
+ ﹝妃嫔(pín)媵(yìng)嫱(qiáng)〕指六国王侯的宫妃。下文的“王子皇孙”,指六国王侯的女儿、孙女。
+ ﹝辞楼下殿,辇(niǎn)来于秦〕辞别(六国的)楼阁宫殿,乘辇车来到秦国。辇,君王及后妃所乘的车。
+ ﹝明星荧荧,开妆镜也〕(光如)明星闪亮,是(宫人)打开梳妆的镜子。荧荧,明亮的样子。
+ ﹝涨腻〕涨起了脂膏。下文“脂水”,指含有脂粉的洗脸水。
+ ﹝椒兰〕两种香料植物,焚烧以熏香衣物。
+ ﹝辘辘远听〕车声越听越远。辘辘,车行的声音。
+ ﹝一肌一容,尽态极妍〕肌肤、姿容都娇媚极了。
+ ﹝缦立〕久立。
+ ﹝三十六年〕指嬴政在位期间(前247—前210)。
+ ﹝收藏〕指收藏的金玉珍宝等物。下文的“经营”“精英”也指金玉珍宝等物。
+ ﹝剽(piāo)掠其人〕从百姓那里抢来。剽,抢劫、掠夺。
+ ﹝倚叠〕堆叠。
+ ﹝鼎铛(chēng)玉石,金块珠砾〕把宝鼎看作铁锅,把美玉看作石头,把黄金看作土块,把珍珠看作石子。铛,平底的浅锅。
+ ﹝逦迤〕连续不断。这里有“到处都是”的意思。
+ ﹝负栋之柱〕支撑房屋大梁的柱子。
+ ﹝磷磷〕有棱角的样子。这里形容钉头突出。
+ ﹝庾〕谷仓。
+ ﹝九土〕九州。
+ ﹝独夫〕残暴无道、失去人心的统治者。这里指秦始皇。
+ ﹝骄固〕骄横顽固。
+ ﹝戍卒叫〕指陈涉、吴广起义。
+ ﹝楚人一炬〕指项羽占领咸阳后纵火焚烧秦宫室。
+ ﹝族〕灭族。
+ ﹝递〕依次传递。
== 六国论 苏洵
六国破灭,非兵不利,战不善,弊在赂秦。
赂秦而力亏,破灭之道也。
或曰:六国互丧,率赂秦耶?曰:不赂者以赂者丧。
盖失强援,不能独完。
故曰:弊在赂秦也。
秦以攻取之外,小则获邑,大则得城。
较秦之所得,与战胜而得者,其实百倍;诸侯之所亡,与战败而亡者,其实亦百倍。
则秦之所大欲,诸侯之所大患,固不在战矣。
思厥先祖父,暴霜露,斩荆棘,以有尺寸之地。
子孙视之不甚惜,举以予人,如弃草芥。
今日割五城,明日割十城,然后得一夕安寝。
起视四境,而秦兵又至矣。
然则诸侯之地有限,暴秦之欲无厌,奉之弥繁,侵之愈急。
故不战而强弱胜负已判矣。
至于颠覆,理固宜然。
古人云:“以地事秦,犹抱薪救火,薪不尽,火不灭。
”此言得之。
齐人未尝赂秦,终继五国迁灭,何哉?与嬴而不助五国也。
五国既丧,齐亦不免矣。
燕赵之君,始有远略,能守其土,义不赂秦。
是故燕虽小国而后亡,斯用兵之效也。
至丹以荆卿为计,始速祸焉。
赵尝五战于秦,二败而三胜。
后秦击赵者再,李牧连却之。
洎牧以谗诛,邯郸为郡,惜其用武而不终也。
且燕赵处秦革灭殆尽之际,可谓智力孤危,战败而亡,诚不得已。
向使三国各爱其地,齐人勿附于秦,刺客不行,良将犹在,则胜负之数,存亡之理,当与秦相较,或未易量。
呜呼!以赂秦之地封天下之谋臣,以事秦之心礼天下之奇才,并力西向,则吾恐秦人食之不得下咽也。悲夫!有如此之势,而为秦人积威之所劫,日削月割,以趋于亡。
为国者无使为积威之所劫哉!
夫六国与秦皆诸侯,其势弱于秦,而犹有可以不赂而胜之之势。
苟以天下之大,下而从六国破亡之故事,是又在六国下矣。
+ 选自《嘉祐集笺注》卷三(上海古籍出版社1993年版)。苏洵(1009—1066),字明允,眉州眉山(今属四川)人,北宋散文家。
+ ﹝赂秦〕以财物赠予秦国,这里指向秦割地求和。赂,赠送财物。
+ ﹝或曰〕有人说。这是设问。下句的“曰”是对设问的回答。
+ ﹝互丧〕相继灭亡。
+ ﹝率〕全都,一概。
+ ﹝完〕保全。
+ ﹝以攻取〕用攻战(的方法)取得。
+ ﹝厥先祖父〕他们的祖辈父辈。厥,相当于“其”。祖父,泛指祖辈、父辈。
+ ﹝暴(pù)霜露〕暴露在霜露之中。和下文的“斩荆棘”连起来,形容创业的艰苦。暴,同“曝”。
+ ﹝举以予人〕拿来送给别人。
+ ﹝奉之弥繁,侵之愈急〕六国送给秦越多,秦侵犯六国越厉害。
+ ﹝判〕决定,确定。
+ ﹝以地事秦……火不灭〕语出《史记·魏世家》和《战国策·魏策》。
+ ﹝迁灭〕灭亡。
+ ﹝与嬴〕亲附秦国。与,亲附、亲近。
+ ﹝远略〕长远的谋略。
+ ﹝至丹以荆卿为计,始速祸焉〕等到燕太子丹用荆卿(刺秦王)作为(对付秦国的)策略,才招致祸患。《史记》记载,荆轲刺秦王未成,秦王大怒,发兵灭燕。荆卿,荆轲,即下文提到的“刺客”。速,招致。
+ ﹝李牧〕赵国大将,曾几次打退秦军。前229年,秦将王翦攻赵,李牧率兵抵抗,赵王中了秦的反间计,杀李牧。第二年,王翦破赵军,虏赵王。下文的“邯郸为郡”即指秦夺取赵国都城邯郸,改为秦的邯郸郡。
+ ﹝洎(jì)〕及,等到。
+ ﹝三国〕指韩、魏、楚三国。这三国都曾经割地赂秦。
+ ﹝胜负之数,存亡之理〕胜败存亡的命运。数、理,指天数、命运。
+ ﹝较〕较量。
+ ﹝积威〕积久而成的威势。
+ ﹝劫〕胁迫,挟持。
+ ﹝为(wéi)国者〕治理国家的人。
+ ﹝下〕降低身份。
+ ﹝故事〕旧事。
= 选必上
#columns[
== 《论语》十二章
子曰:“君子食无求饱,居无求安,敏于事而慎 于言,就有道而正焉,可谓好学也已。”(《学而》)
子曰:“人而不仁,如礼何?人而不仁,如乐 何?”(《八佾》)
子曰:“朝闻道,夕死可矣。”(《里仁》)
子曰:“君子喻于义,小人喻于利。”(《里仁》)
子曰:“见贤思齐焉,见不贤而内自省也。”(《里仁 》)
子曰:“质胜文则野,文胜质则史。文质彬彬, 然后君子。”(《雍也》)
曾子曰:“士不可以不弘毅,任重而道远。仁以为己任,不亦重乎?死而后已,不亦远乎?”(《泰伯》)
子曰:“譬如为山,未成一篑,止,吾止也。譬如平地,虽覆一篑,进,吾往也。”(《子罕》)
子曰:“知者不惑,仁者不忧,勇者不惧。”(《子罕》)
颜渊问仁。子曰:“克己复礼为仁。一日克己复礼,天下归仁焉。为仁由己,而由人乎哉?”颜渊曰:“请问其目。”子曰:“非礼勿视,非礼勿听,非礼勿言,非礼勿动。”颜渊曰:“回虽不敏,请事斯语矣。”(《颜渊》)
子贡问曰:“有一言而可以终身行之者乎?”子曰:“其‘恕’乎!己所不欲,勿施于人。”(《卫灵公》)
子曰:“小子何莫学夫《诗》?《诗》可以兴,可以观,可以群,可以怨。迩之事父,远之事君。多识于鸟兽草木之名。”(《阳货》)
+ 选自《论语译注》(中华书局2006年版)。
+ 〔敏〕勤勉。
+ 〔就有道而正焉〕到有道的人那里去匡正自己。有道, 指有才艺或有道德的人。
+ 〔而〕如果。
+ 〔如礼何〕怎样对待礼呢?
+ 〔喻〕知晓,明白。
+ 〔质胜文则野〕质朴超过文采就会粗野鄙俗。质, 质朴、朴实。文,华美、文采。野,粗野、鄙俗。
+ 〔史〕虚饰,浮夸。
+ 〔文质彬彬〕文质兼备、配合适当的样子。
+ 〔弘毅〕志向远大,意志坚强。弘,广、大,这里 指志向远大。
+ 〔未成一篑(kuì)〕只差一筐土没有成功。篑,盛土 的竹筐。
+ 〔止,吾止也〕停下来,是我自己停下来的。
+ 〔平地〕填平洼地。
+ 〔知〕同“智”。
+ 〔克己复礼〕约束自我,使言行归复于先王之礼。
+ 〔一日〕一旦。
+ 〔归〕称赞,称许。
+ 〔目〕条目,细则。
+ 〔事〕实践,从事。
+ 〔一言〕一个字。
+ 〔小子〕老师对学生的称呼。
+ 〔夫〕那。
+ 〔兴〕指激发人的感情。
+ 〔观〕指观察政治的得失、风俗的盛衰。
+ 〔群〕指提高人际交往能力。
+ 〔怨〕指讽刺时政。
+ 〔迩(ěr)〕近。
== 梦游天姥吟留别 李白
海客谈瀛洲,烟涛微茫信难求;\
越人语天姥,云霞明灭或可睹。\
天姥连天向天横,势拔五岳掩赤城。\
天台四万八千丈,对此欲倒东南倾。
我欲因之梦吴越,一夜飞度镜湖月。\
湖月照我影,送我至剡溪。\
谢公宿处今尚在,渌水荡漾清猿啼。\
脚著谢公屐,身登青云梯。\
半壁见海日,空中闻天鸡。\
千岩万转路不定,迷花倚石忽已暝。\
熊咆龙吟殷岩泉,栗深林兮惊层巅。\
云青青兮欲雨,水澹澹兮生烟。\
列缺霹雳,丘峦崩摧。洞天石扉,訇然中开。\
青冥浩荡不见底,日月照耀金银台。\
霓为衣兮风为马,云之君兮纷纷而来下。\
虎鼓瑟兮鸾回车,仙之人兮列如麻。\
忽魂悸以魄动,恍惊起而长嗟。\
惟觉时之枕席,失向来之烟霞。
世间行乐亦如此,古来万事东流水。\
别君去兮何时还?且放白鹿青崖间,须行即骑访名山。\
安能摧眉折腰事权贵,使我不得开心颜?
+ 〔列缺〕闪电。列,同“裂”。
+ 〔洞天石扉,訇(hōng)然中开〕仙府的石门,訇 的一声从中间打开。洞天,仙人居住的洞府。訇 然,形容声音很大。
+ 〔青冥〕天空。
+ 〔金银台〕金银筑成的楼台,指神仙居住的地方。
+ 〔云之君〕泛指驾乘云彩的神仙。
+ 〔鸾回车〕鸾鸟拉车回转。鸾,传说中的神鸟。
+ 〔悸(jì)〕因惊惧而心跳。
+ 〔恍〕猛然惊醒的样子。
+ 〔觉(jiào)〕醒。
+ 〔失向来之烟霞〕刚才(梦中)所见的烟雾云霞消 失了。向来,原来。烟霞,指前面所写的仙境。
+ 〔且放白鹿青崖间,须行即骑访名山〕暂且把白鹿 放在青青的山崖间,等到要走的时候就骑上它去探 访名山。传说中神仙、隐士多骑白鹿。
+ 〔摧眉折腰〕低头弯腰,即卑躬屈膝。摧眉,即低眉, 低头。
== 无衣 《诗经·秦风》
岂曰无衣?与子同袍。\
王于兴师,修我戈矛,与子同仇。\
岂曰无衣?与子同泽。\
王于兴师,修我矛戟,与子偕作。\
岂曰无衣?与子同裳。\
王于兴师,修我甲兵,与子偕行。\
+ 选自《诗经注析》(中华书局1991年版)。
+ 〔袍〕长袍,类似于斗篷。行军者白天当衣服穿, 晚上当被子盖。
+ 〔王于兴师〕周王出兵打仗。于,句中助词。
+ 〔同仇〕指共同对付敌人。
+ 〔泽〕同“襗(zé)”,贴身穿的衣服。
+ 〔偕作〕一同起来,指共同行动。作,起。
+ 〔甲兵〕铠甲和兵器。
== 春江花月夜 张若虚
春江潮水连海平,海上明月共潮生。\
滟滟随波千万里,何处春江无月明。\
江流宛转绕芳甸,月照花林皆似霰。\
空里流霜不觉飞,汀上白沙看不见。\
江天一色无纤尘,皎皎空中孤月轮。\
江畔何人初见月?江月何年初照人?\
人生代代无穷已,江月年年望相似。\
不知江月待何人,但见长江送流水。\
白云一片去悠悠,青枫浦上不胜愁。\
谁家今夜扁舟子?何处相思明月楼?\
可怜楼上月裴回,应照离人妆镜台。\
玉户帘中卷不去,捣衣砧上拂还来。\
此时相望不相闻,愿逐月华流照君。\
鸿雁长飞光不度,鱼龙潜跃水成文。\
昨夜闲潭梦落花,可怜春半不还家。\
江水流春去欲尽,江潭落月复西斜。\
斜月沉沉藏海雾,碣石潇湘无限路。\
不知乘月几人归,落月摇情满江树。\
+ 选自《全唐诗》卷二十一(中华书局1999年版)。 春江花月夜,乐府旧题。张若虚(约660—约720), 扬州(今属江苏)人,唐代诗人。与贺知章、张 旭、包融并称“吴中四士”。
+ 〔滟滟〕形容波光荡漾。
+ 〔月明〕月光。
+ 〔芳甸〕花草茂盛的原野。
+ 〔霰(xiàn)〕白色不透明的小冰粒。
+ 〔流霜〕飞霜,比喻从空中洒落的月光。
+ 〔青枫浦〕即双枫浦,在湖南浏阳南。
+ 〔扁舟子〕指飘荡江湖的游子。
+ 〔明月楼〕明月映照下的楼阁。这里指楼上的思妇。
+ 〔裴回〕同“徘徊”。
+ 〔离人〕指守候在家的思妇。
+ 〔玉户帘中卷不去〕意思是,月光洒在玉门帘上,欲卷而去之而不得。玉户,用玉装饰的门,也用作 门的美称。
+ 〔月华〕月光。
+ 〔流照〕照射。
+ 〔鸿雁长飞光不度〕大雁远飞却不能飞出月光。暗示鸿雁不能传书。
+ 〔鱼龙潜跃水成文〕鱼儿出没只能使水面泛出波纹。 暗示鱼儿不能传书。古人有鱼儿传书一说。乐府诗 《饮马长城窟行》:“呼儿烹鲤鱼,中有尺素书。”鱼龙,这里指鱼。
+ 〔潇湘〕潇水和湘江,均流入洞庭湖。
+ 〔落月摇情满江树〕意思是,落月牵动着离人的别愁,将光辉洒满江畔的林木。
== 将进酒 李白
君不见,黄河之水天上来,奔流到海不复回。\
君不见,高堂明镜悲白发,朝如青丝暮成雪。\
人生得意须尽欢,莫使金樽空对月。\
天生我材必有用,千金散尽还复来。\
烹羊宰牛且为乐,会须一饮三百杯。\
岑夫子,丹丘生,将进酒,杯莫停。\
与君歌一曲,请君为我倾耳听。\
钟鼓馔玉不足贵,但愿长醉不复醒。\
古来圣贤皆寂寞,惟有饮者留其名。\
陈王昔时宴平乐,斗酒十千恣欢谑。\
主人何为言少钱,径须沽取对君酌。\
五花马,千金裘,呼儿将出换美酒,\
与尔同销万古愁。
+ 选自《李白集校注》卷三(上海古籍出版社1980年版)。将(qiānɡ)进酒,汉乐府旧题。将,请。进酒,饮酒。此诗大约作于天宝十一载(752)。李白和友人岑勋在嵩山另一好友元丹丘的颍阳山居做客,三人登高欢饮。诗中的“岑夫子”即岑勋,“丹丘生”即元丹丘。
+ 〔高堂〕高大的厅堂。
+ 〔得意〕指有兴致。
+ 〔会须〕应当。
+ 〔钟鼓馔玉〕指击钟敲鼓,食用珍美的菜肴,代指富贵生活。馔玉,像玉一样珍美的食品。
+ 〔愿〕一作“复”。
+ 〔寂寞〕指不为世所用,默默无闻。
+ 〔陈王〕指曹植,曾被封为陈王。
+ 〔平乐〕宫观名,故址在今河南洛阳附近。
+ 〔斗酒十千〕一斗酒值十千钱,指酒美而贵。
+ 〔恣欢谑(xuè)〕尽情地欢乐戏谑。
+ 〔主人〕指元丹丘。
+ 〔径须沽取〕毫不犹豫地买酒。径须,直须、应当。
+ 〔五花马〕一种名贵的马,毛色作五花(一说把马鬃修剪成五个花瓣)。
+ 〔千金裘〕珍贵的皮衣。
+ 〔儿〕指侍僮。
+ 〔将出〕牵出,拿出。
+ 〔销〕排遣。
== 江城子·乙卯正月二十日夜记梦 苏轼
十年生死两茫茫。不思量,自难忘。千里孤坟,无处话凄凉。纵使相逢 应不识,尘满面,鬓如霜。
夜来幽梦忽还乡。小轩窗,正梳妆。相顾无言,惟有泪千行。料得年年肠断处,明月夜,短松冈。
+ 选自《东坡乐府笺》卷一(上海古籍出版社2009 年版)。这首词作于宋神宗熙宁八年(1075), 是 苏轼在密州(今山东诸城)做知州时悼念妻子王弗 的作品。王弗去世于宋英宗治平二年(1065)。
+ 〔两茫茫〕指双方茫然不相知。
+ 〔千里孤坟〕王弗葬地在四川眉山,与苏轼任职的山 东密州相距遥远,故称亡妻的坟为“千里孤坟”, 有感伤自己不能与她同穴相伴之意。
+ 〔幽梦〕隐约迷离的梦。
+ 〔轩窗〕窗户。
+ 〔短松冈〕长着矮小松树的山冈,指王弗坟茔所在地。
]
= 选必中
== 屈原列传 司马迁
屈原者,名平,楚之同姓也。
为楚怀王左徒。
博闻强志,明于治乱,娴于辞令。
入则与王图议国事,以出号令;出则接遇宾客,应对诸侯。
王甚任之。
上官大夫与之同列,争宠而心害其能。
怀王使屈原造为宪令,屈平属草稿未定,上官大夫见而欲夺之,屈平不与。
因谗之曰:“王使屈平为令,众莫不知。
每一令出,平伐其功,曰以为‘非我莫能为’也。
”王怒而疏屈平。
屈平疾王听之不聪也,谗谄之蔽明也,邪曲之害公也,方正之不容也,故忧愁幽思而作《离骚》。
“离骚”者,犹离忧也。
夫天者,人之始也;父母者,人之本也。
人穷则反本,故劳苦倦极,未尝不呼天也;疾痛惨怛,未尝不呼父母也。
屈平正道直行,竭忠尽智以事其君,谗人间之,可谓穷矣。
信而见疑,忠而被谤,能无怨乎?屈平之作《离骚》,盖自怨生也。
《国风》好色而不淫,《小雅》怨诽而不乱。
若《离骚》者,可谓兼之矣。
上称帝喾,下道齐桓,中述汤、武,以刺世事。
明道德之广崇,治乱之条贯,靡不毕见。
其文约,其辞微,其志洁,其行廉。
其称文小而其指极大,举类迩而见义远。
其志洁,故其称物芳;其行廉,故死而不容。
自疏濯淖污泥之中,蝉蜕于浊秽,以浮游尘埃之外,不获世之滋垢,皭然泥而不滓者也。
推此志也,虽与日月争光可也。
屈平既绌,其后秦欲伐齐,齐与楚从亲。
惠王患之,乃令张仪详去秦,厚币委质事楚,曰:“秦甚憎齐,齐与楚从亲,楚诚能绝齐,秦愿献商於之地六百里。
”楚怀王贪而信张仪,遂绝齐,使使如秦受地。
张仪诈之曰:“仪与王约六里,不闻六百里。
”楚使怒去,归告怀王。
怀王怒,大兴师伐秦。
秦发兵击之,大破楚师于丹、淅,斩首八万,虏楚将屈匄,遂取楚之汉中地。
怀王乃悉发国中兵,以深入击秦,战于蓝田。
魏闻之,袭楚至邓。
楚兵惧,自秦归。
而齐竟怒不救楚,楚大困。
明年,秦割汉中地与楚以和。
楚王曰:“不愿得地,愿得张仪而甘心焉。
”张仪闻,乃曰:“以一仪而当汉中地,臣请往如楚。
”如楚,又因厚币用事者臣靳尚,而设诡辩于怀王之宠姬郑袖。
怀王竟听郑袖,复释去张仪。
是时屈平既疏,不复在位,使于齐,顾反,谏怀王曰:“何不杀张仪?”怀王悔,追张仪,不及。
其后诸侯共击楚,大破之,杀其将唐眜。
时秦昭王与楚婚,欲与怀王会。
怀王欲行,屈平曰:“秦,虎狼之国,不可信。
不如毋行。
”怀王稚子子兰劝王行:“奈何绝秦欢?”怀王卒行。
入武关,秦伏兵绝其后,因留怀王,以求割地。
怀王怒,不听。
亡走赵,赵不内。
复之秦,竟死于秦而归葬。
长子顷襄王立,以其弟子兰为令尹。
楚人既咎子兰以劝怀王入秦而不反也。
屈平既嫉之,虽放流,眷顾楚国,系心怀王,不忘欲反,冀幸君之一悟,俗之一改也。
其存君兴国而欲反覆之,一篇之中三致志焉。
然终无可奈何,故不可以反。
卒以此见怀王之终不悟也。
人君无愚、智、贤、不肖,莫不欲求忠以自为,举贤以自佐;然亡国破家相随属,而圣君治国累世而不见者,其所谓忠者不忠,而所谓贤者不贤也。
怀王以不知忠臣之分,故内惑于郑袖,外欺于张仪,疏屈平而信上官大夫、令尹子兰,兵挫地削,亡其六郡,身客死于秦,为天下笑。
此不知人之祸也。
……
令尹子兰闻之,大怒,卒使上官大夫短屈原于顷襄王,顷襄王怒而迁之。
屈原至于江滨,被发行吟泽畔,颜色憔悴,形容枯槁。
渔父见而问之曰:“子非三闾大夫欤?何故而至此?”屈原曰:“举世混浊而我独清,众人皆醉而我独醒,是以见放。
”渔父曰:“夫圣人者,不凝滞于物,而能与世推移。
举世混浊,何不随其流而扬其波?众人皆醉,何不𫗦其糟而啜其醨?何故怀瑾握瑜,而自令见放为?”屈原曰:“吾闻之,新沐者必弹冠,新浴者必振衣。
人又谁能以身之察察,受物之汶汶者乎?宁赴常流而葬乎江鱼腹中耳,又安能以晧晧之白,而蒙世俗之温蠖乎?”乃作《怀沙》之赋。
……于是怀石,遂自投汨罗以死。
屈原既死之后,楚有宋玉、唐勒、景差之徒者,皆好辞而以赋见称;然皆祖屈原之从容辞令,终莫敢直谏。
其后楚日以削,数十年,竟为秦所灭。
……
太史公曰:“余读《离骚》《天问》《招魂》《哀郢》,悲其志。
适长沙,观屈原所自沉渊,未尝不垂涕,想见其为人。
及见贾生吊之,又怪屈原以彼其材,游诸侯,何国不容,而自令若是!读《服鸟赋》,同死生,轻去就,又爽然自失矣。
”
#columns()[
+ 节选自《史记·屈原贾生列传》(中华书局2014年版)。
+ 〔左徒〕官名。
+ 〔博闻强志〕知识广博,长于记忆。闻,学识。志,记。
+ 〔明于治乱〕明晓国家治乱(的道理)。治,指国家安定。乱,指国家动荡。
+ 〔娴于辞令〕擅长外交辞令。娴,熟练、熟悉。辞令,应对的言辞。
+ 〔图议〕谋划计议。
+ 〔任〕信任。
+ 〔上官大夫与之同列〕上官大夫和屈原地位相同。上官,复姓。大夫,官名。列,朝列、班列。
+ 〔害其能〕嫉妒屈原的才能。害,嫉妒。
+ 〔宪令〕国家法令。
+ 〔属(zhǔ)〕撰写。
+ 〔夺〕强取。
+ 〔伐〕自夸,炫耀。
+ 〔曰以为〕“曰”和“以为”是同义连用。一说,“曰”为衍文。
+ 〔疾王听之不聪〕痛心于楚怀王惑于小人之言,不能明辨是非。疾,痛心。聪,明察。
+ 〔谗谄之蔽明〕说人坏话、奉承献媚的小人混淆黑白,蒙蔽怀王。
+ 〔邪曲之害公〕品行不正的小人损害国家。
+ 〔方正之不容〕端方正直的人不为(昏君谗臣)所容。
+ 〔离忧〕遭遇忧患。离,同“罹”,遭受。
+ 〔人穷则反本〕人困窘没有出路,就会追念根本。
+ 〔倦极〕疲倦困苦。极,疲困。
+ 〔惨怛(dá)〕忧伤,悲痛。
+ 〔信而见疑〕诚实不欺却被怀疑。见,被。
+ 〔盖自怨生也〕大概是由怨愤引起的。
+ 〔《国风》好色而不淫,《小雅》怨诽而不乱〕《国风》好描写男女恋情但不失分寸,《小雅》怨愤发牢骚但不坏乱礼法。淫,过度、无节制。
+ 〔上称帝喾(kù)〕往远处说提到帝喾(传说中的五帝之一)。
+ 〔下道齐桓〕往近处说提到齐桓公。
+ 〔汤、武〕即商汤、周武王。
+ 〔以刺世事〕(称引古代帝王)以此讥刺当世的事。
+ 〔广崇〕广大崇高。
+ 〔条贯〕条理。
+ 〔靡〕无,没有。
+ 〔约〕简约。
+ 〔微〕含蓄隐晦。
+ 〔其称文小而其指极大〕其文辞描写的是寻常事物,但是它的意旨却极为博大(因为关系到国家的治乱)。指,同“旨”。
+ 〔举类迩而见义远〕列举的事例浅近,而表达的意思很深远。类,事物。迩,近。
+ 〔称物芳〕指《离骚》里面多用美人香草来比喻。
+ 〔故死而不容〕所以至死不容于世。
+ 〔自疏濯淖(nào)污泥之中〕自动地远离污浊。濯、淖、污、泥,都是“污浊”的意思。
+ 〔蝉蜕于浊秽〕像蝉脱壳那样摆脱污秽的境地。
+ 〔不获世之滋垢〕不为尘世的污垢所辱。获,辱、被辱。滋,黑。
+ 〔皭(jiào)然泥(niè)而不滓(zǐ)者也〕意思是,屈原是出淤泥而不染、保持高洁品德的人。皭,清白、洁净。泥,同“涅”,染黑。滓,污染。
+ 〔推〕推赞,推许。
+ 〔绌〕同“黜”,指被罢免官职。
+ 〔齐与楚从(zòng)亲〕齐国和楚国合纵相亲。从,同“纵”,合纵,联合抗秦。
+ 〔惠王〕秦惠王。
+ 〔乃令张仪详(yáng)去秦,厚币委质事楚〕就令张仪假装离开秦国,拿着丰厚的礼物进献给楚国,表示愿意侍奉楚王。张仪,魏国人。他后来为秦惠王游说六国,主张“连横”。详,同“佯”,假装。厚币,丰厚的礼物。委,呈献。质,同“贽”,见面礼。张仪入楚在楚怀王十六年(前313)。
+ 〔绝齐〕与齐国断绝外交关系。
+ 〔商於〕地名,在今河南淅(xī)川西南。一说,指商(今陕西丹凤西北商镇)、於(在今河南西峡境)两邑及两邑之间的地区,即今丹江中下游一带。
+ 〔使使如秦受地〕派使者到秦国接受秦国答应割让的土地。
+ 〔丹、淅〕丹水、淅水一带。丹水发源于陕西商洛,东入河南与淅水汇合,至湖北丹江口入汉水。淅水发源于河南卢氏,流经内乡、淅川等地。前312年,秦军在丹阳(今河南西峡西丹水以北地区)大败楚军。
+ 〔匄〕读gài。
+ 〔蓝田〕在今湖北钟祥西北。
+ 〔邓〕在今湖北襄阳北。
+ 〔明年〕第二年。指楚怀王十八年(前311)。
+ 〔又因厚币用事者臣靳尚〕又趁机送厚礼给楚国当权的臣子靳尚。因,趁机。用事,当权。
+ 〔设诡辩〕说假话。
+ 〔顾反〕回来。
+ 〔眜〕读mò。
+ 〔武关〕秦国的南关,在今陕西丹凤东。
+ 〔咎〕怪罪,责怪。
+ 〔嫉〕恨。
+ 〔存〕思念。一说,保全。
+ 〔反覆〕回归。
+ 〔三致志〕再三表达(这种)意愿。
+ 〔自为(wèi)〕帮助自己。
+ 〔相随属(zhǔ)〕接连出现。
+ 〔治国〕安定太平的国家。
+ 〔六郡〕指汉中一带。
+ 〔短〕诋毁。
+ 〔迁〕放逐。
+ 〔形容〕外貌,模样。形,身形。容,面容。
+ 〔三闾(lǘ)大夫〕官名。屈原此前曾任此职。
+ 〔是以见放〕因此被放逐。
+ 〔圣人〕这里指聪明通达的人。
+ 〔不凝滞于物〕不为外物所拘束。凝滞,拘泥、执着。
+ 〔与世推移〕随世道变化而变化。
+ 〔随其流而扬其波〕指随从世俗,与之同流。
+ 〔(bū)其糟而啜(chuò)其醨(lí)〕吃众人的酒糟,喝众人的薄酒。意思是与众人同醉。,吃。啜,喝。醨,薄酒。
+ 〔怀瑾握瑜〕比喻保持高洁美好的节操志向。瑾、瑜,都是美玉。
+ 〔弹冠〕弹去帽子上的灰尘。
+ 〔察察〕洁净的样子。
+ 〔汶(mén)汶〕浑浊的样子。
+ 〔常流〕即“长流”,指江水。
+ 〔晧(hào)晧之白〕比喻品德的高尚纯洁。晧,同“皓”。晧晧,皎洁的样子。
+ 〔温蠖(huò)〕尘垢。
+ 〔汨罗〕江名,在湖南东北部。
+ 〔辞〕文辞,这里指文学。
+ 〔祖〕效法,继承。
+ 〔从容〕委婉得体。
+ 〔太史公曰〕太史公是司马迁的自称。后面的文字是司马迁对历史人物和历史事件的评论、总结。
+ 〔《天问》《招魂》《哀郢》〕均为屈原的作品。《哀郢》是《九章》中的一篇。
+ 〔适〕到某地去。
+ 〔贾生吊之〕指西汉政论家、文学家贾谊路过湘水,写《吊屈原赋》凭吊屈原。
+ 〔彼其材〕他那样的才能。
+ 〔《服鸟赋》〕贾谊的赋作,借与服鸟问答抒发自己忧愤不平的情感。
+ 〔同死生〕将生死同等看待。
+ 〔去就〕指离官去职或在朝任职。
+ 〔爽然自失〕茫然若有所失。
]
== 过秦论 贾谊
秦孝公据崤函之固,拥雍州之地,君臣固守以窥周室,有席卷天下,包举宇内,囊括四海之意,并吞八荒之心。
当是时也,商君佐之,内立法度,务耕织,修守战之具,外连衡而斗诸侯。
于是秦人拱手而取西河之外。
孝公既没,惠文、武、昭襄蒙故业,因遗策,南取汉中,西举巴、蜀,东割膏腴之地,北收要害之郡。
诸侯恐惧,会盟而谋弱秦,不爱珍器重宝肥饶之地,以致天下之士,合从缔交,相与为一。
当此之时,齐有孟尝,赵有平原,楚有春申,魏有信陵。
此四君者,皆明智而忠信,宽厚而爱人,尊贤而重士,约从离衡,兼韩、魏、燕、楚、齐、赵、宋、卫、中山之众。
于是六国之士,有甯越、徐尚、苏秦、杜赫之属为之谋,齐明、周最、陈轸、召滑、楼缓、翟景、苏厉、乐毅之徒通其意,吴起、孙膑、带佗、倪良、王廖、田忌、廉颇、赵奢之伦制其兵。
尝以十倍之地,百万之众,叩关而攻秦。
秦人开关延敌,九国之师,逡巡而不敢进。
秦无亡矢遗镞之费,而天下诸侯已困矣。
于是从散约败,争割地而赂秦。
秦有余力而制其弊,追亡逐北,伏尸百万,流血漂橹;因利乘便,宰割天下,分裂山河。
强国请服,弱国入朝。
延及孝文王、庄襄王,享国之日浅,国家无事。
及至始皇,奋六世之余烈,振长策而御宇内,吞二周而亡诸侯,履至尊而制六合,执敲扑而鞭笞天下,威振四海。
南取百越之地,以为桂林、象郡;百越之君,俯首系颈,委命下吏。
乃使蒙恬北筑长城而守藩篱,却匈奴七百余里;胡人不敢南下而牧马,士不敢弯弓而报怨。
于是废先王之道,焚百家之言,以愚黔首;隳名城,杀豪杰;收天下之兵,聚之咸阳,销锋镝,铸以为金人十二,以弱天下之民。
然后践华为城,因河为池,据亿丈之城,临不测之渊,以为固。
良将劲弩守要害之处,信臣精卒陈利兵而谁何。
天下已定,始皇之心,自以为关中之固,金城千里,子孙帝王万世之业也。
始皇既没,余威震于殊俗。
然陈涉瓮牖绳枢之子,氓隶之人,而迁徙之徒也;才能不及中人,非有仲尼、墨翟之贤,陶朱、猗顿之富;蹑足行伍之间,而倔起阡陌之中,率疲弊之卒,将数百之众,转而攻秦;斩木为兵,揭竿为旗,天下云集响应,赢粮而景从。
山东豪俊遂并起而亡秦族矣。
且夫天下非小弱也,雍州之地,崤函之固,自若也。
陈涉之位,非尊于齐、楚、燕、赵、韩、魏、宋、卫、中山之君也;锄櫌棘矜,非铦于钩戟长铩也;谪戍之众,非抗于九国之师也;深谋远虑,行军用兵之道,非及乡时之士也。
然而成败异变,功业相反,何也?试使山东之国与陈涉度长絜大,比权量力,则不可同年而语矣。
然秦以区区之地,致万乘之势,序八州而朝同列,百有余年矣;然后以六合为家,崤函为宫;一夫作难而七庙隳,身死人手,为天下笑者,何也?仁义不施而攻守之势异也。
+ 选自《新书校注》卷一(中华书局2000年版)。个别字句依《史记》和萧统《文选》改。贾谊(前200—前168),洛阳(今属河南)人,西汉政论家、文学家。著有《新书》十卷。《过秦论》有上中下三篇,这里选的是上篇。过秦,意思是指斥秦的过失。
+ 〔秦孝公〕秦国的国君。他任用商鞅变法,富国强兵。下文的商君就是商鞅。
+ 〔崤(xiáo)函〕崤山和函谷关。崤山,在函谷关的东边。函谷关,在今河南灵宝。
+ 〔雍州〕在今陕西中部北部、甘肃、青海的东南部和宁夏一带。
+ 〔有席卷天下,包举宇内,囊括四海之意,并吞八荒之心〕意思是,(秦孝公)有统一天下的野心。席卷、包举、囊括,都有“并吞”的意思。宇内、四海、八荒,都是“天下”的意思。八荒,原指八方最边远的地方。
+ 〔连衡〕秦国采用的一种离间六国的策略,使它们各自同秦国联合,从而各个击破。也作“连横”。
+ 〔拱手〕两手合抱,形容毫不费力。
+ 〔西河〕战国时魏地。
+ 〔惠文、武、昭襄〕惠文王、武王、昭襄王。惠文王是孝公的儿子,武王是惠文王的儿子,昭襄王是武王的异母弟。
+ 〔蒙故业,因遗策〕继承已有的基业,沿袭前代的政策。蒙,继承。
+ 〔要害之郡〕(政治、经济、军事上都)非常重要的地区。
+ 〔弱〕削弱。
+ 〔爱〕吝惜。
+ 〔致〕招致,招引。
+ 〔合从(zòng)缔交,相与为一〕采用合纵的策略缔结盟约,互相援助,成为一体。
+ 〔齐有孟尝,赵有平原,楚有春申,魏有信陵〕孟尝君,田文,齐国贵族;平原君,赵胜,赵国贵族;春申君,黄歇,楚国贵族;信陵君,魏无忌,魏国贵族。他们是战国时有名的“四公子”,皆以招揽宾客著称。
+ 〔约从离衡〕相约为合纵,击破秦国的连衡策略。约,结。离,离散。
+ 〔甯(nìng)越、徐尚、苏秦、杜赫之属为之谋〕甯越、徐尚这些人为他们谋划。属,与下文的“徒”“伦”都是“类、辈”的意思,指某一类人。
+ 〔齐明、周最、陈轸(zhěn)、召(shào)滑、楼缓、翟景、苏厉、乐毅之徒通其意〕齐明、周最这些人沟通他们的意图。
+ 〔吴起、孙膑、带佗、倪良、王廖(liáo)、田忌、廉颇、赵奢之伦制其兵〕吴起、孙膑这些人统率他们的军队。制,统领、统率。
+ 〔叩关〕攻打函谷关。叩,攻打。
+ 〔延敌〕迎击敌人。
+ 〔九国〕就是上文的韩、魏、燕、楚、齐、赵、宋、卫、中山等国。
+ 〔逡(qūn)巡〕有所顾虑而徘徊不敢前进。
+ 〔镞〕箭头。
+ 〔制其弊〕利用他们的弱点制服他们。弊,弱点。
+ 〔追亡逐北〕追逐败逃的军队。北,败逃,这里指败逃的军队。
+ 〔橹〕大盾牌。
+ 〔孝文王、庄襄王〕孝文王,昭襄王的儿子,在位三天死去。庄襄王,孝文王的儿子,在位三年。
+ 〔奋六世之余烈〕奋力发展六世遗留下来的功业。奋,振兴。六世,指孝公、惠文王、武王、昭襄王、孝文王、庄襄王。
+ 〔振长策而御宇内〕意思是用武力来统治各国。振,举起。策,马鞭子。御,驾驭、统治。
+ 〔二周〕在东周王朝最后在位的周赧(nǎn)王时,东西周分治。西周都于河南东部旧王城,东周则都巩,史称“东西二周”。二周灭于秦始皇继位前,作者只是为了行文方便,才这样写的。
+ 〔履至尊而制六合〕登上皇帝的宝座控制天下。至尊,至高无上的地位,指帝位。六合,天地四方。
+ 〔执敲扑而鞭笞天下〕用严酷的刑罚来奴役天下的百姓。敲扑,行刑用的棍杖,短的叫“敲”,长的叫“扑”。
+ 〔百越〕古代越族居住在桂、浙、闽、粤等地,每个部落都有名称,统称“百越”。也叫“百粤”。
+ 〔以为桂林、象郡〕设置了桂林郡、象郡(在今广西一带)。
+ 〔俯首系颈〕意思是愿意降服。系颈,颈上系绳,表示投降。
+ 〔委命下吏〕(百越之君)把自己的性命交给狱官。下吏,下级官吏,这里指狱官。
+ 〔蒙恬〕秦将领。秦始皇时领兵三十万北逐匈奴,修筑长城。
+ 〔藩篱〕比喻边疆上的屏障。藩,篱笆。
+ 〔却〕使退却。
+ 〔百家之言〕各学派的著作。
+ 〔黔首〕秦朝对百姓的称呼。黔,黑色。秦朝百姓用黑色头巾包头,故称“黔首”。
+ 〔隳(huī)〕毁坏。
+ 〔销锋镝(dí)〕销毁兵器。锋,兵刃。镝,箭头。
+ 〔践华为城,因河为池〕意思是,据守华山作为帝都城墙,凭借黄河作为帝都的护城河。践,踏。
+ 〔亿丈之城〕指华山。
+ 〔不测之渊〕指黄河。
+ 〔信臣〕可靠的大臣。
+ 〔谁何〕盘诘查问。
+ 〔金城〕坚固的城池。金,比喻坚固。
+ 〔殊俗〕不同的风俗,指边远的地方。
+ 〔瓮牖(yǒu)绳枢〕用瓮做窗户,用草绳系门扇,形容家里穷。牖,窗户。枢,门扇开关的枢轴。
+ 〔氓(méng)隶〕指下层百姓。氓,民。隶,低贱的人。
+ 〔迁徙之徒〕被征发的人。指陈涉被征发戍守渔阳。
+ 〔中人〕平常的人。
+ 〔陶朱、猗(yī)顿〕陶朱,就是春秋时期越国的范蠡(lǐ)。他帮助越王勾践灭吴后,离开越国到陶(今山东定陶西北),自称“陶朱公”。他因善于做生意而致富,所以后人常以“陶朱”为富人的代称。猗顿,春秋时鲁国人。他向陶朱公学致富之术,大畜牛羊于猗氏(今山西临猗)南部,积累了很多财物。
+ 〔蹑足〕置身,参与。
+ 〔倔起〕兴起。
+ 〔揭〕举。
+ 〔赢粮而景从〕(许多人)担着粮食如影随形地跟着(陈涉)。赢,担负。景,同“影”。
+ 〔山东〕崤山以东,代指东方诸国。
+ 〔自若〕意思是像是原来的样子。
+ 〔锄櫌(yōu)棘矜(qín),非铦(xiān)于钩戟长铩(shā)也〕农具木棍不如钩戟长矛锋利。櫌,同“耰”,碎土平田用的农具。棘矜,用酸枣木做的棍子。棘,酸枣木。这里的意思是农民军的武器,只有农具和木棍。铦,锋利。钩戟,带钩的戟。长铩,长矛。
+ 〔谪戍〕因有罪而被征调去守边。
+ 〔抗〕匹敌,相当。
+ 〔乡时〕先前。乡,同“向”。
+ 〔度(duó)长絜(xié)大〕量量长短,比比大小。絜,衡量。
+ 〔万乘〕兵车万辆。表示军事力量强大。
+ 〔序八州而朝同列〕统理八州,使六国诸侯都来朝见。序,安置使有序。八州,兖州、冀州、青州、徐州、豫州、荆州、扬州、梁州。古时天下分九州,秦居雍州,六国分居其他八州。同列,指六国诸侯。秦与六国本来是同列诸侯。
+ 〔一夫作难(nàn)〕指陈涉起义。作难,起事。
+ 〔七庙隳〕宗庙毁灭,就是国家灭亡的意思。七庙,古代天子的宗庙。
+ 〔身死人手〕指秦王子婴为项羽所杀。
+ 〔攻守之势异也〕攻和守的形势不同了。攻,指秦兼并六国时处于攻势。守,指秦统一天下后处于守势。
== 五代史伶官传序 欧阳修
呜呼!盛衰之理,虽曰天命,岂非人事哉!原庄宗之所以得天下,与其所以失之者,可以知之矣。
世言晋王之将终也,以三矢赐庄宗而告之曰:“梁,吾仇也;燕王吾所立,契丹与吾约为兄弟,而皆背晋以归梁。
此三者,吾遗恨也。
与尔三矢,尔其无忘乃父之志!”庄宗受而藏之于庙。
其后用兵,则遣从事以一少牢告庙,请其矢,盛以锦囊,负而前驱,及凯旋而纳之。
方其系燕父子以组,函梁君臣之首,入于太庙,还矢先王,而告以成功,其意气之盛,可谓壮哉!及仇雠已灭,天下已定,一夫夜呼,乱者四应,仓皇东出,未及见贼而士卒离散,君臣相顾,不知所归,至于誓天断发,泣下沾襟,何其衰也!岂得之难而失之易欤?抑本其成败之迹,而皆自于人欤?《书》曰:“满招损,谦得益。
”忧劳可以兴国,逸豫可以亡身,自然之理也。
故方其盛也,举天下之豪杰,莫能与之争;及其衰也,数十伶人困之,而身死国灭,为天下笑。
夫祸患常积于忽微,而智勇多困于所溺,岂独伶人也哉?
+ 〔万乘〕兵车万辆。表示军事力量强大。
+ 〔序八州而朝同列〕统理八州,使六国诸侯都来朝见。序,安置使有序。八州,兖州、冀州、青州、徐州、豫州、荆州、扬州、梁州。古时天下分九州,秦居雍州,六国分居其他八州。同列,指六国诸侯。秦与六国本来是同列诸侯。
+ 〔一夫作难(nàn)〕指陈涉起义。作难,起事。
+ 〔七庙隳〕宗庙毁灭,就是国家灭亡的意思。七庙,古代天子的宗庙。
+ 〔身死人手〕指秦王子婴为项羽所杀。
+ 〔攻守之势异也〕攻和守的形势不同了。攻,指秦兼并六国时处于攻势。守,指秦统一天下后处于守势。
+ 选自《新五代史·伶官传》(中华书局2000年版)。《新五代史》是二十四史之一,记载907年至960年间后梁、后唐、后晋、后汉、后周五代的历史。本文是《新五代史·伶官传》开头的短序。古称演戏的人为伶,在宫廷中授有官职的伶人叫作伶官。
+ 〔人事〕人的作为。
+ 〔原〕推其根本。
+ 〔庄宗〕后唐庄宗李存勖(885—926),五代后唐王朝的建立者,923年至926年在位。
+ 〔晋王〕李存勖之父李克用,沙陀部人(他的父亲姓朱邪,名赤心,有功于唐朝,赐姓名为李国昌),因出兵帮助唐朝镇压黄巢起义,受封为晋王。
+ 〔梁,吾仇也〕梁王朱温是我的仇敌。梁,黄巢部将朱温,投降唐朝,赐名全忠,受封为梁王。唐僖宗时,他设计谋杀李克用,李克用也屡次上表请求讨伐他。李克用曾长期与朱温交战。
+ 〔燕王吾所立〕刘仁恭本来是幽州将领,借李克用的势力夺取幽州,任卢龙节度使。后来刘仁恭归附朱温,他的儿子刘守光开始称燕王,后来称帝。这里称刘仁恭为燕王,是笼统的说法。
+ 〔契丹与吾约为兄弟〕李克用和契丹首领耶律阿保机订立盟约,结为兄弟,希望共同举兵攻打朱温。后来阿保机背盟,派人和朱温通好。
+ 〔其〕副词,表示祈使语气。
+ 〔从事〕官名,这里泛指一般属官。
+ 〔一少牢〕羊、猪各一头。古代祭祀用牛、羊、猪各一头叫“太牢”,用羊、猪各一头叫“少牢”。牢,祭祀用的牲畜。
+ 〔告庙〕天子或诸侯遇出巡、战争等重大事件而祭告祖庙。
+ 〔请其矢〕恭敬地取出他父亲(留下)的箭。请,敬辞,用以代替某些动词,表示恭敬、慎重。
+ 〔纳之〕把箭收藏(在祖庙里)。
+ 〔系燕父子以组〕用绳索捆绑着刘仁恭、刘守光父子。911年,刘守光自称大燕皇帝。913年,李存勖派兵攻破幽州,俘获刘仁恭及其族人;刘守光逃到沧州,仍被捕获。父子都被处死。系,缚。组,丝带、丝绳,这里泛指绳索。
+ 〔函梁君臣之首〕用木匣子装着后梁皇帝、大臣的头。923年,后唐军队攻入开封。后梁末帝朱友贞命令部将皇甫麟杀死自己。皇甫麟杀了末帝,随后自杀。函,匣子,这里用作动词,用匣子装。
+ 〔仇雠(chóu)〕仇人。雠,与“仇”同义。
+ 〔一夫夜呼,乱者四应〕一个人夜里呼喊,作乱的人四方响应。926年,屯驻在贝州(今河北清河)的后唐军士皇甫晖勾结党羽作乱,拥立指挥使赵在礼为帅,攻入邺都(今河南安阳)。邢州(今河北邢台)、沧州(今属河北)驻军相继叛乱。
+ 〔仓皇东出……泣下沾襟〕皇甫晖作乱以后,李存勖从洛阳往东逃,到了万胜镇(在今河南中牟),听说李嗣源(李克用养子,当时已叛变)已经占据大梁(今河南开封),只好命令军队返回。一路上士兵叛逃,失散了一半。至洛阳附近,置酒痛哭。诸将一百多人相对号泣,都截断头发,放在地上,表示誓死以报。
+ 〔抑〕或者,还是。
+ 〔本〕考察,探究。
+ 〔皆自于人欤〕都出自人的原因吗?
+ 〔满招损,谦得益〕语出《尚书·大禹谟》。原句是“满招损,谦受益”。
+ 〔逸豫〕安乐。指李存勖喜好音律,宠用伶人,以至自傅粉墨,与伶人共戏于庭。
+ 〔举〕全,整个。
+ 〔数十伶人困之〕伶人郭从谦趁李嗣源攻占大梁,李存勖众叛亲离之际,起兵作乱。李存勖率兵抵御,被乱箭射死。
+ 〔国灭〕李存勖死后,李嗣源即位(即后唐明宗),群臣中有人劝他自建国号,此事虽未实行,但是庄宗死后,李克用嫡亲子孙都被杀,也可以说是“国灭”。
+ 〔忽微〕极小的事。忽,一寸的十万分之一。微,一寸的百万分之一。
+ 〔所溺〕所溺爱的人或物。溺,沉湎、无节制。
#pagebreak()
= 选必下 |
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/styleMenlive.typ | typst | #import "/style.typ": *
#import "/utilsMenlive.typ": *
#let hlasVecieren(day, dayidx, h_st, s_st, t) = {
let c = counter("day")
let n = 10
if dayidx == 100 {
n = 4
} else if dayidx != 0 {
n = 6
}
if "HV" in day {
[==== #t("HOSPODI_VOZVACH") <X>]
let (..verse, last) = day.at("HV")
c.update(n)
let h = h_st.map(it => make3(it)).slice(-1*n)
let z = verse.zip(h)
if dayidx != 100 {
z = z.slice(0,n - 3)
}
let tbl = {
z.map(k => (
[], makeGray(k.at(1)),
primText[#c.display("1:"); #c.update(c => c - 1)], k.at(0),
)
)
}
if dayidx != 100 {
tbl.push(tblNote(t, "HV_MINEA"))
tbl.push(tblNote(t, "HV_NOTE"))
}
tbl.push((primText[S:I:], last))
styleTable3(tbl)
}
if "S" in day {
[==== #t("STICHOVNI") <X>]
let (first, ..verse, last) = day.at("S")
c.update(2)
let stichy = ()
if (str(dayidx) in s_st) {
stichy = s_st.at(str(dayidx)).map(it => make3(it))
} else {
stichy = s_st.at("x").map(it => make3(it))
}
// let s = stichy.slice(-1*(verse.len()))
let z = verse.zip(stichy)
let tbl = {
z.map(k => (
[], makeGray(k.at(1)),
primText[#c.display("i:"); #c.step()], k.at(0),
)
)
}
c.update(1)
tbl.insert(0, (primText[#c.display("i:"); #c.step()], first))
tbl.push((primText[S:I:], last))
styleTable3(tbl)
}
if "T" in day {
[==== #t("TROPAR") <X>]
let (tropar, last) = day.at("T")
let tbl = (
(primText[$#sym.TT$], tropar),
(primText[$#sym.BB$], last)
)
styleTable3(tbl)
}
}
#let hlasPovecerie(day, p_st, t) = {
for k in range(1,10) {
if str(k) in day {
let c = counter("kanon-vers")
c.update(1)
[===== #t("PIESEN") #k <X>]
let (irmos, ..verse, semilast, last) = day.at(str(k))
let tbl = {
verse.map(k => (
primText[#c.display("i:"); #c.step()], k
)
)
}
tbl.insert(0,(primText[$#sym.II$], irmos))
tbl.insert(1,(primText[$#sym.rho$], makeGray(make3(p_st))))
tbl.push((primText[S:], semilast))
tbl.push((primText[I:], last))
styleTable3(tbl)
if k == 6 {
[===== #t("SIDALEN") <X>]
[
#set par(first-line-indent: 1em)
#styleOne(day.at("S").at(0))
]
}
}
}
}
#let hlasPolnocnica(day, n_st, t) = {
for k in range(1,10) {
if str(k) in day {
let c = counter("kanon-vers")
c.update(1)
[===== #t("PIESEN") #k <X>]
let (irmos, ..verse, semilast, last) = day.at(str(k))
let tbl = {
verse.map(k => (
primText[#c.display("i:"); #c.step()], k
)
)
}
tbl.insert(0,(primText[$#sym.II$], irmos))
tbl.insert(1,(primText[$#sym.rho$], makeGray(make3(n_st))))
tbl.push((primText[S:], semilast))
tbl.push((primText[I:], last))
styleTable3(tbl)
if k == 3 {
[===== #t("SIDALEN") <X>]
let sdl = ()
sdl.push((primText[$#sym.SS$], day.at("S1").at(0)))
sdl.push((primText[S:I:], day.at("S1").at(1)))
styleTable3(sdl)
}
if k == 6 {
[===== #t("SIDALEN") <X>]
let sdl = ()
sdl.push((primText[$#sym.SS$], day.at("S2").at(0)))
sdl.push((primText[S:I:], day.at("S2").at(1)))
styleTable3(sdl)
}
}
}
}
#let pripiv(pripivy, day, kanon, stich) = {
pripivy.at(str(day)).at(int(kanon)-1)
}
#let kanonUtieren(kanon, dayIdx, typs, pripivy, t) = {
// FIXME: think about and fix headers
// let typ = typs.at(str(dayIdx))
// if "?" in kanon {
// // TODO: check and translate all cannons
// typ = kanon.at("?")
// }
for k in range(1,10) {
let kk = "P"+str(k)
if kk in kanon {
[===== #t("PIESEN") #k <X>]
let piesen = kanon.at(kk)
for i in range(1, 4) {
if str(i) in piesen {
let c = counter("kanon-vers")
c.update(1)
let y = piesen.at(str(i))
let tbl = ()
if dayIdx == 6 {
let (irmos, ..verse, semilast, last) = y
tbl = {
verse.map(k => (
primText[#c.display("i:"); #c.step()], k
)
)
}
if (irmos.at(2).len() > 0) {
tbl.insert(0,(primText[$#sym.II _#i$], irmos))
}
tbl.push((primText[S:], semilast))
tbl.push((primText[I:], last))
} else if dayIdx in (0,3,5) {
let (irmos, ..verse) = y
tbl = {
verse.map(k => (
primText[#c.display("i:"); #c.step()], k
)
)
}
if (irmos.at(2).len() > 0) {
tbl.insert(0,(primText[$#sym.II _#i$], irmos))
}
} else {
let (irmos, ..verse, last) = y
tbl = {
verse.map(k => (
primText[#c.display("i:"); #c.step()], k
)
)
}
if (irmos.at(2).len() > 0) {
tbl.insert(0,(primText[$#sym.II _#i$], irmos))
}
tbl.push((primText[S:I:], last))
}
// TODO: pridat pripivy
if dayIdx == 0 {
let p = pripiv(pripivy, dayIdx, i, 0)
tbl.insert(1,(primText[$#sym.rho$], makeGray(make3(p))))
}
// if typ != none {
// tbl.insert(0, ("", makeSec(make3(typ.at(i - 1)))))
// }
styleTable3(tbl)
}
}
if k == 6 and "K" in kanon {
[===== #t("KONDAK_IKOS") <X>]
let (kon, ikos) = kanon.at("K")
let tbl = ()
tbl.push((primText[$#sym.KK$], kon))
tbl.push((primText[$#sym.II #sym.KK$], ikos))
styleTable3(tbl)
}
}
}
}
#let hlasUtieren(day, dayIdx, typs, pripivy, sd_st, ch_st, su_st, t) = {
let c = counter("day")
if "T" in day {
[==== #t("TROPAR") <X>]
let (tropar, bohorodicen) = day.at("T")
let tbl = ()
tbl.push((primText[$#sym.TT$], tropar))
tbl.push(tblNote(t, "T_NOTE"))
tbl.push((primText[$#sym.BB$], bohorodicen))
styleTable3(tbl)
}
[==== #t("SIDALENY") <X>]
for i in range(1,4) {
let s = "S"+str(i)
if s in day {
// TODO: fix
[===== #t("SIDALEN_PO") #i <X>]
c.update(1)
let (..verse, last) = day.at(s)
let tbl = {
verse.map(k => (
primText[#c.display("i:"); #c.step()], k
)
)
}
if dayIdx == 0 {
if i == 1 {
tbl.insert(1, ([],makeGray(make3(sd_st.at(0)))))
} else if i == 2 {
tbl.insert(1, ([],makeGray(make3(sd_st.at(1)))))
}
}
tbl.push((primText[S:I:], last))
styleTable3(tbl)
}
}
if "Y" in day {
[==== #t("YPAKOJ") <X>]
let k = day.at("Y").at(0)
styleOne(k)
}
// CU & GR difference
if "A1" in day {
[==== #t("STEPENNY") <X>]
for i in range(1,5) {
let a = "A"+str(i)
if a in day {
[===== #t("ANTIFON") #i <X>]
c.update(1)
// let (..verse, semilast, last) = day.at(a)
let (..verse, last) = day.at(a)
let tbl = {
verse.map(k => (
primText[#c.display("i:"); #c.step()], k
)
)
}
// tbl.push((primText[S:], semilast))
// tbl.push((primText[I:], last))
tbl.push((primText[S:I:], last))
styleTable3(tbl)
}
}
}
if "P" in day {
[==== #t("PROKIMEN") <X>]
let (prokimen, versv) = day.at("P")
[
#set par(first-line-indent: 1em)
#prokimen.at(2)
#primText[#t("STICH"):] #versv.at(2)
]
}
if "K" in day {
[==== #t("KANON") <X>]
let kanon = day.at("K")
kanonUtieren(kanon, dayIdx, typs, pripivy, t)
}
if "CH" in day {
[==== #t("CHVALITE") <X>]
let tbl = {}
if dayIdx == 0 {
/* NEDELA */
let (..verse) = day.at("CH")
let b = ch_st.map(x=>make3(x)).slice(-1*(verse.len()))
let z = verse.zip(b)
c.update(verse.len())
tbl = {
z.map(k => (
[], makeGray(k.at(1)),
primText[#c.display("1:"); #c.update(c => c - 1)], k.at(0),
)
)
}
styleTable3(tbl)
} else {
/* TYZDEN */
let (..verse, last) = day.at("CH")
let b = ch_st.map(x=>make3(x)).slice(-1*(verse.len()+2),-2)
let z = verse.zip(b)
c.update(verse.len())
tbl = {
z.map(k => (
[], makeGray(k.at(1)),
primText[#c.display("1:"); #c.update(c => c - 1)], k.at(0),
)
)
}
tbl.push((primText[S:I:], last))
styleTable3(tbl)
}
}
if "ST" in day {
[==== #t("STICHOVNI") <X>]
let (first, ..verse, last) = day.at("ST")
let s = ()
if str(dayIdx) in su_st {
s = su_st.at(str(dayIdx)).map(x=>make3(x))
} else {
s = su_st.at("x").map(x=>make3(x))
}
let stichy = s.slice(-1*(verse.len()))
c.update(1)
let z = verse.zip(stichy)
let tbl = {
z.map(k => (
[], makeGray(k.at(1)),
primText[#c.display("i:"); #c.step()], k.at(0),
)
)
}
tbl.insert(0, (primText[#c.display("i:"); #c.step()], first))
tbl.push((primText[S:I:], last))
styleTable3(tbl)
}
}
#let hlasLiturgia(day, b_st, t) = {
if "B" in day {
[==== #t("BLAZENNA") <X>]
let c = counter("day")
let (..verse, semilast, last) = day.at("B")
c.update(verse.len())
let b = b_st.map(x=>make3(x)).slice(-1*(verse.len()))
let z = verse.zip(b)
let tbl = {
z.map(k =>
if k.at(1).at(2) == "" {(
primText[#c.display("1:"); #c.update(c => c - 1)], k.at(0)
)} else {(
[], makeGray(k.at(1)),
primText[#c.display("1:"); #c.update(c => c - 1)], k.at(0),
)}
)
}
tbl.push((primText[S:], semilast))
tbl.push((primText[I:], last))
styleTable3(tbl)
}
if "TKB" in day {
[==== #t("TROPAR_KONDAK") <X>]
let (t,k,b) = day.at("TKB")
let tbl = ()
tbl.push((primText[$#sym.TT$], t))
tbl.push((primText[$#sym.KK$], k))
tbl.push((primText[$#sym.BB$], b))
styleTable3(tbl)
}
if "P" in day {
let (prokimen, vers, aleluja, versA) = day.at("P")
[==== #t("PROKIMEN") <X>]
[
#set par(first-line-indent: 1em)
#prokimen.at(2)
#primText[#t("STICH"):] #vers.at(2)
]
[===== #t("ALLILUJA") <X>]
[
#set par(first-line-indent: 1em)
#aleluja.at(2)
#primText[#t("STICH"):] #versA.at(2)
]
}
}
#let hlas_all(ne_m, ne_v, ne_p, ne_n, ne_u, ne_l,
po_v, po_p, po_u, po_l,
ut_v, ut_p, ut_u, ut_l,
sr_v, sr_p, sr_u, sr_l,
st_v, st_p, st_u, st_l,
pi_v, pi_p, pi_u, pi_l,
so_v, so_p, so_u, so_l,
h_st, s_st, p_st, n_st,
typs, pripivy,
sd_st, ch_st, su_st, b_st,
t, use) = [
#show: rest => columns(2, rest)
== #t("Ne")
#if (use.at(0)) [
=== #t("M")
#header[(#t("So_V"))]
#hlasVecieren(ne_m, 100, h_st, s_st, t)
#colbreak(weak: true)
]
#if use.at(1) [
=== #t("V")
#header[(#t("So_V"))]
#hlasVecieren(ne_v, 0, h_st, s_st, t)
#colbreak(weak: true)
]
#if use.at(2) [
=== #t("P")
#header[(#t("So_N"))]
#hlasPovecerie(ne_p, p_st, t)
#colbreak(weak: true)
]
#if use.at(3) [
=== #t("N")
#hlasPolnocnica(ne_n, n_st, t)
#colbreak(weak: true)
]
#if use.at(4) [
=== #t("U")
#hlasUtieren(ne_u, 0, typs, pripivy, sd_st, ch_st, su_st, t)
#colbreak(weak: true)
]
#if use.at(5) [
=== #t("L")
#header[(#t("I"))]
#hlasLiturgia(ne_l, b_st, t)
#colbreak(weak: true)
]
== #t("Po")
#if use.at(1) [
=== #t("V")
#header[(#t("Ne_V"))]
#hlasVecieren(po_v, 1, h_st, s_st, t)
#colbreak(weak: true)
]
#if use.at(2) [
=== #t("P")
#header[(#t("Ne_N"))]
#hlasPovecerie(po_p, p_st, t)
#colbreak(weak: true)
]
#if use.at(4) [
=== #t("U")
#hlasUtieren(po_u, 1, typs, pripivy, sd_st, ch_st, su_st, t)
#colbreak(weak: true)
]
#if use.at(5) [
=== #t("L")
#header[(#t("I"))]
#hlasLiturgia(po_l, b_st, t)
#colbreak(weak: true)
]
== #t("Ut")
#if use.at(1) [
=== #t("V")
#header[(#t("Po_V"))]
#hlasVecieren(ut_v, 2, h_st, s_st, t)
#colbreak(weak: true)
]
#if use.at(2) [
=== #t("P")
#header[(#t("Po_N"))]
#hlasPovecerie(ut_p, p_st, t)
#colbreak(weak: true)
]
#if use.at(4) [
=== #t("U")
#hlasUtieren(ut_u, 2, typs, pripivy, sd_st, ch_st, su_st, t)
#colbreak(weak: true)
]
#if use.at(5) [
=== #t("L")
#header[(#t("I"))]
#hlasLiturgia(ut_l, b_st, t)
#colbreak(weak: true)
]
== #t("Sr")
#if use.at(1) [
=== #t("V")
#header[(#t("Ut_V"))]
#hlasVecieren(sr_v, 3, h_st, s_st, t)
#colbreak(weak: true)
]
#if use.at(2) [
=== #t("P")
#header[(#t("Ut_N"))]
#hlasPovecerie(sr_p, p_st, t)
#colbreak(weak: true)
]
#if use.at(4) [
=== #t("U")
#hlasUtieren(sr_u, 3, typs, pripivy, sd_st, ch_st, su_st, t)
#colbreak(weak: true)
]
#if use.at(5) [
=== #t("L")
#header[(#t("I"))]
#hlasLiturgia(sr_l, b_st, t)
#colbreak(weak: true)
]
== #t("St")
#if use.at(1) [
=== #t("V")
#header[(#t("Sr_V"))]
#hlasVecieren(st_v, 4, h_st, s_st, t)
#colbreak(weak: true)
]
#if use.at(2) [
=== #t("P")
#header[(#t("Sr_N"))]
#hlasPovecerie(st_p, p_st, t)
#colbreak(weak: true)
]
#if use.at(4) [
=== #t("U")
#hlasUtieren(st_u, 4, typs, pripivy, sd_st, ch_st, su_st, t)
#colbreak(weak: true)
]
#if use.at(5) [
=== #t("L")
#header[(#t("I"))]
#hlasLiturgia(st_l, b_st, t)
#colbreak(weak: true)
]
== #t("Pi")
#if use.at(1) [
=== #t("V")
#header[(#t("St_V"))]
#hlasVecieren(pi_v, 5, h_st, s_st, t)
#colbreak(weak: true)
]
#if use.at(2) [
=== #t("P")
#header[(#t("St_N"))]
#hlasPovecerie(pi_p, p_st, t)
#colbreak(weak: true)
]
#if use.at(4) [
=== #t("U")
#hlasUtieren(pi_u, 5, typs, pripivy, sd_st, ch_st, su_st, t)
#colbreak(weak: true)
]
#if use.at(5) [
=== #t("L")
#header[(#t("I"))]
#hlasLiturgia(pi_l, b_st, t)
#colbreak(weak: true)
]
== #t("So")
#if use.at(1) [
=== #t("V")
#header[(#t("Pi_V"))]
#hlasVecieren(so_v, 6, h_st, s_st, t)
#colbreak(weak: true)
]
#if use.at(2) [
=== #t("P")
#header[(#t("Pi_N"))]
#hlasPovecerie(so_p, p_st, t)
#colbreak(weak: true)
]
#if use.at(4) [
=== #t("U")
#hlasUtieren(so_u, 6, typs, pripivy, sd_st, ch_st, su_st, t)
#colbreak(weak: true)
]
#if use.at(5) [
=== #t("L")
#header[(#t("I"))]
#hlasLiturgia(so_l, b_st, t)
#colbreak(weak: true)
]
] |
|
https://github.com/hesampakdaman/resume | https://raw.githubusercontent.com/hesampakdaman/resume/main/resume.typ | typst | MIT License | #import "class.typ": template, skill_entry, experience_entry
#let contact_data = (
(
"service": "github",
"display": "hesampakdaman",
"link": "https://github.com/hesampakdaman"
),
)
#show: doc => template("<NAME>", contact_data, black, doc)
#align(center)[
#skill_entry("Programming languages",
(
"Go",
"Python",
"Lisp",
"Rust",
)
)
]
= Experience
#experience_entry(
logo_path: "./logo/einride.png",
logo_size: 0.85cm,
company: "Einride",
role: "Software Engineer",
start_date: "Aug 2024",
description: "Einride is a leader in autonomous and electric transport, focusing on sustainable and efficient logistics solutions. The company pioneers innovative technology to reduce" + $"CO"_2$ + " emissions and enhance freight mobility, aiming to create a more sustainable future for road freight.",
)
#experience_entry(
logo_path: "./logo/hm.png",
logo_size: 0.85cm,
company: "H&M Group",
role: "Software Engineer",
start_date: "Mar 2023",
end_date: "June 2024",
description: "I developed the e-commerce platform Creator Studio, a venture within global fashion company H&M, for designing, ordering, and selling custom print-on-demand merchandise globally with an emphasis on minimal environmental impact.",
skills: (
"K8s",
"Kafka",
"MongoDB",
"PostgreSQL",
)
)
#experience_entry(
logo_path: "./logo/budbee.png",
company: "Budbee",
role: "Machine Learning Engineer",
start_date: "Apr 2022",
end_date: "Feb 2023",
description: "Budbee is a Swedish last-mile delivery company focusing on efficient deliveries for online shopping across Europe. I was part of the ML team, providing predictions and data insights to support various departments within the company.",
skills: (
"LightGBM",
"Metaflow",
"MySQL",
"PyTorch",
)
)
#experience_entry(
logo_path: "./logo/entecon.png",
company: "Entecon",
role: "Machine Learning Engineer",
start_date: "Feb 2021",
end_date: "Mar 2022",
description: "Entecon is a Swedish consultancy firm. I was contracted to work for Nielsen, a US-based company providing advanced video metadata solutions to leading media companies. My role was to assist the team responsible for video segmentation.",
skills: (
"Matplotlib",
"NumPy",
"Pandas",
"PyTorch",
)
)
#experience_entry(
logo_path: "./logo/ding.png",
company: smallcaps("ding"),
role: "Machine Learning Engineer",
start_date: "Jan 2018",
end_date: "Feb 2021",
description: "Hired at " + smallcaps("ding") + " as a consultant for Convini, a Swedish company providing workplace food solutions through self-service stations. I built a deep learning system using cameras mounted on fridges to detect products customers selected.",
skills: (
"CUDA",
"FLIR",
"NumPy",
"PyTorch"
)
)
= Education
#grid(
columns: (1.5cm, 1fr),
gutter: 0.5cm,
inset: (x: 30pt, y: 5pt),
grid.cell(
align: left,
image("./logo/kth.svg", width: 1.4cm)
),
grid.cell(
align: left,
[
*KTH Royal Institute of Technology* \
_Civilingenjör i Teknisk fysik_
- 2015―2018 MSc. Computer Science
- 2012―2015 BSc. Engineering Physics
]
),
)
\
#show link: underline
= Hobby projects
#link("https://github.com/hesampakdaman/rust_1brc")[*1 billion row challenge*].
This challenge involves processing one billion temperature
measurements to compute the minimum, mean, and maximum temperatures
per weather station. I implemented this in Rust, leveraging its
`std::sync::mpsc` and `std::thread` standard libraries for efficient,
parallel data handling and memory-mapped files for optimized I/O
performance and a customize hash function tailored for the dataset.
The project achieves high performance, processing the entire 13GB
input file using all available CPU cores. On an Apple M1 Pro it
processes the input file in $~2.75$s.
// \
// \
// #link("https://github.com/hesampakdaman/rustic_factors")[*Integer factorization*].
// In this project, I explored various number factorization algorithms.
// The aim was to learn more about Rust's advanced features such as
// generics, dynamic dispatch, and procedural macros while implementing
// design patterns like Strategy, Builder, and New Type. The project
// includes algorithms such as Miller-Rabin, Fermat's factorization
// method, Pollard's Rho, and trial division. A trait system was used to
// apply these strategies, and a test framework was developed using the
// Builder pattern to ensure robust and modular code.
|
https://github.com/WannesMalfait/vub-huisstijl-typst | https://raw.githubusercontent.com/WannesMalfait/vub-huisstijl-typst/main/template/main.typ | typst | MIT License | #import "@preview/stv-vub-huisstijl:0.1.0": vub-titlepage
// Adapt the default arguments to your needs.
#vub-titlepage(
title: "Title of the thesis",
subtitle: "An optional subtitle",
pretitle: "Graduation thesis submitted in partial fulfillment of the requirements for the degree of Master of Science in Mathematics",
authors: ("<NAME>",),
promotors: ("<NAME>",),
faculty: "Sciences and Bio-Engineering Sciences",
date: datetime.today().display("[month repr:long] [day], [year]"),
) |
https://github.com/MilanR312/ugent_typst_template | https://raw.githubusercontent.com/MilanR312/ugent_typst_template/main/template/methods/header.typ | typst | MIT License | #import "globals.typ": *
#let default_header(title, short_title) = context{
let titles_before = query(
heading.where(level: 1).before(here())
).rev().filter(x => state("body").at(x.location()) or state("appendix").at(x.location()))
let all_headings = query(
heading.where(level: 1)
).filter(x => state("body").at(x.location()) or state("appendix").at(x.location()))
let current_page = counter(page).at(here())
let is_on_same_page = false
for header in all_headings {
let page_of_header = counter(page).at(header.location())
if current_page == page_of_header{
is_on_same_page = true
}
}
let is_on_title_page = (is_on_same_page and state("init").get() == false) or titles_before.len() == 0
let is_in_body = state("body").get()
let is_in_appendix = state("appendix").get()
set text(size: default_fontsize)
if not is_on_title_page and (is_in_body or is_in_appendix){
let title = titles_before.first()
let current_page = counter(page).get().first()
let title_page = counter(page).at(title.location()).first()
let pagediff = (current_page - title_page)
if calc.even(pagediff) {
grid(
columns: (20%, 60%, 20%),
[], align(short_title, center), align(title.body, right)
)
} else {
let curr = query(selector(heading.where(level: 1)).before(here())).last()
let numb = numbering(curr.numbering, counter(curr.func()).at(curr.location()).first())
grid(
columns: (20%, 60%, 20%),
align(
[#curr.supplement #numb],
left
), align(short_title, center), []
)
}
line(length: 100%)
} else {
align(short_title, center)
align(line(length: 80%), center)
}
} |
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/os/lectures/2024-09-02.typ | typst | = Обзор. Введение
<NAME>
`<EMAIL>`
Оценка:
$ О_"теор" (О_"кр" + О_"экз") / 2 $
$ О_"итог" (2 * О_"практ" * О_"теор") / (О_"практ" + O_"теор") $
0 за $O_"теор"$ или $O_"практ"$ обнулит $O_"итог"$
== Структура вычислительной системы
- Пользователь (человек или устройство)
- Программное обеспечение
- Прикладные программы
- Системные программы
- Прочие системные программы
- Операционная система
- Техническое обеспечение
Границы между прикладным и системными программами условны
== Определение операционной системы. Основные точки зрения
- Распорядитель ресурсов
- Защитник (разграничитель) пользователей и программ
- Виртуальная машина (создание абстракций для работы с файлами, памятью и тд)
- "Кот в мешке"
- Постоянно функционирующее ядро (программа, которая поддерживает работу других программ)
- ...
== Эволюция вычислительных систем
Факторы отбора эволюции выч. систем:
- Удобство пользования
- Стоимость
- Производительность
Развитие hard- и software нужно рассматривать совокупно
Периоды развития:
=== 1-ый период (1945 -- 1955)
- Ламповые машины
- Огромные
- Часто перегорали
- Нет разделения персонала
- Ввод программы коммутацией или перфокартами
- Одновременное выполнение только одной операции (те только либо
программирование, либо расчеты, либо счет перфокарты и тд)
- Появление прообразов первых компиляторов
- Нет операционных систем
<NAME> имеет минимальное отношение к принципам <NAME>
ENIAC работал в 10-ой ссч
=== 2-ой период (1955 -- начало 60-ых)
- Полупроводниковые компьютеры
- Разделение персонала
- Бурное развитии алгоритмических языков
- Ввод задания колодой перфокарт
- Вывод результатов на печать
- Пакеты заданий и системы пакетной обработки (прообраз операционных систем)
Начало использования ЭВМ в коммерческих и исследовательских целях
=== 3-период (начало 60-ых -- 1980)
- Микросхемы, машины на интегральных схемах
- Машины меньше
- Сигнал идет быстрее, можно повысить тактовую частоту
- Считыватели и принтеры становятся bottleneck
- Использование спулинга (отдельные процессоры для ввода, вывода и счета)
- Планирование заданий (из-за создания магнитных дисков)
- Мультипрограммные пакетные системы
- Системы разделения времени (time-sharing)
Изменения из-за мультипрограммирования:
#figure(table(
columns: 2,
table.header("Software", "Hardware"),
[
- Планирование заданий
- Управление памятью
- Сохранение контекста
- Планирование использования процессора
- Системные вызовы
- Средства коммуникации между программами
- Средства синхронизации
],
[
- Защита памяти
- Сохранение контекста
- Механизм прерываний
- Привилегированные команды (в тч команды ввода/ вывода)
]
))
|
|
https://github.com/Thumuss/utpm | https://raw.githubusercontent.com/Thumuss/utpm/dev/README.md | markdown | MIT License | <div align="center">

> _Unofficial typst package manager_
**UTPM** is a _package manager_ for **[local](https://github.com/typst/packages#local-packages)** and **remote** packages. Create quickly new _projects_ and _templates_ from a **singular tool**, and then **publish** it _directly_ to **Typst**!
[](https://github.com/Thumuss/utpm "Go to GitHub repo")
[](https://github.com/Thumuss/utpm)
[](https://github.com/Thumuss/utpm)
<br/>
[](https://github.com/Thumuss/utpm/releases/)
[](#license)
[](https://github.com/Thumuss/utpm/issues)
</div>
## 🔥 Features
- [x] ✨ Create packages automatically (`utpm ws create`)
- [x] ⏯️ Interactive
- [x] ⌨️ CLI version
- [x] 🛠 Put your package directly into your local packages (`utpm ws link`)
- [x] 💻 Link without copying! (`utpm ws link --no-copy`)
- [x] 🌐 Dependencies outsite typst!
- [x] 📦 Install directly from the tool
- [x] 🔒 Portable installer (limited for now)
- [x] 📃 List all your packages
- [x] 🗃️ As a list `utpm pkg list`
- [x] 🌲 As a tree `utpm pkg tree`
- [ ] 💥 Customize your output (json or classic, `-j` in your commands)
- [x] 🗄️ Delete and bulk delete your packages (`utpm pkg unlink`, `utpm pkg bulk-delete`)
- [ ] 🚀 Publish it directly to Typst!
**_And many other features!_**
## 🔎 How to use it?
### The basic workflow
- _Firstly, you'll need to [create](#create) your `typst.toml` file!_
- _Then, edit your file! Like `index.typ` or `lib.typ`_
- _Finally, [link](#link) your new package to typst!_
### Commands
#### 🗄️ Bulk Delete
<!-- TODO: GIF -->
_A command to delete multiple packages at once!_

<div id="create">
#### ✨ Create
_Create a `typst.toml` to make a package_

<!-- TODO: GIF v2 -->
</div>
<div id="help">
#### ❓ Help
_Generate a help message_

</div>
<div id="install">
#### 📦 Install

<!-- TODO: GIF & text-->
</div>
<div id="link">
#### 🛠 Link

<!-- TODO: GIF & text-->
</div>
<div id="list">
#### 🗃️ List
<!-- TODO: text -->

</div>
<div id="package-path">
<!-- TODO: text -->
#### 🚦 Package Path

</div>
<div id="tree">
#### 🌲 Tree
_A simple command to show all packages installed in your local dir like a tree!_

</div>
<div id="unlink">
<!-- TODO: GIF -->
#### 🗄️ Unlink

</div>
## ⚡ Install
You will need Cargo and Rust.
The easiest way to install utpm using Cargo is:
```bash
$ cargo install --git https://github.com/Thumuss/utpm
```
## ❤️ Contribution
If you want to help me develop this package, simply make an issue or a PR!
By using this app, you contribute to it, thank you! <3
|
https://github.com/dantevi-other/kththesis-typst | https://raw.githubusercontent.com/dantevi-other/kththesis-typst/main/parts/4-outline.typ | typst | MIT License | //-- Configurations
#set page(
numbering: "i"
)
//-- Content
#outline(
indent: true
) |
https://github.com/minijackson/2024-04-hepix-nix | https://raw.githubusercontent.com/minijackson/2024-04-hepix-nix/master/README.md | markdown | # 2024-04 HEPiX Nix
Slides and demos of my HEPiX Spring 2024 presentation about Nix/NixOS.
## Demos
They're in the `demos` directory.
You will need Nix to run them.
To install Nix,
follow the [official instructions].
You will also need to [enable the flakes feature].
[official instructions]: https://nixos.org/download/#nix-install-linux
[enable the flakes feature]: https://wiki.nixos.org/wiki/Flakes#Other_Distros,_without_Home-Manager
## Build the slides
``` bash
nix develop -c typst compile main.typ main.pdf
```
|
|
https://github.com/gongke6642/tuling | https://raw.githubusercontent.com/gongke6642/tuling/main/Math/op.typ | typst | #set text(
size:10pt,
)
#set page(
paper:"a5",
margin:(x:1.8cm,y:1.5cm),
)
#set par(
justify: true,
leading: 0.52em,
)
= 文本运算符
等式中的文本运算符。
= 例
#image("49.png")
= 预定义运算符
Typst预定义运算符有arccos, arcsin, arctan, arg, cos, cosh, cot, coth, csc, csch, ctg, deg, det, dim, exp, gcd, hom, id, im, inf, ker, lg, lim, liminf, limsup, ln, log, max, min, mod, Pr, sec, sech, sin, sinc, sinh, sup, tan, tanh, tg and tr.
= 参数
#image("50.png")
= 文本
运算符的文本。
= 限制
操作员是否应在显示模式下将附件显示为限制。
默认:false |
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/065.%20investors.html.typ | typst | investors.html
How to Present to Investors
Want to start a startup? Get funded by
Y Combinator.
August 2006, rev. April 2007, September 2010In a few days it will be Demo Day, when the startups we funded
this summer present to investors. Y Combinator funds startups twice
a year, in January and June. Ten weeks later we invite all the
investors we know to hear them present what they've built so far.Ten weeks is not much time. The average startup probably doesn't
have much to show for itself after ten weeks. But the average
startup fails. When you look at the ones that went on to do great
things, you find a lot that began with someone pounding out a
prototype in a week or two of nonstop work. Startups are a
counterexample to the rule that haste makes waste.(Too much money seems to be as bad for startups as too much time,
so we don't give them much money either.)A week before Demo Day, we have a dress rehearsal called Rehearsal Day.
At other Y Combinator events we allow outside guests, but not at
Rehearsal Day. No one except the other founders gets to see the rehearsals.The presentations on Rehearsal Day are often pretty rough. But this is
to be expected. We try to pick founders who are good at building
things, not ones who are slick presenters. Some of the founders
are just out of college, or even still in it, and have never spoken
to a group of people they didn't already know.So we concentrate on the basics. On Demo Day each startup will
only get ten minutes, so we encourage them to focus on just two
goals: (a) explain what you're doing, and (b) explain why users
will want it.That might sound easy, but it's not when the speakers have no
experience presenting, and they're explaining technical matters to
an audience that's mostly non-technical.This situation is constantly repeated when startups present to
investors: people who are bad at explaining, talking to people who
are bad at understanding. Practically every successful startup,
including stars like Google, presented at some point to investors
who didn't get it and turned them down. Was it because the founders
were bad at presenting, or because the investors were obtuse? It's
probably always some of both.At the most recent Rehearsal Day, we four Y Combinator partners found
ourselves saying a lot of the same things we said at the last two.
So at dinner afterward we collected all our tips about presenting
to investors. Most startups face similar challenges, so we hope
these will be useful to a wider audience.
1. Explain what you're doing.Investors' main question when judging a very early startup is whether
you've made a compelling product. Before they can judge whether
you've built a good x, they have to understand what kind of x you've
built. They will get very frustrated if instead of telling them
what you do, you make them sit through some kind of preamble.Say what you're doing as soon as possible, preferably in the first
sentence. "We're Jeff and Bob and we've built an easy to use web-based
database. Now we'll show it to you and explain why people need
this."If you're a great public speaker you may be able to violate this
rule. Last year one founder spent the whole first half of his talk
on a fascinating analysis of the limits of the conventional desktop
metaphor. He got away with it, but unless you're a captivating
speaker, which most hackers aren't, it's better to play it safe.2. Get rapidly to demo.This section is now obsolete for YC founders presenting
at Demo Day, because Demo Day presentations are now so short
that they rarely include much if any demo. They seem to work
just as well without, however, which makes me think I was
wrong to emphasize demos so much before.A demo explains what you've made more effectively than any verbal
description. The only thing worth talking about first is the problem
you're trying to solve and why it's important. But don't spend
more than a tenth of your time on that. Then demo.When you demo, don't run through a catalog of features. Instead
start with the problem you're solving, and then show how your product
solves it. Show features in an order driven by some kind of purpose,
rather than the order in which they happen to appear on the screen.If you're demoing something web-based, assume that the network
connection will mysteriously die 30 seconds into your presentation,
and come prepared with a copy of the server software running on
your laptop.3. Better a narrow description than a vague one.One reason founders resist describing their projects concisely is
that, at this early stage, there are all kinds of possibilities.
The most concise descriptions seem misleadingly narrow. So for
example a group that has built an easy web-based database might
resist calling their applicaton that, because it could be so much
more. In fact, it could be anything...The problem is, as you approach (in the calculus sense) a description
of something that could be anything, the content of your description
approaches zero. If you describe your web-based database as "a
system to allow people to collaboratively leverage the value of
information," it will go in one investor ear and out the other.
They'll just discard that sentence as meaningless boilerplate, and
hope, with increasing impatience, that in the next sentence you'll
actually explain what you've made.Your primary goal is not to describe everything your system might
one day become, but simply to convince investors you're worth talking
to further. So approach this like an algorithm that gets the right
answer by successive approximations. Begin with a description
that's gripping but perhaps overly narrow, then flesh it out to the
extent you can. It's the same principle as incremental development:
start with a simple prototype, then add features, but at every point
have working code. In this case, "working code" means a working
description in the investor's head.4. Don't talk and drive.Have one person talk while another uses the computer. If the same
person does both, they'll inevitably mumble downwards at the computer
screen instead of talking clearly at the audience.As long as you're standing near the audience and looking at them,
politeness (and habit) compel them to pay attention to you. Once
you stop looking at them to fuss with something on your computer,
their minds drift off to the errands they have to run later.5. Don't talk about secondary matters at length.If you only have a few minutes, spend them explaining what your
product does and why it's great. Second order issues like competitors
or resumes should be single slides you go through quickly at the
end. If you have impressive resumes, just flash them on the screen
for 15 seconds and say a few words. For competitors, list the top
3 and explain in one sentence each what they lack
that you have. And put this kind of thing at the end, after you've
made it clear what you've built.6. Don't get too deeply into business models.It's good to talk about how you plan to make money, but mainly
because it shows you care about that and have thought about it.
Don't go into detail about your business model, because (a) that's
not what smart investors care about in a brief presentation, and
(b) any business model you have at this point is probably wrong
anyway.Recently a VC who came to speak at Y Combinator talked about a
company he just invested in. He said their business model was wrong
and would probably change three times before they got it right.
The founders were experienced guys who'd done startups before and
who'd just succeeded in getting millions from one of the top VC
firms, and even their business model was crap. (And yet he invested
anyway, because he expected it to be crap at this stage.)If you're solving an important problem, you're going to sound a lot
smarter talking about that than the business model. The business
model is just a bunch of guesses, and guesses about stuff that's
probably not your area of expertise. So don't spend your precious
few minutes talking about crap when you could be talking about
solid, interesting things you know a lot about: the problem you're
solving and what you've built so far.As well as being a bad use of time, if your business model seems
spectacularly wrong, that will push the stuff you want investors
to remember out of their heads. They'll just remember you as the
company with the boneheaded plan for making money, rather than the
company that solved that important problem.7. Talk slowly and clearly at the audience.Everyone at Rehearsal Day could see the difference between the people
who'd been out in the world for a while and had presented to groups,
and those who hadn't.You need to use a completely different voice and manner talking to
a roomful of people than you would in conversation. Everyday life
gives you no practice in this. If you can't already do it, the
best solution is to treat it as a consciously artificial trick,
like juggling.However, that doesn't mean you should talk like some kind of
announcer. Audiences tune that out. What you need to do is talk
in this artificial way, and yet make it seem conversational. (Writing
is the same. Good writing is an elaborate effort to seem spontaneous.)If you want to write out your whole presentation beforehand and
memorize it, that's ok. That has worked for some groups in the
past. But make sure to write something that sounds like spontaneous,
informal speech, and deliver it that way too.Err on the side of speaking slowly. At Rehearsal Day, one of the founders
mentioned a rule actors use: if you feel you're speaking too slowly,
you're speaking at about the right speed.8. Have one person talk.Startups often want to show that all the founders are equal partners.
This is a good instinct; investors dislike unbalanced teams. But
trying to show it by partitioning the presentation is going too
far. It's distracting. You can demonstrate your respect
for one another in more subtle ways. For example, when one of the
groups presented at Demo Day, the more extroverted of the two
founders did most of the talking, but he described his co-founder
as the best hacker he'd ever met, and you could tell he meant it.Pick the one or at most two best speakers, and have them do most
of the talking.Exception: If one of the founders is an expert in some specific
technical field, it can be good for them to talk about that for a
minute or so. This kind of "expert witness" can add credibility,
even if the audience doesn't understand all the details. If Jobs
and Wozniak had 10 minutes to present the Apple II, it might be a good plan
to have Jobs speak for 9 minutes and have Woz speak for a minute
in the middle about some of the technical feats he'd pulled off in
the design. (Though of course if it were actually those two, Jobs
would speak for the entire 10 minutes.)9. Seem confident.Between the brief time available and their lack of technical
background, many in the audience will have a hard time evaluating
what you're doing. Probably the single biggest piece of evidence,
initially, will be your own confidence in it. You have
to show you're impressed with what you've made.And I mean show, not tell. Never say "we're passionate" or "our
product is great." People just ignore that—or worse, write you
off as bullshitters. Such messages must be implicit.What you must not do is seem nervous and apologetic. If you've
truly made something good, you're doing investors a favor by
telling them about it. If you don't genuinely believe that, perhaps
you ought to change what your company is doing. If you don't believe
your startup has such promise that you'd be doing them a favor by
letting them invest, why are you investing your time in it?10. Don't try to seem more than you are.Don't worry if your company is just a few months old and doesn't
have an office yet, or your founders are technical people with no
business experience. Google was like that once, and they turned out
ok. Smart investors can see past such superficial flaws. They're
not looking for finished, smooth presentations. They're looking
for raw talent. All you need to convince them of is that you're
smart and that you're onto something good. If you try too hard to
conceal your rawness—by trying to seem corporate, or pretending
to know about stuff you don't—you may just conceal your talent.You can afford to be candid about what you haven't figured out yet.
Don't go out of your way to bring it up (e.g. by having a slide
about what might go wrong), but don't try to pretend either that
you're further along than you are. If you're a hacker and you're
presenting to experienced investors, they're probably better at
detecting bullshit than you are at producing it.11. Don't put too many words on slides.When there are a lot of words on a slide, people just skip reading
it. So look at your slides and ask of each word "could I cross
this out?" This includes gratuitous clip art. Try to get your
slides under 20 words if you can.Don't read your slides. They should be something in the background
as you face the audience and talk to them, not something you face
and read to an audience sitting behind you.Cluttered sites don't do well in demos, especially when they're
projected onto a screen. At the very least, crank up the font size
big enough to make all the text legible. But cluttered sites are
bad anyway, so perhaps you should use this opportunity to make your
design simpler.12. Specific numbers are good.If you have any kind of data, however preliminary, tell the audience.
Numbers stick in people's heads. If you can claim that the median
visitor generates 12 page views, that's great.But don't give them more than four or five numbers, and only give
them numbers specific to you. You don't need to tell them the size
of the market you're in. Who cares, really, if it's 500 million
or 5 billion a year? Talking about that is like an actor at the
beginning of his career telling his parents how much <NAME>
makes. Yeah, sure, but first you have to become <NAME>. The
important part is not whether he makes ten million a year or a
hundred, but how you get there.13. Tell stories about users.The biggest fear of investors looking at early stage startups is
that you've built something based on your own a priori theories of
what the world needs, but that no one will actually want. So it's
good if you can talk about problems specific users have and how you
solve them.<NAME> said one thing Sequoia looks for is the "proxy for
demand." What are people doing now, using inadequate tools, that
shows they need what you're making?Another sign of user need is when people pay a lot for something.
It's easy to convince investors there will be demand for
a cheaper alternative to something popular, if you preserve
the qualities that made it popular.The best stories about user needs are about your own. A remarkable
number of famous startups grew out of some need the founders had:
Apple, Microsoft, Yahoo, Google. Experienced investors know that,
so stories of this type will get their attention. The next best
thing is to talk about the needs of people you know personally,
like your friends or siblings.14. Make a soundbite stick in their heads.Professional investors hear a lot of pitches. After a while they
all blur together. The first cut is simply to be one of those
they remember. And the way to ensure that is to create a descriptive
phrase about yourself that sticks in their heads.In Hollywood, these phrases seem to be of the form "x meets y."
In the startup world, they're usually "the x of y" or "the x y."
Viaweb's was "the Microsoft Word of ecommerce."Find one and launch it clearly (but apparently casually) in your
talk, preferably near the beginning.It's a good exercise for you, too, to sit down and try to figure
out how to describe your startup in one compelling phrase. If you
can't, your plans may not be sufficiently focused.How to Fund a StartupHackers' Guide to InvestorsSpanish TranslationJapanese TranslationRussian Translation
Image: <NAME>: Trevor Blackwell at Rehearsal Day, summer 2006
|
|
https://github.com/MatheSchool/typst-g-exam | https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/src/auxiliary.typ | typst | MIT License | #import "./global.typ" : *
#let __g-student-data(
page: [], // first, odd, pair.
show-student-data: "first-page",
// show-student-data: (
// given-name: first-page,
// family-name: first-page,
// group: first-page,
// date: first-page
// ),
) = {
let family-label = [
#context __g-localization.final().family-name: #box(width: 2fr, repeat[.])
]
let give-label = [
#context __g-localization.final().given-name: #box(width:1fr, repeat[.])
]
let group-label = [
#context __g-localization.final().group: #box(width:2.5cm, repeat[.])
]
let date-label = [
#context __g-localization.final().date: #box(width:4cm, repeat[.])
]
if type(show-student-data) != "dictionary" {
if type(show-student-data) == "array" and page != "first" {
return
}
if show-student-data == false {
return
}
if show-student-data == "first-page" and page != "first" {
return
}
if show-student-data == "odd-pages" and not(page == "first" or page == "odd") {
return
}
}
else {
let family-name-value = show-student-data.at("family-name", default: "first-page")
let give-name-value = show-student-data.at("given-name", default: "first-page")
let group-value = show-student-data.at("group", default: "first-page")
let date-value = show-student-data.at("date", default: "first-page")
if family-name-value == false or (family-name-value == "first-page" and page != "first") or (family-name-value == "odd-pages" and not(page == "first" or page == "odd")) {
family-label =[]
}
if give-name-value == false or (give-name-value == "first-page" and page != "first") or (give-name-value == "odd-pages" and not(page == "first" or page == "odd")) {
give-label =[]
}
if group-value == false or (group-value == "first-page" and page != "first") or (group-value == "odd-pages" and not(page == "first" or page == "odd")) {
group-label =[]
}
if date-value == false or (date-value == "first-page" and page != "first") or (date-value == "odd-pages" and not(page == "first" or page == "odd")) {
date-label =[]
}
}
family-label
give-label
v(1pt)
align(right, {
group-label
date-label
}
)
}
#let __g-grade-table-header(decimal-separator: ".") = {
let end-g-question-locations = query(<end-g-question-localization>)
let columns-number = range(0, end-g-question-locations.len() + 1)
let question-row = columns-number.map(n => {
if n == 0 {align(left + horizon)[#text(hyphenate: false, context __g-localization.final().grade-table-queston)]}
else if n == end-g-question-locations.len() {align(left + horizon)[#text(hyphenate: false, context __g-localization.final().grade-table-total)]}
else [ #n ]
}
)
let total-point = 0
if end-g-question-locations.len() > 0 {
total-point = end-g-question-locations.map(ql => __g-question-point.at(ql.location())).sum()
}
let points = ()
if end-g-question-locations.len() > 0 {
points = end-g-question-locations.map(ql => __g-question-point.at(ql.location()))
}
let point-row = columns-number.map(n => {
if n == 0 {align(left + horizon)[#text(hyphenate: false, context __g-localization.final().grade-table-points)]}
else if n == end-g-question-locations.len() [
#strfmt("{0:}", calc.round(total-point, digits:2), fmt-decimal-separator: decimal-separator)
]
else {
let point = points.at(n)
[
#strfmt("{0}", calc.round(point, digits: 2), fmt-decimal-separator: decimal-separator)
]
}
}
)
let grade-row = columns-number.map(n =>
{
if n == 0 {
align(left + horizon)[#text(hyphenate: false, context __g-localization.final().grade-table-grade)]
}
}
)
align(center, table(
stroke: 0.8pt + luma(80),
columns: columns-number.map( n =>
{
if n == 0 {auto}
else if n == end-g-question-locations.len() {auto}
else {30pt}
}),
rows: (auto, auto, 30pt),
..question-row.map(n => n),
..point-row.map(n => n),
..grade-row.map(n => n),
)
)
}
#let __g-scholl-header = () => {
}
#let __g-show_clarifications = (clarifications: none) => {
if clarifications != none {
let clarifications-content = []
if type(clarifications) == "content" {
clarifications-content = clarifications
}
else if type(clarifications) == "string" {
clarifications-content = clarifications
}
else if type(clarifications) == "array" {
clarifications-content = [
#for clarification in clarifications [
- #clarification
]
]
}
else {
panic("Not implementation clarificationso of type: '" + type(clarifications) + "'")
}
rect(
width: 100%,
stroke: luma(120),
inset:8pt,
radius: 4pt,
clarifications-content
)
v(5pt)
}
}
#let __document-name = (
exam-info: (
academic-period: none,
academic-level: none,
academic-subject: none,
number: none,
content: none,
model: none
)) => {
let document-name = ""
if exam-info.at("name", default: none) != none { document-name += " " + exam-info.name }
if exam-info.at("content", default: none) != none { document-name += " " + exam-info.content }
if exam-info.at("number", default: none) != none { document-name += " " + exam-info.number }
if exam-info.at("model", default: none) != none { document-name += " " + exam-info.model }
return document-name
}
#let __read-localization = (
language: "en",
localization: (
grade-table-queston: none,
grade-table-total: none,
grade-table-points: none,
grade-table-grade: none,
point: none,
points: none,
page: none,
page-counter-display: none,
family-name: none,
given-name: none,
group: none,
date: none,
draft-label: none,
)) => {
let __lang_data = toml("./lang.toml")
if(__lang_data != none) {
let __read_lang_data = __lang_data.at(language, default: localization)
if(__read_lang_data != none) {
let __read-localization-value = (read_lang_data: none, field: "", localization: none) => {
let __parameter_value = localization.at(field, default: none)
if(__parameter_value != none) { return __parameter_value }
let value = read_lang_data.at(field, default: __g-default-localization.at(field))
if(value == none) { value = __g-default-localization.at(field)}
return value
}
let __grade_table_queston = __read-localization-value(read_lang_data: __read_lang_data, field: "grade-table-queston", localization: localization)
let __grade_table_total = __read-localization-value(read_lang_data: __read_lang_data, field: "grade-table-total", localization: localization)
let __grade_table_points = __read-localization-value(read_lang_data: __read_lang_data, field: "grade-table-points", localization: localization)
let __grade_table_grade = __read-localization-value(read_lang_data: __read_lang_data, field: "grade-table-grade", localization: localization)
let __point = __read-localization-value(read_lang_data: __read_lang_data, field:"point", localization: localization)
let __points = __read-localization-value(read_lang_data: __read_lang_data, field: "points", localization: localization)
let __page = __read-localization-value(read_lang_data: __read_lang_data, field: "page", localization: localization)
let __page-counter-display = __read-localization-value(read_lang_data: __read_lang_data, field: "page-counter-display", localization: localization)
let __family_name = __read-localization-value(read_lang_data: __read_lang_data, field: "family-name", localization: localization)
let __given_name = __read-localization-value(read_lang_data: __read_lang_data, field: "given-name", localization: localization)
let __group = __read-localization-value(read_lang_data: __read_lang_data, field: "group", localization: localization)
let __date = __read-localization-value(read_lang_data: __read_lang_data, field: "date", localization: localization)
let __draft-label = __read-localization-value(read_lang_data: __read_lang_data, field: "draft-label", localization: localization)
let __g-localization_lang_data = (
grade-table-queston: __grade_table_queston,
grade-table-total: __grade_table_total,
grade-table-points: __grade_table_points,
grade-table-grade: __grade_table_grade,
point: __point,
points: __points,
page: __page,
page-counter-display: __page-counter-display,
family-name: __family_name,
given-name: __given_name,
group: __group,
date: __date,
draft-label: __draft-label
)
context __g-localization.update(__g-localization_lang_data)
}
}
}
#let __show-header = (
page-number: 1,
school: (
name: none,
logo: none,
),
exam-info: (
academic-period: none,
academic-level: none,
academic-subject: none,
number: none,
content: none,
model: none
),
show-student-data: "first-page",
// show-student-data: (
// given-name: true,
// family-name: true,
// group: true,
// date: true
// ),
) => {
if (page-number==1) {
align(right)[#box(
width:108%,
grid(
columns: (auto, auto),
gutter:0.7em,
align(left + top)[
#if type(school) == "dictionary" {
if(school.at("logo", default : none) != none) {
set image(height:2.5cm, width: 2.7cm, fit:"contain")
if(type(school.logo) == "content") {
school.logo
}
else if(type(school.logo) == "bytes") {
image.decode(school.logo, height:2.5cm, fit:"contain")
}
else {
assert(type(school.logo) in (none, "content", "bytes") , message: "school.logo be of type content or bytes.")
}
}
}
],
grid(
rows: (auto, auto, auto),
gutter:1em,
grid(
columns: (auto, 1fr, auto),
align(left + top)[
#if type(school) == "dictionary" [
#school.at("name", default : none) \
]
#exam-info.academic-period \
#exam-info.academic-level
],
align(center + top)[
// #exam-info.number #exam-info.content \
],
align(right + top)[
#exam-info.at("academic-subject", default: none) \
#exam-info.number \
#exam-info.content
],
),
line(length: 100%, stroke: 1pt + gray),
__g-student-data(
page: "first",
show-student-data: show-student-data
)
)
)
)]
}
else if calc.rem-euclid(page-number, 2) == 1 {
grid(
columns: (auto, 1fr, auto),
gutter:0.3em,
align(left + top)[
#if type(school) == "dictionary" [
#school.at("name", default : none) \
]
#exam-info.academic-period \
#exam-info.academic-level
],
align(center + top)[
// #exam-info.number #exam-info.content \
],
align(right + top)[
#exam-info.at("academic-subject", default: none) \
#exam-info.number \
#exam-info.content
]
)
line(length: 100%, stroke: 1pt + gray)
__g-student-data(
page: "odd",
show-student-data: show-student-data
)
}
else {
grid(
columns: (auto, 1fr, auto),
gutter:0.3em,
align(left + top)[
#if type(school) == "dictionary" [
#school.at("name", default : none) \
]
#exam-info.academic-period \
#exam-info.academic-level
],
align(center + top)[
// #exam-info.number #exam-info.content \
],
align(right + top)[
#exam-info.at("academic-subject", default: none) \
#exam-info.number \
#exam-info.content \
]
)
line(length: 100%, stroke: 1pt + gray)
__g-student-data(
page: "pair",
show-student-data: show-student-data
)
}
}
}
#let __show-watermark = (
author: (
name: "",
email: none,
watermark: none
),
school: (
name: none,
logo: none,
),
exam-info: (
academic-period: none,
academic-level: none,
academic-subject: none,
number: none,
content: none,
model: none
),
question-points-position: left,
) => {
let dx = if question-points-position == left { 58pt } else { 72pt }
place(
top + right,
float: true,
clearance: 0pt,
// dx:72pt,
dx:dx,
dy:-115pt,
rotate(270deg,
origin: top + right,
{
if author.at("watermark", default: none) != none {
text(size:7pt, fill:luma(90))[#author.watermark]
h(35pt)
}
if exam-info.at("model", default: none) != none {
text(size:8pt, luma(40))[#exam-info.model]
}
}
)
)
}
#let __show-draft = (
draft-show: true,
draft-label: [],
) => {
if draft-show {
place(
center,
clearance: 0pt,
dx: -50pt,
dy: 330pt,
rotate(-45deg,
origin: top + right,
text(size:70pt, fill:silver)[
#context __g-localization.final().draft-label
]
)
)
}
}
|
https://github.com/kotatsuyaki/canonical-nthu-thesis | https://raw.githubusercontent.com/kotatsuyaki/canonical-nthu-thesis/main/layouts/body.typ | typst | MIT License | #let body-impl(
margin: (:),
it,
) = {
// Returns whether the current page has a chapter (top-level) heading.
let is-chapter-start-page() = {
// Find chapter headings on the current page.
let all-chapter-headings = query(heading.where(level: 1))
let current = counter(page).get()
let page-chapter-headings = all-chapter-headings.filter(m => m.location().page() == here().page())
return page-chapter-headings.len() > 0
}
// Set the page numbering to arabic numerals.
//
// Although we use custom headers and footers to display the page numbers in the body part,
// this is still required to show the page numbers in arabic numerals in the outlines.
set page(numbering: "1")
set page(
margin: margin,
header: context {
if not is-chapter-start-page() {
let chapter-headings-so-far = query(heading.where(level: 1).before(here()))
let chapter-heading = chapter-headings-so-far.last()
let chapter-number = counter(heading).at(chapter-heading.location()).at(0)
// Show the chapter number, the chapter name, and the page number in the header.
smallcaps("Chapter " + str(chapter-number) + ".")
h(0.75em)
smallcaps(chapter-heading.body)
h(1fr)
counter(page).display()
}
},
footer: context {
if is-chapter-start-page() {
// Show the chapter number centered in the footer.
h(0.5fr)
counter(page).display()
h(0.5fr)
}
}
)
// Reset the page counter for the body.
// TODO: Figure out why is-chapter-start-page returns true for page 2 when this line is moved above.
counter(page).update(1)
set par(
leading: 1.5em,
first-line-indent: 2em,
linebreaks: "optimized",
)
set heading(numbering: "1.1.1")
show heading: it => locate(loc => {
let size = if it.level == 2 {
18pt
} else {
14pt
}
block(width: 100%, {
set text(size: size)
// Collapse 1em vertically if there is a parent heading close enough above.
// Otherwise, space 1em vertically.
let all-prev-headings = query(selector(heading).before(loc), loc)
if all-prev-headings.len() > 1 {
let prev-heading = all-prev-headings.at(-2)
let is-same-page = prev-heading.location().page() == it.location().page()
let is-close = prev-heading.location().position().y + 250pt > it.location().position().y
let is-parent = prev-heading.level == it.level - 1
if (is-same-page and is-close and is-parent) {
v(-1em)
} else {
v(1em)
}
} else {
v(1em)
}
// Show the numbering and the body of the heading.
set par(justify: false)
grid(columns: 2, gutter: 1em, counter(heading).display(it.numbering), it.body)
v(1em)
})
})
show heading.where(
level: 1,
): it => {
// Start a chapter on a new page unless it's the 1st chapter,
// in which case it is already on a new page.
if counter(heading).get() != (1,) {
pagebreak()
}
// Do not justify top-level headings, which have a large font.
set par(justify: false)
if it.numbering == none {
// Show the body of the heading.
block(width: 100%, {
set text(size: 24pt)
v(3em)
it.body
v(2em)
})
} else {
// Show "Chapter n" and the body of the heading on 2 separate lines.
block(width: 100%, {
set text(size: 24pt)
v(3em)
text([Chapter ] + counter(heading).display(it.numbering))
linebreak()
it.body
v(2em)
})
}
}
it
}
|
https://github.com/gongke6642/tuling | https://raw.githubusercontent.com/gongke6642/tuling/main/可视化/模式/moshi.typ | typst | = 模式
重复图案填充。
Typst 支持最常见的平铺图案类型的图案,其中图案以网格状方式重复,覆盖填充或描边元素的整个区域。该模式由图块大小和定义每个单元格内容的主体定义。您还可以在 patterng 的单元格之间添加水平或垂直间距。
#image("1.png")
文本上也支持模式,但前提是将相对性设置为(默认值)或 。若要创建逐字或逐字形模式,可以手动或通过显示规则将文本的字词或字符换行到框中。auto"parent"
#image("2.png")
您还可以使用图案的间距特征将元素间隔得更远或更近。如果间距小于图案的大小,则图案将重叠。如果较高,则图案将具有与图案背景颜色相同的间隙。
#image("3.png")
= 相对性
模式起点的位置取决于容器的尺寸。这个容器可以是它被涂漆的形状,也可以是最近的周围容器。这由模式构造函数的参数控制。默认情况下,图案相对于它们所绘制的形状,除非图案应用于文本,在这种情况下,它们相对于最接近的祖先容器。relative
Typst 按如下方式确定祖先容器:
对于放置在文档根/顶层的形状,最接近的祖先是页面本身。
对于其他形状,祖先是包含该形状的最内层块或框。这包括由显示规则和元素隐式创建的框和块。例如,旋转不会影响渐变的父级,但栅格会影响。
#image("4.png")
#image("5.png") |
|
https://github.com/dainbow/MatGos | https://raw.githubusercontent.com/dainbow/MatGos/master/themes/15.typ | typst | #import "../conf.typ": *
= Дифференциальные формы на открытых подмножествах евклидова пространства, оператор внешнего дифференцирования $dif$ и его независимость от криволинейной замены координат
== Дифференциальные формы, оператор внешнего дифференцирования
В этом и других билетов, связанных с дифференциальными формами введём понятия $E = RR^n$ -- евклидово
пространство.
$E^*$ -- сопряжённое к нему, aka пространство линейных функционалов aka линейных
форм aka ковекторов.
Если мы будем употреблять $p in NN$, то мы имеем ввиду количество векторов
#eq[
$x_1, ..., x_p in E$
]
Если мы будем употреблять $q in NN$, то мы имеем ввиду количество ковекторов
#eq[
$y^1, ..., y^q in E^*$
]
Обратите внимание на индексы, это важно.
#definition[
*Полилинейной формой валентности $(p, q)$* называется функция $U : E^p times (E^*)^q -> RR$,
линейная по каждому из аргументов.
]
#proposition[
Полилинейная форма однозначно определяется значениями на базисных элементах $E$ и $E^*$,
то есть числами
#eq[
$omega_(bold(i))^(bold(j)) := omega_(i_1, ..., i_p)^(j_1, ..., j_q) = U(e_i_1, ..., e_i_p, e^(j_1), ..., e^(j_q))$
]
где $seq(idx: i, end: n, e)$ -- базис $E$, а ${e^j}_(j = 1)^q$ -- двойственный
базис $E^*$.
]
#proof[
Очевидно из линейности.
]
#definition[
Набор чисел ${omega_(bold(i))^(bold(j)) | i in (overline("1, n"))^p, j in (overline("1, n"))^q}$ (то
есть мы рассматриваем значения на всех комбинациях базисных векторов и
ковекторов) называется *тензором*
]
#proposition[
Множество полилинейных форм валентности $(p ,q)$ образует *линейное
пространство* $Omega_p^q$.
]
#definition[
*Тензорным произведением* форм $U in Omega_(p_1)^(q_1); V in Omega_(p_2)^(q_2)$ называется
форма $U times.circle V in Omega_(p_1 + p_2)^(q_1 + q_2)$, задаваемая формулой.
#eq[
$\ forall bold(x) in E^(p_1 + p_2) : forall bold(y) in E^(q_1 + q_2) : \ U times.circle V (x_1, ..., x_p_1, x_(p_1 + 1), ..., x_(p_1 + p_2), y^1, ..., y^(q_1), y^(q_1 + 1), ..., y^(q_1 + q_2)) = \
U(x_1, ..., x_p_1, y^1, ..., y^(q_1))dot V(x_(p_1 + 1), ..., x_(p_1 + p_2), y^(q_1 + 1), ..., y^(q_1 + q_2))$
]
]
#definition[
$W in Omega_p^0$ называется *симметрической*, если она не изменяется при любой
перестановке её аргументов.
]
#definition[
$W in Omega_p^0$ называется *антисимметрической (кососимметрической)*, если при
любой перестановке пары её аргументов она меняет знак.
Введём линейное пространство антисимметрических форм:
#eq[
$Lambda_p := { W in Omega_p^0 | W - "антисимметрическая" }$
]
]
#definition[
Пусть $pi_p = (i_1, ..., i_p)$ -- перестановка индексов ${1, ..., p}$. Тогда
#eq[
$forall W in Omega_p^0 : forall bold(x) in E^p : space (pi_p W) (x_1, ..., x_p) := W(x_i_1, ..., x_i_p)$
]
]
#definition[
*Симметризацией формы* $W in Omega_p^0$ называется форма
#eq[
$"sym" W := 1 / p! sum_(pi_p in S_p) pi_p W$
]
]
#definition[
*Антисимметризацией формы* $W in Omega_p^0$ называется форма
#eq[
$"asym" W := 1 / p! sum_(pi_p in S_p) "sgn" pi_p dot pi_p W$
]
]
#definition[
Если $U in Lambda_p, V in Lambda_q$, то их *внешним произведением* называется
#eq[
$U and V := (p + q)! / (p!q!) "asym" (U times.circle V)$
]
]
#theorem(
"Основные свойства внешнего произведения",
)[
+ Линейность
- $(alpha_1 U_1 + alpha_2 U_2) and V = alpha_1 (U_1 and V) + alpha_2 (U_2 and V)$
- $U and (alpha_1 V_1 + alpha_2 V_2) = alpha_1 (U and V_1) + alpha_2 (U and V_2)$
+ Ассоциативность
- $(U and V) and W = U and (V and W)$
+ Антикоммутативность
- $forall U in Lambda_p : forall V in Lambda_q : space U and V = (-1)^(p q) (V and U)$
]
#proposition[
Базисом в пространстве $Lambda_p$ является система
#eq[
${f^(i_1) and ... and f^(i_p) | 1 <= i_1 < ... < i_p <= n}$
]
где $seq(idx: i, end: n, f)$ -- базис в $E^* = Lambda_1$. (Принято брать базис
проекторов)
] <form-basic>
#definition[
*$p$-формой (дифференциальной формой валентности (степени) $p$)* на множестве $U subset E$ называется
отображение $Omega : U -> Lambda_p$.
В силу линейности пространства $Lambda_p$, нам достаточно задать поведение
получаемой формы лишь на базисе, поэтому
#eq[
$forall x in U : space Omega(x) := sum_(1 <= i_1 < ... < i_p <= n) omega_(i_1, ..., i_p) (x) f^(i_1) and ... and f^(i_p)$
]
Таким образом, дифференциальная форма однозначно задаётся наобором
действительнозначных функций
#eq[
${omega_(i_1, ..., i_p) (x) | 1 <= i_1 < ... < i_p <= n}$
]
]
#definition[
*Внешнее дифференцирование $p$-формы* определяется как $(p + 1)$-форма
#eq[
$dif Omega : U -> Lambda_(p + 1)$
]
По правилу
#eq[
$forall x in U : space dif Omega (x) := (p + 1) "asym" (Omega' (x))$
] где под производной подразумевается производная по Фреше.
Стоит заметить, что, формально $Omega' : U -> U -> Lambda_p$, однако мы считаем,
что $U -> Lambda_p subset Omega_(p + 1)^0$ (Действительно, линейно по $p + 1$ вектору
получаем число).
Также стоит упомянуть, что для любого базиса $(e_1, ..., e_n)$ из $E$ и
двойственного к нему базиса $(e^1, ..., e^n)$ существует соглашение, что
#eq[
$forall i = overline("1, n") : space e^i = dif e_i$
]
Которое не лишено смысла, ведь $e_i$ -- это 0-форма. А $e^i$ -- это функционал,
то есть $1$-форма.
]
#theorem(
"Основные свойства операции внешнего дифференцирования",
)[
+ $dif (Omega and Pi) = (dif Omega and Pi) + (-1)^p (Omega and dif Pi)$, где $Omega$ -- $p$-форма,
а $Pi$ -- $q$-форма.
+ $d(d Omega) = 0$
]
#proof[
+ Для простоты считаем, что форма -- одночлен, по линейности всё очевидно
доказывается для произвольной формы.
Фиксируем базис, в котором
#eq[
$Omega (x) = omega(x) dif x^(i_1) and ... and dif x^(i_p); quad Pi(x) = pi(x) dif x^(j_1) and ... and dif x^(j_q)$
]
Тогда
#eq[
$dif (Omega and Pi) = dif (omega(x) pi(x) dif x^(i_1) and ... and dif x^(i_p) and dif x^(j_1) and ... and dif x^(j_q)) = \
dif (omega(x) pi(x)) and dif x^(i_1) and ... and dif x^(i_p) and dif x^(j_1) and ... and dif x^(j_q) = \
pi(x) sum_(i = 1)^n (partial omega) / (partial x_i) (x) dif x^(i_1) and ... and dif x^(i_p) and dif x^(j_1) and ... and dif x^(j_q) + \
omega(x) sum_(i = 1)^n (partial pi) / (partial x_i) (x) dif x^(i_1) and ... and dif x^(i_p) and dif x^(j_1) and ... and dif x^(j_q) = \
d Omega and Pi (x) + (-1)^p (Omega and dif Pi)$
]
В последнем переходе мы воспользовались свойством антикоммутативности внешнего
произведения для перестановки всех $dif x^(j_...)$ перед всеми $dif x^(i_...)$,
остальное свернули по определению
+ Распишем двойной дифференциал:
#eq[
$dif(dif Omega) = dif(
sum_(j, forall k : j != i_k) (partial omega) / (partial x_j) dif x^j and dif x^(i_1) and ... and dif x^(i_p)
) = \
sum_(l, l != j, forall k : l != l_k)sum_(j, forall k : j != i_k) (partial^2 omega) / (partial x_l partial x_j) dif x^l and dif x^j and dif x^(i_1) and ... and dif x^(i_p) = \
sum_(j, l, j < l, forall k : j != i_k and l != i_k) ((partial^2 omega) / (partial x_l partial x_j) - (partial^2 omega) / (partial x_j partial x_l)) dif x^l and dif x^j and dif x^(i_1) and ... and dif x^(i_p) = 0$
]
]
== Независимость внешнего дифференцирования от замены координат
#definition[
Пусть $D subset RR^n$.
$D$ называется *связным*, если
#eq[
$forall x_1, x_2 in D : x_1 != x_2 : space exists gamma(t) subset D "кривая" : space gamma(0) = x_1 and gamma(1) = x_2$
]
]
#definition[
*Областью* называется открытое связное множество.
]
#definition[
Непрерывно дифференцируемое взаимооднозначное отображение $phi$ называется *диффеоморфизмом*.
]
#definition[
Пусть
- $Omega$ -- дифференциальная $p$-форма в области $U subset RR^n$
- $phi : V -> U$ -- диффеоморфизм области $V subset RR^n$ на $U$
Тогда $phi^* Omega$ -- дифференциальная $p$-форма в области $V$, определяемая
как
#eq[
$forall bold(b) in RR^n : space (phi^* Omega) (y) (bold(b)) := Omega (phi(y)) (phi'(y) b_1, ..., phi'(y) b_p)$
]
]
#proposition(
"Правило подсчёта",
)[
Мы можем выразить форму после замены координат через упомянутое выше базисное
представление:
#eq[
$(phi^* Omega)(y) = sum_(1 <= i_1 < ... < i_p <= n) omega_(i_1, ..., i_p)(phi(y)) dif phi^(i_1)(y) and ... and dif phi^(i_p)(y)$
]
]
#proof[
Заметим, что для произвольного вектора $b in RR^n$ верно
#eq[
$dif phi^i (y)(b) = sum_(l = 1)^n (partial phi^i) / (partial y^l)(y) dif f^l (b) = sum_(l = 1)^n (partial phi^i) / (partial y^l)(y) b^l = (phi'(y) b)^i = dif f^i (phi'(y) b)$
]
Не забывайте, что в качестве $dif f^i$ мы берём проекцию на $i$-ую координату.
Что и требовалось.
]
#lemma("Независимость внешнего дифференцирования от замены координат")[
#eq[
$phi^*(dif Omega) = dif (phi^* Omega)$
]
]
#proof[
БОО считаем, что $Omega$ -- это одночлен, для многочленов обобщается очевидно по
линейности.
Зафиксируем $Omega = omega (x) and dif x^(i_1) and ... and dif x^(i_p)$
Тогда по свойствам внешнего дифференцирования:
#eq[
$dif Omega = dif omega (x) and dif x^(i_1) and ... and dif x^(i_p)$
]
Тогда по правилу подсчёта
#eq[
$phi^* (dif Omega) = dif omega (phi(y)) and dif phi^(i_1)(y) and ... and dif phi^(i_p)(y)$
]
С другой стороны, по определению замены координат
#eq[
$phi^*(Omega) = omega(phi(y)) dif phi^(i_1)(y) and ... and dif phi^(i_p) (y)$
]
Применим оба свойства внешнего дифференцирования (двойной дифференциал нулевой и
псевдодистрибутивность):
#eq[
$dif (phi^* Omega) = dif omega (phi(y)) and dif phi^(i_1)(y) and ... and dif phi^(i_p)(y)$
]
]
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/text/smartquote.typ | typst | --- smartquote ---
#set text(lang: "en")
"The horse eats no cucumber salad" was the first sentence ever uttered on the 'telephone.'
--- smartquote-de ---
#set text(lang: "de")
"Das Pferd frisst keinen Gurkensalat" war der erste jemals am 'Fernsprecher' gesagte Satz.
--- smartquote-de-ch ---
#set text(lang: "de", region: "CH")
"Das Pferd frisst keinen Gurkensalat" war der erste jemals am 'Fernsprecher' gesagte Satz.
--- smartquote-es ---
#set text(lang: "es", region: none)
"El caballo no come ensalada de pepino" fue la primera frase pronunciada por 'teléfono'.
--- smartquote-es-mx ---
#set text(lang: "es", region: "MX")
"El caballo no come ensalada de pepino" fue la primera frase pronunciada por 'teléfono'.
--- smartquote-fr ---
#set text(lang: "fr")
"Le cheval ne mange pas de salade de concombres" est la première phrase jamais prononcée au 'téléphone'.
--- smartquote-fr-ch ---
#set text(lang: "fr", region: "CH")
"Le cheval ne mange pas de salade de concombres" est la première phrase jamais prononcée au 'téléphone'.
--- smartquote-fi ---
#set text(lang: "fi")
"Hevonen ei syö kurkkusalaattia" oli ensimmäinen koskaan 'puhelimessa' lausuttu lause.
--- smartquote-gr ---
#set text(lang: "gr")
"Το άλογο δεν τρώει αγγουροσαλάτα" ήταν η πρώτη πρόταση που ειπώθηκε στο 'τηλέφωνο'.
--- smartquote-he ---
#set text(lang: "he")
"הסוס לא אוכל סלט מלפפונים" היה המשפט ההראשון שנאמר ב'טלפון'.
--- smartquote-ro ---
#set text(lang: "ro")
"Calul nu mănâncă salată de castraveți" a fost prima propoziție rostită vreodată la 'telefon'.
--- smartquote-ru ---
#set text(lang: "ru")
"Лошадь не ест салат из огурцов" - это была первая фраза, сказанная по 'телефону'.
--- smartquote-it ---
#set text(lang: "it")
"Il cavallo non mangia insalata di cetrioli" è stata la prima frase pronunciata al 'telefono'.
--- smartquote-la ---
#set text(lang: "la")
#set smartquote(alternative: true)
"Equus cucumeris sem non edit" prima sententia in 'telephono' prolata fuit.
--- smartquote-empty ---
// Test single pair of quotes.
""
--- smartquote-apostrophe ---
// Test sentences with numbers and apostrophes.
The 5'11" 'quick' brown fox jumps over the "lazy" dog's ear.
He said "I'm a big fella."
--- smartquote-escape ---
// Test escape sequences.
The 5\'11\" 'quick\' brown fox jumps over the \"lazy' dog\'s ear.
--- smartquote-slash ---
// Test that smartquotes can open before non-whitespace if not nested.
"Hello"/"World" \
'"Hello"/"World"' \
""Hello"/"World""
--- smartquote-close-before-letter ---
// Test that smartquotes can close before alphabetic letters.
Straight "A"s and "B"s
--- smartquote-prime ---
// Test that primes result after numbers when possible.
A 2" nail. \
'A 2" nail.' \
"A 2" nail."
--- smartquote-bracket ---
// Test that brackets indicate an opening quote.
"a ["b"] c" \
"a b"c"d e"
--- smartquote-disable ---
// Test turning smart quotes off.
He's told some books contain questionable "example text".
#set smartquote(enabled: false)
He's told some books contain questionable "example text".
--- smartquote-disabled-temporarily ---
// Test changing properties within text.
"She suddenly started speaking french: #text(lang: "fr")['Je suis une banane.']" Roman told me.
Some people's thought on this would be #[#set smartquote(enabled: false); "strange."]
--- smartquote-nesting ---
// Test nested double and single quotes.
"'test statement'" \
"'test' statement" \
"statement 'test'"
--- smartquote-with-embedding-chars ---
#set text(lang: "fr")
"#"\u{202A}"bonjour#"\u{202C}"" \
#"\u{202A}""bonjour"#"\u{202C}"
--- smartquote-custom ---
// Use language quotes for missing keys, allow partial reset
#set smartquote(quotes: "«»")
"Double and 'Single' Quotes"
#set smartquote(quotes: (double: auto, single: "«»"))
"Double and 'Single' Quotes"
--- smartquote-custom-complex ---
// Allow 2 graphemes
#set smartquote(quotes: "a\u{0301}a\u{0301}")
"Double and 'Single' Quotes"
#set smartquote(quotes: (single: "a\u{0301}a\u{0301}"))
"Double and 'Single' Quotes"
--- smartquote-custom-bad-string ---
// Error: 25-28 expected 2 characters, found 1 character
#set smartquote(quotes: "'")
--- smartquote-custom-bad-array ---
// Error: 25-35 expected 2 quotes, found 4 quotes
#set smartquote(quotes: ("'",) * 4)
--- smartquote-custom-bad-dict ---
// Error: 25-45 expected 2 quotes, found 4 quotes
#set smartquote(quotes: (single: ("'",) * 4))
--- issue-3662-pdf-smartquotes ---
// Smart quotes were not appearing in the PDF outline, because they didn't
// implement `PlainText`.
= It's "Unnormal Heading"
= It’s “Normal Heading”
#set smartquote(enabled: false)
= It's "Unnormal Heading"
= It's 'single quotes'
= It’s “Normal Heading”
--- issue-1041-smartquotes-in-outline ---
#set page(width: 15em)
#outline()
= "This" "is" "a" "test"
--- issue-1540-smartquotes-across-newlines ---
// Test that smart quotes are inferred correctly across newlines.
"test"#linebreak()"test"
"test"\
"test"
|
|
https://github.com/kiwiyou/algorithm-lecture | https://raw.githubusercontent.com/kiwiyou/algorithm-lecture/main/advanced/02-shortest-path.typ | typst | #import "@preview/cetz:0.1.2"
#import "@preview/algorithmic:0.1.0"
#import "../slide.typ"
#show: slide.style
#show link: slide.link
#show footnote.entry: slide.footnote
#let algorithm(..args) = text(
font: ("linux libertine", "Pretendard"),
size: 17pt,
)[#algorithmic.algorithm(..args)]
#let func(body) = text(font: ("linux libertine", "Pretendard"))[#smallcaps[#body]]
#align(horizon + center)[
= 알고리즘 중급 세미나
02: 그래프의 최단거리
#text(size: 0.8em)[
연세대학교 전우제#super[kiwiyou] \
2023.12.05.r1
]
]
#slide.slide(
[누적 합],
)[
- 구간의 합을 합의 차로 구하는 테크닉
- $S_i = a_1 + a_2 + dots.c + a_i $일 때, $a_i + a_(i+1) + dots.c + a_j = S_j - S_(i-1)$
- $a_i$가 변하지 않을 때 구간의 합을 $cal(O)(1)$에 구함
]
#slide.slide(
[2차원 누적 합],
)[
- 직사각형의 합을 구하는 테크닉
#[
#show math.equation: set text(size: 22pt)
$
S_(r, c) = sum mat(
a_(1, 1), a_(1, 2), ..., a_(1, c);
a_(2, 1), a_(2, 2), ..., a_(2, c);
dots.v, dots.v, dots.down, dots.v;
a_(r, 1), a_(r, 2), ..., a_(r, c);
)
$
$ sum mat(
a_(t, l), a_(t, l+1), ..., a_(t, r);
a_(t+1, l), a_(t+1, l+1), ..., a_(t+1, r);
dots.v, dots.v, dots.down, dots.v;
a_(b, l), a_(b, l+1), ..., a_(b, r);
) = S_(b, r) - S_(t - 1, r) - S_(b, l - 1) + S_(t - 1, l - 1) $
]
#pagebreak()
- 직사각형을 4분할한 뒤 생각
#align(center + horizon)[
#show math.equation: set text(size: 20pt)
#cetz.canvas({
import cetz.draw: *
let size = 6
line((0, -.4), (size, -.4))
line((-.4, 0), (-.4, size))
content((0, -.7), $0$, anchor: "top")
content((size/2, -.7), $l$, anchor: "top")
content((size, -.7), $r$, anchor: "top")
content((-.7, size), $0$, anchor: "top-right")
content((-.7, size/2), $t$, anchor: "right")
content((-.7, 0), $b$, anchor: "right")
rect((0, 0, 0), (size, size, 0), fill: rgb(100%, 0, 0, 25%))
rect((0, 0, 1), (size/2, size, 1), fill: rgb(0, 100%, 0, 25%))
rect((0, size/2, 2), (size, size, 2), fill: rgb(0, 0, 100%, 25%))
rect((0, size/2, 3), (size/2, size, 3), fill: rgb(0, 0, 0, 25%))
set-style(line: (stroke: (dash: "dashed")))
line((0, 0, 0), (0, 0, 1))
line((size/2, 0, 0), (size/2, 0, 1))
line((size/2, size/2, 0), (size/2, size/2, 3))
line((size, size/2, 0), (size, size/2, 2))
line((0, size/2, 0), (0, size/2, 3))
line((0, size, 0), (0, size, 3))
line((size/2, size, 0), (size/2, size, 3))
line((size, size, 0), (size, size, 2))
content((size*3/4, size/4), $S_(b, r)$, anchor: "center")
content((size/4+.5, size/4+.4), $S_(b, l - 1)$, anchor: "center")
content((size*3/4+1, size*3/4+1), $S_(t - 1, r)$, anchor: "center")
content((size/4+1.5, size*3/4+1.5), $S_(t - 1, l - 1)$, anchor: "center")
})
]
#pagebreak()
- $S_(r, c)$ 구하는 법
#align(center + horizon)[
#cetz.canvas({
import cetz.draw: *
let size = 8
let count = 5
let step = size / count
grid((-size/2 - .5, 0), (rel: (size, size)), step: step, name: "right")
set-style(
line: (
stroke: (
paint: red,
thickness: 4pt,
),
mark: (
fill: red,
end: ">",
size: 0.3,
angle: 75deg,
),
),
)
let i = 0
while i < 5 {
line((rel: (step/2, i * step + step/2), to: "right.bottom-left"), (rel: (-step/2, i * step + step/2), to: "right.bottom-right"))
i += 1
}
grid((size/2 + .5, 0), (rel: (size, size)), step: step, name: "down")
set-style(
line: (
stroke: (
paint: blue,
),
mark: (
fill: blue,
),
),
)
let i = 0
while i < 5 {
line((rel: (i * step + step/2, -step/2), to: "down.top-left"), (rel: (i * step + step/2, step/2), to: "down.bottom-left"))
i += 1
}
})
]
]
#slide.slide[과제][
- #slide.problem("11660", "구간 합 구하기 5")
- #slide.problem("25682", "체스판 다시 칠하기 2")
- #slide.problem("14846", "직사각형과 쿼리")
]
#slide.slide[플로이드-워셜][
- 모든 두 정점 간 최단 경로 (APSP)
- 도달성(추이 폐포)을 모두 구할 수 있음
- 양수, 음수 가중치 모두 가능
- 음수 사이클의 존재를 판단 가능
#pagebreak()
- 인접행렬 기반
- 매번 각 정점이 양쪽으로 잇는 경로를 탐색 후 최단거리 갱신 (Relaxation)
- 정점 $V$개, 정점과 연결된 양쪽 점을 찾는 데 $cal(O)(V^2)$
- $cal(O)(V^3)$
- 음수 사이클이 있다면 $u -> u$ 최단거리가 갱신
- 오버플로에 주의
#pagebreak()
#algorithm({
import algorithmic: *
Function("Floyd-Warshall", args: ($A$, ), {
For(
cond: [$"via"$ *in* $V$], {
For(
cond: [$u$ *in* $V$], {
For(
cond: [$v$ *in* $V$],
If(
cond: $A[u][v] > A[u]["via"] + A["via"][v]$,
Assign[$A[u][v]$][$A[u]["via"] + A["via"][v]$]
)
)
}
)
For(
cond: [$u$ *in* $V$], {
If(
cond: $A[u][u] < 0$,
State[*report* negative cycle]
)
}
)
}
)
})
})
- $A[u][v]$는 $u -> v$ 간선의 가중치 또는 $infinity$
#pagebreak()
#algorithm({
import algorithmic: *
Function("Transitive-Closure", args: ($A$, ), {
For(
cond: [$"via"$ *in* $V$], {
For(
cond: [$u$ *in* $V$], {
For(
cond: [$v$ *in* $V$],
If(
cond: [$A[u]["via"]$ *and* $A["via"][v]$],
Assign[$A[u][v]$][*true*]
)
)
}
)
}
)
})
})
- $A[u][v]$는 $u -> v$ 간선이 있으면 `true`, 없으면 `false`
]
#slide.slide[과제][
- #slide.problem("1613", "역사")
- #slide.problem("11562", "백양로 브레이크")
]
#slide.slide[벨만-포드][
- 출발점 $s$에서 시작해서 모든 정점으로 끝나는 최단 경로 (SSSP)
- 양수, 음수 가중치 모두 가능
- 음수 사이클의 존재를 판단 가능
#pagebreak()
- $s$를 제외한 모든 정점까지의 거리 $D[u]$를 무한대로 놓고 시작
- $|V|-1$번, 모든 간선을 이용해 Relax
- 모든 최단경로는 $|V|-1$개의 간선으로 이루어짐
- 음수 사이클이 있다면 $|V|$번째에 Relax
- $|V|-1$번 모든 간선을 확인하므로 총 $cal(O)(V E)$
#pagebreak()
#algorithm({
import algorithmic: *
Function("Bellman-Ford", args: ($V$, $E$, $s$), {
Assign[$D[v]$][*inf* for all $v in V$]
Assign[$D[s]$][$0$]
For(
cond: [$|V| - 1$ times], {
For(
cond: [$(u, v, w)$ *in* $E$],
If(
cond: [$D[v] > D[u] + w$],
Assign[$D[v]$][$D[u] + w$]
)
)
}
)
For(
cond: [$(u, v, w)$ *in* $E$],
If(
cond: [$D[v] > D[u] + w$],
State[*report* negative cycle]
)
)
Return[$D$]
})
})
]
#slide.slide[과제][
- #slide.problem("1865", "웜홀")
]
#slide.slide[데이크스트라][
- 출발점 $s$에서 시작해서 모든 정점으로 끝나는 최단 경로 (SSSP)
- $0$ 이상의 가중치에서만 사용 가능
- $D[u]$가 최단거리라면 더 Relax되지 않음
- $s -> v -> w$가 최단거리라면 $s -> v$ 또한 최단거리
#pagebreak()
- $s$를 제외한 모든 정점까지의 거리 $D[u]$를 무한대로 놓고 시작
- 집합 $Q$: 아직 최단거리가 결정되지 않은 정점
- 처음에 $Q = V$
- $Q$에서 $D[u]$가 가장 작은 정점 $u$를 뽑음
- $u$와 연결된 각 정점 $v$를 Relax
- $Q$에서 $u$를 찾는 데 총 $cal(O)(V^2)$, Relax에 쓰이는 간선 확인 총 $cal(O)(E)$
- $cal(O)(V^2+E)$?
#pagebreak()
- 이진 힙 (#sym.in 우선순위 큐)
- 삽입에 $cal(O)(log N)$
- 최소 원소 확인에 $cal(O)(1)$
- 최소 원소 삭제에 $cal(O)(log N)$
- $cal(O)(E)$번의 Relax마다 힙에 삽입하므로 $cal(O)(E log E)$
- 그만큼 삭제가 일어나므로 $cal(O)(E log E)$
#pagebreak()
- 이론적인 최소 시간복잡도 $cal(O)(E + V log V)$ (구현이 복잡하여 느림)
- 피보나치 힙
- 삽입에 $cal(O)(log N)$
- 최소 원소 삭제에 $cal(O)(log N)$
- 우선순위 변경에 $cal(O)(1)$
- $cal(O)(E)$번의 Relax마다 우선순위를 변경하므로 $cal(O)(E)$
- 힙에는 처음에 $cal(O)(V)$개의 원소가 들어가고 $cal(O)(V)$번 삭제가 일어나므로 $cal(O)(V log V)$
#pagebreak()
#algorithm({
import algorithmic: *
Function("Dijkstra", args: ($V$, $E$, $s$), {
Assign[$D[v]$][*inf* for all $v in V$]
Assign[$D[s]$][$0$]
Assign[$Q$][${ (s, D[s]) }$ #Ic[Binary Heap]]
While(
cond: [$Q$ is not empty], {
State[*remove* $(u, d)$ from $Q$ with minimum $d$]
If(
cond: $d > D[u]$,
State[*continue*]
)
For(
cond: [$(u, v, w)$ in $E$], {
If(
cond: $D[v] > D[u] + w$, {
Assign[$D[v]$][$D[u] + w$]
State[*insert* $(v, D[v])$ into $Q$]
}
)
}
)
}
)
Return[$D$]
})
})
- $d > D[u]$ 체크가 빠지면 $cal(O)(V^2 + E log E)$!
]
#slide.slide[과제][
- #slide.problem("14284", "간선 이어가기 2")
- #slide.problem("25636", "소방차")
- #slide.problem("28131", "K-지폐")
] |
|
https://github.com/TGM-HIT/typst-thesis-workshop | https://raw.githubusercontent.com/TGM-HIT/typst-thesis-workshop/main/slides/utils.typ | typst | #import "@preview/codly:1.0.0": *
#let multi-lang(..translations) = {
assert(translations.pos().len() == 0, message: "only named arguments allowed")
let translations = translations.named()
context translations.at(text.lang)
}
#let de-en(de, en) = multi-lang(de: de, en: en)
#let _pro_con_list_options = (
spacing: 0.9em,
)
#let pro-list() = body => {
set list(marker: text(green.darken(20%), sym.plus), .._pro_con_list_options)
show list.item: set block(spacing: 0em)
body
}
#let con-list() = body => {
set list(marker: text(red.darken(10%), sym.minus), .._pro_con_list_options)
body
}
#let pro-con-list(pros, cons) = {
{
show: pro-list()
pros
}
{
show: con-list()
cons
}
}
#let example(code, code-width: 1.2fr, preview-width: 1fr) = {
grid(
columns: (code-width, preview-width),
column-gutter: 1em,
{
set align(top)
code
},
{
set align(top)
show: block.with(inset: (y: 0.3em))
let mode = if code.lang == "typc" { "code" } else { "markup" }
no-codly({
eval(code.text, mode: mode)
})
},
)
}
|
|
https://github.com/jamesrswift/springer-spaniel | https://raw.githubusercontent.com/jamesrswift/springer-spaniel/main/src/package/ctheorems.typ | typst | The Unlicense | #import "@preview/ctheorems:1.1.2": *
#let thmrules = thmrules.with(qed-symbol: $square.stroked$)
#let thmbox = thmbox.with(
padding: (y: 0.25em),
inset: 0pt,
radius: 0pt,
breakable: true,
base_level: 0,
)
#let thmplain = thmbox.with(
padding: (y: 0em), breakable: true,
namefmt: name => emph([(#name)]),
titlefmt: emph
)
#let thmproof = thmplain.with(
namefmt: emph,
bodyfmt: proof-bodyfmt
)
#let theorem = thmbox("theorem", "Theorem")
#let lemma = thmbox("theorem", "Lemma")
#let corollary = thmbox(
"corollary",
"Corollary",
base: "theorem",
base_level: 1
).with(numbering: "1.1")
#let proof = thmproof("proof", "Proof").with(numbering: none)
#let definition = thmbox("definition", "Definition") |
https://github.com/Nrosa01/TFG-2023-2024-UCM | https://raw.githubusercontent.com/Nrosa01/TFG-2023-2024-UCM/main/Memoria%20Typst/capitulos/Conclusions.typ | typst | The Lua implementation turns out to be very versatile given its performance and ease of use considering a technical profile. For use in video games this option can be viable with a little more work to simulate only groups of active particles and not all the particles in memory.
The web simulation is suitable for small sized simulations. Due to its user-friendly interface this implementation can be used to teach basic programming and simulation concepts, as well as an introduction to sand and cellular automata simulators.
Developing GPU simulators turns out to be a good option when high computational power is required or when the size of the simulation is very large, but implementing new behaviors is complicated.
As future work there are several tasks and extensions that can be done. Firstly, in the web simulation, vector calculation could be added, this would allow to perform operations with particles that are far away and not only within the immediate neighbors. It would also be interesting to replicate the web simulation with native code to achieve higher performance. In addition, this would allow exploring the possibility of generating GLSL code from the block interface to be able to run the simulation on GPU. Accomplishing this would involve creating a Blockly-like visual programming interface from scratch.
The web simulation could be modified so that its processing is similar to that of a cellular automaton as in the Lua implementation, this would allow to create the game of life, since in the current state it is not possible.
The Lua implementation could be improved by adding more data for the particles, since currently they only have the `clock` and `id` variables. If this extension were realized, it would be possible to create the aforementioned native visual programming interface to be able to generate Lua code. |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/align_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#set page(height: 100pt)
#stack(dir: ltr,
align(left, square(size: 15pt, fill: eastern)),
align(center, square(size: 20pt, fill: eastern)),
align(right, square(size: 15pt, fill: eastern)),
)
#align(center + horizon, rect(fill: eastern, height: 10pt))
#align(bottom, stack(
align(center, rect(fill: conifer, height: 10pt)),
rect(fill: forest, height: 10pt, width: 100%),
))
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/academic/multiple-choice-question.typ | typst | #import "@local/typkit:0.1.0": *
#let markup = markup-factory(marks.math)
#let annotate(question, annotations) = {
let annotation = {
// boxy(italic(annotations.src, size: 0.7em, fill: blue), stroke: strokes.soft)
italic(annotations.src, size: 0.7em, fill: black, weight: "bold")
}
let container = base-flex(
(content: question, align: (left + top), width: 200pt),
(content: annotation, align: (right + bottom), width: auto),
// column-gutter: 15pt,
// u dont really need the column-gutter
// because it is already aligned
// u also dont really need it to be 1fr
// doing 1fr ... will stretch it to the width of the parent
// which in this case is the root document
)
return box(container, inset: 10pt, stroke: strokes.soft, radius: 10pt)
// let container = shrink({
// lines.thin
// shrink(question, 250pt)
// lines.thin
// place(annotation, bottom + right)
// }, 300pt)
// using block or not using block matters
// it changes where the item is placed
return container
context {
// container
// let c = box(width: 50pt, height: 50pt, fill: black)
let w = measure(annotation).width
container
}
}
#let reference = (
schoolbook: (
block-style: (
),
container-style: (
)
),
singleton: (
block-style: (
// width: 235pt,
// width: 111pt,
// spacing: 0.3em,
// doing this in the arguments
),
container-style: (
stroke: strokes.thin,
inset: (
rest: 10pt,
bottom: 10pt,
// 15pt makes it kind of stick out
// the bottom margin
// it makes the annotation look kind of weird
),
radius: 5pt,
),
annotation-style: arguments(
bottom + right, dx: 5pt, dy: 5pt
)
),
)
#let do-annotation(tags, src) = {
if tags == none {
return
}
let tags = resolve-array(tags)
let callback(tag) = {
// return (text(tag, size: 0.7em, style: "italic", weight: "bold", fill: white), fill: blue)
return boxy(text(tag, size: 0.6em, style: "italic", weight: "bold", fill: white), fill: black, stroke: none)
// return boxy(text(tag, size: 0.6em, style: "italic", weight: "bold", fill: black), fill: gray.lighten(75%), stroke: none)
}
return block({
let p = tags.map(callback).join(h(3pt))
if src != none {
let src-content = text(src, size: 0.85em, fill: blue, weight: "bold")
src-content
h(5pt)
p
}
else if src != none {
context {
let src-content = text(src, size: 0.85em, fill: blue, weight: "bold")
src-content
v(-10pt)
line(stroke: strokes.soft, length: measure(src-content).width)
v(-10pt)
p
}
}
else if src != none {
}
else {
p
}
})
}
#let n2char(i) = {
return "ABCDEFGHIJK".at(i)
}
#let get-letter(template, choice-index, letter-alias) = {
if letter-alias != none {
todo()
} else {
let letter = n2char(choice-index)
let replacer(m) = {
return letter
}
return str-sub(template, "[1Aa]", replacer)
}
}
#let enumerate-choices(choices: Array,
answer: none,
answered: false,
body-indent: 0.5em, // the indent between the prefix and body
indent: 0.5em, // the indent of the entire block
numbering: "A.", // the numbering template
spacing: 0.45em, // the spacing between items
letter-alias: none, // whether to change the letter
) = {
let answer-index = if answered == true {
let finder(n) = {
return str(n) == str(answer)
}
choices.position(finder)
} else {
none
}
let store = ()
for (choice-index, choice) in choices.enumerate() {
let prefix = get-letter(numbering, choice-index, letter-alias)
let body = markup(choice)
let c = {
box(prefix, width: 10pt + body-indent)
body
}
if answered == true and choice-index == answer-index {
c = box(c, outset: 5pt, radius: 8pt, fill: green.lighten(80%))
}
store.push(c)
}
return store.join(v(spacing))
}
#let multiple-choice-question(question: ContentString, answer: Integer, choices: Array, style: "schoolbook", dir: "vertical", answered: false,
place: "lower-right", // where to put the tags and src
body-spacing: 8pt, // the distance between the question & the choices
width: 135pt, // the width of the question
annotations: none,
tags: none, // whether to add tags to the top-left corner
src: none, // whether to specify where the question came from
..sink,
) = context {
let question = {
markup(question)
v(body-spacing)
enumerate-choices(choices: choices, answer: answer, answered: answered)
}
return if annotations == none {
shrink(question, 215pt)
// just looks like a standard question
// doesnt have anything special
// question
} else {
annotate(question, annotations)
}
let (block-style, container-style, annotation-style) = reference.at(style)
// let natural-width =
c = block(width: width, c)
if container-style != none {
let p = do-annotation(tags, src)
if p != none {
// c = {
// c
// typst.place(p, ..annotation-style)
// }
c = {
stack(dir: ltr, c, align(p, top), spacing: 10pt)
// stack(dir: ltr, c, p) //
}
// if place == "above" {
// p
// v(-5pt)
// c
// } else if place == "lower-right" {
// c
// }
}
c = box(..container-style, c)
}
return c
}
#multiple-choice-question(
question: "What does $2 + 111 #equals ?$ abc def ghi hias asdifh asdfa adsf",
answer: 5,
choices: (1, 2, 3, 4, 5, 6),
answered: false,
style: "singleton",
// letter-alias: "g" // kind of hard ...
// tags: ("Barron's SHSAT Q7"), // i cant make these look good
// annotations: none,
// src: "Barron's SHSAT Q7",
annotations: (
topic: "arithmetic",
src: "Barron's SHSAT Q7",
tags: ("ratios"), // i cant make these look good
)
)
// annotations should only exist for full-width questions
// when it is a small question ... the allocation of space isnt correct
// it is complex how the styling interacts together
// to be freaking out ...
|
|
https://github.com/matthiasGmayer/typst-math-template | https://raw.githubusercontent.com/matthiasGmayer/typst-math-template/main/introduction.typ | typst | #import "template.typ": *
#show: sub_project
This is a citation
#ccite[pearl]
#definition[MyDefinition][
$X=1$
]
#labeled[mydef]
#remark[
$X!=2$
]
#proof[
see #tref[mydef]
]
|
|
https://github.com/mariunaise/HDA-Thesis | https://raw.githubusercontent.com/mariunaise/HDA-Thesis/master/pseudocode/bach_1.typ | typst | #import "@preview/lovelace:0.3.0": *
#pseudocode-list(booktabs: true, numbered-title: [Center Point Approximation])[
+ *input*: $bold(cal(o))_"first", bold(x), t, M$
+ *lists*: optimal weights $bold(h)_"opt"$
+ $bold(cal(o)) arrow.l bold(cal(o))_"first"$
+ #line-label(<alg:bach_1_1>) *repeat* t times:
+ *perform* #smallcaps[OptimalWeights($bold(cal(0)), bold(x))$]:
+ #line-label(<alg:bach_1_2>) *update* $bold(h)_"opt"$ with returned weights
+ $bold(z)_"opt" arrow.l$ all returned linear combinations
+ *define* new quantizer $cal(Q)^*$ using the @ecdf based on $bold(z)_"opt"$:
+ *sort* $bold(z)_"opt"$ in ascending order
+ $cal(Q)^* arrow.l $ use @eq:ecdf_inverse with quantizer bounds in the tilde domain
+ #line-label(<alg:bach_1_3>) *update* $bold(cal(o))$ with newly found quantizer step centers
+ *return* $bold(h)_"opt"$
]
|
|
https://github.com/OrangeX4/typst-talk | https://raw.githubusercontent.com/OrangeX4/typst-talk/main/utils.typ | typst | #import "@preview/octique:0.1.0": *
// Logos
#let typst-color = rgb("#239DAD")
#let Typst = text(fill: typst-color, weight: "bold", "Typst")
#let Touying = text(fill: rgb("#425066"), weight: "bold", "Touying")
#let Markdown = text(fill: rgb(purple), weight: "bold", "Markdown")
#let TeX = {
set text(font: "New Computer Modern", weight: "regular")
box(width: 1.7em, {
[T]
place(top, dx: 0.56em, dy: 0.22em)[E]
place(top, dx: 1.1em)[X]
})
}
#let LaTeX = {
set text(font: "New Computer Modern", weight: "regular")
box(width: 2.55em, {
[L]
place(top, dx: 0.3em, text(size: 0.7em)[A])
place(top, dx: 0.7em)[#TeX]
})
}
// Functions
#let linkto(url, icon: "link") = link(url, box(baseline: 30%, move(dy: -.15em, octique-inline(icon))))
#let keydown(key) = box(stroke: 2pt, inset: .2em, radius: .2em, baseline: .2em, key) |
|
https://github.com/Meisenheimer/Notes | https://raw.githubusercontent.com/Meisenheimer/Notes/main/src/Probability.typ | typst | MIT License | #import "@local/math:1.0.0": *
= Probability Theory
== Probability
#env("Definition")[
A *probability space* is a triple $(Omega, cal(F), P)$ consisting of
- the sample space $Omega$: an arbitrary non-empty set;
- the $sigma$-algebra $cal(F) subset.eq 2^Omega$: a set of subsets of $Omega$, called events, such that
- $cal(F)$ contains the sample space: $Omega in cal(F)$;
- $cal(F)$ is closed under complements: if $A in cal(F)$, then also $(Omega backslash A) in cal(F)$;
- $cal(F)$ is closed under countable unions: if $A_i in cal(F), i = 1, dots$, then also $(union_(i=1)^infinity A_i) in cal(F)$;
- the probability measure $P: cal(F) -> [0, 1]$: a function such that
- $P$ is countably additive (also called $sigma$-additive): if ${A_i}_(i=1)^infinity subset.eq cal(F)$ is a countable collection of pairwise disjoint sets, then $P(union_(i=1)^infinity A_i) = sum_(i=1)^infinity P(A_i)$;
- the measure of the entire sample space is equal to one: $P(Omega) = 1$.
]
#env("Definition")[
Given a probability space $(Omega, cal(F), P)$, a *random variable* is a measurable function $X: Omega -> RR$ that for all $t in RR$,
$ {omega in Omega: X(omega) lt.eq t} in cal(F). $
]
#env("Definition")[
The *cumulative distribution function (cdf)* of a random variable $X$ on probability space $(Omega, cal(F), P)$ is
$ F_X (x) = P(X lt.eq x). $
]
=== Continuous random variables
#env("Definition")[
A *continuous random variables* is a random variables with the range of $X$ is uncountable.
]
#env("Definition")[
The *probability density function (pdf)* of a continuous random variables is
$ f(x) = (upright(d) F(x))/(upright(d) x). $
]
#env("Theorem")[
Let $X$ be a discrete random variables, its probability mass function satisfies
+ $f(x) gt.eq 0$;
+ $integral_(-infinity)^(+infinity) f(x) upright(d) x = 1$;
+ $F(x) = integral_(-infinity)^(x) f(t) upright(d) t$.
]
#env("Theorem")[
Let $X$ be a continuous random variables and $Y = g(X)$ is a differentiable bijection, denoted by $f_X (x), f_Y (y)$ the pdf's of $X$ and $Y$, then
$ f_Y (y) = f_X (g^(-1)(y)) abs((upright(d) x)/(upright(d) y)). $
]
=== Discrete random variables
#env("Definition")[
A *discrete random variables* is a random variables with the range of $X$ is countable.
]
#env("Definition")[
The *probability mass function (pmf)* of a discrete random variables is
$ p_X(x) = P(X = x). $
]
#env("Theorem")[
Let $X$ be a discrete random variables, its probability mass function satisfies
$ 0 lt.eq p_X (x) lt.eq 1 "and" sum_(x in "Range"(X)) p_X (x) = 1. $
]
#env("Theorem")[
Let $X$ be a discrete random variables and $Y = g(X)$, denoted by $p_X (x), p_Y (y)$ the pmf's of $X$ and $Y$, then
$ p_Y (y) = sum_(x; g(x) = y) p_X (x). $
In particular, if $g$ is a bijection, then
$ p_Y (y) = p_X (g^(-1)(y)). $
]
#env("Remark")[
The discrete random variable $X$ can be written in continuous form via Dirac delta function, i.e.
$ f_X (x) = sum_(overline(x) in "Range"(X)) p_X (x) delta(x - overline(x)). $
]
=== Multivariate distributions
#env("Definition")[
A *random vector* is a vector $(X_1, dots, X_n)$ where all $X_k$ are random variables.
]
#env("Definition")[
The *joint cdf* of a random vector $(X_1, dots, X_n)$ is defined as
$ F_(X_1, dots, X_n) (x_1, dots, x_n) = P(X_1 lt.eq x_1, dots, X_n lt.eq x_n). $
]
#env("Definition")[
The *joint pmf* of a random vector $(X_1, dots, X_n)$ is defined as
$ p_(X_1, dots, X_n) (x_1, dots, x_n) = P(X_1 = x_1, dots, X_n = x_n). $
]
#env("Definition")[
The *joint pdf* of a random vector $(X_1, dots, X_n)$ is defined as
$ f_(X_1, dots, X_n) (x_1, dots, x_n) = (partial F_(X_1, dots, X_n) (x_1, dots, x_n))/(partial x_1 dots.c partial x_n). $
]
#env("Theorem")[
A random vector $(X_1, dots, X_n)$ satisfies
+ $F_(X_1, dots, X_(n-1)) (x_1, dots, x_(n-1)) = F_(X_1, dots, X_n) (x_1, dots, x_(n-1), +infinity)$;
+ $p_(X_1, dots, X_(n-1)) (x_1, dots, x_(n-1)) = sum_(x in "Range"(X_n)) p_(X_1, dots, X_n) (x_1, dots, x_(n-1), x) #h(1em) ("discrete case")$;
+ $f_(X_1, dots, X_(n-1)) (x_1, dots, x_(n-1)) = integral_(-infinity)^(+infinity) f_(X_1, dots, X_n) (x_1, dots, x_(n-1), x) upright(d) x #h(1em) ("continuous case")$;
+ $p_(X_1, dots, X_n | X_1) (x_1, dots, x_n | x_1) = (p_(X_1, dots, X_n) (x_1, dots, x_n)) / (p_(X_1) (x_1)) #h(1em) ("discrete case")$;
+ $f_(X_1, dots, X_n | X_1) (x_1, dots, x_n | x_1) = (f_(X_1, dots, X_n) (x_1, dots, x_n)) / (f_(X_1) (x_1)) #h(1em) ("continuous case")$.
]
#env("Theorem")[
Given two random vectors $X = (X_1, dots, X_n)$ and $Y = (Y_1, dots, Y_n)$ and a series of bijection ${g_i}$ that $X_i = g_i(Y_i)$, then
$ f_(Y_1, dots, Y_n) (y_1, dots, y_n) = f_(X_1, dots, X_n) (g_1(y_1, dots, y_n), dots, g_n (y_1, dots, y_n)) abs((partial (x_1, dots, x_n))/(partial (y_1, dots, y_n))). $
]
#env("Theorem")[
Two random vectors $X = (X_1, dots, X_n)$ and $Y = (Y_1, dots, Y_n)$ are mutually independent iff
$ cases(p_(X_1, X_2) (x_1, x_2) = p_(X_1) (x_1) p_(X_2) (x_2)\, & #h(1em) ("discrete case")\,,
f_(X_1, X_2) (x_1, x_2) = f_(X_1) (x_1) f_(X_2) (x_2)\, & #h(1em) ("continuous case")\.) $
]
=== Distributional quantities
#env("Definition")[
Given a random variable $X$, the *expectation* of $X$ is
$ & E(X) = sum_(x in "Range"(X)) x p(x), && #h(1em) "if" sum_(x in "Range"(X)) abs(x) p(x) lt infinity & #h(1em) ("discrete case"), \
& E(X) = integral_(-infinity)^(+infinity) x f(x) upright(d) x, && #h(1em) "if" integral_(-infinity)^(+infinity) abs(x) f(x) upright(d) x lt infinity & #h(1em) ("continuous case"). $
]
#env("Definition")[
Given a random variable $X$, the *$k$-th moment* of $X$ is $E(X^k)$, and the *$k$-th central moment* is $E((X - E(X))^k)$.
]
#env("Example")[
The *variance* of random variable $X$ is the *$2$-nd central moment* of $X$,
$ sigma^2 = "Var"(X) = E((X - E(X))^2) = E(X^2) - E(X)^2. $
]
#env("Definition")[
Given a random variable $X$, if $E(e^(t X))$ exists for $t in RR$, then the *moment generating function (mgf)* of $X$ is
$ M_X (t) = E(e^(t X)) = sum_(k=0)^infinity (t^k E(X^k))/(k!). $
]
#env("Theorem")[
The moment generating function (mgf) of random variables $X$ and $Y$ satisfies
+ For all $k in NN^*$, $M^((k)) (0) = E(X^k)$;
+ If $X$ and $Y$ are independent, then $M_(X+Y) (t) = M_X (t) M_Y (t)$.
]
== Characteristic functions
== Probability limit theorems
== Common distributions
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-20.typ | typst | Other | // Test the `filter` method.
#test(().filter(calc.even), ())
#test((1, 2, 3, 4).filter(calc.even), (2, 4))
#test((7, 3, 2, 5, 1).filter(x => x < 5), (3, 2, 1))
|
https://github.com/RanolP/resume | https://raw.githubusercontent.com/RanolP/resume/main/metadata.typ | typst | #let metadata = (
name: (nickname: "RanolP", real-korean: "임상원", real-english: "Im Sang-won"),
bio: (
ko: (
title: text(weight: 300)[사람과 컴퓨터 사이를 #text(weight: 900)[이어주는] 소프트웨어를 만듭니다],
body: text[
*더 쓰고 싶고, 더 쓰기 쉬운 소프트웨어*를 만들어 나갑니다. *누구나 쉽게 접근*할 수 있는 *웹을 가장 선호*하고, \
가장 잘 알고 있지만, CI 파이프라인부터 모바일 앱까지. *색다른 환경도 쉽게 적응*해 헤쳐나갈 수 있습니다. \
TypeScript의 고급 타입 기능이나 Rollup Plugin 등 *기반 도구에도 관심*을 갖고 활용할 수 있으며, \
Rust, Kotlin 등, *다양한 프로그래밍 언어를 사용*해 플랫폼에 최적화된 코드를 쉽게 작성할 수 있습니다.
],
),
en: (
title: [Building Softwares *Connecting* People with Computers],
),
),
role: "소프트웨어 엔지니어",
location: "대한민국 서울특별시",
email: "<EMAIL>",
phone: ("+82", "10", "9542", "6545"),
social: (github: "RanolP", twitter: "RanolP_777", solved-ac: "asdhugh1"),
oss-contribs: (
(url: "https://github.com/oven-sh/bun/pull/10590"),
(url: "https://github.com/openobserve/openobserve/pull/3151"),
(url: "https://github.com/motiondivision/motionone/pull/244"),
(url: "https://github.com/resend/react-email/pull/884"),
(url: "https://github.com/daangn/stackflow/pull/274"),
(url: "https://github.com/solved-ac/ui-react/pull/5", full: true),
(url: "https://github.com/kiwiyou/basm-rs/pull/55"),
(url: "https://github.com/velog-io/velog/pull/38"),
),
)
|
|
https://github.com/pku-typst/unilab | https://raw.githubusercontent.com/pku-typst/unilab/main/titlepage.typ | typst | MIT License | /// Generate a title page
///
/// - `title`: The title of the document
/// - `subtitle`: The subtitle of the document
/// - `author`: The author of the document
/// - `bottom-text`: The text at the bottom of the page
#let title-page(title: none, subtitle: none, author: none, bottom-text: none, logos: (none, none)) = page("a4")[
#v(2.5%)
#align(center)[
#box(
height: 10%,
grid(
align: center + horizon,
columns: (auto, auto),
column-gutter: 2%,
box(height: 100%, logos.at(0, default: none)),
box(height: 60%, logos.at(1, default: none)),
// image("./school-logo.svg", height: 100%),
// image("./school-text.svg", height: 60%),
),
)
]
#align(center)[#text(title, size: 32pt, font: ("Bodoni", "Source Han Serif"))]
#align(center)[#text(subtitle, size: 24pt, font: ("Bodoni", "Source Han Serif"))]
#align(
center,
text(size: 12pt, font: ("Bodoni", "Source Han Serif"))[
#author
],
)
#place(
bottom + center,
[
#align(
center,
text(size: 12pt, font: ("Bodoni", "Source Han Serif"))[
#bottom-text
],
)
],
)
]
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/examples/3d-cetz-attempt-1.typ | typst | // status: working
//
#import "@preview/cetz:0.2.2"
#import cetz.draw: *
#cetz.canvas({
let origin = (0, 0)
set-style(
grid: (
stroke: (
thickness: 0.25pt,
dash: "densely-dotted"
)
),
circle: (
radius: 3pt,
fill: black,
)
)
on-yz({
grid(origin, (4, 4), stroke: (paint: blue))
grid((-4, -4), (0, 0), stroke: (paint: blue))
})
on-xy({
grid(origin, (4, 4), stroke: (paint: purple))
})
on-xz({
grid(origin, (4, 4))
})
//let c = circle.with(radius: 3pt, fill: black)
circle((1, 1, 1))
circle((1, 1, 0))
line((0, 0, 0), (1, 0, 0))
line((1, 0, 0), (1, 1, 0))
line((1, 1, 0), (1, 1, 1))
})
|
|
https://github.com/ShadowMitia/typst-babble-bubbles | https://raw.githubusercontent.com/ShadowMitia/typst-babble-bubbles/main/README.md | markdown | MIT License | # typst-babble-bubbles
A package to create callouts in typst, inspired by the [Obsidan](https://obsidian.md/) callouts.
Use preset callouts, or create your own!

## Usage
Import the package
```typst
#import "@preview/babble-bubbles:0.1.0": *
```
Or grab it locally and use:
```typst
#import "@local/babble-bubbles:0.1.0": *
```
## Presets
Here you can find a list of presets and an example usage of each.
You can customise them with the same parameters as the `callout` function. See the `Custom callouts` for more details.
```typst
#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]
```
## Custom callouts
### `callout`
Create a default callout.
Tweak the parameters to create your own!
```typst
callout(
body,
title: "Callout",
fill: blue,
title-color: white,
body-color: black,
icon: none)
```
### Tips
You can create aliases to more easily handle your
newly create callouts or customise presets by using [with](https://typst.app/docs/reference/types/function/#methods-with).
```
#let mycallout = callout.with(title: "My callout")
#mycallout[Hey this is my custom callout!]
```
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.3.0/src/lib/plot-stub.typ | typst | Apache License 2.0 | // DEPRECATED TODO: Remove this after 0.3.0
#let plot(..args) = panic("cetz plotting library has been moved to its own package, cetz-plot")
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.