repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/Nrosa01/TFG-2023-2024-UCM
https://raw.githubusercontent.com/Nrosa01/TFG-2023-2024-UCM/main/Memoria%20Typst/main.typ
typst
#import "template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( title: "Exploración y análisis de rendimiento y extensibilidad de diferentes implementaciones de simuladores de partículas", titleEng: "Exploration and analysis of performance and extensibility of different implementations of particle simulators.", authors: ( "<NAME>", "<NAME>", ), course: "Trabajo de Fin de Grado ", degree: "Grado en Desarrollo de Videojuegos", directors: ( "<NAME> ", ), // Insert your abstract after the colon, wrapped in brackets. // Example: `abstract: [This is my abstract...]` abstract: lorem(59), date: "7 de mayo de 2024", ) #pagebreak(weak: true) #set heading(outlined: false, numbering: none, bookmarked: true) = Agradecimientos #include "capitulos/Agradecimientos.typ" #pagebreak(weak: true) = Resumen #include "capitulos/0.Resumen.typ" #linebreak() = Palabras clave #v(8pt) - Simuladores de arena - Automatas celulares - Programación paralela - Multihilo - GPU - Lua - Rust - WebAssembly - Blockly - Compute shader #pagebreak(weak: true) = Abstract #include "capitulos/0.Abstract.typ" #linebreak() = Key Words #v(8pt) - Sand simulators - Cellular automata - Parallel programming - Multithreading - GPU - Lua - Rust - WebAssembly - Blockly - Compute shader #pagebreak(weak: true) #outline(indent: auto) #outline( title: "Índice de Figuras", target: figure.where() ) #pagebreak(weak: true) #set heading(outlined: true, numbering: "1.") = Introducción #include "capitulos/1.Introduccion.typ" #pagebreak(weak: true) #counter(heading).update(0) = Introduction #include "capitulos/1.Introduction.typ" #pagebreak(weak: true) = Autómatas celulares y simuladores de arena #include "capitulos/2.1.AutomatasCelulares.typ" #include "capitulos/2.2.SimuladoresDeArena.typ" #pagebreak(weak: true) = Programación paralela #include "capitulos/3.ProgramacionParalela.typ" #pagebreak(weak: true) // = Plug-ins y lenguajes de scripting // #include "capitulos/4.PluginsYScripting.typ" = Estrategias para definir comportamiento en motores de videojuegos #include "capitulos/4.PluginsYScriptingV2.typ" #pagebreak(weak: true) #pagebreak(weak: true) = Simuladores de arena en CPU <SimuladorCPU> #include "capitulos/5.SimuladorCPU.typ" #pagebreak(weak: true) = Simulador de arena en GPU <SimuladorGPU> #include "capitulos/6.SimuladorGPU.typ" #pagebreak(weak: true) = Comparación y pruebas #include "capitulos/ComparacionYPruebas.typ" #pagebreak(weak: true) = Conclusiones y trabajo futuro #include "capitulos/Conclusiones.typ" #pagebreak(weak: true) #counter(heading).update(n => n - 1) = Conclusions and future work #include "capitulos/Conclusions.typ" #pagebreak(weak: true) = Contribuciones #include "capitulos/Contribuciones.typ" #pagebreak(weak: true) #bibliography("bibliography.bib", style: "ieee")
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-18.typ
typst
Other
// Error: 3-11 cannot multiply integer with boolean #(2 * true)
https://github.com/TechnoElf/mqt-qcec-diff-thesis
https://raw.githubusercontent.com/TechnoElf/mqt-qcec-diff-thesis/main/template/cover.typ
typst
#import "colour.typ": * #let cover_page( title: "", author: "", chair: "", school: "" ) = { page( paper: "a4", margin: ( top: 3cm, bottom: 1cm, x: 1cm, ), header: [ #grid( columns: (1fr, 1fr), rows: (auto), text( fill: tum_blue, size: 8pt, font: "TUM Neue Helvetica", [#chair \ #school \ Technical University of Munich] ), align(bottom + right, image("resources/TUM_Logo_blau.svg", height: 50%)) ) ], footer: [] )[ #v(1cm) #align(top + left)[#text(font: "TUM Neue Helvetica", size: 24pt, [*#title*])] #v(3cm) #text(font: "TUM Neue Helvetica", fill: tum_blue, size: 17pt, [*#author*]) #align(bottom + right)[#image("resources/TUM_Tower.png", width: 60%)] ] pagebreak() }
https://github.com/icyzeroice/typst-packages
https://raw.githubusercontent.com/icyzeroice/typst-packages/main/packages/minimal-styling/README.md
markdown
MIT License
# Introduction Minimal styling to make typst look like the preview of github markdown[^1][^2]. > 🎯 My purpose is not to replicate github markdown styling completely. Instead, just make me do not case too much about forming a good styling while taking notes in most cases. ![preview](thumbnail.png) # How to use install [`just`](https://github.com/casey/just) run the following setup steps: ```sh git clone https://github.com/icyzeroice/typst-template-minimal-styling cd typst-template-minimal-styling just sync ``` then, use the local typst package like this: ```typst #import "@local/minimal-styling:0.1.0": template_minimal_styling #show: template_minimal_styling ``` # TODOs - [x] text - [x] headings - [x] code - [x] links - [ ] footnotes - [ ] table # Related works - [`coldy`](https://typst.app/universe/package/codly) : more styling with code - [`octique`](https://typst.app/universe/package/octique) : github handcrafted icons - [`note-me`](https://typst.app/universe/package/note-me) : github-style alert - [`ilm`](https://typst.app/universe/package/ilm/): a minimal template - [`cheq`](https://typst.app/universe/package/cheq): markdown-like checkboxes - [`tablem`](https://typst.app/universe/package/tablem): markdown table markup # Footnotes [^1]: [Markdown Cheatsheet · adam-p/markdown-here Wiki](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) [^2]: [Basic writing and formatting syntax - GitHub Docs](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)
https://github.com/eusebe/sorbonne-slides-typst
https://raw.githubusercontent.com/eusebe/sorbonne-slides-typst/main/test.typ
typst
#import "sorbonne-slides.typ": * #show: sorbonnesante-theme.with( aspect-ratio: "4-3", faculty: "sante", ) #title-slide( title: [A title], subtitle: [A subtitle], short-title: [A short title], date: [February 20, 1967], author: [<NAME>], location: [Aberdeen], ) #slide(title: "Outline")[ #sorbonne-outline ] #slide(title: "Slide title", subtitle: "A subtitle")[ A slide with some maths: $ x_(n+1) = (x_n + a/x_n) / 2 $ #lorem(200) ] #new-section-slide("First section") #slide[ A slide without a title but with #alert[important] infos ] #new-section-slide([Second section]) #slide(title: "Slide title")[ - #lorem(20) - #lorem(10) ] #focus-slide[ #set align(center) A focus slide Wake up! ] #new-subsection-slide([A subsection]) #slide(title: "Slide title")[ - #lorem(20) - #lorem(10) ] #new-subsection-slide([Another subsection]) #slide(title: "Slide title")[ $ A = pi r^2 $ $ "area" = pi dot "radius"^2 $ $ cal(A) := { x in RR | x "is natural" } $ #let x = 5 $ #x < 17 $ $ #x != 17 $ ]
https://github.com/Enter-tainer/typst-preview
https://raw.githubusercontent.com/Enter-tainer/typst-preview/main/docs/intro.typ
typst
MIT License
#import "./book.typ": book-page #import "./templates/gh-page.typ": page-width, is-dark-theme #import "@preview/fontawesome:0.1.0": * #import "@preview/colorful-boxes:1.1.0": * #show: book-page.with(title: "Introduction") #show link: underline = Get Started == Use in VSCode Install the extension from #link("https://marketplace.visualstudio.com/items?itemName=mgt19937.typst-preview")[VSCode Marketplace]. #figure( image("./assets/preview.png", width: 90%), caption: [ Preview in VSCode ], ) Then open a typst document and press `Ctrl+Shift+P` to open the command palette. Type `Typst Preview:` and press enter. The preview page will be opened in a new tab. == Use in other editors #slantedColorbox( title: "Note", color: "blue", radius: 2pt, width: auto )[ When used in other editors, you will have to start the preview server manually. And the cross jump feature will not work. You will also need to trigger compilation manually by saving your document. ] Download the `typst-preview` binary for your platform from #link("https://github.com/Enter-tainer/typst-preview/releases")[GitHub Release Page]. Then start the server by running `typst-preview [your-source-file]` in your terminal. The server will open the preview page in your browser by default. == Why Typst Preview? #link("https://github.com/Enter-tainer/typst-preview")[Typst Preview] provides low latency preview experience for Typst. Comparing to its alternatives, it is more responsive and has better support for Typst's features like cross jump between code and preview. #let cell = rect.with( inset: 12pt, width: 100%, height: auto, radius: 6pt, ) #let pros_and_cons(p, c) = { let columns = if page-width <= 450pt { (1fr) } else { (1fr, 1fr) } let (pros_fill, pros_text) = if not is-dark-theme { (green.lighten(90%), black) } else { (black.lighten(10%), green.darken(10%)) } let (cons_fill, cons_text) = if not is-dark-theme { (red.lighten(90%), black) } else { (black.lighten(10%), red.darken(10%)) } table( columns: columns, inset: 10pt, align: horizon, stroke: none, cell(fill: pros_fill)[ #text(fill: pros_text)[#fa-check() *Pros*: #p] ], cell(fill: cons_fill)[ #text(fill: cons_text)[#fa-times() *Cons*: #c] ] ) } - #link("https://typst.app")[_Official Typst Web App_]: The whole typst compiler runs in your browser as a wasm module. It compiles your document to pixmaps and renders them on a canvas. #pros_and_cons( [It is supported by the official typst team. And it is super fast because all these steps happens in your browser.], [It runs in your browser and cannot use local fonts: You have to upload your fonts to the web app.] ) - _`typst watch`_: Using the official typst cli to watch your files and compile them to pdfs. Then open it with your pdf viewer. #pros_and_cons( [It is supported by the official typst team. Pdf is also the target format of common use cases. This ensures that what you see is what you get.], [It is not responsive. You will have to manually save to document to trigger re-compile. It may takes a few seconds to compile and reload the pdf when your document gets big. It also does not support cross jump between code and preview.] ) - _#link("https://github.com/nvarner/typst-lsp")[Typst LSP]'s Preview_: Typst LSP will watch your files in memory and compile them to pdfs. It will then open the pdfs in your VSCode. #pros_and_cons( [This is quite similar to `typst watch [input]`. But in addition, it can watch changes happening in your VSCode and trigger re-compile. So you can see the preview in real time.], [It is not supported by the official typst team. It also does not support cross jump between code and preview.] ) - #link("https://github.com/Enter-tainer/typst-preview")[_Typst Preview_]: We watch changes in your VSCode editor and send changes to the compiler. The compiler use #link("https://github.com/Myriad-Dreamin/typst.ts")[typst.ts] to export the document to an internal incremental IR and send it the preview frontend. The frontend then uses this IR to render the document. #pros_and_cons( [It is super fast and responsive. It supports cross jump between code and preview. It also supports local fonts.], [It is not supported by the official typst team. It may also introduce some bugs because it have a different rendering backend from the official typst web app.] ) == Bug Report To achieve high performance instant preview, we use a *different rendering backend* from official typst. We are making our best effort to keep the rendering result consistent with official typst. We have set up comprehensive tests to ensure the consistency of the rendering result. But we cannot guarantee that the rendering result is the same in all cases. There can be unknown corner cases that we haven't covered. *Therefore, if you encounter any rendering issue, please report it to this repo other than official typst repo.* == Acknowledgement This book is written in typst, and compiled to HTML using #link("https://github.com/Myriad-Dreamin/typst-book/")[typst book]
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/system-implementation/technology.typ
typst
== Project Technology Stack To effectively implement the Ungrammar Language Ecosystem, we have carefully selected a robust set of technologies and applications: #[ #show figure: set block(breakable: true) #figure( table( columns: 3, align: left, table.header([*Technology Stack*], [*Version*], [*Description*]), // Neovim [Neovim], [0.10.1], [Primary editor for developing and testing the LSP (Language Server Protocol) implementation], // VSCode [Visual Studio Code], [1.93.1], [Used for testing the VS Code extension product, ensuring compatibility and proper functionality within the VS Code environment (@sec-vscode)], // TypeScript [TypeScript], [5.5.4], [A versatile programming language used to develop the language server and other components, ensuring efficient and maintainable code (@sec-typescript)], // VSCode Language Client [VSCode Language Client], [9.0.1], [A library that facilitates communication between the code editor and the language server, enabling seamless integration and feature support], // VSCode Language Server [VSCode Language Server], [9.0.1], [The core component responsible for providing language-specific features and functionalities, such as syntax highlighting, code completion, and diagnostics], // VSCode Text Document [VSCode Text Document], [1.0.11], [A fundamental component of VS Code that represents and manages text documents within the editor], // Lezer [Lezer], [1.7.1], [A high-performance parser generator used for parsing Ungrammar syntax, providing the foundation for language analysis and understanding (@sec-lezer)], // ESBuild [ESBuild], [0.23.0], [A modern JavaScript bundler that offers fast and efficient compilation and optimization for our project (@sec-esbuild)], // Bun [Bun], [1.1.21], [A versatile JavaScript runtime that combines the best features of Node.js and Deno, providing a robust environment for running our application (@sec-bun)], // Astro [Astro], [4.14.5], [A next-generation web framework that streamlines the development of static sites and single-page applications (@sec-astro)], // Preact [Preact], [10.23.2], [A lightweight JavaScript library for building user interfaces (@sec-preact)], // Daisy UI [Daisy UI], [4.12.10], [A popular UI framework built on top of Tailwind CSS, providing a collection of pre-designed components and styles for rapid UI development (@sec-daisyui)], // Lerna [Lerna], [8.1.8], [A tool for managing multiple packages within a single repository (@sec-lerna)], ), caption: [Ungrammar Language Ecosystem Technology Stack], ) ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/001%20-%20Magic%202013/005_Threadbare.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Threadbare", set_name: "Magic 2013", story_date: datetime(day: 23, month: 07, year: 2012), author: "<NAME>", doc ) #figure(image("005_Threadbare/01.png", height: 40%), caption: [], supplement: none, numbering: none) Can you see it? That red dot high in the night sky? It's a harbinger of destruction. There's not much in this mad world you can rely on. But if I am certain about one thing, that red dot is headed straight for me. I am an emissary of pain. I've survived countless battles, seen generations pass into dust, and watched mighty kings tumble into history. I have been tortured and cursed... yet I have survived. I have experienced things that would make most fall to their knees weeping in despair. Yes, I have endured. Not long ago, in the midst of the Slaughter of the Arches, I had a revelation. I was knee deep in the blood and muck of a rain-soaked battlefield. For hours, men and beasts had raged against each other in furious combat. Thunder crashed around me, nearly drowning out the howls of pain and fury. Suddenly, I was overcome with an overwhelming sense of unfairness. If I had a mouth, I would have screamed to the heavens: "Absurdity! Is it all vain absurdity?" In that instant, a golden blade pierced my belly. Staring down at the gilded sword in my gullet, I was struck by a moment of clarity in an insane world. Suddenly, I had to know: Was I made to suffer? #figure(image("005_Threadbare/02.jpg", width: 100%), caption: [Stuffy Doll | Art by <NAME>], supplement: none, numbering: none) Can you see it? That red dot high in the night sky? It's a harbinger of destruction. There's not much in this mad world you can rely on. But if I am certain about one thing, that red dot is headed straight for me. I am an emissary of pain. I've survived countless battles, seen generations pass into dust, and watched mighty kings tumble into history. I have been tortured and cursed... yet I have survived. I have experienced things that would make most fall to their knees weeping in despair. Yes, I have endured. Not long ago, in the midst of the Slaughter of the Arches, I had a revelation. I was knee deep in the blood and muck of a rain-soaked battlefield. For hours, men and beasts had raged against each other in furious combat. Thunder crashed around me, nearly drowning out the howls of pain and fury. Suddenly, I was overcome with an overwhelming sense of unfairness. If I had a mouth, I would have screamed to the heavens: "Absurdity! Is it all vain absurdity?" In that instant, a golden blade pierced my belly. Staring down at the gilded sword in my gullet, I was struck by a moment of clarity in an insane world. Suddenly, I had to know: Was I made to suffer? #figure(image("005_Threadbare/04.jpg", width: 100%), caption: [Stuffy Doll | Art by <NAME>za], supplement: none, numbering: none) After I slogged my way to higher ground, I set out on a quest to find answers. I sought out great mages in illustrious academies of learning. I implored monks in their stark towers to share their hidden knowledge. I fell at the feet of philosophers debating the foundations of life itself. None had answers for a doll in the midst of an existential crisis... just more questions and, inevitably, attempts to harness me for their personal ambitions. For a time, I wandered the back roads and byways in search of a purpose. The sight of a happy peasant family through a cottage window sent me spiraling into despair. Am I alone in the world? Yes, everywhere I look there are other people, but sometimes it feels like no one else can relate. It's like an invisible barrier prevents me from really connecting with anyone else. Pain is ever present. In the end, someone always gets hurt. And I'm hell to be around when I have a guilty conscience. A few months ago, I was kidnapped by bandits and sold to an evil toymaker. He had a stuffed-bear minion who was possessed by the spirit of murdered man. Finally! I believed I was among my own kind and no longer relegated to the punishing whims of a mage. But alas, the stuffed-bear lacked my resilience and was incinerated in his first battle with the villagers. The villagers arrested the toymaker, and I was out on the streets, left to my own threadbare devices. #figure(image("005_Threadbare/05.jpg", width: 100%), caption: [Mist Raven | Art by <NAME>], supplement: none, numbering: none) The ravens mocked me as I set out, alone again. You reach a certain age, and you find yourself asking, #emph[am I more than the sum of my parts] ? Surely I have an essence beyond mere burlap and cotton. With as much torment as I've suffered, am I not entitled to something greater? Soon, the thud of galloping hooves shook the ground. A caravan of nomads rumbled into sight, their tattered banners the last remnants of a kingdom now passed into the enemies' hands. As I was plucked from the roadside and shoved into a shaman's pack, I wanted to rage at the heavens. If I had a fist, I would have shook it at the sky. Do I not have free will? Alas, given my self-destructive tendencies, this has proven to be the least fruitful line of philosophical inquiry of all. #figure(image("005_Threadbare/06.jpg", width: 100%), caption: [Knight of Glory | Art by <NAME>hrbacher], supplement: none, numbering: none) Today, I'm the follower of a mighty nomad shaman. She is yet another contender in the epic struggle for power that plays out over the epochs and changing borders. Tonight, we're locked in battle with a legion of knights, as she pits herself against a famous crusader. I can see him on the ridge overlooking the battlefield. His great helm flashes silver as lightning crashes across the sky. Yet for all his glory, he is oblivious to the red dot, growing larger by the second. Life marches ever onward, and I perambulate an endless road. Despite the battle raging around me, I take a moment to pause and reflect. If I had a spine, I would lift my head toward that beacon of destruction. My fate is vengeful toil, and acceptance is the path of least resistance. After all, I know what's bearing down on me, and how in just seconds, the battle will be over. #figure(image("005_Threadbare/07.jpg", width: 100%), caption: [Shivan Meteor | Art by Chippy], supplement: none, numbering: none) Over for the crusader anyway. Me? It's just another day, another meteor, and no closer to the meaning of life.
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CU/minea/1_generated/00_all/07_marec.typ
typst
#import "../../../all.typ": * #show: book = #translation.at("M_07_marec")
https://github.com/hitszosa/universal-hit-thesis
https://raw.githubusercontent.com/hitszosa/universal-hit-thesis/main/harbin/bachelor/components/typography.typ
typst
MIT License
#let special-chapter-format-heading(it: none, font: none, size: none, weight: "regular") = { set text(font: font, size: size) text(weight: weight)[ #if it != none { it.body } ] v(0.5em) } #let main-format-heading(it: none, font: none, size: none, weight: "regular") = { set text(font: font, size: size) text(weight: weight)[ #counter(heading).display() #if it != none { it.body } ] v(0.5em) }
https://github.com/tlsnotary/docs-mdbook
https://raw.githubusercontent.com/tlsnotary/docs-mdbook/main/research/ole-zero-check.typ
typst
#set page(paper: "a4") #set par(justify: true) #set text(size: 12pt) = Zero Check for Oblivious Linear Evaluation In many subprotocols of TLSNotary we use OLEs to convert shares of a product into shares of a sum. We recall the definition of the functionality: === Functionality $cal(F)_"OLE"$ Define the functionality $cal(F)_"OLE"$. After getting input $a$ from $P_A$ and $b$ from $P_B$ return $x$ to $P_A$ and $y$ to $P_B$ such that $y = a dot b + x$. Problems arise in the presence of a malicious adversary, who inputs $0$ into the protocol, because now $y = x$, which means that privacy for the honest party's output is no longer guaranteed. To address this shortcoming both parties can run the following protocol, which allows an honest party to detect an input of $0$. Without loss of generality let's assume $P_B$ is honest and wants to check if $P_A$ used a 0 input. The protocol can be repeated with roles swapped, to also check that $P_B$ was honest. Note that these executions can be batched. === Protocol $Pi_"OLE-Zero"$ + $P_A$ chooses some OLE input $a_k$ and $P_B$ chooses $b_k$ for $k = 1...l$. These are the base OLEs we want to check for 0 input of $P_A$. + Both parties call $cal(F)_"ROLE" -> (a_0, b_0), (x_0, y_0)$. This is needed as a mask later. + $P_A$ sets $a_(k + 1) := a_(k - l)^(-1)$ , and $P_B$ sets $b_(k + 1) := y_(k - l)$ for $k = l...2l$. + Both parties call $cal(F)_"OLE" (a_k, b_k) -> (x_k, y_k)$ for $k = 1...(2l + 1)$. + $P_A$ computes $ s = sum_(k = 0)^l - x_k dot a_k^(-1) + sum_(k = l + 1)^(2l + 1) - x_k$ and sends $s$ to $P_B$. + $P_B$ checks that $sum_(k = 0)^l b_k = s + sum_(k = l + 1)^(2l + 1) y_k $. If this does not hold $P_B$ aborts. === Intuition + We notice that a linear function has an inverse: $ y(x) &= m x + n \ y^(-1)(x) &= 1/m x - 1/m n $ such that $y^(-1)(y(x)) = x$. So if we have some value $x_0$ and plug it in into $y(x)$ we get $y(x_0) = y_0$. Then the inverse function gives us back $y^(-1)(y_0) = x_0$. + Having a function $y(x) = n$, is a constant function. This function does not have an inverse, because we cannot solve for $x$. So there is no way to get back from $y_0 arrow.r x_0$. But this is the exact thing what happens when some of the parties $P_(A"/"B)$ inputs 0 into the OLE. Maybe we can exploit this to construct some check. + To have an easy example, we now look at a single OLE, but it also works for an arbitrary number. So we want to come up with a check for a single $cal(F)_"OLE" (a_0, b_0) -> (x_0, y_0)$. We assume now $P_B$ wants to check if $P_A$ did input $a_0 = 0$ into this OLE. So $P_A$ inputs $a_0$ and gets $x_0$, and $P_B$ inputs $b_0$ and gets $y_0$, such that $y_0 = a_0 b_0 + x_0$. Notice, how we have the analogy to the linear function. We now have $y(b)$, $P_A$ being the function provider, defining the function with slope $a_0$ and offset $x_0$. $P_B$ is the evaluator, plugging in $b_0$ into $y(b)$ and getting $y_0$. + $P_A$ now has to pass a check. He is required to invert the function, which gives him $ y^(-1) (b) = 1/a b - 1/a x $ Now the problem is that when trying to do an OLE with this inverse function $P_A$ can only invert the slope $a_1$ but not the offset $x_1$ since this is the output of the OLE for him. But what he can do is calculate the difference and send this as a correction to $P_B$. $P_B$ will input his output from the OLE before and expect to get his original input (including a correction term), since they call the inverse function. So both parties will now call the inverse OLE. $P_A$ will input $a_1 = a_0^(-1)$ and $P_B$ will input $b_1 = y_0$, such that $ cal(F)_"OLE" (a_1, b_1) arrow.r (x_1, y_1) = cal(F)_"OLE" (a_0^(-1), y_0) arrow.r (x_1, y_1)$. So the equation will be $ y_1 = 1/a_0 y_0 + x_1 $ Using that $y_0 = a_0 b_0 + x_0$, we get $ y_1 = b_0 + x_0 / a_0 + x_1 $ In other words $P_B$ will get $y_1$ as an output. $P_A$ will send him the correction term $s = -x_0/a_0 - x_1$ and $P_B$ will check that $y_1 + s = b_0$. + The last thing we have to make sure is that $P_B$ cannot abuse this check to get some information about the inputs and outputs of $P_A$. For example, when $P_B$ plugs in a $b_1 eq.not y_0$ he would learn another point on the inverse function, not belonging to the original point. He can easily do the math and arrive at $ x_0 &= (b_0 b_1 -y_0 (y_1 + s)) / (b_0 - y_1 - s) \ a_0 &= (y_0 - x_0) / b_0 \ a_1 &= 1 / a_0 \ x_1 &= - x_0 / a_0 - s $ Since $P_B$ knows $y_0, y_1, b_0, b_1, s$ this would totally leak the inputs and outputs of $P_A$. + We address this by introducing a ROLE which works as a mask for the correction term. $P_A$ and $P_B$ call $cal(F)_"ROLE" arrow.r (a_2, x_2), (b_2, y_2)$ and then the inverse OLE for this ROLE (note this has to be an OLE because it is chosen input) $ cal(F)_"OLE" (a_3, b_3) arrow.r (x_3, y_3) = cal(F)_"OLE" (a_2^(-1), y_2) arrow.r (x_3, y_3)$. Then instead of sending $s = -x_0 / a_0 - x_1$, $P_A$ will send $s = -x_0 / a_0 - x_1 -x_2 / a_2 - x_3$ and $P_B$ will check that $y_1 + y_3 + s = b_0 + b_2$. Note that a single ROLE is enough to mask the correction term for an arbitrary amount of OLEs, not just 1 like in this example.
https://github.com/desid-ms/desid_report
https://raw.githubusercontent.com/desid-ms/desid_report/main/template.typ
typst
MIT License
// Some definitions presupposed by pandoc's typst output. #let blockquote(body) = [ #set text( size: 0.8em ) #align(right, block(inset: (right: 5em, top: 0.2em, bottom: 0.2em))[#body]) ] #let horizontalrule = [ #line(start: (25%,0%), end: (75%,0%)) ] #let endnote(num, contents) = [ #stack(dir: ltr, spacing: 3pt, super[#num], contents) ] #show terms: it => { it.children .map(child => [ #strong[#child.term] #block(inset: (left: 1.5em, top: -0.4em))[#child.description] ]) .join() } // Some quarto-specific definitions. #show raw.where(block: true): block.with( fill: luma(230), width: 100%, inset: 8pt, radius: 2pt ) #let block_with_new_content(old_block, new_content) = { let d = (:) let fields = old_block.fields() fields.remove("body") if fields.at("below", default: none) != none { // TODO: this is a hack because below is a "synthesized element" // according to the experts in the typst discord... fields.below = fields.below.amount } return block.with(..fields)(new_content) } #let empty(v) = { if type(v) == "string" { // two dollar signs here because we're technically inside // a Pandoc template :grimace: v.matches(regex("^\\s*$")).at(0, default: none) != none } else if type(v) == "content" { if v.at("text", default: none) != none { return empty(v.text) } for child in v.at("children", default: ()) { if not empty(child) { return false } } return true } } // Subfloats // This is a technique that we adapted from https://github.com/tingerrr/subpar/ #let quartosubfloatcounter = counter("quartosubfloatcounter") #let quarto_super( kind: str, caption: none, label: none, supplement: str, position: none, subrefnumbering: "1a", subcapnumbering: "(a)", body, ) = { context { let figcounter = counter(figure.where(kind: kind)) let n-super = figcounter.get().first() + 1 set figure.caption(position: position) [#figure( kind: kind, supplement: supplement, caption: caption, { show figure.where(kind: kind): set figure(numbering: _ => numbering(subrefnumbering, n-super, quartosubfloatcounter.get().first() + 1)) show figure.where(kind: kind): set figure.caption(position: position) show figure: it => { let num = numbering(subcapnumbering, n-super, quartosubfloatcounter.get().first() + 1) show figure.caption: it => { num.slice(2) // I don't understand why the numbering contains output that it really shouldn't, but this fixes it shrug? [ ] it.body } quartosubfloatcounter.step() it counter(figure.where(kind: it.kind)).update(n => n - 1) } quartosubfloatcounter.update(0) body } )#label] } } // callout rendering // this is a figure show rule because callouts are crossreferenceable #show figure: it => { if type(it.kind) != "string" { return it } let kind_match = it.kind.matches(regex("^quarto-callout-(.*)")).at(0, default: none) if kind_match == none { return it } let kind = kind_match.captures.at(0, default: "other") kind = upper(kind.first()) + kind.slice(1) // now we pull apart the callout and reassemble it with the crossref name and counter // when we cleanup pandoc's emitted code to avoid spaces this will have to change let old_callout = it.body.children.at(1).body.children.at(1) let old_title_block = old_callout.body.children.at(0) let old_title = old_title_block.body.body.children.at(2) // TODO use custom separator if available let new_title = if empty(old_title) { [#kind #it.counter.display()] } else { [#kind #it.counter.display(): #old_title] } let new_title_block = block_with_new_content( old_title_block, block_with_new_content( old_title_block.body, old_title_block.body.body.children.at(0) + old_title_block.body.body.children.at(1) + new_title)) block_with_new_content(old_callout, new_title_block + old_callout.body.children.at(1)) } // 2023-10-09: #fa-icon("fa-info") is not working, so we'll eval "#fa-info()" instead #let callout(body: [], title: "Callout", background_color: rgb("#dddddd"), icon: none, icon_color: black) = { block( breakable: false, fill: background_color, stroke: (paint: icon_color, thickness: 0.5pt, cap: "round"), width: 100%, radius: 2pt, block( inset: 1pt, width: 100%, below: 0pt, block( fill: background_color, width: 100%, inset: 8pt)[#text(icon_color, weight: 900)[#icon] #title]) + if(body != []){ block( inset: 1pt, width: 100%, block(fill: white, width: 100%, inset: 8pt, body)) } ) } // margin notes #import "@preview/drafting:0.2.0" #let article( title: none, subtitle: none, authors: none, contract: none, project: none, product: none, citation: none, date: none, abstract: none, abstract-title: none, margin: (left: 1cm, top: 1.5cm, right: 7cm, bottom: 1.5cm), paper: "a4", lang: "pt", region: "BR", font: (), fontsize: 11pt, sectionnumbering: "1.1.a", cols: 1, toc: true, toc_depth: 1, toc_title: "Sumário", toc_indent: 1.5em, doc, ) = { set page( paper: "a4", margin: (left: 1cm, top: 1.5cm, right: 7cm, bottom: 1.5cm), numbering: "1", header-ascent: .5cm, footer-descent: .5cm, header: locate(loc => { if (loc.page() != 1) { block( width: 19cm, stroke: (bottom: 1pt + gray), inset: (bottom: 8pt, right: 2pt, left: 2pt), [ #set text(font: "Lato", size: 8pt, fill: gray.darken(50%)) #grid( columns: (1fr, 1fr), align(left, []), align(right, text(weight: "bold", upper[Relatório])), ) ], ) } }), footer: block( width: 19cm, stroke: (top: 1pt + gray), inset: (top: 8pt, right: 2pt), [ #set text(font: "Lato", size: 8pt, fill: gray.darken(50%)) #grid( columns: (75%, 25%), align(left)[#date - #title], align( right )[#counter(page).display() de #locate((loc) => { counter(page).final(loc).first() })], ) ], ) ) set par(justify: true, linebreaks: "optimized") set text(lang: lang, region: region, historical-ligatures: true, ligatures: true, font: "Merriweather", size: 10pt, fractions: true) set heading(numbering: sectionnumbering) show heading: it => { set par(leading: 2em) // set block(spacing: 2em) set text(font:"Lato", weight: "semibold", fractions: true) smallcaps(it) v(.54em) } if title != none { block(width:19cm)[ #text(font: "Lato", fill: gray.lighten(60%), upper[Relatório]) #v(.2cm) #text(font: "Merriweather", size: 20pt, weight: "black", title) #if subtitle != none { v(-.3cm) text(font: "Merriweather", size: 16pt, weight: "regular", subtitle) } #if abstract != none { block(inset: 1.5em)[ #text(weight: "semibold", font:"Lato")[#abstract-title] #h(1em) #text(size: 8pt)[#abstract] ] } else {v(.5cm)} #line(length: 100%, stroke: 3pt + rgb("#316E6B")) #v(.25cm) ] } if authors != none { place(dx:7cm, right, block(width: 7cm,inset: 1em,)[ #set align(left) #block(width: 5.65cm, inset:1em, fill: rgb("#316E6B").lighten(95%), radius: 6pt)[ #set text(font:"Lato", size: 8pt) #for (author) in authors [ #if author.role != none [#text(weight: "bold", author.role) \ ] #h(1em)#author.name #if author.affiliation!=none {text(font: "SF Mono")[(#author.affiliation)]} #if author.email != none [#v(-.5em)#h(1em)#text(size: 7pt, font: "SF Mono", author.email)] ] #if contract != none [ *Contrato* #h(1em)#text(size: 7pt, font: "SF Mono", contract) ] #if project != none [ *Projeto* #h(1em)#text(size: 7pt, font: "SF Mono", project) ] #if product != none [ *Produto* #h(1em)#text(size: 7pt, font: "SF Mono", product) ] #if date != none [ *Publicação* #h(1em)#text(size: 7pt, font: "SF Mono", date) ] ] #if toc { v(1cm) set text(size:.6em, font: "Lato") block(above: 0em, below: 2em)[ #outline( title: "Sumário", depth: 2, indent: 1em ); ] } ] ) } if cols == 1 { doc } else { columns(cols, doc) } } #set table( inset: 6pt, stroke: none ) // Typst custom formats typically consist of a 'typst-template.typ' (which is // the source code for a typst template) and a 'typst-show.typ' which calls the // template's function (forwarding Pandoc metadata values as required) // // This is an example 'typst-show.typ' file (based on the default template // that ships with Quarto). It calls the typst function named 'article' which // is defined in the 'typst-template.typ' file. // // If you are creating or packaging a custom typst template you will likely // want to replace this file and 'typst-template.typ' entirely. You can find // documentation on creating typst templates here and some examples here: // - https://typst.app/docs/tutorial/making-a-template/ // - https://github.com/typst/templates #show: doc => article( title: [Título do Relatório], authors: ( ( name: [<NAME>], affiliation: [MS], role: [Autor], email: [<EMAIL>] ), ), date: [2024-07-29], contract: [Nome do Contrato], product: [Produto 1], lang: "pt", region: "BR", abstract: [Resumo opcional do relatório ("abstract"). O Resumo oferece uma visão geral concisa e clara dos principais pontos do trabalho, permitindo ao leitor compreender rapidamente o conteúdo e os objetivos da pesquisa sem precisar ler o documento inteiro. Um bom resumo deve conter informações suficientes para que o leitor possa avaliar a relevância do estudo para seus próprios interesses e determinar se deve ler o trabalho completo. ], abstract-title: "Resumo", toc_title: [Índice], toc_depth: 3, cols: 1, doc, ) = Introdução <introdução> #emph[TODO] Create an example file that demonstrates the formatting and features of your format. = Mais informações <mais-informações> You can learn more about creating custom Typst templates here: #link("https://quarto.org/docs/prerelease/1.4/typst.html#custom-formats")
https://github.com/r8vnhill/apunte-bibliotecas-de-software
https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/unit3.typ
typst
#import "@preview/ctheorems:1.1.2": * #show: thmrules #let definition = thmbox("definition", "Definición", inset: (x: 1.2em, top: 1em)) = Unidad 3: Build systems #definition("Build system")[ Un sistema de compilación es una herramienta de software que automatiza el proceso de convertir código fuente en un ejecutable o una librería, realizando tareas como la compilación de código, gestión de dependencias y empaquetado de software. ] Estos sistemas son esenciales para la gestión eficiente de proyectos de software, especialmente en entornos donde la escalabilidad y la reproducibilidad son importantes. #include "Unit3/BuildSystems.typ" #include "Unit3/StaticAnalysis.typ" #include "Unit3/Tasks.typ" #include "Unit3/Plugins.typ" #include "Unit3/Compilation.typ" #include "Unit3/Publish.typ" == Respuestas *Ejercicio: Orden de Ejecución de Acciones* ```txt First Action - Preparation Step 2 First Action - Preparation Step 1 Last Action - Cleanup Step 1 Last Action - Cleanup Step 2 ``` *Ejercicio: Tamaño del Proyecto* ```kt tasks.register("countCompiledSize") { group = "build" description = "Count the size of the compiled classes" dependsOn("compileKotlin") doLast { val files = fileTree("build/classes/kotlin/main") var size = 0L for (file in files) { size += file.length() } println( "The size of the compiled classes in subproject1 is $size bytes" ) } } ``` *Ejercicio: Tarea de Fibonacci* ```txt Preparing to calculate the 10th Fibonacci number The 10th Fibonacci number is 55 Finished calculating the 10th Fibonacci number ``` *Ejercicio: Reporte de Archivos* ```kt class KotlinFilesReportPlugin : Plugin<Project> { override fun apply(project: Project) { project.tasks.register("generateKotlinFilesReport") { group = "reporting" description = "Generates a report of all Kotlin files in the project." doLast { val kotlinFiles = project.fileTree(".").matching { include("**/*.kt", "**/*.kts") }.files println("Kotlin Files Report:\n\n") for (file in kotlinFiles) { println(file.name) } } } } } apply<KotlinFilesReportPlugin>() ```
https://github.com/UriMtzF/typst-templates
https://raw.githubusercontent.com/UriMtzF/typst-templates/main/uaemex-heading/main.typ
typst
MIT License
#import "lib.typ": * #show: project.with( subject: "Materia", title: "Título", authors: "Author", accountNum: "1234567" )
https://github.com/Tran-Thu-Le/tybank
https://raw.githubusercontent.com/Tran-Thu-Le/tybank/main/utils.typ
typst
#import "@preview/suiji:0.1.0": * #let print(x) = [#x\ ] #let permute_choices(random_seed, number_of_questions, permute_bool) = { let perm = range(number_of_questions).map(x=>range(4)) if permute_bool { for i in range(number_of_questions) { (random_seed, perm.at(i)) = shuffle(random_seed, range(4)) } } return perm } #let permute_questions(random_seed, number_of_questions, permute_bool) = { let hoanvi = range(number_of_questions) if permute_bool { hoanvi = shuffle(random_seed, range(number_of_questions)).at(1) } return hoanvi } #let format_a_choice(choice: str, correct: false) = { let choice = [*#choice*] if correct { // choice = highlight(underline(choice)) // choice = rect(highlight(choice)) choice = box(stroke: black, inset: (x: 1pt, y: 1pt), fill: yellow)[#choice] // choice = inline(circle(fill: yellow, height: 2em, stroke: black)[#align(center)[#choice]]) } return choice } #let get_position_of_correct_answer_after_permutation(question, permutation) = { let dapandung_vitri_bandau = question.correct_choice for i in (0,1,2,3) { if dapandung_vitri_bandau == permutation.at(i) { return i break } } } #let position_to_abcd(i) = { if i==0 { return "A" } else if i==1 { return "B" } else if i==2 { return "C" } else if i==3 { return "D" } } #let format_choices(question, permutation, correct: false)={ let noidung_dinhdang = () let dapan_nhan = ("A.", "B.", "C.", "D.") let luachon_noidung = ( question.choice0, question.choice1, question.choice2, question.choice3, ) let dapandung_vitri_bandau = question.correct_choice for i in (0,1,2,3) { let dapan_kytu = format_a_choice(choice: dapan_nhan.at(i), correct: correct and permutation.at(i) == dapandung_vitri_bandau) noidung_dinhdang.push([#(dapan_kytu + " " + luachon_noidung.at(permutation.at(i)))]) } return noidung_dinhdang } #let motdong(caua, caub, cauc, caud) = { grid( columns: (1fr, 1fr, 1fr, 1fr), gutter: 10pt, caua, caub, cauc, caud, ) } #let haidong(caua, caub, cauc, caud) = { grid( columns: (1fr, 1fr), gutter: 10pt, caua, caub, cauc, caud, ) } #let bondong(caua, caub, cauc, caud) = { grid( columns: (1fr), gutter: 10pt, caua, caub, cauc, caud, ) } #let display_choices(choices, textwidth) = { context { let widthof(x) = measure(x).width // measure() can only be called inside context let cau-dai-nhat = calc.max(widthof(choices.at(0)), widthof(choices.at(1)), widthof(choices.at(2)), widthof(choices.at(3))) if cau-dai-nhat < 0.2*textwidth { motdong(choices.at(0), choices.at(1), choices.at(2), choices.at(3)) } else if cau-dai-nhat < 0.45*textwidth { haidong(choices.at(0), choices.at(1), choices.at(2), choices.at(3) ) } else { bondong(choices.at(0), choices.at(1), choices.at(2), choices.at(3) ) } } // end of context } // end of display_choices() #let display_list_of_correct_choices(questions, permuted_questions, permuted_choices) = { let number_of_questions = questions.len() let answers =() for i in range(number_of_questions) { let permuted_index = permuted_questions.at(i) let correct_choice_after_perm = position_to_abcd(get_position_of_correct_answer_after_permutation(questions.at(permuted_index), permuted_choices.at(i))) let dapani = [Câu #str(i+1). #correct_choice_after_perm] answers.push(dapani) } for i in range(number_of_questions) { if calc.rem(i, 5)==0 { [\ ] } [#answers.at(i) \ ] } } // -------------------------- // Variation table // -------------------------- // #let row0 = "x -oo ... 1 ... 2 ... +oo" // #let row1 = "y' ... - 0 + 0 - ..." // // #let row2 = "y +oo arrow.br 2 arrow.tr -2 arrow.br -oo" // #let row2 = "y +oo down 2 up -2 down -oo" #let vartab_str2typ(..strings) ={ let a = () for (i, astr) in strings.pos().enumerate() { let items = astr.split() for (i,item) in items.enumerate() { if item == "..." { items.at(i) = " " } else if item == "up" { items.at(i) = "arrow.tr" } else if item == "down" { items.at(i) = "arrow.br" } } let items = "($"+items.join("$, $")+"$)" let items = eval(items) a.push(items) } return a } #let variation_table(..rows) = { let the_rows = vartab_str2typ(..rows) let n = the_rows.at(0).len() let new_rows = () for (i,items) in the_rows.enumerate() { for (j, item) in items.enumerate() { new_rows.push(item) } if i< the_rows.len()-1 { new_rows.push(table.hline(start: 0)) } } align(center, table( stroke: none, align: center, table.vline(start: 0, x: 1), columns: range(n).map(i=> auto), ..new_rows )) } // #variation_table(row0, row1, row2)
https://github.com/hei-templates/hevs-typsttemplate-thesis
https://raw.githubusercontent.com/hei-templates/hevs-typsttemplate-thesis/main/02-main/03-analysis.typ
typst
MIT License
#import "../00-templates/helpers.typ": * #pagebreak() = Analysis <sec:analysis> #lorem(50) #minitoc(after:<sec:analysis>, before:<sec:design>) #pagebreak() == Section 1 #lorem(50) == Section 2 #lorem(50) == Conclusion #lorem(50)
https://github.com/Cubik65536/typst-playground
https://raw.githubusercontent.com/Cubik65536/typst-playground/main/vector-maybe.typ
typst
#import "@preview/cetz:0.2.2" #cetz.canvas({ import cetz: * import cetz.plot import cetz.draw: * line((0,0), (x: 10), mark: (end: ">"), name: "x-axis") line((0,0), (y: 10), mark: (end: ">"), name: "y-axis") line((0,0), (x: -3), name: "x-axis-neg") line((0,0), (y: -3), name: "y-axis-neg") line((1, 1), (2, 3), (1, 2), (0, 0), fill: yellow) set-style(content: (stroke: none, fill: none, padding: .1)) content( "x-axis.end", anchor: "north", padding: .15, [x] ) content( "y-axis.end", anchor: "west", padding: .15, [y] ) line((0, 0), (1, 1), mark: (end: ">"), stroke: green, name: "vector-a") line((1, 1), (2, 3), mark: (end: ">"), stroke: red, name: "vector-b") content( "vector-a.end", anchor: "west", padding: .2, [(1, 1)] ) content( (name: "vector-a", anchor: 75%), anchor: "north-west", padding: .1, [$arrow(a)$] ) content( "vector-b.end", anchor: "south-west", [(2, 3)] ) content( (name: "vector-b", anchor: 75%), anchor: "north-west", padding: .1, [$arrow(b)$] ) line((0, 0), (2, 3), mark: (end: ">"), stroke: blue, name: "vector-c") content( "vector-c.end", anchor: "south-west", [(2, 3)] ) content( (name: "vector-c", anchor: 75%), anchor: "south-east", padding: .1, [$arrow(c)$] ) }) $ arrow(a) + arrow(b) = arrow(c) $
https://github.com/jrihon/multi-bibs
https://raw.githubusercontent.com/jrihon/multi-bibs/main/lib/layout.typ
typst
MIT License
// Layout template file #let layout(document) = { set text( font: "Roboto", weight: "regular", size: 11pt, ) set align(left) set page( paper: "a4", margin: ( left: 2cm, right: 2cm, top: 2cm, bottom: 2cm, ), ) document }
https://github.com/Mufanc/hnuthss-template
https://raw.githubusercontent.com/Mufanc/hnuthss-template/main/pages/acknowledgments.typ
typst
#import "/configs.typ": font, fontsize #import "/components.typ": anchor, paragraph, fp #let acknowledgments = [ #align(center, text(size: fontsize.L3, font: font.sans)[致#h(2em)谢]) #anchor[致 谢] #v(2em) #paragraph[ #fp 这篇毕业论文是我用心血和汗水浇灌出来的成果,是我学术生涯的里程碑。在耗时半年的刻苦努力中,我不断攀登知识的高峰,翻阅文献,进行实验,分析数据,推敲论点,每一步都是迈向成功的脚印。当我最终在电脑屏幕上敲下最后一个字时,内心涌动着一股成就感和喜悦。 在此,我要深深感谢我的导师和指导老师,他们的悉心指导和耐心教诲让我受益良多,是我学术道路上的引路人。同时,也要感谢所有支持我、鼓励我、帮助过我的家人、朋友和同学们,在我遇到困难时给予我无私的支持和关怀。 最后,我要特别感谢大学四年的生活!这四年是我人生中最宝贵的时光,是我收获知识、结交朋友、成长成才的重要阶段。在这里,我度过了无数个日日夜夜,留下了难忘的回忆和珍贵的经历,这些都将成为我人生道路上闪烁的星光,照亮我前行的方向。 感谢所有给予我支持和帮助的人们,正是有了你们的支持和鼓励,我才能完成这篇论文,迈向新的征程。愿我们共同披荆斩棘,勇往直前,创造更加美好的明天! #align(right, "—— ChatGPT" + h(1em)) ] ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-27C0.typ
typst
Apache License 2.0
#let data = ( ("THREE DIMENSIONAL ANGLE", "Sm", 0), ("WHITE TRIANGLE CONTAINING SMALL WHITE TRIANGLE", "Sm", 0), ("PERPENDICULAR", "Sm", 0), ("OPEN SUBSET", "Sm", 0), ("OPEN SUPERSET", "Sm", 0), ("LEFT S-SHAPED BAG DELIMITER", "Ps", 0), ("RIGHT S-SHAPED BAG DELIMITER", "Pe", 0), ("OR WITH DOT INSIDE", "Sm", 0), ("REVERSE SOLIDUS PRECEDING SUBSET", "Sm", 0), ("SUPERSET PRECEDING SOLIDUS", "Sm", 0), ("VERTICAL BAR WITH HORIZONTAL STROKE", "Sm", 0), ("MATHEMATICAL RISING DIAGONAL", "Sm", 0), ("LONG DIVISION", "Sm", 0), ("MATHEMATICAL FALLING DIAGONAL", "Sm", 0), ("SQUARED LOGICAL AND", "Sm", 0), ("SQUARED LOGICAL OR", "Sm", 0), ("WHITE DIAMOND WITH CENTRED DOT", "Sm", 0), ("AND WITH DOT", "Sm", 0), ("ELEMENT OF OPENING UPWARDS", "Sm", 0), ("LOWER RIGHT CORNER WITH DOT", "Sm", 0), ("UPPER LEFT CORNER WITH DOT", "Sm", 0), ("LEFT OUTER JOIN", "Sm", 0), ("RIGHT OUTER JOIN", "Sm", 0), ("FULL OUTER JOIN", "Sm", 0), ("LARGE UP TACK", "Sm", 0), ("LARGE DOWN TACK", "Sm", 0), ("LEFT AND RIGHT DOUBLE TURNSTILE", "Sm", 0), ("LEFT AND RIGHT TACK", "Sm", 0), ("LEFT MULTIMAP", "Sm", 0), ("LONG RIGHT TACK", "Sm", 0), ("LONG LEFT TACK", "Sm", 0), ("UP TACK WITH CIRCLE ABOVE", "Sm", 0), ("LOZENGE DIVIDED BY HORIZONTAL RULE", "Sm", 0), ("WHITE CONCAVE-SIDED DIAMOND", "Sm", 0), ("WHITE CONCAVE-SIDED DIAMOND WITH LEFTWARDS TICK", "Sm", 0), ("WHITE CONCAVE-SIDED DIAMOND WITH RIGHTWARDS TICK", "Sm", 0), ("WHITE SQUARE WITH LEFTWARDS TICK", "Sm", 0), ("WHITE SQUARE WITH RIGHTWARDS TICK", "Sm", 0), ("MATHEMATICAL LEFT WHITE SQUARE BRACKET", "Ps", 0), ("MATHEMATICAL RIGHT WHITE SQUARE BRACKET", "Pe", 0), ("MATHEMATICAL LEFT ANGLE BRACKET", "Ps", 0), ("MATHEMATICAL RIGHT ANGLE BRACKET", "Pe", 0), ("MATHEMATICAL LEFT DOUBLE ANGLE BRACKET", "Ps", 0), ("MATHEMATICAL RIGHT DOUBLE ANGLE BRACKET", "Pe", 0), ("MATHEMATICAL LEFT WHITE TORTOISE SHELL BRACKET", "Ps", 0), ("MATHEMATICAL RIGHT WHITE TORTOISE SHELL BRACKET", "Pe", 0), ("MATHEMATICAL LEFT FLATTENED PARENTHESIS", "Ps", 0), ("MATHEMATICAL RIGHT FLATTENED PARENTHESIS", "Pe", 0), )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/justify-hanging-indent_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set par(hanging-indent: 2.5cm, justify: true) #lorem(5)
https://github.com/CryptoFraudDetection/paper
https://raw.githubusercontent.com/CryptoFraudDetection/paper/main/main.typ
typst
MIT License
#import "template.typ": template #import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge #import fletcher.shapes: house, hexagon // Load template & set header #show: template.with( title: [Fraud Detection of Cryptocurrencies], authors: ( ( name: "<NAME>", organization: [Fachhochschule Nordwestschweiz], email: "<EMAIL>" ), ( name: "<NAME>", organization: [Fachhochschule Nordwestschweiz], email: "<EMAIL>" ), ( name: "<NAME>", organization: [Fachhochschule Nordwestschweiz], email: "<EMAIL>" ), ( name: "<NAME>", organization: [Fachhochschule Nordwestschweiz], email: "<EMAIL>" ), ), abstract: [ #lorem(200) ], ) // Start of body = Introduction #lorem(100) #lorem(120) #colbreak() == Overview #lorem(50) #v(4pt) #figure([ #let blob(pos, label, tint: white, ..args) = node( pos, align(center, label), width: 26mm, fill: tint.lighten(60%), stroke: 1pt + tint.darken(20%), corner-radius: 5pt, ..args, ) #diagram( spacing: 8pt, cell-size: (8mm, 10mm), edge-stroke: 1pt, edge-corner-radius: 5pt, mark-scale: 70%, blob((0,1), [Add & Norm], tint: yellow, shape: hexagon), edge(), blob((0,2), [Multi-Head\ Attention], tint: orange), blob((0,4), [Input], shape: house.with(angle: 30deg), width: auto, tint: red), for x in (-.3, -.1, +.1, +.3) { edge((0,2.8), (x,2.8), (x,2), "-|>") }, edge((0,2.8), (0,4)), edge((0,3), "l,uu,r", "--|>"), edge((0,1), (0, 0.35), "r", (1,3), "r,u", "-|>"), edge((1,2), "d,rr,uu,l", "--|>"), blob((2,0), [Softmax], tint: green), edge("<|-"), blob((2,1), [Add & Norm], tint: yellow, shape: hexagon), edge(), blob((2,2), [Feed\ Forward], tint: blue), ) #v(8pt) ], caption: [A curious figure. @noauthor_chatgpt_2024], placement: none ) <figure_id> #lorem(50) = Methods #lorem(300) = Results #lorem(200) = Insights #lorem(200) = Acknowledgments #lorem(50)
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/type_check/annotation_tag.typ
typst
Apache License 2.0
/// #let tag-full = `tag("configs", ns: "@preview/touying")` /// #let tag = `tag("configs")` /// /// -> tag #let config-common() = none
https://github.com/jneug/schule-typst
https://raw.githubusercontent.com/jneug/schule-typst/main/src/themes/default.typ
typst
MIT License
// TODO: Improve theme support // TODO: Add more theme style keys #let typst-text = text // General colors #let primary = rgb(40, 70, 167) #let secondary = rgb(204, 74, 71) #let muted = luma(174) // General backgrounds #let bg = ( primary: primary.lighten(90%), secondary: secondary.lighten(90%), muted: muted.lighten(90%), code: muted.lighten(90%), solution: muted.lighten(85%), ) // Text colors #let text = ( default: black, light: white, header: luma(20%), // primary footer: luma(70%), title: primary, subject: luma(33%), primary: white, secondary: white ) // Font settings #let fonts = ( default: ( "Fira Sans", "Liberation Sans", "Avenir Next", "Avenir", "Helvetica Neue", "Helvetica", "Apple Color Emoji", ), headings: ("Charter", "Georgia", "Apple Color Emoji"), code: ("Fira Code", "Liberation Mono", "Courier New"), serif: (/*"EB Garamond 12",*/ "Garamond", "Charter", "Georgia"), sans: ("Fira Sans", "Liberation Sans", "Avenir Next", "Avenir", "Helvetica Neue", "Helvetica"), ) // Table colors and styles #let table = ( header: bg.primary, even: bg.muted, odd: white, stroke: .6pt + muted, ) #let cards = { let (type1, type2, type3, help) = ( rgb("#36c737"), rgb("#ffcc02"), rgb("#cd362c"), rgb("#b955b6"), ) ( type1: gradient.linear(type1.lighten(15%), type1.darken(33%), angle: 90deg), type2: gradient.linear(type2.lighten(15%), type2.darken(33%), angle: 90deg), type3: gradient.linear(type3.lighten(15%), type3.darken(33%), angle: 90deg), help: gradient.linear(help.lighten(15%), help.darken(33%), angle: 90deg), back: rgb("#ffffb2"), ) } #let init(body) = { body }
https://github.com/CheneyNine/Resume-in-Typst-Template
https://raw.githubusercontent.com/CheneyNine/Resume-in-Typst-Template/main/Typst中文教程.typ
typst
// 设置页面 #set page( paper:"a4", margin: ( top:27.5mm, bottom:25.4mm, left:35.7mm, right:27.7mm ), header:[ #set text(10pt) #h(1fr) #emph("Typst 中文文档 translated by Casea") #v(-0.8em) #line(length:100%,stroke:1pt) ], numbering:"1/1", number-align:center, ) // 设置正文文字格式 #set text( font:("Times New Roman","SimSun"), style:"normal", weight:"regular", size: 12pt, ) // 设置段落 #set par( leading:20pt, justify: true, first-line-indent: 2em, ) // 设置标题格式 #set heading(numbering: "1.1.1.1") #show heading: it => locate(loc => { let levels = counter(heading).at(loc) let deepest = if levels != () { levels.last() } else { 1 } set text(12pt) if it.level == 1 [ #if deepest !=1 { // pagebreak() } #set par(first-line-indent: 0pt) #set align(center) #let is-ack = it.body in ([Acknowledgment], [Acknowledgement]) #set text(if is-ack { 15pt } else { 15pt },font:("Times New Roman","SimSun")) #v(36pt, weak: true) #if it.numbering != none and not is-ack { numbering("第 1 章", deepest) h(3pt, weak: true) } #it.body #v(36pt, weak: true) ] else if it.level == 2 [ #set par(first-line-indent: 0pt) #set text(size:14pt,font:("Times New Roman","SimSun")) #v(24pt, weak: true) #if it.numbering != none { numbering("1.1 ",..levels) h(3pt, weak: true) } #it.body #v(24pt, weak: true) ] else if it.level == 3 [ #set par(first-line-indent: 0pt) #set text(size:14pt,font:("Times New Roman","SimSun")) #v(15pt, weak: true) #if it.numbering != none { numbering("1.1.1 ",..levels) h(3pt, weak: true) } #it.body #v(15pt, weak: true) ] else [ #set par(first-line-indent: 0pt) #set text(size:12pt,font:("Times New Roman","SimSun")) #v(12pt, weak: true) #if it.numbering != none { numbering("1.1.1.1 ",..levels) h(3pt, weak: true) } #it.body #v(12pt, weak: true) ] }) // 设置代码块样式 // 设置block格式 #let blockk(term)=block(width:100%,inset: 7pt,radius:5pt,stroke: gray+1pt)[ #set par(first-line-indent:0em) #text(weight:700,size:11pt,fill: rgb("#FF0000"),"#Demo") \ #term ] #show raw.where(block: false): box.with( fill: luma(240), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) #show raw.where(lang:"typ"): it=>{ block(width:100%,fill:luma(245),inset:10pt,radius: 5pt,stroke:0.8pt+rgb("#00B7FF").darken(10%))[ #par(leading: 1em, justify:true, linebreaks: "optimized", first-line-indent: 0em, text(font: "Monospac821 BT", style: "normal", weight:"regular", size:10pt, spacing: 100%, text(font: "Inria Serif", weight:700,size:11pt,fill: rgb("#FF0000"),"#Code") + it ) ) ] } #show raw.where(lang:"para"): it=>{ block(width:100%,fill:luma(245),inset:10pt,radius: 5pt,stroke:0.8pt+rgb("#000000").darken(10%))[ #par(leading: 1em, justify:true, linebreaks: "optimized", first-line-indent: 0em, text(font: "Inria Serif", style: "normal", weight:"regular", size:10pt, spacing: 200%, text(font: "Inria Serif",weight:700,size:11pt,fill: rgb("#FF0000"),"#Func") + it ) ) ] } // 封面 #[ #set page(header:none,numbering:none) #set align(right) #set terms(separator:[: ]) #place( right, dy:20%, text(weight:700,size:28pt)[一份(不太)简短的Typst介绍], ) #line(start:(0%,25%),end:(100%,25%),length:100%,stroke: 5pt) #place( right, dy:2%, text(weight:400,style:"italic",size:16pt)[Typst官方文档中文翻译版], ) #place( right, dy:36%, text(weight:400,style:"italic",size:16pt)[中文翻译: Casea] ) #place( right, dy:40%, text(weight:400,style:"italic",size:16pt)[版本: June 30, 2023] ) #place( right, dy:44%, text(weight:400,style:"italic",size:16pt)[日期: July 03, 2023] ) ] #pagebreak() // 前言 #[ #set page(header:none,numbering:none) #set align(center) #text(weight:700,size:28pt)[前言] #set align(left) 此文档是我在#link("https://typst.app/")[学习Typst时],翻译官方manual时的一些记录。目前,全文已经翻译完了,但是请时刻关注翻译的版本与官网的版本。因为有一定的翻译滞后性以及官网更新的频繁,所以可能出现有些功能不能使用。之后的工作就是好好优化一下页面的排版。#parbreak() 粗略地制作了文档的封面,该封面是仿照《一份(不太)简短的LaTeX 2e介绍》制作的,在此感谢。#parbreak() 目前来说Typst很对我的胃口,但是还是存在着很多的问题,但我相信随着更新与发展,typst一定会越来越好用。#parbreak() 欢迎加入#link("https://typst.cn/#/")[typst中文社区:https://typst.cn]! #set align(right) Casea #parbreak() 2023.04.22 ] #pagebreak() // 更新历史 #[ #set page(header:none,numbering:none) #set par(first-line-indent:0em) #set align(center) #text(weight:700,size:20pt)[Change logs] #set align(left) #set list(marker: ([•], [-])) - *2023.06.30 Version 0.6.0:* - 内置了包管理工具。可以导入社区发布包或者自行创建。 - *2023.06.23 Version 0.5.0:* - 支持更多代码高亮。 - 扩展了大纲格式设定。 - 公式语法规则改进: `$f^abs(3)$` 被解释为 `$f^(abs(3))$`,可以通过添加空格消除歧义:`$f^zeta (3)$`。 - 对数学公式添加了强制尺寸命令。 - 添加datetime类型 - *2023.05.20 Version 0.4.0:* - 添加对footnote的支持。 - 添加对LaTex用户的指南 - 注:一些笔者认为的小修改并未加入到此手册中。 - *2023.04.26 Version 0.3.0:* - 重命名了一些符号:`dot.op->dot` `dot->dpt.basic` `ast`和`tlide`同理。 - 将`mod`重命名为`rem`,目前`mod`仍可使用,直到版本更新。 - 移除`query`函数的`before`和`after`定位参数,改用`selector()`函数进行定位。`query(heading,before:loc)` -> `query(selector(heading).before(loc),loc)` - `bottom`和`top`重命名为`b`和`t`,支持左右上下标。 - 支持删除线样式。支持pdf大纲显示。 - *2023.04.22:* - loops取消了对index和value的迭代,现在可以通过unpacking和enumerating处理。map()方法同理。目前的写法`(index,value) in keys.enumerate()`。 - 字典方法现在可以使用插入顺序而不是字母顺序。 - 新增了`unpacking(),enumerate(),path,layout,sorted()`method。 - 添加了`New Computer Modern`字体。 - *2023.04.09:* - 对于源码部分使用等宽字体`Monospac821 BT`,感谢supernova的建议。 - 对标题进行了部分汉化,但是是缺少一点味道。 - 附录添加了symbol速查表。 - *2023.04.05:* - 2023/04/04 typst推出了v0.1的正式版本,修正了编号问题(目前从0开始)。在我看来其最大的改进就是中文排版的优化(并不支持斜体加粗等格式)。 - 2023/4/5 14:07:58 已完成官方文档的翻译,但是总觉得还缺点什么。想了想那便是自己的理解吧:单纯翻译文档谁都可以做,但是如何使文档更加通俗易懂以及让人快速上手就需要下一点功夫了。 - 接下来的安排:使用show set规则将typ文件大幅缩短(预计一半篇幅);文章结构(调整章节顺序,语句修改);优化排版(力气活 \u{1F921})。 ] #pagebreak() // 生成目录 #[ #set par(first-line-indent: 0em) #set page(header:none,numbering:"I") #counter(page).update(1) #outline(title: "目录",indent:true,depth:2) ] #pagebreak() #counter(page).update(1) #[ #set heading(numbering: none) #show heading: it => block[ #set align(center) #set text(size:28pt,weight:700) #it.body ] = Part I Guide for LaTex Users ] #[ #set heading(numbering: none) = 前言 此部分将会简明的介绍LaTeX和Typst的差异之处,并使LaTeX玩家快速上手Typst。 就像LaTeX,Typst是一个基于标记的排版系统。你可以在文本文件中编写文档,并使用命令和语法进行标记。然后使用编译器将源文件排版为PDF格式。然而,Typst在以下几个方面不同于LaTeX:一方面,Typst 使用更专用的语法(就像您可能从 Markdown 中了解到的那样)用于常见任务。 Typst 的命令也更有原则性:它们的工作原理相同,因此与 LaTeX 不同,您只需要了解几个通用概念,而不是学习每个包的不同约定。此外,Typst 的编译速度比 LaTeX 快:编译通常需要几毫秒,而不是几秒钟,因此 Web 应用程序和编译器都可以提供即时预览。 我们将在下文介绍从 LaTeX 转换过来的用户在使用 Typst 编写文档时遇到的一些最常见的问题。如果您更喜欢 Typst 的分步介绍,请查看我们的教程。 = 创建文档 就像LaTeX创建`.tex`文件一样,Typst只需要创建`.typ`文件即可。无需提供模板文件。默认情况使用的是A4大小的页面,如果使用web版,只需要单击`+ Empty document`,就可以创建项目并进入编辑器。和LaTeX一样只需要使用空行就可以实现段落。 = 如何创建章标题,强调? LaTeX使用命令`\section`、`\subsection`、`\subsubsection`创建章标题与子标题。根据写作内容的不同,还支持`\part`和`\chapter`。 在Typst中,标题的表现形式十分简约:`= Introduction`、`== In this paper`。标题的深度取决于你使用了多少个等号`=`。 内容强调通常以斜体文本的形式呈现,通过将文本括在下划线中表示\(`_underscores_`\),着重强调使用粗体表示\(`*stars*`\)。 如下表格为LaTeX命令与Typst命令的对比。也可以查看完整的cheatsheet。 #table( columns:(auto,auto,auto,auto), inset:10pt, align:horizon, [*Element*],[*LaTeX*],[*Typst*],[*See*], [Strong emphasis],[\textbf{strong}],[*strong*],[@strong], [Emphasis],[\emph{emphasis}],[_emphasis_],[@emph], [Monospace code],[\texttt{print(1)}],[`print(1)`],[@raw], [Link],[\url{https://typst.app}],[https://typst.app/],[@link], [Label],[\label{intro}],[\<intro\>],[@label], [Reference],[\ref{intro}],[\@intro],[@ref], [Citation],[\cite{humphrey97}],[\@humphrey97],[@cite], [Bullet list],[itemize environment],[- List],[@list], [Numbered list],[enumerate environment],[\+ List],[@enum], [Term list],[description environment],[\/ Term: List],[@terms], [Figure],[figure environment],[figure function],[@image], [Table],[table environment],[table function],[@table], [Equation],[\$x\$, align / equation environments],[\$x\$, \$ x = y \$],[@equation], ) Typst中Lists不依赖于环境。相反的,他们具有像标题一样的轻量化语法。如果需要创建无序列表,只需要在列表项前面加连字符。 ```typ To write this list in Typst... ``` ```latex \begin{itemize} \item Fast \item Flexible \item Intuitive \end{itemize} ``` ```typ ...just type this: - Fast - Flexible - Intuitive ``` #[ #show:blockk To write this list in Typst... ```latex \begin{itemize} \item Fast \item Flexible \item Intuitive \end{itemize} ``` ...just type this: - Fast - Flexible - Intuitive ] 通过将它们缩进到连字符之外,您还可以在单​​个列表项中包含多个段落或嵌套列表。如果列表项变得更长,最好在列表项之间放置空行。这会增加列表项之间的间距。 要改为获取编号列表(枚举),请使用 + 而不是连字符。对于术语列表(描述),写 `/ Term: Description` 代替。 = 命令 LaTeX 严重依赖命令(以反斜杠为前缀)。它使用这些宏来影响排版过程以及插入和操作内容。一些命令接受参数,最常见的是它们被括在花括号中:`\cite{rasmus}`。 Typst 区分标记模式和代码模式。标记模式是默认设置,您可以在其中编写文本并使用语法结构,例如`*`星号表示粗体文本。代码模式类似于 Python 等其他编程语言,允许您编写类似 `1 + 2 == 3` 的代码。 在 Typst 的标记中,您可以使用井号`#`为单个命令(或者更确切地说,表达式)切换到代码模式。这就是您调用函数和使用标记内导入等功能的方式。在这些命令和函数调用中,代码模式适用。要将内容作为值嵌入,您可以使用方括号返回标记模式: ```typ First, a rectangle: #rect() Let me show how to do #underline([_underlined_ text]) We can also do some maths: #calc.max(3, 2 * 4) And finally a little loop: #for x in range(3) [ Hi #x. ] ``` #[ #show:blockk First, a rectangle: #rect() Let me show how to do #underline([_underlined_ text]) We can also do some maths: #calc.max(3, 2 * 4) And finally a little loop: #for x in range(3) [ Hi #x. ] ] 函数调用总是涉及函数的名称(rect、underline、calc.max、range),然后是参数列表,即使它是空的。参数列表括在括号中。 一个函数可以有多个参数。一些参数是位置性的,即您只需提供值:函数 `#lower("SCREAM")` 以全小写形式返回其参数。许多函数使用命名参数而不是位置参数来提高易读性。例如,矩形的尺寸和笔划是使用命名参数定义的: ```typ #rect( width: 2cm, height: 1cm, stroke: red, ) ``` #[ #show:blockk #rect( width: 2cm, height: 1cm, stroke: red, ) ] 您可以通过首先输入名称(如上所示,width, height, and stroke)、冒号和值`(2cm, 1cm, red)`来指定命名参数。您可以在每个函数的参考页或键入时的自动完成面板中找到可用的命名参数。命名参数类似于一些 LaTeX 环境的配置方式,例如,您将键入 `\begin{enumerate}[label={\alph*)}]` 以使用标签 `a)`、`b)` 等开始列表。 通常,您希望为函数提供一些内容。例如,LaTeX 命令 `\underline{Alternative A}` 在 Typst 中将转换为`#underline([Alternative A])`。方括号表示一个值是内容。在这些括号内,您可以使用普通标记。然而,对于一个非常简单的构造来说,这是很多括号。这就是为什么您还可以在括号之后移动尾随内容参数(如果括号最终为空,则省略括号)。 ```typ Typst is an #underline[alternative] to LaTeX. #rect(fill: aqua)[Get started here!] ``` #[ #show:blockk Typst is an #underline[alternative] to LaTeX. #rect(fill: aqua)[Get started here!] ] #h(2em)您可能已经注意到参数具有不同的数据类型。 Typst 支持多种数据类型。下面是一个表格,其中包含一些最重要的内容以及如何编写它们: #align( center, table( columns:(auto,auto), inset:10pt, align:horizon, [*Data type*],[*Example*], [Content],[\*fast\* typesetting], [String],["<NAME>"], [Integer],[23], [Floating point number],[1.459], [Absolute length],[12pt, 5in, 0.3cm, ...], [Relative length],[65%], ) ) #h(2em)内容和字符串之间的区别在于内容可以包含标记,包括函数调用,而字符串实际上只是一个字符序列。您可以像在传统编程语言中那样使用 `+` 运算符求和和 `==` 等运算符来计算这些类型的相等性,而不是使用 `\addtocounter` 或 `\ifnum`。您甚至可以定义变量并使用它们进行计算。 为了指定任何这些类型的值,您必须处于代码模式! 在 LaTeX 中,一些像 `\textbf{bold text}` 这样的命令在花括号中传递它们的参数并且只影响那个参数,而其他像 `\bfseries bold text` 这样的命令充当开关并改变文档或当前范围中所有后续内容的外观(由一组大括号表示)。 在 Typst 中,函数可以两种方式使用:效果应用到文档或块的末尾,或者只应用到它的参数。例如,`#text(weight: "bold")[bold text]` 只会加粗它的论点,而 `#set text(weight: "bold")` 会加粗任何文本,直到当前块结束。一个函数的效果是显而易见的,这取决于它是在调用中使用还是在设置规则中使用。 ```typ I am starting out with small text. #set text(14pt) This is a bit #text(18pt)[larger,] don't you think? ``` #[ #show:blockk I am starting out with small text. #set text(14pt) This is a bit #text(18pt)[larger,] don't you think? ] #h(2em)set规则可能出现在文档中的任何地方,并且可以被认为是预先设置其函数的参数: ```typ #set enum(numbering: "I.") Good results can only be obtained by + following best practices + being aware of current results of other researchers + checking the data for biases ``` #[ #show:blockk #set enum(numbering: "I.") Good results can only be obtained by + following best practices + being aware of current results of other researchers + checking the data for biases ] #h(2em)`+` 是调用枚举函数的语法糖(将其视为缩写),我们在上面应用了一组规则。大多数语法都以这种方式链接到函数。如果你需要设置一个元素的样式超出其参数启用的范围,你可以使用显示规则(有点类似于 `\renewcommand`)完全重新定义它的外观。 = 模板 在 LaTeX 中,您可以使用 `\documentclass{article}` 命令启动您的主 `.tex` 文件,以定义您的文档的外观。在该命令中,您可能已将 article 替换为另一个值,例如 report 和 amsart 以选择不同的外观。 使用 Typst 时,您可以使用函数来设计文档的样式。通常,您使用的模板提供了一个功能,可以为整个文档设置样式。首先,您从模板文件导入函数。然后,将其应用于整个文档。这是通过将以下文档包装在给定函数中的显示规则来实现的。下面的例子说明了它是如何工作的: ```typ #import "conf.typ": conf #show: conf.with( title: [ Towards Improved Modelling ], authors: ( ( name: "<NAME>", affiliation: "Artos Institute", email: "<EMAIL>", ), ( name: "<NAME>", affiliation: "Honduras State", email: "<EMAIL>", ), ), abstract: lorem(80), ) Let's get started writing this article by putting insightful paragraphs right here! ``` `import` 语句使来自另一个文件的函数(和其他定义)可用。在此示例中,它从 `conf.typ` 文件导入 `conf` 函数。此功能将内容格式化为会议文章。我们使用 `show` 规则将其应用于文档,并配置一些关于文章的元数据。最后,我们可以开始写下面的文章了! 函数是 Typst 的“命令”,可以将它们的参数转换为输出值,包括文档内容。函数是“纯”的,这意味着它们除了创建输出值/输出内容之外不能有任何效果。这与可以对您的文档产生任意影响的 LaTeX 宏形成鲜明对比。 为了让函数为整个文档设置样式,show 规则处理它之后的所有内容,并调用冒号后指定的函数,并将结果作为参数。 `.with` 部分是一种采用 conf 函数并在将其传递给 show 规则之前预先配置其参数的方法。 在 Web 应用程序中,您可以从预定义的模板中进行选择,甚至可以使用模板向导创建您自己的模板。您还可以查看 awesome-typst 存储库以查找社区制作的模板。我们计划构建一个包管理器,使模板在未来更容易共享! 您还可以创建自己的自定义模板。它们比相应的 `LaTeX .sty` 文件短几个数量级,可读性更强,所以试一试吧! = 导入包 大多数你在 LaTeX 中加载包的东西都只包含在 Typst 中,不需要加载或安装任何东西。下面,我们整理了一张表格,列出了经常加载的包及其对应的 Typst 函数。 如果您需要从另一个文件加载函数和变量,例如使用模板,您可以使用 `import` 语句。如果你想包含另一个文件的文本内容,你可以使用 `include` 语句。它将产生包含文件的内容并将其放入您的文档中。 目前,Typst 没有包管理器,但我们计划构建一个,以便您可以轻松地使用来自社区的工具和模板的包,并发布您自己的包。 #align( center, table( columns:(auto,auto), inset:10pt, align:horizon, [graphicx, svg],[image function], [tabularx],[table, grid functions], [fontenc, inputenc, unicode-math],[Just start writing!], [babel, polyglossia],[text function: #set text(lang: "zh")], [amsmath],[Math mode], [amsfonts, amssymb],[sym module and syntax], [geometry, fancyhdr],[page function], [xcolor],[text function: #set text(fill: rgb("#0178A4"))], [hyperref],[link function], [bibtex, biblatex, natbib],[cite, bibliography functions], [lstlisting, minted],[raw function and syntax], [parskip],[block and par functions], [csquotes],[Type " or ' and set the text language], [caption],[figure function], [enumitem],[list, enum, terms functions], ) ) = 数学公式 要在 Typst 中使用数学模式,只需将您的方程用美元符号括起来。您可以通过在开始和结束美元符号和等式之间放置空格或换行符来进入显示模式。 ```typ The sum of the numbers from $1$ to $n$ is: $ sum_(k=1)^n k = (n(n+1))/2 $ ``` #[ #show:blockk The sum of the numbers from $1$ to $n$ is: $ sum_(k=1)^n k = (n(n+1))/2 $ ] 数学模式的工作方式与普通标记或代码模式不同。单个字符和任意数量的数字会被显示为数学变量和数值(取决于你的方程式),而多个连续的非数字字符将被解释为Typst变量。 正如你在上面的例子中看到的,Typst在数学模式下预先定义了很多有用的变量。所有的希腊字母和一些希伯来字母都由它们的名字来解决。请参考符号页或使用自动完成面板来检查哪些符号是可用的。符号的替代形式和相关形式通常可以通过在句点后附加一个修饰语来选择。例如,`arrow.l.squiggly`插入了一个左旋的箭头。如果你想在你的表达式中插入多字母文本,请用双引号将其括起来: 你可以用<=、>=和->等速记符号输入许多符号。同样,定界符也会为其表达式自动缩放,就像LaTeX中隐含插入的 \left 和 \right 命令一样。你可以使用lr函数自定义定界符的行为。 Typst会自动将斜线/周围的术语设置为分数,同时尊重运算符优先级。所有的圆括号都会出现在输出中,而不会因为分数而出现多余的括号。 下标和上标在 Typst 和 LaTeX 中的工作方式类似。输入 `$x^2$` 会产生一个上标,`$x_2$` 会产生一个下标。如果您想在下标或上标中包含多个值,请将它们的内容括在括号中:`$x_(a -> epsilon)$`。 就像您可以在不键入 `#` 或 `/` 的情况下插入变量一样,您也可以使用“裸”函数。 上面的例子使用 cases 函数来描述 f。在 cases 函数中,参数使用逗号分隔,并且参数也被解释为数学。如果您需要将参数解释为 Typst 值,请在它们前面加上`#`。 您可以在数学模式下使用所有 Typst 函数并插入任何内容。如果您希望它们正常工作,在参数列表中使用代码模式,您可以在它们的调用前加上`#`。没有人能阻止您再使用矩形或表情符号作为变量。 如果您想直接输入您的数学符号作为 Unicode,那也是可能的! 数学调用可以使用二维参数列表;作为分隔符。最常见的用途是创建矩阵的 mat 函数。 ```typ $ delta "if" x <= 5 $ $ f(x) = (x + 1) / x $ $ f(x, y) := cases( 1 "if" (x dot y)/2 <= 0, 2 "if" x "is even", 3 "if" x in NN, 4 "else", ) $ $ (a + b)^2 = a^2 + text(fill: #maroon, 2 a b) + b^2 $ $ sum^10_(🥸=1) #rect(width: 4mm, height: 2mm)/🥸 = 🧠 maltese $ $ mat( 1, 2, ..., 10; 2, 2, ..., 10; dots.v, dots.v, dots.down, dots.v; 10, 10, ..., 10; ) $ ``` #[ #show:blockk $ delta "if" x <= 5 $ $ f(x) = (x + 1) / x $ $ f(x, y) := cases( 1 "if" (x dot y)/2 <= 0, 2 "if" x "is even", 3 "if" x in NN, 4 "else", ) $ $ (a + b)^2 = a^2 + text(fill: #maroon, 2 a b) + b^2 $ $ sum^10_(🥸=1) #rect(width: 4mm, height: 2mm)/🥸 = 🧠 maltese $ $ mat( 1, 2, ..., 10; 2, 2, ..., 10; dots.v, dots.v, dots.down, dots.v; 10, 10, ..., 10; ) $ ] = “盗版”LaTeX 在 LaTeX 中设置的论文具有明确无误的外观。这主要是由于它们的字体、Computer Modern、对齐、窄行距和宽边距。 这应该是一个很好的起点!如果您想更进一步,为什么不创建一个可重复使用的模板呢? - sets wide margins - enables justification, tighter lines and first-line-indent - sets the font to "New Computer Modern", an OpenType - derivate of Computer Modern for both text and code blocks - disables paragraph spacing - increases spacing around headings ```typ #set page(margin: 1.75in) #set par(leading: 0.55em, first-line-indent: 1.8em, justify: true) #set text(font: "New Computer Modern") #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) ``` = 局限性 尽管 Typst 可以成为当今许多人的 LaTeX 替代品,但 Typst 仍然(尚)不支持某些功能。以下是它们的列表,其中在适用的情况下包含可能的解决方法。 - 图表绘制Native charts and plots. LaTeX users often create charts along with their documents in PGF/TikZ. Typst does not yet include tools to draw diagrams, but the community is stepping up with solutions such as typst-canvas, typst-plot, and circuitypst. You can add those to your document to get started with drawing diagrams. - 页边距Change page margins without a pagebreak. In LaTeX, margins can always be adjusted, even without a pagebreak. To change margins in Typst, you use the page function which will force a page break. If you just want a few paragraphs to stretch into the margins, then reverting to the old margins, you can use the pad function with negative padding. - 浮动图片Floating figures. The figure command of LaTeX will smartly choose where to place a figure, be it on the top or bottom of the page, or a dedicated figure page. Typst's figure will always appear at the spot where they have been inserted in the markup. While this behavior can save some headache, it is often cumbersome to manually place figures. We will be adding this feature soon! - 包含PDF Include PDFs as images. In LaTeX, it has become customary to insert vector graphics as PDF or EPS files. Typst supports neither format as an image format, but you can easily convert both into SVG files with online tools or Inkscape. We plan to add automatic conversion for these file formats to the Typst web app, too! - 分页优化Page break optimization. LaTeX runs some smart algorithms to not only optimize line but also page breaks. While Typst tries to avoid widows and orphans, it uses less sophisticated algorithms to determine page breaks. You can insert custom page breaks in Typst using` #pagebreak(weak: true)` before submitting your document. The argument weak ensures that no double page break will be created if this spot would be a natural page break anyways. You can also use `#v(1fr)` to distribute space on your page. It works quite similar to LaTeX's \vfill. - 参考数目格式Bibliographies are not customizable. In LaTeX, the packages bibtex, biblatex, and natbib provide a wide range of reference and bibliography formats. You can also use custom .bbx files to define your own styles there. Typst only supports a small set of citation styles at the moment, but we want to build upon this by supporting Citation Style Language (CSL), an XML-based format backed by Zotero that allows you to describe your own bibliography styles. ] #pagebreak() #[ #set heading(numbering: none) #show heading: it => block[ #set align(center) #set text(size:28pt,weight:700) #it.body ] = Part II 简明教程 ] // align = 内容对齐 ```para // 水平/垂直对直内容 align( set alignment 2d alignment, // 沿两个轴排列 横向排列:start end left center right // 竖向排列:top horizon bottom, 使用+号实现横向竖向排列设置 content, ) -> content ``` ```typ #align(center)[#lorem(10)] #align(right)[#lorem(10)] #align(left)[#lorem(10)] #align(center+top)[#lorem(10)] ``` #[ #show:blockk #align(center)[#lorem(10)] #align(right)[#lorem(10)] #align(left)[#lorem(10)] #align(center+top)[#lorem(10)] ] = 图片插入 <image> ```para 带有标题的图片及引用 figure( content, // 图片内容 set caption: `none` `content`, // 图片标题 set numbering: `none` `string` `function`, // 图片标号 set gap: `length`, // 图片与标题之间的距离 ) -> content ``` ```para 图片 image( `string`, // 图片路径 set width: `auto` `relative length`, // 图片宽度 set height: `auto` `relative length`, // 图片高度 set alt: `none` `string` // 图片描述 set fit: `string`, // 如何自动调节:cover(默认,完全覆盖整个区域)、 // contain(完全包含整个区域)、stretch(拉伸图象以完全填满) ) -> content ``` ```typ @gege shows the right pose of playing basketball #figure( image("profile.jpg",height:20%), caption: [ Playing basketball. ], numbering: "1", ) <gege> ``` #[ #show:blockk @gege shows the right pose of playing basketball #figure( image("profile.jpg",height:23%), caption: [ Playing basketball. ], numbering: "1", ) <gege> ] #pagebreak() = 盒子创建 盒子的创建对于页面布局十分有用。 ```para 内联级的container,除了公式、文字、box之外所有的元素都是block级的,不能出现在一个段落中 box可以用来将元素整合到一个段落中 box( set width: `auto` `relative length` `fraction`, // 盒子宽度 set height: `auto` `relative length`, // 盒子高度 set baseline: `relative length`, // 盒子基线 set fill: `none` `color`, // 背景颜色 set stroke: `none` `length` `color` `dictionary` `stroke`, // 盒子边界 set radius: `relative length` `dictionary`, // 盒子圆角半径 set inset: `relative length` `dictionary`, // 内容距离盒子边界距离 set outset: `relative length` `dictionary`, // 盒子外扩值 set `none` `content`, ) -> content ``` ```typ Image with baseline 50%: #box(width:auto, height: 10%, baseline: 50%, stroke: gray+2pt, radius:5pt, inset: 1pt, outset: 1pt, image("profile.jpg") ) ``` #[ #show:blockk Image with baseline 50%: #box(width:auto, height: 12%, baseline: 50%, stroke: gray+2pt, radius:5pt, inset: 1pt, outset: 1pt, image("profile.jpg") ) ] #set page(columns:2) = 强制分栏 ```para 强制分栏,当在单列布局或页面的最后一列中使用时,该函数将表现得像pagebreak()。否则,分栏后的内容将被放置在下一栏。 在此处可以看到Typst处理中文文字间距时还不是很完美空格判定有缺陷。 colbreak( set weak: boolean ) -> content ``` ```typ Preliminary findings from our .. 使用\#colbreak()强制换列 #colbreak() Through rigorous experimentation .. 需要注意到,此处的省略号只有两个,那是因为如果使用三个省略号中文将会出现乱码情况。 ``` #[ #show:blockk Preliminary findings from our ongoing research project have revealed a hitherto unknown phenomenon of extraordinary significance. \ 使用\#colbreak()强制换列 #colbreak() Through rigorous experimentation and analysis, we have discovered a hitherto uncharacterized process that defies our current understanding of the fundamental laws of nature. ] = 设置列数 ```para #pagebreak()可以强制换页 #set page(columns:2)可以设置页面列数 分栏,将一个区域分割成多个相同大小的列,不会分配列的高度,列可以跨页断开 columns( set integer, // 列数目 set gutter: `relative length`, // 每列之间的间距 content, ) -> content ``` ```typ #box(height:150pt,columns(2, gutter: 20pt)[ #set par(justify: true) This research was funded by the National Academy of Sciences. NAoS provided support for field tests and interviews with a grant of up to USD 40.000 for a period of 6 months. ] ) In recent years, deep learning has increasingly been used to solve a variety of problems. ``` #[ #show:blockk #box(height:150pt,columns(2, gutter: 20pt)[ #set par(justify: true) This research was funded by the National Academy of Sciences. NAoS provided support for field tests and interviews with a grant of up to USD 40.000 for a period of 6 months. ] ) In recent years, deep learning has increasingly been used to solve a variety of problems. ] // enum = 有序列表 <enum> enum用于创建有序无序列表以及连续编号,enum函数也有专门的语法糖: 以+起行,创建一个自动编号的枚举项目. 以数字和.开头的一行将创建一个明确编号的枚举项目. 枚举项目可以包含多个段落和其他块级内容.所有缩进超过一个项目的+或.的内容都成为该项目的一部分。 #colbreak() ```typ enum( set tight: `boolean`, // 紧凑显示 set numbering: `string` `function`, // 如何编号 set start: `integer`, // 编号起始值 set full: `boolean`, // 是否显示全部编号 set indent: `length`, // 每个元素的缩进 set body-indent: `length`, // 编号与内容之间的间距 set spacing: `auto` `relative length` `fraction`, // 行间距 ..contentarray, ) -> content ``` ```typ #block(fill:gray,width:100%, inset:5pt,radius:5pt)[ Automatically numbered: + Preparations + Analysis Manually numbered: 2. What is the first step? 5. I am confused. + Moving on ... Function call. #enum[First][Second] ] ``` #colbreak() #[ #show:blockk #block(fill:gray,width:100%, inset:5pt,radius:5pt)[ Automatically numbered: + Preparations + Analysis Manually numbered: 2. What is the first step? 5. I am confused. + Moving on ... Function call. #enum[First][Second] ] ] ```typ #block(fill:green,width:100%, radius:5pt)[ #set enum(numbering: "a)") + Starting off ... + Don't forget step two ] ``` #[ #show:blockk #block(fill:green,width:100%,inset:5pt,radius:5pt)[ #set enum(numbering: "a)") + Starting off ... + Don't forget step two ] ] ```typ #block(fill:rgb("#b1f2eb"), width:100%, inset:5pt, radius:5pt)[ #set enum(numbering: "1.a)") + Different + Numbering + Nested + Items + Style #set enum(numbering: n => super[#n]) + Superscript + Numbering! #enum( start: 3, numbering: "a.", [Skipping], [Ahead], ) ] ``` #[ #show:blockk #block(fill:rgb("#b1f2eb"), width:100%, inset:5pt, radius:5pt)[ #set enum(numbering: "1.a)") + Different + Numbering + Nested + Items + Style #set enum(numbering: n => super[#n]) + Superscript + Numbering! #enum( start: 3, numbering: "a.", [Skipping], [Ahead], ) ] ] #colbreak() ```typ #block(fill:rgb("#b1f2eb"), width:100%,inset:5pt, radius:5pt)[ #enum( start: 3, numbering: "a.", [Skipping], [Ahead], ) ] ``` #block(fill:rgb("#b1f2eb"), width:100%,inset:5pt,radius:5pt)[ #enum( start: 3, numbering: "a.", [Skipping], [Ahead], ) ] ```typ #block(fill:rgb("#b122eb"), width:100%,inset:5pt, radius:5pt)[ #set enum(numbering: "1.a)", full: true) + Cook + Heat water + Add integredients + Eat ] ``` #block(fill:rgb("#b122eb"), width:100%,inset:5pt,radius:5pt)[ #set enum(numbering: "1.a)", full: true) + Cook + Heat water + Add integredients + Eat ] #pagebreak() #set page(columns:1) // Grid = 网格排版 <grid> 在网格中排版内容. grid允许将内容安排在一个grid中. 可以定义行和列的数量, 以及它们之间的间距. 有多种列和行的模式, 可以用来创建复杂的布局. ```para grid( set columns: `auto` `integer` `relative length` `fraction` `array`, // 列数 set rows: `auto` `integer` `relative length` `fraction` `array`, // 行数 set gutter: `auto` `integer` `relative length` `fraction` `array`, // 行或列间距 set column-gutter: `auto` `integer` `relative length` `fraction` `array`, // 列间距,优先级高于gutter set row-gutter: `auto` `integer` `relative length` `fraction` `array`, // 行间距,优先级高于gutter ..content, ) -> content ``` ```typ #let cell = rect.with( inset: 8pt, fill: rgb("e4e5ea"), width: 100%, radius: 6pt ) #grid( columns: (60pt, 1fr, 60pt), rows: (60pt, auto), gutter: 3pt, cell(height: 100%)[Easy to learn], cell(height: 100%)[Great output], cell(height: 100%)[Intuitive], cell[Our best Typst yet], cell[ Responsive \ design in \ print for everyone ], cell[One more thing...], ) ``` #[ #show:blockk #let cell = rect.with( inset: 8pt, fill: rgb("e4e5ea"), width: 100%, radius: 6pt ) #grid( columns: (60pt, 1fr, 60pt), rows: (60pt, auto), gutter: 3pt, cell(height: 100%)[Easy to learn], cell(height: 100%)[Great output], cell(height: 100%)[Intuitive], cell[Our best Typst yet], cell[ Responsive \ design in \ print for everyone ], cell[One more thing...], ) ] == Figure、Grid结合绘制子图 ```typ #let subfigure(body, caption: "", numbering: "(a)") = { let figurecount = counter(figure) let subfigurecount = counter("subfigure") let subfigurecounterdisply = counter("subfigurecounter") let number = locate(loc => { let fc = figurecount.at(loc) let sc = subfigurecount.at(loc) if fc == sc.slice(0,-1) { subfigurecount.update( fc + (sc.last()+1,) ) subfigurecounterdisply.update((sc.last()+1,)) } else { subfigurecount.update( fc + (1,)) subfigurecounterdisply.update((1,)) } subfigurecounterdisply.display(numbering) }) body v(-.65em) if not caption == none { align(center)[#number #caption] } } #figure( grid(columns: 3, gutter: 2em, subfigure(image("profile.jpg", width: 50%)), subfigure(image("profile.jpg", width: 50%)), subfigure(image("profile.jpg", width: 50%), caption: "Test Caption") ), caption: "Test caption" ) #v(2em) #figure( grid( columns: (1fr, 1fr, 1fr), rows: (auto, auto), gutter: 1pt, image("profile.jpg",width:50%), image("profile.jpg",width:50%), image("profile.jpg",width:50%), image("profile.jpg",width:50%), image("profile.jpg",width:50%), image("profile.jpg",width:50%), ), numbering: "1", caption: [ SubFigures. ] ) ``` #pagebreak() #[ #show:blockk #let subfigure(body, caption: "", numbering: "(a)") = { let figurecount = counter(figure) let subfigurecount = counter("subfigure") let subfigurecounterdisply = counter("subfigurecounter") let number = locate(loc => { let fc = figurecount.at(loc) let sc = subfigurecount.at(loc) if fc == sc.slice(0,-1) { subfigurecount.update( fc + (sc.last()+1,) ) subfigurecounterdisply.update((sc.last()+1,)) } else { subfigurecount.update( fc + (1,)) subfigurecounterdisply.update((1,)) } subfigurecounterdisply.display(numbering) }) body v(-.65em) if not caption == none { align(center)[#number #caption] } } #figure( grid(columns: 3, gutter: 2em, subfigure(image("profile.jpg", width: 40%)), subfigure(image("profile.jpg", width: 40%)), subfigure(image("profile.jpg", width: 40%), caption: "Test Caption") ), caption: "Test caption" ) #v(2em) #figure( grid( columns: (1fr, 1fr, 1fr), rows: (auto, auto), gutter: 1pt, image("profile.jpg",width:35%), image("profile.jpg",width:35%), image("profile.jpg",width:35%), image("profile.jpg",width:35%), image("profile.jpg",width:35%), image("profile.jpg",width:35%), ), numbering: "1", caption: [ SubFigures. ] ) ] #pagebreak() #[ #set heading(numbering: none) #show heading: it => block[ #set align(center) #set text(size:28pt,weight:700) #it.body ] = Part III 手册 ] // Styling = 自定义格式 Typst有灵活的排版格式. 通过使用set规则, 可以设置元素的基本性质. 但是对于稀奇古怪的要求, 内置的性质可能无法达到要求, 因此Typst可以使用show规则重新定义元素的显示效果. 如果只想设定在某些位置有效, 可以将其置于块内\#\[\]. 有时像重复使用一组规则,此时可以使用set-if规则. == set规则 ```typ This list is affected: #[ #set list(marker: [--]) - Dash ] This one is not: - Bullet \ #let task(body, critical: false) = { set text(red) if critical [- #body] } #task(critical: true)[Food today?] #task(critical: false)[Work deadline] ``` #[ #show:blockk This list is affected: #[ #set list(marker: [--]) - Dash ] This one is not: - Bullet #let task(body, critical: false) = { set text(red) if critical [- #body] } #task(critical: true)[Food today?] #task(critical: false)[Work deadline] ] == show规则 使用show规则, 可以深度定义一种元素的外观. show规则的最基本形式是show-set规则. show 函数: set规则. 这使设置规则仅适用于所选元素. 在下面的示例中, 标题变为深蓝色, 而所有其他文本保持黑色. 使用 show-set 规则,您可以混合和匹配来自不同函数的属性以实现许多不同的效果. 但它们仍然限制您使用 Typst 中预定义的内容. 为了获得最大的灵活性, 您可以编写一个show规则来定义如何从头开始格式化元素. 要编写这样的show规则, 请将:后面的 set 规则替换为任意函数. 此函数接收元素并可以返回任意内容. 传递给函数的元素上有不同的字段. 下面, 定义一个显示规则, 用于格式化标题. show规则和set规则一样, 一旦设定, 一直使用到结束, 可以使用\#\[\]限定使用范围. 除了函数之外, show右边还可以使用直接替换原色的文字字符串或者内容块. 除了函数之外, show左侧也可使用其他的选择器定义这些转换的适用范围: ```para - Everything: show: rest => ..转换所有内容,有助于将更复杂的布局应用于整个文档 - Text: show "Text": .. 文本样式、转换、替换 - Regex: show regex("\w+"): . 使用正则灵活选择和转换文本 - Function with fields: show heading.where(level: 1): .. 转换指定fileds的袁术,举个例子:只改变一级标题 - Label: show <intro>: .. 选择和转换指定标签的元素 ``` ```typ #[ #show heading: set text(navy) === This is navy-blue But this stays black ] #[ #set heading(numbering: "(I)",outlined:false) #show heading: it => block[ #set align(center) #set text(font: "Inria Serif") \~ #emph(it.body) #counter(heading).display() \~ ] = Dragon With a base health of 15, the dragon is the most powerful creature. = Manticore While less powerful than the dragon, the manticore gets extra style points. ] #[ We started Project in 2019 and are still working on it. Project is progressing badly. #parbreak() #show "Project":smallcaps #show "badly":"great" We started Project in 2019 and are still working on it. Project is progressing badly. ] ``` #[ #show heading: set text(navy) === This is navy-blue But this stays black ] #[ #show:blockk #set heading(numbering: "(I)",outlined:false) #show heading: it => block[ #set align(center) #set text(font: "Inria Serif") \~ #emph(it.body) #counter(heading).display() \~ ] = Dragon With a base health of 15, the dragon is the most powerful creature. = Manticore While less powerful than the dragon, the manticore gets extra style points. We started Project in 2019 and are still working on it. Project is progressing badly. #parbreak() #show "Project":smallcaps #show "badly":"great" We started Project in 2019 and are still working on it. Project is progressing badly. ] // 将标题回退两个 #counter(heading).update(n => n - 2 ) // Scripting = Typst脚本语言 Typst拥有强大的脚本语言(应该是得益于rust). 可以使用代码自动格式化文档以及创建更加复杂的样式. == 表达式 在 Typst 中, 标记和代码合而为一. 除了最常见的元素外, 其余所有元素都是用函数创建的. 为了尽可能方便, Typst 提供了紧凑的语法来将代码表达式嵌入到标记中: 表达式以井号 \(\#\) 引入, 表达式完成后恢复正常的标记解析。如果字符将继续表达式但应解释为文本,则可以强制以分号 \(\;\) 结束表达式。 ```typ #emph[Hello] \ #emoji.face \ #"hello".len() ``` #[ #show:blockk #set align(center) #emph[Hello] \ #emoji.face \ #"hello".len() ] 一些表达式与主题标签语法不兼容(例如二元运算符表达式). 要将它们嵌入到标记中, 您可以使用括号,如 \#\(1 \+ 2\). \ 注意空格的存在!! == 代码块Blocks Typst提供了两个blocks: - 代码块: { let x = 1; x + 2} \ 编写代码时,希望拆分为多个语句、创建一些中间变量等。代码块让您可以在需要一个表达式的地方编写多个表达式。代码块中的各个表达式应该用换行符或分号分隔。代码块中各个表达式的输出值被连接在一起以确定块的值。 - 内容块: [*Hey* there!] 使用内容块,您可以将标记/内容作为编程值处理,将其存储在变量中并将其传递给函数。内容块由方括号分隔并且可以包含任意标记。内容块产生内容类型的值。可以将任意数量的内容块作为尾随参数传递给函数。也就是说,list([A], [B]) 等价于 list[A][B]。 \ 内容和代码块可以任意嵌套。在下面的示例中,[hello] 与 a + [ the ] + b 的输出相结合产生 [hello from the *world*]。 ```typ #{ let a = [from] let b = [*world*] [hello ] a + [ the ] + b } ``` #[ #show:blockk #{ let a = [from] let b = [*world*] [hello ] a + [ the ] + b } ] == Let定义变量 使用 let 绑定来定义变量。变量被赋予 = 符号后的表达式的值。赋值是可选的,如果没有赋值,变量将被初始化为none。 let 关键字也可用于创建自定义命名函数。可以为包含块或文档的其余部分访问 Let 绑定。 ```typ #let name = "Typst" This is #name's documentation. It explains #name. #let add(x, y) = x + y Sum is #add(2, 3). ``` #[ #show: blockk #let name = "Typst" #let add(x, y) = x + y This is #name's documentation. It explains #name. \ Sum is #add(2, 3). ] Let可以用于解构数组以及字典 ```typ #let (x, y) = (1, 2) The coordinates are #x, #y. #let (a, .., b) = (1, 2, 3, 4) The first element is #a. The last element is #b. #let books = ( Shakespeare: "Hamlet", Homer: "The Odyssey", Austen: "Persuasion", ) #let (Austen,) = books Austen wrote #Austen. #let (Homer: h) = books Homer wrote #h. #let (Homer, ..other) = books #for (author, title) in other [ #author wrote #title. ] ``` #[ #show:blockk #let (x, y) = (1, 2) The coordinates are #x, #y. #let (a, .., b) = (1, 2, 3, 4) The first element is #a. The last element is #b. #let books = ( Shakespeare: "Hamlet", Homer: "The Odyssey", Austen: "Persuasion", ) #let (Austen,) = books Austen wrote #Austen. #let (Homer: h) = books Homer wrote #h. #let (Homer, ..other) = books #for (author, title) in other [ #author wrote #title. ] ] 也可以使用下划线丢弃解构模式中的元素 ```typ #let (_, y, _) = (1, 2, 3) The y coordinate is #y. ``` #[ #show:blockk #let (_, y, _) = (1, 2, 3) The y coordinate is #y. ] == 条件判断语句 判断语句,可以根据条件来显示和计算不同的内容。目前`Typst`支持`if`, `else if`和`else`语句。 ```typ #if 1 < 2 [ This is shown ] else [ This is not. ] ``` #[ #show: blockk #if 1 < 2 [ This is shown ] else [ This is not. ] ] 对于判读语句来说,每个分支都有一个代码块或者内容块作为主体。 - if condition {..} - if condition [..] - if condition [..] else {..} - if condition [..] else if condition {..} else [..] == 循环语句 使用loops可以重复计算或者显示内容。`Typst`支持两种格式`for`和`while`。前者遍历指定的集合,而后者只要满足条件就进行迭代。就像块一样,循环将每次迭代的结果连接成一个值。 下例中,for 循环创建的三个句子连接在一起成为一个内容值,而 while 循环中长度为 1 的数组连接在一起成为一个更大的数组。 ```typ #for c in "ABC" [ #c is a letter. ] #let n = 2 #while n < 10 { n = (n * 2) - 1 (n,) } ``` #[ #show: blockk #let n = 2 #for c in "ABC" [ #c is a letter.\ ] #while n < 10 { n = (n * 2) - 1 (n,) } ] - for letter in "abc" {..} \ 遍历字符串的字符。(从技术上讲,迭代字符串的字素簇。大多数时候,一个字素簇只是一个字符/代码点。但是,由多个代码点组成的标志表情符号等一些结构仍然只是一个簇。) - for value in array {..} \ 迭代数组中的值。还可以提供每个值的索引。 - for pair in dict {..}\ for (key, value) in dict {..}\ 迭代字典的键值对 为了控制循环的执行,Typst 提供了 break 和 continue 语句。前者提前退出循环,而后者跳到循环的下一次迭代。 ```typ #for letter in "abc nope" { if letter == " " { break } letter } ``` #[ #show: blockk #for letter in "abc nope" { if letter == " " { break } letter } ] 循环函数的主体可以是代码块或者内容块。 - for .. in collection {..} - for .. in collection [..] - while condition {..} - while condition [..] == 字段访问 可以使用.访问值上的字段: - 拥有指定键的字典 dictionary - 具有指定修饰符的符号 symbol - 特殊定义的模块 module - 指定域的内容 content ```typ #let dict = (greet: "Hello") #dict.greet \ #emoji.face ``` #[ #show: blockk #let dict = (greet: "Hello") #dict.greet \ #emoji.face ] == 方法Methods Method是一类与特定类型耦合的函数。它使用相同的.表示法对其类型的值进行调用:value.method(..)。Type文档列出了每个内置类型的可用method。目前还不能定义自己的方法。 ```typ #let array = (1, 2, 3, 4) #array.pop() \ #array.len() \ #("a, b, c" .split(", ") .join[ --- ]) ``` #[ #show: blockk #let array = (1, 2, 3, 4) #array.pop() \ #array.len() \ #("a, b, c" .split(", ") .join[ --- ]) ] Methods是Typst中唯一可以修改调用值的函数。 == 模块 可以将Typst项目拆分为多个modules文件,同时module可以使用多种方式调用: - Including: include "bar.typ" \ 判断bar.typ是否存在,并返回结果内容 - Import: import "bar.typ" \ 判断文件是否存在,并将module当作bar导入当前scope - Import items: import "bar.typ": a, b \ 判断bar.typ是否存在,提取变量 a 和 b 的值(需要在 bar.typ 中定义,例如通过 let 绑定)并在当前文件中定义它们。用 \* 导入模块中定义的所有变量。 除了导入路径,还可以使用module值 ```typ #import emoji: face #face.grin ``` #[ #show: blockk #import emoji: face #face.grin ] == Packages 为了在不同的项目中重复使用构建块,你也可以创建和导入Typst包。一个包的导入需要指定三个要素:namespce、name、version。 ```typ #import "@preview/example:0.1.0": add #add(2, 7) ``` #[ #show:blockk #import "@preview/example:0.1.0": add #add(2, 7) ] `preview` namespace包含社区共享的软件包。你可以在https://typst.app/docs/packages/ 找到可用的社区软件包的可搜索列表。 如果你在本地使用Typst,你也可以创建你自己的系统本地包。有关这方面的更多细节,请参见https://github.com/typst/packages。 == 运算符 下表列出了所有可用的一元和二元运算符,具有效果、元数(一元、二元)和优先级。 #table( columns: (1fr,1fr), inset:10pt, align: center+horizon, [操作符],[优先级], [\#],[7], [\+],[7], [\*],[6], [\/],[6], [\-],[5], [==],[4], [!=],[4], [<],[4], [<=],[4], [>],[4], [>=],[4], [in],[4], [not in],[4], [not],[3], [and],[3], [or],[2], [=],[1], [+=],[1], [-=],[1], [\*\=],[1], [/=],[1], ) // Types = Typst内置类型 Typst使用不同类型的值设置文档样式:指定元素大小的长度、文本和形状的颜色等等。 除了非常基本的数值类型和编程语言中已知的典型类型之外,Typst 还提供了一种特殊的内容类型。这种类型的值可以包含您可以输入到文档中的任何内容:文本、标题和形状等元素以及样式信息。 在 Typst 的某些地方使用了更专业的数据类型。这里没有列出所有这些,而是​​在相关的地方进行了解释。 == none 缺省值, none 类型只有一个值:none。 当插入到文档中时,它是不可见的。这也是空代码块产生的值。它可以与任何值结合,产生另一个值。 == auto 自动识别类型 == boolean 布尔值, true or false == integer 整数。该数字可以是负数、零或正数。由于 Typst 使用 64 位存储整数,因此整数不能小于 -9223372036854775808 或大于 9223372036854775807。 == float 浮点数。有限精度表示实数。 Typst 使用 64 位来存储浮点数。在需要浮点数的地方,您也可以传递一个整数。 ```typ #3.14 \ #1e4 \ #(10 / 4) ``` #[ #show: blockk #3.14 \ #1e4 \ #(10 / 4) ] == length 大小或距离,可能用上下文单位表示。 Typst 支持以下长度单位: - Points: 72pt - Millimeters: 254mm - Centimeters: 2.54cm - Inches: 1in - Relative to font size: 2.5em ```typ #rect(width: 20pt) #rect(width: 2em) #rect(width: 1in) ``` #[ #show: blockk #rect(width: 20pt) #rect(width: 2em) #rect(width: 1in) ] == angle 角度,支持如下单位: - Degrees: 180deg - Radians: 3.14rad ```typ #rotate(10deg)[Hello there!] ``` #[ #show:blockk #rotate(10deg)[Hello there!] ] == ratio 整体的比例。数字+百分号。 ```typ #set align(center) #scale(x: 150%)[ Scaled apart. ] ``` #[ #show:blockk #set align(center) #scale(x: 150%)[ Scaled apart. ] ] == relative length 与某个已知长度相关的长度。这种类型是长度与比值的组合。它是长度和比率的加减法结果。在需要相对长度的地方,您也可以使用裸长度或比率。 ```typ #rect(width: 100% - 50pt) ``` #[ #show: blockk #rect(width: 100% - 50pt) ] == fraction 定义布局中剩余空间的分布方式。 ```typ Left #h(1fr) Left-ish #h(2fr) Right ``` #[ #show:blockk Left #h(1fr) Left-ish #h(2fr) Right ] == color 颜色空间的设定,支持三个空间: - sRGB - CMYK - D65 同时也内嵌了如下色彩:black, gray, silver, white, navy, blue, aqua, teal, eastern, purple, fuchsia, maroon, red, orange, yellow, olive, green, and lime. === Methods ==== lighten 增亮颜色 \ ```typ value.lighten(ratio) -> color ``` ==== darken 使颜色变暗 ```typ value.darken(ratio) -> color ``` ==== negate 反色 ```typ value.negate() -> color ``` === sRGB <rgb> 创建RGB色彩,颜色在sRGB空间中指定 ```para rgb( hex: string, // 16进制色彩表示,与以下参数不同时出现 red: integer ratio, // 红色比率 green: integer ratio, // 绿色比率 blue: integer ratio, // 蓝色比率 alpha: integer ratio, // 透明度 ) -> color ``` ```typ #square(fill: rgb("#b1f2eb")) #square(fill: rgb(87, 127, 230)) #square(fill: rgb(25%, 13%, 65%)) #text(16pt, rgb("#239dad"))[ *Typst* ] ``` #[ #show:blockk #square(fill: rgb("#b1f2eb")) #square(fill: rgb(87, 127, 230)) #square(fill: rgb(25%, 13%, 65%)) #text(16pt, rgb("#239dad"))[*Typst*] ] === CMYK <cmyk> 创建 CMYK 颜色。如果您想针对特定打印机,这很有用。为显示预览转换为 RGB 可能与您的打印机再现颜色的方式不同。 ```para cmyk( cyan: ratio, magenta: ratio, yellow: ratio, key: ratio, ) -> color ``` ```typ #square( fill: cmyk(27%, 0%, 3%, 5%) ) ``` #[ #show:blockk #square(fill: cmyk(27%, 0%, 3%, 5%)) ] === D65 <luma> 创建灰度图 ```para luma(integer ratio) -> color ``` ```typ #for x in range(250, step: 50) { box(square(fill: luma(x))) } ``` #[ #show:blockk #for x in range(250, step: 25) { box(square(fill: luma(x))) } ] == Datetime datetime表示日期、时间或两者的组合。可以通过使用`datetime`函数指定自定义日期时间或使用`datetime.today`获取当前日期来创建。(仅翻译部分) ```typ #let date = datetime( year: 2020, month: 10, day: 4, ) #date.display() \ #date.display( "y:[year repr:last_two]" ) #let time = datetime( hour: 18, minute: 2, second: 23, ) #time.display() \ #time.display( "h:[hour repr:12][period]" ) ``` #[ #show:blockk #let date = datetime( year: 2020, month: 10, day: 4, ) #date.display() \ #date.display( "y:[year repr:last_two]" ) #let time = datetime( hour: 18, minute: 2, second: 23, ) #time.display() \ #time.display( "h:[hour repr:12][period]" ) ] == 符号 <symbol> Unicode符号,Typst定义了常用符号,从而轻松输入符号。这些符号在模块中定义,可以使用字段访问。 - 通用符号在sym module中定义 \ - Emoji在emoji module中定义 \ 更进一步可以使用symbol函数自定义符号 \ 文末附录列出了Typst内置的通用符号。 ```para // 自定义符号 // 可以只是一个由单个字符组成的字符串,表示无修饰符变体,也可以是一个数组,其中包含两个指定修饰符和符号的字符串。 // 各个修饰符应该用点分隔。显示符号时,Typst 从具有所有附加修饰符和最少数量的其他修饰符的变体中选择第一个。 symbol(..string array) -> symbol ``` ```typ #sym.arrow.r \ #sym.gt.eq.not \ $gt.eq.not$ \ #emoji.face.halo ``` #[ #show:blockk #sym.arrow.r \ #sym.gt.eq.not \ $gt.eq.not$ \ #emoji.face.halo ] ```typ #let envelope = symbol( "🖂", ("stamped", "🖃"), ("stamped.pen", "🖆"), ("lightning", "🖄"), ("fly", "🖅"), ) #envelope #envelope.stamped #envelope.stamped.pen #envelope.lightning #envelope.fly ``` #[ #show:blockk #let envelope = symbol( "🖂", ("stamped", "🖃"), ("stamped.pen", "🖆"), ("lightning", "🖄"), ("fly", "🖅"), ) #envelope #envelope.stamped #envelope.stamped.pen #envelope.lightning #envelope.fly ] 许多符号有不同的变体,可以通过在修饰符后面附加点符号来选择。修饰符的顺序无关紧要。访问符号模块的文档页面并单击符号以查看其可用变体。 ```typ $arrow.l$ \ $arrow.r$ \ $arrow.t.quad$ ``` #[ #show:blockk $arrow.l$ \ $arrow.r$ \ $arrow.t.quad$ ] == 字符串 <string> 您可以使用 for 循环遍历字符串。字符串可以用 + 运算符相加、连接在一起并与整数相乘。 Typst 提供了用于字符串操作的实用方法。(split, trim, replace) 所有长度和索引均以 UTF-8 字节表示。 ```typ #"hello world!" \ #"\"hello\n world\"!" \ #"1 2 3".split() \ #"1,2;3".split(regex("[,;]")) \ #(regex("\d+") in "ten euros") \ #(regex("\d+") in "10 euros") #str(10) \ #str(2.7) \ #str(1e8) \ ``` #[ #show:blockk #"hello world!" \ #"\"hello\n world\"!" \ #"1 2 3".split() \ #"1,2;3".split(regex("[,;]")) \ #(regex("\d+") in "ten euros") \ #(regex("\d+") in "10 euros") \ #str(10) \ #str(2.7) \ #str(1e8) \ ] 一些转义序列: - \\\\ 空格 - \\" 引用 - \\n 新行 - \\r 回车 - \\t tab - \\u\{1f600\} 16进制转义序列 === Methods ```para // 用法和编程语言相似 // 获取字符串长度 value.len() -> integer // 获取第一个字符 value.first() -> any // 获取最后一个字符 value.last() -> any // 获取指定index的字符 value.at(integer) -> string // 获取字符串切片 value.slice(start:integer,end:integer,count: integer,) -> string // 将字符串的单字符作为子字符串数组返回。 value.clusters() -> array // 将字符串的 Unicode 代码点作为子字符串数组返回。 value.codepoints() -> array // 是否包含某些字符,可以使用正则 value.contains(string regex) -> boolean // 是否以指定字符开始 value.starts-with(string regex) -> boolean // 是否以指定字符结束 value.ends-with(string regex) -> boolean // 在字符串中搜索指定的字符并返回第一个匹配项作为字符串,如果没有匹配项则返回无。 value.find(string regex) -> stringnone // 搜寻指定字符并返回第一个匹配项的索引值 value.position(string regex) -> integer none // 字符串匹配 value.match(string regex) -> dictionary none value.matches(string regex) -> array // 替换字符串 value.replace(pattern: string|regex,replacement: string,count: integer,) -> string // 去除匹配项 value.trim(pattern: string | regex, at: alignment,repeat: boolean,) -> string // 拆分字符串 value.split(string|regex) -> array #str.from-unicode(97) str.from-unicode( integer ) -> string str.to-unicode( string ) -> integer ``` ```typ #str.to-unicode("a") \ #"a\u{0300}".codepoints().map(str.to-unicode) ``` #[ #show:blockk #str.to-unicode("a") \ #"a\u{0300}".codepoints().map(str.to-unicode) ] == 文本 文档内容是 Typst 的核心。编写的所有标记和您调用的大多数函数都会产生内容值。可以通过在方括号\[\]中来创建内容值。这也是将内容传递给函数的方式。 ```typ Type of *Hello!* is #type([*Hello!*]) ``` #[ #show: blockk Type of *Hello!* is #type([*Hello!*]) ] === Methods ```para // func()函数。此函数可用于创建此内容中包含的元素。 // 它可以用于元素的设置和显示规则。可以与全局函数进行比较以检查您是否具有特定种类的元素。 value.func() -> function // 内容是否含有指定字段 value.has(string) -> boolean // 访问指定字段 value.at(string) -> any // 查询内容的位置。 value.location() -> location // 返回此内容的字段。 value.fields() ``` ```typ #rect( width: 10cm, height: 10cm, ).fields() ``` #[ #show:blockk #rect( width: 10cm, height: 10cm, ).fields() ] // 数组 == 数组 创建圆括号包围,逗号分隔的数组。数组内的值不需要具有相同的类型。使用`.at()`方法访问和更新数组项。索引从 _0_ 开始,同时支持负索引。可以使用#emph("loop")遍历数组,数组可以使用`+`相加(类似于rust语法)。空数组写作`()` ```typ #let values = (1, 7, 4, -3, 2) #values.at(0) \ #(values.at(0) = 3) #values.at(-1) \ #values.find(calc.even) \ #values.filter(calc.odd) \ #values.map(calc.abs) \ #values.rev() \ #(1, (2, 3)).flatten() \ #(("A", "B", "C") .join(", ", last: " and ")) ``` #[ #show:blockk #let values = (1, 7, 4, -3, 2) #values.at(0) \ #(values.at(0) = 3) #values.at(-1) \ #values.find(calc.even) \ #values.filter(calc.odd) \ #values.map(calc.abs) \ #values.rev() \ #(1, (2, 3)).flatten() \ #(("A", "B", "C") .join(", ", last: " and ")) ] === Methods ```para // rust语法! // 数组长度 value.len() -> integer // 数组第一项 value.first() -> any // 数组最后一项 value.last() -> any // 数组指定位置值 value.at(index: integer) -> any // 在最后添加一项 value.push(value: any) // 删除最后一项并返回 value.pop() -> any // 在指定位置插入 value.insert(index: integer, value: any,) // 移除指定位置值 value.remove(index: integer) -> any // 获得数组切片 value.slice(start: integer, end: integer, count: integer,) -> array // 是否包含指定值 value.contains(value: any) -> boolean // 根据函数搜寻值并返回第一个匹配项 value.find(function) -> anynone // 根据函数搜寻值并返回index value.position(function) -> integer none // 过滤数组并创建为新数组 value.filter(function) -> array // 根据目标函数创建新数组 value.map(function) -> array // 返回新的数组包含值和index // 返回的数组有长度为2的数组(index,value)对组成。可以使用let或者for函数解构 value.enumerate() -> array // 用另一个数组压缩数组。如果两个数组的长度不等,它只会压缩到较小数组的最后一个元素,其余元素将被忽略。 value.zip(array) -> array // 使用累加将所有项合并为一个值 value.fold(any,function,) -> any // 数组加和 value.sum(default:any) -> any // Calculates the product all items (works for any types that can be multiplied) value.product(default:any) -> any // 只要一个值满足函数返回true就返回true value.any(function) -> boolean // 所有值满足函数返回true就返回true value.all(function) -> boolean // 将数组展开 value.flatten() -> array // 将数组反向排列 value.rev() -> array // 将所有项合并为一个数组 value.join(separator: any,last: any,) -> any // 排序 // key:如果给定,则将函数用于数组中的元素以筛选排序的键 value.sorted(key:function) -> array ``` == 字典 字典:键值对。通过在大括号中使用逗号分隔的键:值来构造字典。这些值不必是相同的类型。字典在概念上类似于数组,但它是由字符串索引而不是整数索引的。可以使用.at()方法访问和创建字典条目。如果知道key,那么您也可以使用字段访问表示法(.key)来访问对应value。字典可以使用+运算符添加并连接在一起。要检查字典中是否存在关键字,请使用in关键字。可以使用for循环来迭代字典中的键值对。字典总是按键排序。由于空括号已经产生了一个空数组,因此必须使用特殊的(:)语法来创建一个空字典。 ```typ #let dict = ( name: "Typst", born: 2019, ) #dict.name \ #(dict.launch = 20) #dict.len() \ #dict.keys() \ #dict.values() \ #dict.at("born") \ #dict.insert("city", "Berlin ") #("name" in dict) ``` #[ #show: blockk #let dict = ( name: "Typst", born: 2019, ) #dict.name \ #(dict.launch = 20) #dict.len() \ #dict.keys() \ #dict.values() \ #dict.at("born") \ #dict.insert("city", "Berlin ") #("name" in dict) ] === Methods ```para // 字典长度 value.len() -> integer // 返回与字典中指定键关联的值。 value.at(string) -> any // 插入新的键值对 value.insert(string,any,) // 返回排序后的所有键 value.keys() -> array // 返回值 value.values() -> array // 以成对数组的形式返回字典的键和值。每一对都表示为一个长度为2的数组。 value.pairs() -> array // 按键名删除键值对 value.remove(key: string) -> any ``` == 函数 函数 函数调用是typst的特色,用户可以定义并调用函数来自定义输出格式。 可以通过指定参数列表后跟 => 和函数体来创建匿名函数。如果您的函数只有一个参数,则参数列表周围的括号是可选的。匿名函数主要用于显示规则。 ```typ // Call a function. #list([A], [B]) // Named arguments and trailing // content blocks. #enum(start: 2)[A][B] // Version without parentheses. #list[A][B] ``` #[ #show: blockk #list([A], [B]) #enum(start: 2)[A][B] #list[A][B] ] 使用\#let设置变量,通过\#调用 ```typ #let alert(body, fill: red) = { set text(white) set align(center) rect( fill: fill, inset: 8pt, radius: 4pt, [*Warning:\ #body*], ) } #alert[ Danger is imminent! ] #alert(fill: blue)[ KEEP OFF TRACKS ] #show "once?": it => [#it #it] once? ``` #[ #show:blockk #let alert(body, fill: red) = { set text(white) set align(center) rect( fill: fill, inset: 8pt, radius: 4pt, [*Warning:\ #body*], ) } #alert[ Danger is imminent! ] #alert(fill: blue)[ KEEP OFF TRACKS ] #show "once?": it => [#it #it] once? ] === Methods ```para // 返回一个预先应用了给定参数的新函数。 value.with(..any) -> function // 返回一个选择器,用于过滤属于此函数的元素,其字段具有给定参数的值。 value.where(..fields:any) -> selector ``` == 参数 捕获函数的参数。 与内置函数一样,自定义函数也可以采用可变数量的参数。可以指定一个参数接收器sink,它将所有多余的参数收集为 ..sink。sink值属于arguments类型。它公开了访问位置参数和命名参数的方法,并且可以使用 for 循环进行迭代。相反,您可以使用展开运算符将参数、数组和字典展开到函数调用中:func(..args)。 ```typ #let format(title, ..authors) = [ *#title* \ _Written by #(authors .pos() .join(", ", last: " and "));._ ] #format("ArtosFlow", "Jane", "Joe") ``` #[ #show:blockk #let format(title, ..authors) = [ *#title* \ _Written by #(authors .pos() .join(", ", last: " and "));._ ] #format("ArtosFlow", "Jane", "Joe") ] === Methods ```para // 返回位置参数数组。 value.pos() -> array // 返回命名参数字典。 value.named() -> dictionary ``` == seletor 选择文档的元素。 #parbreak() 可以使用如下方法构建选择器: - use an element function - filter for an element function with specific fields - use a string or regular expression - use a \<label\> - use a location - call the selector function to convert any of the above types into a selector value and use the methods below to refine it #parbreak() 选择器用于将样式规则应用于元素。您还可以使用选择器在文档中查询某些类型的元素。 #parbreak() 此外,您可以将选择器传递给几个 Typst 的内置函数来配置它们的行为。一个这样的例子是大纲,它可以用来改变大纲中列出的元素。 #parbreak() 可以使用下面显示的方法组合多个选择器。但是,目前并非所有地方都支持所有类型的选择器。 #parbreak() ```typ #locate(loc => query( heading.where(level: 1) .or(heading.where(level: 2)), loc, )) = This will be found == So will this === But this will not. ``` ```para value.or(..selector) value.and(..selector) value.before(selector,inclusive: boolean,) value.after(selector,inclusive: boolean,) ``` == 模块 ```typ #import "utils.typ" #utils.add(2, 5) #import utils: sub #sub(1, 4) ``` // 文本设置 = 文本 == lorem 随机生成指定数量的blind text,对于用来排版占位特别有效。 ```para lorem(words: integer) -> string ``` ```typ = Blind Text #lorem(30) = More Blind Text #lorem(15) ``` #[ #show:blockk #lorem(30) \ #v(1em) #lorem(15) ] == 斜体emph <emph> 将内容设置为斜体以示强调,同时提供了语法糖,使用下划线\(\_\_\),只对单词有效。 - 如果目前text格式为`normal`,则变为`italic` - 如果已经是`italic`或者`oblique`,则变为`normal` ```para emph(content) -> content ``` ```typ This is _emphasized._ \ This is #emph[too.] #show emph: it => { text(blue, it.body) } This is _emphasized_ differently. ``` #[ #show:blockk This is _emphasized._ \ This is #emph[too.] #show emph: it => { text(blue, it.body) } This is _emphasized_ differently. ] == 加粗strong emphasis <strong> 字体加粗,语法糖: \* ```para strong( // 加粗对于字体weight的添加量 set delta: integer, content, ) -> content ``` ```typ This is *strong.* \ This is #strong[too.] \ #show strong: set text(red) And this is *evermore.* #set strong(delta: 0) No *effect!* ``` #[ #show:blockk This is *strong.* \ This is #strong[too.] \ #show strong: set text(red) And this is *evermore.* \ #set strong(delta: 0) No *effect!* \ ] == 换行linebreak 插入换行符,将段落切至下一行,段落末尾的换行符会被忽略。语法糖: \\ ```para // justify 是否在断行前对齐行。 // 如果在对齐的文本中发现比 Typst 更好的换行机会,这将很有用。 linebreak(set justify:boolean) -> content ``` ```typ *Date:* 26.12.2022 \ *Topic:* Infrastructure Test \ *Severity:* High \ ``` #[ #show:blockk *Date:* 26.12.2022 \ *Topic:* Infrastructure Test \ *Severity:* High \ ] ```typ #set par(justify: true) #let jb = linebreak(justify: true) I have manually tuned the #jb line breaks in this paragraph #jb for an _interesting_ result. #jb ``` #[ #show:blockk #set par(justify: true) #let jb = linebreak(justify: true) I have manually tuned the #jb line breaks in this paragraph #jb for an _interesting_ result. #jb ] == 小写转换lowercase 大小写转换 ```para lower(string content) -> string content ``` ```typ #lower("ABC") \ #lower[*My Text*] \ #lower[already low] ``` #[ #show:blockk #lower("ABC") \ #lower[*My Text*] \ #lower[already low] ] == 大写转换uppercase 大小写转换 ```para upper(string content) -> string content ``` ```typ #upper("abc") \ #upper[*my text*] \ #upper[ALREADY HIGH] ``` #[ #show:blockk #upper("abc") \ #upper[*my text*] \ #upper[ALREADY HIGH] ] == 上划线overline 文本上划线 ```para overline( // 设置上划线样式 set stroke: auto length color stroke, // 设置上划线距离基线距离 set offset: auto length, // 设置上划线长度 set extent: length, // 上划线是否跳过会与字形发生冲突的部分。 set evade: boolean, content, ) -> content ``` ```typ #overline[A line over text.] ``` #[ #show:blockk #overline[A line over text.] ] ```typ #set text(fill: olive) #overline( stroke: green.darken(20%), offset: -12pt, [The Forest Theme], ) ``` #[ #show:blockk #set text(fill: olive) #overline( stroke: green.darken(20%), offset: -12pt, [The Forest Theme], ) ] ```typ #overline(offset: -1.2em)[ The Tale Of A Faraway Line II ] ``` #[ #show:blockk #overline(offset: -1.2em)[ The Tale Of A Faraway Line II ] ] ```typ #set overline(extent: 4pt) #set underline(extent: 4pt) #overline(underline[Typography Today]) ``` #[ #show:blockk #set overline(extent: 4pt) #set underline(extent: 4pt) #overline(underline[Typography Today]) ] ```typ #overline( evade: false, offset: -7.5pt, stroke: 1pt, extent: 3pt, [Temple], ) ``` #[ #show:blockk #overline( evade: false, offset: -7.5pt, stroke: 1pt, extent: 3pt, [Temple], ) ] == 下划线underline 下划线用法与下划线一致 ```para underline( // 设置下划线样式 set stroke: auto length color stroke, // 设置下划线距离基线距离 set offset: auto length, // 设置下划线长度 set extent: length, // 下划线是否跳过会与字形发生冲突的部分。 set evade: boolean, content, ) -> content ``` ```typ Take #underline( stroke: 1.5pt + red, offset: 2pt, [care], ) #underline(offset: 5pt)[ The Tale Of A Faraway Line I ] #align(center, underline(extent: 2pt)[Chapter 1] ) This #underline(evade: true)[is great]. This #underline(evade: false)[is less great]. ``` #[ #show:blockk Take #underline( stroke: 1.5pt + red, offset: 2pt, [care], ) #underline(offset: 5pt)[ The Tale Of A Faraway Line I ] #align(center, underline(extent: 2pt)[Chapter 1] ) This #underline(evade: true)[is great]. This #underline(evade: false)[is less great]. ] == 代码块构建raw text/code <raw> 可以使用一个\`或者三个\`构建代码块,三个\`组成的代码块后面可以添加指定的语言tag,以自动语法高亮。 ```para raw( // 文本 text: string, // 原始文本是否显示为单独的块。 set block: boolean, // 语法高亮显示的语言。 // 除了 Markdown 中已知的典型语言标签外,它还分别支持 Typst 标记和 Typst 代码的“typ”和“typc”标签。 set lang: nonestring, ) -> content ``` ```typ Adding `rbx` to `rcx` gives the desired result. \`\`\`rust fn main() { println!("Hello World!"); } \`\`\` ``` #[ #show:blockk Adding `rbx` to `rcx` gives the desired result. ```rust fn main() { println!("Hello World!"); } ``` ] ```typ // Parse numbers in raw blocks with the // `mydsl` tag and sum them up. #show raw.where(lang: "mydsl"): it => { let sum = 0 for part in it.text.split("+") { sum += int(part.trim()) } sum } \`\`\`mydsl 1 + 2 + 3 + 4 + 5 \`\`\` ``` #[ #show:blockk // Parse numbers in raw blocks with the // `mydsl` tag and sum them up. #show raw.where(lang: "mydsl"): it => { let sum = 0 for part in it.text.split("+") { sum += int(part.trim()) } sum } ```mydsl 1 + 2 + 3 + 4 + 5 ``` ] ```typ // Display inline code in a small box // that retains the correct baseline. #show raw.where(block: false): box.with( fill: luma(240), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) // Display block code in a larger block // with more padding. #show raw.where(block: true): block.with( fill: luma(240), inset: 10pt, radius: 4pt, ) With `rg`, you can search through your files quickly. \`\`\`bash rg "Hello World" \`\`\` ``` #[ #show:blockk // Display inline code in a small box // that retains the correct baseline. #show raw.where(block: false): box.with( fill: luma(240), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) // Display block code in a larger block // with more padding. #show raw.where(block: true): block.with( fill: luma(240), inset: 10pt, radius: 4pt, ) With `rg`, you can search through your files quickly. ```bash rg "Hello World" ``` ] == small capitals 以小写字母显示文本。 \ 注意:这会为字体启用 OpenType smcp 功能。并非所有字体都支持此功能。有时小型大写字母是专用字体的一部分,有时它们根本不可用。未来该功能将支持选择专用smallcaps字体,以及从普通字母合成smallcaps,但目前尚未实现。 ```para smallcaps(content) -> content ``` ```typ #set par(justify: true) #set heading(numbering: "I.") #show heading: it => { set block(below: 10pt) set text(weight: "regular") align(center, smallcaps(it)) } = Introduction #lorem(40) ``` == 引用smart quote 根据活动文本语言使用适当的引用符号。语法糖:\'和\" ```para smartquote( // 双引号 set double: boolean, // 是否使用智能引号 set enabled: boolean, ) -> content ``` ```typ "This is in quotes." #set text(lang: "de") "Das ist in Anführungszeichen." #set text(lang: "fr") "C'est entre guillemets." ``` #[ #show:blockk "This is in quotes." #set text(lang: "de") "Das ist in Anführungszeichen." #set text(lang: "fr") "C'est entre guillemets." ] ```typ #set smartquote(enabled: false) These are "dumb" quotes. ``` #[ #show:blockk #set smartquote(enabled: false) These are "dumb" quotes. ] == 删除线strikethrough 删除线 ```para strike( // 删除线样式 set stroke: auto length color stroke, // 删除线基于基线位置 set offset: auto length, // 删除线是否比文本更长或者更短 set extent: length, content, ) -> content ``` ```typ This is #strike[not] relevant. ``` #[ #show:blockk This is #strike[not] relevant. ] ```typ This is #strike(stroke: 1.5pt + red)[very stricken through]. \ This is #strike(stroke: 10pt)[redacted].\ #set text(font: "Inria Serif")\ This is #strike(offset: auto)[low-ish]. \ This is #strike(offset: -3.5pt)[on-top].\ This #strike(extent: -2pt)[skips] parts of the word.\ This #strike(extent: 2pt)[extends] beyond the word. ``` #[ #show:blockk This is #strike(stroke: 1.5pt + red)[very stricken through]. \ This is #strike(stroke: 10pt)[redacted].\ #set text(font: "Inria Serif") This is #strike(offset: auto)[low-ish]. \ This is #strike(offset: -3.5pt)[on-top].\ This #strike(extent: -2pt)[skips] parts of the word.\ This #strike(extent: 2pt)[extends] beyond the word. ] == 下标subscript 设置下标 ```para sub( // 是否使用偏好字体的专用下标字符。 // 如果启用,Typst 首先尝试将文本转换为下标代码点。如果失败,它会退回到渲染降低和缩小的正常字母。 set typographic: boolean, set baseline: length, // 下标字体大小 set size: length, content, ) -> content ``` ```typ Revenue#sub[yearly] N#sub(typographic: true)[1] N#sub(typographic: false)[1] ``` #[ #show:blockk Revenue#sub[yearly] \ N#sub(typographic: true)[1] \ N#sub(typographic: false)[1] ] == 上标superscript 设置上标,与下标相同 ```para super( // 是否使用偏好字体的专用上标字符。 // 如果启用,Typst 首先尝试将文本转换为上标代码点。如果失败,它会退回到渲染降低和缩小的正常字母。 set typographic: boolean, set baseline: length, // 上标字体大小 set size: length, content, ) -> content ``` ```typ 1#super[st] try! \ N#super(typographic: true)[1] \ N#super(typographic: false)[1] \ ``` #[ #show:blockk 1#super[st] try! \ N#super(typographic: true)[1] \ N#super(typographic: false)[1] \ ] == 文本格式text 以多种方式自定义文本的外观和布局。 ```para text( // 字体系列的优先顺序。 //处理文本时,Typst 按顺序尝试所有指定的字体系列,直到找到具有必要字形的字体。 set font: string array, // 当主要字体列表不包含匹配项时是否允许其他字体。这使 Typst 可以在所有可用字体中搜索具有必要字形的最相似字体。 // 注意:当回退被禁用并且没有找到字形时,没有警告。相反,您的文本以“tofus”的形式显示:表示缺少适当字形的小方框。 set fallback: boolean, // 字型 normal italic oblique set style: string, // 字体粗细。接受 100 到 900 之间的整数或预定义的权重名称之一。 // thin(100) extralight(200) light(300) regular(400) medium(500) // semibold(600) bold(700) extrabold(800) black(900) set weight: integer string, // 字型宽度 set stretch: ratio, // 字号 set size: length, // 字体颜色 set fill: color, // 字符间距 set tracking: length, // 单词空格 set spacing: relative length, // 文本基线 set baseline: length, // 对齐 set overhang: boolean, // 文本框上边距 // ascender cap-height x-height baseline descender set top-edge: length string, // 文本框下边距 // ascender cap-height x-height baseline descender set bottom-edge: length string, // 语言 set lang: string, set region: none string, // 方向 // auto ltr(左到右) rtl(右到左) set dir: auto direction, // 是否对文本断字以换行 set hyphenate: auto boolean, // 自动字距调整 set kerning: boolean, // 文本替代 set alternates: boolean, set stylistic-set: none integer, // 是否启用连字显示 set ligatures: boolean, set discretionary-ligatures: boolean, set historical-ligatures: boolean, set number-type: auto string, set number-width: auto string, // 是否有一条斜线穿过0 set slashed-zero: boolean, // 是否将数字转换为分数。将此设置为 true 可启用 OpenType frac 字体功能。 set fractions: boolean, set features: array dictionary, content, ) -> content ``` ```typ #set text(18pt) With a set rule. #emph(text(blue)[ With a function call. ]) ``` #[ #show:blockk #set text(18pt) With a set rule. #emph(text(blue)[ With a function call. ]) ] ```typ #set text(font: ( "Inria Serif", "Noto Sans Arabic", )) This is Latin. \ هذا عربي. ``` #[ #show:blockk #set text(font: ( "Inria Serif", "Noto Sans Arabic", )) This is Latin. \ هذا عربي. ] ```typ #set text(font: "Inria Serif") هذا عربي #set text(fallback: false) هذا عربي ``` #[ #show:blockk #set text(font: "Inria Serif") هذا عربي #set text(fallback: false) هذا عربي ] ```typ #text(font: "Linux Libertine", style: "italic")[Italic] #text(font: "DejaVu Sans", style: "oblique")[Oblique] ``` #[ #show:blockk #text(font: "Linux Libertine", style: "italic")[Italic] #text(font: "DejaVu Sans", style: "oblique")[Oblique] ] ```typ #text(weight: "light")[Light] \ #text(weight: "regular")[Regular] \ #text(weight: "medium")[Medium] \ #text(weight: 500)[Medium] \ #text(weight: "bold")[Bold] ``` #[ #show:blockk #text(weight: "light")[Light] \ #text(weight: "regular")[Regular] \ #text(weight: "medium")[Medium] \ #text(weight: 500)[Medium] \ #text(weight: "bold")[Bold] ] ```typ #text(stretch: 75%)[Condensed] \ #text(stretch: 100%)[Normal] ``` #[ #show:blockk #text(stretch: 75%)[Condensed] \ #text(stretch: 100%)[Normal] ] ```typ #set text(size: 20pt) very #text(1.5em)[big] text ``` #[ #show:blockk #set text(size: 20pt) very #text(1.5em)[big] text ] ```typ #set text(tracking: 1.5pt) Distant text. ``` #[ #show:blockk #set text(tracking: 1.5pt) Distant text. ] ```typ #set text(spacing: 200%) Text with distant words. A #text(baseline: 3pt)[lowered] word. #set par(justify: true) In this particular text, the justification produces a hyphen in the first line. Letting this hyphen hang slightly into the margin makes for a clear paragraph edge. #set text(overhang: false) In this particular text, the justification produces a hyphen in the first line. This time the hyphen does not hang into the margin, making the paragraph's edge less clear. ``` #[ #show:blockk #set text(spacing: 200%) Text with distant words. A #text(baseline: 3pt)[lowered] word. #set par(justify: true) In this particular text, the justification produces a hyphen in the first line. Letting this hyphen hang slightly into the margin makes for a clear paragraph edge. #set text(overhang: false) In this particular text, the justification produces a hyphen in the first line. This time the hyphen does not hang into the margin, making the paragraph's edge less clear. ] ```typ #set rect(inset: 0pt) #set text(size: 20pt) #set text(top-edge: "ascender") #rect(fill: aqua)[Typst] #set text(top-edge: "cap-height") #rect(fill: aqua)[Typst] #set rect(inset: 0pt) #set text(size: 20pt) #set text(bottom-edge: "baseline") #rect(fill: aqua)[Typst] #set text(bottom-edge: "descender") #rect(fill: aqua)[Typst] ``` #[ #show:blockk #set rect(inset: 0pt) #set text(size: 20pt) #set text(top-edge: "ascender") #rect(fill: aqua)[Typst] #set text(top-edge: "cap-height") #rect(fill: aqua)[Typst] #set rect(inset: 0pt) #set text(size: 20pt) #set text(bottom-edge: "baseline") #rect(fill: aqua)[Typst] #set text(bottom-edge: "descender") #rect(fill: aqua)[Typst] ] ```typ #set text(dir: rtl) هذا عربي. #set par(justify: true) This text illustrates how enabling hyphenation can improve justification. #set text(hyphenate: false) This text illustrates how enabling hyphenation can improve justification. #set text(size: 25pt) Totally #set text(kerning: false) Totally #set text(size: 20pt) 0, a, g, ß #set text(alternates: true) 0, a, g, ß #set text(size: 20pt) A fine ligature. #set text(ligatures: false) A fine ligature. ``` #[ #show:blockk #set text(dir: rtl) هذا عربي. #set par(justify: true) This text illustrates how enabling hyphenation can improve justification. #set text(hyphenate: false) This text illustrates how enabling hyphenation can improve justification. #set text(size: 25pt) Totally #set text(kerning: false) Totally #set text(size: 20pt) 0, a, g, ß #set text(alternates: true) 0, a, g, ß #set text(size: 20pt) A fine ligature. #set text(ligatures: false) A fine ligature. ] ```typ #set text(font: "Noto Sans", 20pt) #set text(number-type: "lining") Number 9. #set text(number-type: "old-style") Number 9. #set text(font: "Noto Sans", 20pt) #set text(number-width: "proportional") A 12 B 34. \ A 56 B 78. #set text(number-width: "tabular") A 12 B 34. \ A 56 B 78. 0, #text(slashed-zero: true)[0] 1/2 \ #text(fractions: true)[1/2] // Enable the `frac` feature manually. #set text(features: ("frac",)) 1/2 ``` #[ #show:blockk #set text(font: "Noto Sans", 20pt) #set text(number-type: "lining") Number 9. \ #set text(number-type: "old-style") Number 9. \ #set text(font: "Noto Sans", 20pt) #set text(number-width: "proportional") A 12 B 34. \ A 56 B 78. \ #set text(number-width: "tabular") A 12 B 34. \ A 56 B 78. \ 0, #text(slashed-zero: true)[0] \ 1/2 \ #text(fractions: true)[1/2] // Enable the `frac` feature manually. #set text(features: ("frac",)) 1/2 \ ] = 数学公式 Typst 有特殊的语法和库函数来排版数学公式。数学公式可以与文本一起显示,也可以作为单独的块显示。如果它们以至少一个空格开始和结束(例如 `$ x^2 $`),它们将被排版到自己的块中。 在数学中,单个字母总是按原样显示。然而,多个字母被解释为变量和函数。要逐字显示多个字母,可以将它们放在引号中,要访问单个字母变量,您可以使用主题标签语法。 ```typ $ A = pi r^2 $ $ "area" = pi dot.op "radius"^2 $ $ cal(A) := { x in RR | x "is natural" } $ #let x = 5 $ #x < 17 $ ``` #[ #show:blockk $ A = pi r^2 $ $ "area" = pi dot.op "radius"^2 $ $ cal(A) := { x in RR | x "is natural" } $ #let x = 5 $ #x < 17 $ ] \ 数学模式提供多种符号选择,例如 pi、dot.op 或 RR。许多数学符号有不同的变体。您可以通过对符号应用修饰符来在不同的变体之间进行选择。 Typst 进一步识别许多速记序列,如 => 近似于一个符号。当存在这样的速记时,符号的文档会列出它。 ```typ $ x < y => x gt.eq.not y $ ``` #[ #show:blockk $ x < y => x gt.eq.not y $ ] \ 公式也可以包含换行符。每行可以包含一个或多个对齐点 (&),然后对齐。 ```typ $ sum_(k=0)^n k &= 1 + ... + n \ &= (n(n+1)) / 2 $ ``` #[ #show:blockk $ sum_(k=0)^n k &= 1 + ... + n \ &= (n(n+1)) / 2 $ ] \ 数学模式支持不带主题标签前缀的特殊函数调用。在这些“数学调用”中,参数列表的工作方式与代码中的略有不同: - 在它们内部,Typst 仍处于“数学模式”。因此,您可以将数学直接写入其中,但需要使用\#来传递代码表达式(字符串除外,数学语法中提供)。 - 它们支持位置和命名参数,但不支持尾随内容块和参数传播。 - 它们为二维参数列表提供额外的语法。分号 (;) 将前面用逗号分隔的参数合并到一个数组参数中。 ```typ $ frac(a^2, 2) $ $ vec(1, 2, delim: "[") $ $ mat(1, 2; 3, 4) $ $ lim_x = op("lim", limits: #true)_x $ ``` #[ #show:blockk $ frac(a^2, 2) $ $ vec(1, 2, delim: "[") $ $ mat(1, 2; 3, 4) $ $ lim_x = op("lim", limits: #true)_x $ ] \ 要在数学公式中使用逗号或分号,请使用反斜杠将其转义。另一方面,如果冒号前面直接有标识符,则只能以特殊方式识别冒号,因此在这些情况下要逐字显示它,您可以在它之前插入一个空格。 以\#开头的函数调用是正常的代码函数调用,不受这些规则的影响。 所有数学函数都是数学模块的一部分,默认情况下在方程式中可用。在方程式之外,可以通过数学来访问它们。字首。 ```typ #show math.equation: set text(font: "Fira Math") $ sum_(i in NN) 1 + i $ ``` #[ #show:blockk #show math.equation: set text(font: "Fira Math") $ sum_(i in NN) 1 + i $ ] \ == 上下标 上标,下标和极限,下标、上标和极限。attach 函数支持\$a_b^c\$语法,该语法将顶部和底部附件添加到方程的一部分。attach可以显示为下标/上标或极限。 Typst 会根据基础自动决定哪个更合适,但您也可以使用脚本和限制功能手动控制它。 ```para // 语法糖:使用下划线 (_) 表示底部附件,使用帽子 (^) 表示顶部附件。 attach( // 文本 content, // 上标 t: none content, // 下标 b: none content, // 左上标 tl: none content, // 左下标 bl: none content, // 右上标 tr: none content, // 右下标 br: none content, ) -> content ``` ```typ // With syntax. $ sum_(i=0)^n a_i = 2^(1+i) $ // With function call. $ attach( Pi, t: alpha, b: beta, tl: 1, tr: 2, bl: 3, br: 4, ) $ ``` #[ #show:blockk // With syntax. $ sum_(i=0)^n a_i = 2^(1+i) $ // With function call. $ attach( Pi, t: alpha, b: beta, tl: 1, tr: 2, bl: 3, br: 4, ) $ ] ```typ $ sum_(i=0)^n a_i = 2^(1+i) $ ``` #[ #show:blockk $ sum_(i=0)^n a_i = 2^(1+i) $ ] ```para scripts( // Force a base to display attachments as scripts. content ) -> content ``` ```typ $ scripts(sum)_1^2 != sum_1^2 $ ``` #[ #show:blockk $ scripts(sum)_1^2 != sum_1^2 $ ] ```para // Force a base to display attachments as limits. limits( content, // 是否也要在内联方程中强制限制。 // 当全局应用限制时(例如,通过显示规则),一般来说,禁用这个是个好主意。 inline: boolean, ) -> content ``` ```typ $ limits(A)_1^2 != A_1^2 $ ``` #[ #show:blockk $ limits(A)_1^2 != A_1^2 $ ] == 分数 分数。 语法糖:使用\/将相邻表达式转换为分数。可以使用圆括号将多个原子分组到一个表达式中。括号会在输出中删除,但您可以嵌套多个以强制使用它们,或者使用转义符号。 ```para frac( // 分子 num: content, // 分母 denom: content, ) -> content ``` ```typ $ 1/2 < (x+1)/2 $ $ ((x+1)) / 2 = frac(a, b) $ ``` #[ #show:blockk $ 1/2 < (x+1)/2 $ $ ((x+1)) / 2 = frac(a, b) $ ] \ == 方程 <equation> 一个数学方程式。可以与文本内联显示或作为单独的块显示。 语法糖:在\$内写入数学标记以创建方程式。以至少一个空格开始和结束等式将其提升到水平居中的单独块中。 ```para equation( // 方程式是否显示为单独的块。 set block: boolean, // 如何对块级方程进行编号。 set numbering: nonestringfunction, // 对于方程的引用 set supplement: none auto content function content, ) -> content ``` ```typ #set text(font: "New Computer Modern") Let $a$, $b$, and $c$ be the side lengths of right-angled triangle. Then, we know that: $ a^2 + b^2 = c^2 $ Prove by induction: $ sum_(k=1)^n k = (n(n+1)) / 2 $ ``` #[ #show:blockk #set text(font: "New Computer Modern") Let $a$, $b$, and $c$ be the side lengths of right-angled triangle. Then, we know that: $ a^2 + b^2 = c^2 $ Prove by induction: $ sum_(k=1)^n k = (n(n+1)) / 2 $ ] ```typ #set math.equation(numbering: "(1)") We define: $ phi.alt := (1 + sqrt(5)) / 2 $ <ratio> With @ratio, we get: $ F_n = floor(1 / sqrt(5) phi.alt^n) $ ``` #[ #show:blockk #set math.equation(numbering: "(1)") We define: $ phi.alt := (1 + sqrt(5)) / 2 $ <ratio> With @ratio, we get: $ F_n = floor(1 / sqrt(5) phi.alt^n) $ ] ```typ #set math.equation(numbering: "(1)", supplement: [Eq.]) We define: $ phi.alt := (1 + sqrt(5)) / 2 $ <ratio> With @ratio, we get: $ F_n = floor(1 / sqrt(5) phi.alt^n) $ ``` #[ #show:blockk #set math.equation(numbering: "(1)", supplement: [Eq.]) We define: $ phi.alt := (1 + sqrt(5)) / 2 $ <ratio1> With @ratio1, we get: $ F_n = floor(1 / sqrt(5) phi.alt^n) $ ] == 向量 列向量。矢量元素中的内容可以与 \& 符号对齐。 ```para vec( // 向量括号形式:"(" "[" "{" "|" "||" set delim: nonestring, ..content, ) -> content ``` ```typ $ vec(a, b, c) dot.op vec(1, 2, 3) = a + 2b + 3c $ #set math.vec(delim: "[") $ vec(1, 2) $ ``` #[ #show:blockk $ vec(a, b, c) dot.op vec(1, 2, 3) = a + 2b + 3c $ #set math.vec(delim: "[") $ vec(1, 2) $ ] == 矩阵 创建矩阵。一行的元素应该用逗号分隔,而行本身应该用分号分隔。分号语法将前面用逗号分隔的参数合并到一个数组中。您还可以使用这种特殊的数学函数调用语法来定义采用二维数据的自定义函数。同一行单元格中的内容可以用 \& 符号对齐。 ```para mat( // 矩阵括号形式:"(" "[" "{" "|" "||" set delim: nonestring, // 具有矩阵行数组的数组。 ..array, ) -> content ``` ```typ $ mat( 1, 2, ..., 10; 2, 2, ..., 10; dots.v, dots.v, dots.down, dots.v; 10, 10, ..., 10; ) $ ``` #[ #show:blockk $ mat( 1, 2, ..., 10; 2, 2, ..., 10; dots.v, dots.v, dots.down, dots.v; 10, 10, ..., 10; ) $ ] ```typ #set math.mat(delim: "[") $ mat(1, 2; 3, 4) $ ``` #[ #show:blockk #set math.mat(delim: "[") $ mat(1, 2; 3, 4) $ ] ```typ #let data = ((1, 2, 3), (4, 5, 6)) #let matrix = math.mat(..data) $ v := matrix $ ``` #[ #show:blockk #let data = ((1, 2, 3), (4, 5, 6)) #let matrix = math.mat(..data) $ v := matrix $ ] == 选择语句 选择语句,区分大小写,对于跨越不同分支的内容可以使用\&对齐。 ```para cases( // 选择括号形式:"(" "[" "{" "|" "||" set delim: string, ..content, ) -> content ``` ```typ $ f(x, y) := cases( 1 "if" (x dot.op y)/2 <= 0, 2 "if" x "is even", 3 "if" x in NN, 4 "else", ) $ ``` #[ #show:blockk $ f(x, y) := cases( 1 "if" (x dot.op y)/2 <= 0, 2 "if" x "is even", 3 "if" x in NN, 4 "else", ) $ ] ```typ #set math.cases(delim: "[") $ x = cases(1, 2) $ ``` #[ #show:blockk #set math.cases(delim: "[") $ x = cases(1, 2) $ ] == 定界符 分隔符匹配。lr 函数允许匹配两个定界符并根据它们包含的内容缩放它们。虽然这对于语法匹配的定界符也会自动发生,但 lr 允许您匹配两个任意定界符并精确控制它们的大小。除了 lr 函数之外,Typst 还提供了一些函数来为绝对值、上限值和下限值以及范数创建定界符对。 ```para // 刻度定界符。虽然匹配的定界符默认缩放,但这可用于缩放不匹配的定界符并更精确地控制定界符缩放。 lr( // 括号的大小,相对于包裹内容的高度。默认为 100%。 set size: auto relative length, content, ) -> content ``` ```typ $ lr(]a, b/2]) $ $ lr(]sum_(x=1)^n] x, size: #50%) $ ``` #[ #show:blockk $ lr(]a, b/2]) $ $ lr(]sum_(x=1)^n] x, size: #50%) $ ] ```para // 绝对值符号 abs( content ) -> content ``` ```typ $ abs(x/2) $ ``` #[ #show:blockk $ abs(x/2) $ ] ```para // 范数符号 norm( content ) -> content ``` ```typ $ norm(x/2) $ ``` #[ #show:blockk $ norm(x/2) $ ] ```para // 上半封顶括号 floor( content ) -> content ``` ```typ $ floor(x/2) $ ``` #[ #show:blockk $ floor(x/2) $ ] ```para // 下半封顶括号 ceil( content ) -> content ``` ```typ $ ceil(x/2) $ ``` #[ #show:blockk $ ceil(x/2) $ ] == 上下分隔符 等式部分上方或下方的分隔符。大括号和方括号进一步允许您在其下方或上方添加可选注释。 ```para // 公式下划线 underline(content) -> content // 公式上划线 overline(content) -> content // 可加注释的下水平括号 underbrace( content, // 括号下方注释 set none content, ) -> content // 可加注释的上水平括号 overbrace( content, // 括号上方注释 set none content, ) -> content // 可加注释的下水平方括号 underbracket( content, // 注释 set none content, ) -> content // 可加注释的上水平方括号 overbracket( content, // 注释 set nonecontent, ) -> content ``` ```typ $ underline(1 + 2 + ... + 5) $ $ overline(1 + 2 + ... + 5) $ $ underbrace(1 + 2 + ... + 5, "numbers") $ $ overbrace(1 + 2 + ... + 5, "numbers") $ $ underbracket(1 + 2 + ... + 5, "numbers") $ $ overbracket(1 + 2 + ... + 5, "numbers") $ ``` #[ #show:blockk $ underline(1 + 2 + ... + 5) $ $ overline(1 + 2 + ... + 5) $ $ underbrace(1 + 2 + ... + 5, "numbers") $ $ overbrace(1 + 2 + ... + 5, "numbers") $ $ underbracket(1 + 2 + ... + 5, "numbers") $ $ overbracket(1 + 2 + ... + 5, "numbers") $ ] == 字母accent 给字母添加"帽子"。 ```para accent( // 加帽子的字母或者字符串 base: content, // 帽子类型,见下表 accent: string content, ) -> content ``` ```typ $grave(a) = accent(a, `)$ \ $arrow(a) = accent(a, arrow)$ \ $tilde(a) = accent(a, \u{0303})$ ``` #[ #show:blockk $grave(a) = accent(a, `)$ \ $arrow(a) = accent(a, arrow)$ \ $tilde(a) = accent(a, \u{0303})$ ] ```typ $arrow(A B C)$ ``` #[ #show:blockk $arrow(A B C)$ ] #[ #set align(center) #table( columns:(auto,auto,auto), inset: 10pt, align:horizon+center, [*Accent*],[*Name*],[*Codepoint*], [Grave],[grave],[\`], [Acute],[acute],[\´], [Circumflex],[hat],[\^], [Tilde],[tilde],[\~], [Macron],[macron],[\-], [Breve],[breve],[\˘], [Dot],[dot],[\.], [Diaeresis],[diaer],[\¨], [Circle],[circle],[\∘], [Double acute],[acute.double],[\˝], [Caron],[grave],[\ˇ], [Right arrow],[arrow, \-\>],[\→], [Left arrow],[arrow.l, \<\-],[\←], ) ] == 公式字体替换 替换公式中的字体。这些函数与文本函数不同,因为数学字体包含每个字母的多种变体。 ```para // 数学中的衬线(罗马)字体样式。默认。 serif(content) -> content ``` ```para // Sans-serif字体 sans(content) -> content ``` ```typ $ sans(A B C) $ ``` #[ #show:blockk $ sans(A B C) $ ] ```para // Fraktur 字体样式。 frak(content) -> content ``` ```typ $ frak(P) $ ``` #[ #show:blockk $ frak(P) $ ] ```para // 数学中的等宽字体样式。 mono(content) -> content ``` ```typ $ mono(x + y = z) $ ``` #[ #show:blockk $ mono(x + y = z) $ ] ```para // 数学中的黑板粗体(双打)字体样式。对于大写拉丁字母,还可以通过 NN 和 RR 形式的符号使用黑板粗体。 bb(content) -> content ``` ```typ $ bb(b) $ $ bb(N) = NN $ $ f: NN -> RR $ ``` #[ #show:blockk $ bb(b) $ $ bb(N) = NN $ $ f: NN -> RR $ ] ```para // 数学中的书法字体样式。 cal(content) -> content ``` ```typ Let $cal(P)$ be the set of ... ``` #[ #show:blockk Let $cal(P)$ be the set of ... ] == 字体样式设置 设置公式中的字母形式。这些函数与文本函数不同,因为数学字体包含每个字母的多种变体。 ```para // 数学中的直立(非斜体)字体样式。 upright(content) -> content // 数学中的斜体字体样式。对于罗马字母和希腊小写字母,这已经是默认值。 italic(content) -> content // 数学中的粗体字体样式。 bold(content) -> content ``` ```typ $ upright(A) != A $ $ bold(A) := B^+ $ ``` #[ #show:blockk $ upright(A) != A $ $ bold(A) := B^+ $ ] == round 使用半括号包围表达式 ```para round(content) -> content ``` ```typ $ round(x/2) $ ``` #[ #show:blockk $ round(x/2) $ ] == 运算符 文本运算符。Typst 预定义了运算符 arccos, arcsin, arctan, arg, cos, cosh, cot, ctg, coth, csc, deg, det, dim, exp, gcd, hom, mod, inf, ker, lg, lim, ln, log, max, min, Pr, sec, sin, sinc, sinh, sup, tan, tg, tanh, liminf和limsup. ```para op( // 文本 text: string, // Whether the operator should force attachments to display as limits. Defaults to false. set limits: boolean, ) -> content ``` ```typ $ tan x = (sin x)/(cos x) $ $ op("custom", limits: #true)_(n->oo) n $ ``` #[ #show:blockk $ tan x = (sin x)/(cos x) $ $ op("custom", limits: #true)_(n->oo) n $ ] == 根号运算 平方根和多次方根 现在 `$root(x+y)$`等价于`$√(x+y)$`. ```para // 多次方根 root( // 几次根 index: none content, // 开根表达式 radicand: content, ) -> content // 平方根 sqrt( // 对其求平方根的表达式。 radicand: content ) -> content ``` ```typ $ root(3, x) $ $ sqrt(x^2) = x = sqrt(x)^2 $ ``` #[ #show:blockk $ root(3, x) $ $ sqrt(x^2) = x = sqrt(x)^2 $ ] == Sizes 强制公式内表达式的大小样式。 这些函数允许手动配置方程元素的大小,使它们看起来像在显示/内联方程中,或者就像在根或子/上标中使用一样。 === display function 强制数学公式的显示样式。这是block equations的正常显示大小。 ```typ $sum_i x_i/2 = display(sum_i x_i/2)$ ``` #[ #show:blockk $sum_i x_i/2 = display(sum_i x_i/2)$ ] ```para display( content, // 是否对指数施加高度限制,就像常规的上下标一样,default:false cramped: boolean, ) -> content ``` === inline function 强制数学公式为inline显示样式。这是inline equations的正常显示大小。 ```typ $ sum_i x_i/2 = inline(sum_i x_i/2) $ ``` #[ #show:blockk $ sum_i x_i/2 = inline(sum_i x_i/2) $ ] ```para inline( content, // 是否对指数施加高度限制,就像常规的上下标一样,default:false cramped: boolean, ) -> content ``` === script function 强制数学公式为script显示样式。这是幂、下标或上标中使用的较小尺寸。 ```typ $sum_i x_i/2 = script(sum_i x_i/2)$ ``` #[ #show:blockk $sum_i x_i/2 = script(sum_i x_i/2)$ ] ```para script( content, // 是否对指数施加高度限制,就像常规的上下标一样,default:false cramped: boolean, ) -> content ``` === sscript function 强制数学公式为二级script显示样式。这是最小的尺寸,用于二级下标和上标(脚本的脚本)。(更小的显示大小) ```typ $sum_i x_i/2 = sscript(sum_i x_i/2)$ ``` #[ #show:blockk $sum_i x_i/2 = sscript(sum_i x_i/2)$ ] ```para sscript( content, // 是否对指数施加高度限制,就像常规的上下标一样,default:false cramped: boolean, ) -> content ``` == cancel 在方程的一部分上显示对角线。这通常用于表示一个术语的消除。 ```para cancel( content, length: relative length, inverted: boolean, cross: boolean, rotation: angle, stroke: length color dictionary stroke, ) -> content ``` ```typ Here, we can simplify: $ (a dot b dot cancel(x)) / cancel(x) $ ``` #[ #show:blockk Here, we can simplify: $ (a dot b dot cancel(x)) / cancel(x) $ ] ```typ $ a + cancel(x, length: #200%) - cancel(x, length: #200%) $ ``` #[ #show:blockk $ a + cancel(x, length: #200%) - cancel(x, length: #200%) $ ] ```typ $ (a cancel((b + c), inverted: #true)) / cancel(b + c, inverted: #true) $ ``` #[ #show:blockk $ (a cancel((b + c), inverted: #true)) / cancel(b + c, inverted: #true) $ ] ```typ $ cancel(Pi, cross: #true) $ ``` #[ #show:blockk $ cancel(Pi, cross: #true) $ ] ```typ $ cancel(Pi, rotation: #30deg) $ ``` #[ #show:blockk $ cancel(Pi, rotation: #30deg) $ ] ```typ $ cancel( sum x, stroke: #( paint: red, thickness: 1.5pt, dash: "dashed", ), ) $ ``` #[ #show:blockk $ cancel( sum x, stroke: #( paint: red, thickness: 1.5pt, dash: "dashed", ), ) $ ] == binom 二项式表达式? ```para binom( // 二项式上索引 upper: content, // 二项式下索引 lower: content, ) -> content ``` ```typ $ binom(n, k) $ ``` #[ #show:blockk $ binom(n, k) $ ] = 页面布局 以不同方式排列页面上的元素。通过组合布局功能,您可以创建复杂的自动布局。 == 对齐align 水平或者垂直对齐内容 ```para align( // 水平排列 start end left center right // 竖直排列 top horizon bottom // 同时沿两个轴对齐,使用 + 运算符添加两个对齐以获得 2d 对齐。例如,top + right 将内容对齐到右上角。 set alignment2d alignment, content, ) -> content ``` ```typ #set align(center) Centered text, a sight to see \ In perfect balance, visually \ Not left nor right, it stands alone \ A work of art, a visual throne ``` #[ #show:blockk #set align(center) Centered text, a sight to see \ In perfect balance, visually \ Not left nor right, it stands alone \ A work of art, a visual throne ] == 块block 使用block可以分割内容,给内容添加背景,也可以跨页展示。 Block可以强制本来内联的元素变为block层级,特别是编写show规则时 ```para block( set width: auto relative length, // 设置block宽度 set height: auto relative length, // 设置block的高度。当设置高度大于该页剩余空间, // breakable为true时,block将在下一个页面上继续。 set breakable: boolean, // block是否可打断 set fill: nonecolor, // 背景颜色 set stroke: none length color dictionary stroke, // 边界颜色 set radius: relative length dictionary, // block圆角半径 set inset: relative length dictionary, // 内容与block边界距离 set outset: relative length dictionary, // block外扩多少距离 set spacing: relative length fraction, // block距离上下文的间距 可以使用above,below代替 set above: content, // block与上一个block的间距。优先于spacing。 // 可以与show结合使用,以调整任意块级元素周围的间距。 set below: content, // block与下一个block的间距。优先于spacing。 // 可以与show结合使用,以调整任意块级元素周围的间距。 set clip: boolean, // 是否裁剪内容 (v0.1新增) set `none` content, // block内容 ) -> content ``` ```typ #align(center)[ #block( width:50%, height: 15em, breakable: true, fill: gray, stroke: black + 2pt, radius:5pt, inset:15pt, outset:1pt, spacing: 50%, lorem(20), ) ] ``` #[ #show:blockk #block( width:50%, height: 15em, breakable: true, fill: gray, stroke: black + 2pt, radius:5pt, inset:15pt, outset:1pt, spacing: 50%, lorem(20), ) ] == 盒子box ```para 内联级的container,除了公式、文字、box之外所有的元素都是block级的,不能出现在一个段落中 box可以用来将元素整合到一个段落中 box( set width: `auto` `relative length` `fraction`, // 盒子宽度 set height: `auto` `relative length`, // 盒子高度 set baseline: `relative length`, // 盒子基线 set fill: `none` `color`, // 背景颜色 set stroke: `none` `length` `color` `dictionary` `stroke`, // 盒子边界 set radius: `relative length` `dictionary`, // 盒子圆角半径 set inset: `relative length` `dictionary`, // 内容距离盒子边界距离 set outset: `relative length` `dictionary`, // 盒子外扩值 set clip: boolean, // 是否裁剪内容 (v0.1新增) set `none` `content`, ) -> content ``` ```typ Line in #box(width: 1fr, line(length: 100%)) between. An inline #box( fill: luma(235), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, )[rectangle]. ``` #[ #show:blockk Line in #box(width: 1fr, line(length: 100%)) between. \ An inline #box( fill: luma(235), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, )[rectangle]. ] == 表格table <table> 表格用于排列单元格中的内容。单元格可以包含任意内容,包括多个段落,并以行优先顺序指定。 ```para table( // 列 set columns: auto integer relative length fraction array, // 行 set rows: auto integer relative length fraction array, // 行列间距 set gutter: auto integer relative length fraction array, // 列间距 set column-gutter: auto integer relative length fraction array, // 行间距 set row-gutter: auto integer relative length fraction array, // 填充样式 set fill: none color function, // 对齐规则 set align: auto function alignment2d alignment, // 盒子格式 set stroke: none length color stroke, // 内容与盒子边距 set inset: relative length, ..content, ) -> content ``` ```typ #table( columns: (auto, auto, auto), inset: 10pt, align: horizon, [], [*Area*], [*Parameters*], image("cylinder.svg",height:5%), $ pi h (D^2 - d^2) / 4 $, [ $h$: height \ $D$: outer radius \ $d$: inner radius ], image("tetrahedron.svg",height:5%), $ sqrt(2) / 12 a^3 $, [$a$: edge length] ) ``` #[ #show:blockk #set align(center) #table( columns: (auto, auto, auto), inset: 10pt, align: horizon, [], [*Area*], [*Parameters*], image("profile.jpg",height:5%), $ pi h (D^2 - d^2) / 4 $, [ $h$: height \ $D$: outer radius \ $d$: inner radius ], image("profile.jpg",height:5%), $ sqrt(2) / 12 a^3 $, [$a$: edge length] ) ] ```typ #table( fill: (col, _) => if calc.odd(col) { luma(240) } else { white }, align: (col, row) => if row == 0 { center } else if col == 0 { left } else { right }, columns: 4, [], [*Q1*], [*Q2*], [*Q3*], [Revenue:], [1000 €], [2000 €], [3000 €], [Expenses:], [500 €], [1000 €], [1500 €], [Profit:], [500 €], [1000 €], [1500 €], ) ``` #[ #show:blockk #set align(center) #table( fill: (col, _) => if calc.odd(col) { luma(240) } else { white }, align: (col, row) => if row == 0 { center } else if col == 0 { left } else { right }, columns: 4, [], [*Q1*], [*Q2*], [*Q3*], [Revenue:], [1000 €], [2000 €], [3000 €], [Expenses:], [500 €], [1000 €], [1500 €], [Profit:], [500 €], [1000 €], [1500 €], ) ] ```typ #table( columns: 3, align: (x, y) => (left, center, right).at(x), [Hello], [Hello], [Hello], [A], [B], [C], ) ``` #[ #show:blockk #set align(center) #table( columns: 3, align: (x, y) => (left, center, right).at(x), [Hello], [Hello], [Hello], [A], [B], [C], ) ] == 列表list <list> 项目符号列表。垂直显示一系列项目,每个项目由一个标记引入。 ```para list( // 是否紧凑布局 set tight: boolean, // 列表标记 set marker: contentarrayfunction, // 缩进 set indent: length, // 标记与主体间的距离 set body-indent: length, // 列表间间距 set spacing: autorelative lengthfraction, ..content, ) -> content ``` ```typ - *Content* - Text - Math - Layout - Visualize - Meta - Symbols - *Compute* #list( [Foundations], [Calculate], [Construct], [Data Loading], ) ``` #[ #show:blockk - *Content* - Text - Math - Layout - Visualize - Meta - Symbols - *Compute* #list( [Foundations], [Calculate], [Construct], [Data Loading], ) ] ```typ #set list(marker: [--]) - A more classic list - With en-dashes #set list(marker: ([•], [--])) - Top-level - Nested - Items - Items #for letter in "ABC" [ - Letter #letter ] ``` #[ #show:blockk #set list(marker: [--]) - A more classic list - With en-dashes #set list(marker: ([•], [--])) - Top-level - Nested - Items - Items #for letter in "ABC" [ - Letter #letter ] ] == 强制分栏colbreak 强制分栏。在单列布局或页面的最后一列中使用时,该函数的行为类似于分页符。否则,分栏后的内容将放在下一栏中。 ```para // 如果为 true,则在当前列已经为空时跳过分栏符。 colbreak(set weak:boolean) -> content ``` ```typ #set page(columns: 2) Preliminary findings from our ongoing research project have revealed a hitherto unknown phenomenon of extraordinary significance. #colbreak() Through rigorous experimentation and analysis, we have discovered a hitherto uncharacterized process that defies our current understanding of the fundamental laws of nature. ``` == 分列clolumns 将一个区域分成多个大小相同的列。列功能允许将任何容器的内部分成多个列。它不会使列的高度相等,相反,列将占用其容器的高度或页面上的剩余高度。如有必要,列功能可以跨页。 ```para columns( // 列数 set integer, // 列间距 set gutter: relative length, content, ) -> content ``` ```typ #box(height: 68pt, columns(2, gutter: 11pt)[ #set par(justify: true) This research was funded by the National Academy of Sciences. NAoS provided support for field tests and interviews with a grant of up to USD 40.000 for a period of 6 months. ] ) In recent years, deep learning has increasingly been used to solve a variety of problems. ``` #[ #show:blockk #box(height: 68pt, columns(2, gutter: 11pt)[ #set par(justify: true) This research was funded by the National Academy of Sciences. NAoS provided support for field tests and interviews with a grant of up to USD 40.000 for a period of 6 months. ] ) In recent years, deep learning has increasingly been used to solve a variety of problems. ] == enum 见之前章节 @enum 描述 == grid 见之间章节 @grid 描述 == 水平间距h 在段落中插入水平间距。间距可以是绝对的、相对的或分数。在最后一种情况下,线上的剩余空间根据它们的相对分数分布在所有分数间距中。 ```para h( // 插入多少间距 amount: relative length fraction, set weak: boolean, ) -> content ``` ```typ First #h(1cm) Second \ First #h(30%) Second \ First #h(2fr) Second #h(1fr) Third ``` #[ #show:blockk First #h(1cm) Second \ First #h(30%) Second \ First #h(2fr) Second #h(1fr) Third ] == 垂直间距v 将垂直间距插入块流中。间距可以是绝对的、相对的或分数。在最后一种情况下,页面上的剩余空间根据它们的相对分数分布在所有分数间距中。 ```para v( // 插入多少间距 amount: relative length fraction, set weak: boolean, ) -> content ``` ```typ #grid( rows: 3cm, columns: 6, gutter: 1fr, [A #parbreak() B], [A #v(0pt) B], [A #v(10pt) B], [A #v(0pt, weak: true) B], [A #v(40%, weak: true) B], [A #v(1fr) B], ) ``` #[ #show:blockk #grid( rows: 3cm, columns: 6, gutter: 1fr, [A #parbreak() B], [A #v(0pt) B], [A #v(10pt) B], [A #v(0pt, weak: true) B], [A #v(40%, weak: true) B], [A #v(1fr) B], ) ] == 隐藏内容hide 隐藏内容而不影响布局。隐藏功能允许您在布局仍“看到”内容时隐藏内容。这对于创建与某些内容一样大的空白很有用。编辑内容也可能有用,因为它的参数不包含在输出中。 ```para hide(content) -> content ``` ```typ Hello Jane \ #hide[Hello] Joe ``` #[ #show:blockk Hello Jane \ #hide[Hello] Joe ] == 测量measure 衡量内容的布局大小。measure 函数可让您确定内容的布局大小。相同的内容可以有不同的大小,具体取决于布局时处于活动状态的样式。 ```para // measure 函数返回一个字典,其中包含条目 width 和 height,两者都是 length 类型。 measure( content, styles, ) -> dictionary ``` ```typ #let content = [Hello!] #content #set text(14pt) #content ``` #[ #show:blockk #let content = [Hello!] #content #set text(14pt) #content ] 因此,要进行有意义的measure,您首先需要使用 style 函数检索活动样式。然后您可以将它们传递给测量函数。 ```typ #let thing(body) = style(styles => { let size = measure(body, styles) [Width of "#body" is #size.width] }) #thing[Hey] \ #thing[Welcome] ``` #[ #show:blockk #let thing(body) = style(styles => { let size = measure(body, styles) [Width of "#body" is #size.width] }) #thing[Hey] \ #thing[Welcome] ] == 移动move 移动内容而不影响布局。move允许您移动内容,而layout仍然在原始位置“看到”它。容器仍将调整大小,就好像内容没有被移动一样。 ```para move( // 水平移动距离 set dx: relative length, // 垂直移动距离 set dy: relative length, content, ) -> content ``` ```typ #rect(inset: 0pt, move( dx: 6pt, dy: 6pt, rect( inset: 8pt, fill: white, stroke: black, [Abra cadabra] ) )) ``` #[ #show:blockk #rect(inset: 0pt, move( dx: 6pt, dy: 6pt, rect( inset: 8pt, fill: white, stroke: black, [Abra cadabra] ) )) ] == 间距padding pad 函数在内容周围添加间距。可以为每一边单独指定间距,或者通过指定位置参数一次为所有边指定间距。 ```para pad( // 左边距 set left: relative length, // 上边距 set top: relative length, // 右边距 set right: relative length, // 下边距 set bottom: relative length, // 水平间距,优先级低于左右边距设置 set x: relative length, // 垂直间距,优先级低于上下边距 set y: relative length, // 所有边的填充。所有其他参数优先于此。 set rest: relative length, content, ) -> content ``` ```typ #set align(center) #pad(x: 16pt, image("typing.jpg")) _Typing speeds can be measured in words per minute._ ``` #[ #show:blockk #set align(center) #pad(x: 16pt, image("profile.jpg",height: 10%)) _Typing speeds can be measured in words per minute._ ] == 页面格式page 设置页面格式 将其子级布局到一页或多页上。 尽管此函数主要用于设置规则以影响页面属性,但它也可用于将其参数显式呈现到其自己的一组页面上。 页面可以设置为使用 auto 作为自适应宽度或高度。在这种情况下,页面将增长以适应各自轴上的内容。 ```para page( // 设置页面大小,默认为a4 set paper: string, // 页面宽度 set width: auto length, // 页面高度 set height: auto length, // 页面是否翻转为横向 set flipped: boolean, // 页边距 // 可以使用字典{ }单独设置边距, // (top: value,right: value,bottom: value,left: value,inside: value,outside: value, x: value,y: value,z: value,rest: value) set margin: auto relative length dictionary, // 页面装订位置 auto(=left) left right set binding: auto alignment // 列数 set columns: integer, // 背景颜色 set fill: none color, // 给页码编号。如果给出了明确的页脚,则编号将被忽略。 set numbering: none string function, // 页码对齐方式 set number-align: alignment2d alignment, // 页眉 set header: none content, // 页眉距离上边距的量 set header-ascent: relative length, // 页面的页脚。填充每页的底部边距。对于页码,编号属性通常就足够了。 // 如果要创建自定义页脚,但仍显示页码,则可以直接访问页码计数器。 set footer: none content, // 页脚距离下边距的距离 set footer-descent: relative length, // 页面背景中的内容。此内容将放置在页面正文的后面。它可用于放置背景图像或水印。 set background: none content, // 页面前景中的内容。此内容将覆盖页面的主体。 set foreground: none content, content, ) -> content ``` ```typ #set page("us-letter") There you go, US friends ``` ```typ #set page( width: 3cm, margin: (x: 0cm), ) #for i in range(3) { box(square(width: 1cm)) } ``` ```typ #set page( "us-business-card", flipped: true, fill: rgb("f2e5dd"), ) #set align(bottom + end) #text(14pt)[*<NAME>*] \ _Procurement Manager_ #set text(10pt) 17 Main Street \ New York, NY 10001 \ +1 555 555 5555 ``` ```typ #set page( width: 3cm, height: 4cm, margin: (x: 8pt, y: 4pt), ) #rect( width: 100%, height: 100%, fill: aqua, ) ``` ```typ #set page(columns: 2, height: 4.8cm) Climate change is one of the most pressing issues of our time, with the potential to devastate communities, ecosystems, and economies around the world. It's clear that we need to take urgent action to reduce our carbon emissions and mitigate the impacts of a rapidly changing climate. ``` ```typ #set page(fill: rgb("444352")) #set text(fill: rgb("fdfdfd")) *Dark mode enabled.* ``` ```typ #set page( height: 100pt, margin: (top: 16pt, bottom: 24pt), numbering: "1 / 1", ) #lorem(48) ``` ```typ #set page( margin: (top: 16pt, bottom: 24pt), numbering: "1", number-align: right, ) #lorem(30) ``` ```typ #set par(justify: true) #set page( margin: (top: 32pt, bottom: 20pt), header: [ #set text(8pt) #smallcaps[Typst Academcy] #h(1fr) _Exercise Sheet 3_ ], ) #lorem(19) ``` ```typ #set par(justify: true) #set page( height: 100pt, margin: 20pt, footer: [ #set align(right) #set text(8pt) #counter(page).display( "1 of I", both: true, ) ] ) #lorem(48) ``` ```typ #set page(background: rotate(24deg, text(18pt, fill: rgb("FFCBC4"))[ *CONFIDENTIAL* ] )) = Typst's secret plans In the year 2023, we plan to take over the world (of typesetting). ``` ```typ #set page(foreground: text(24pt)[🥸]) Reviewer 2 has marked our paper "Weak Reject" because they did not understand our approach... ``` == 换页符pagebreak 手动分页符 ```para // if true, 如果当前页为空,则不使用分页符 pagebreak( weak: boolean, // 如果给定,则确保下一页将是偶数/奇数页,如有必要,中间有一个空页。 // even(下一页偶数页) odd(下一页奇数页) to: nonestring, ) -> content ``` ```typ The next page contains more details on compound theory. #pagebreak() == Compound Theory In 1984, the first ... ``` ```typ #set page(height: 30pt) First. #pagebreak(to: "odd") Third. ``` == 段落par 将文本、间距和行内级元素排列到一个段落中。尽管此函数主要用于设置规则以影响段落属性,但它也可用于将其参数显式呈现到其自己的段落中。 ```para par( // 行间距 default 0.65em set leading: length, // 是否在行中对其文本 set justify: boolean, // 如何确定换行符。auto simple optimized set linebreaks: auto string, // 连续段落的第一行应该有的缩进。页面上的第一段永远不会缩进。按照排版惯例,段落分隔符由段落之间的一些空格或首行缩进表示。使用此属性时请考虑关闭段落间距(例如使用#show par: set block(spacing: 0pt))。 set first-line-indent: length, set hanging-indent: length, set body: content, ) -> content ``` ```typ #set par(first-line-indent: 1em, justify: true) #show par: set block(spacing: 0.65em) We proceed by contradiction. Suppose that there exists a set of positive integers $a$, $b$, and $c$ that satisfies the equation $a^n + b^n = c^n$ for some integer value of $n > 2$. Without loss of generality, let $a$ be the smallest of the three integers. Then, we ... ``` #[ #show:blockk #set par(first-line-indent: 1em, justify: true) #show par: set block(spacing: 0.65em) We proceed by contradiction. Suppose that there exists a set of positive integers $a$, $b$, and $c$ that satisfies the equation $a^n + b^n = c^n$ for some integer value of $n > 2$. Without loss of generality, let $a$ be the smallest of the three integers. Then, we ... ] ```typ #set page(width: 190pt) #set par(linebreaks: "simple") Some texts are frustratingly challenging to break in a visually pleasing way. This very aesthetic example is one of them. #set par(linebreaks: "optimized") Some texts are frustratingly challenging to break in a visually pleasing way. This very aesthetic example is one of them. ``` #[ #show:blockk #set par(linebreaks: "simple") Some texts are frustratingly challenging to break in a visually pleasing way. This very aesthetic example is one of them. #set par(linebreaks: "optimized") Some texts are frustratingly challenging to break in a visually pleasing way. This very aesthetic example is one of them. ] == 换段符parbreak 段落终断符 \ ```para parbreak() -> content ``` ```typ #for i in range(3) { [Blind text #i: ] lorem(5) parbreak() } ``` #[ #show:blockk #set par(first-line-indent:0pt) #for i in range(3) { [Blind text #i: ] lorem(5) parbreak() } ] == 内容放置place 将内容放在绝对位置。放置的内容不会影响其他内容的位置。 Place 始终相对于其父容器,并且将位于容器中所有其他内容的前台。 ```para place( set alignment2d alignment, // 水平位移 set dx: relative length, // 垂直位移 set dy: relative length, content, ) -> content ``` ```typ Hello, world! #place( top + right, square( width: 20pt, stroke: 2pt + blue ), ) ``` #[ #show:blockk Hello, world! #place( top + right, square( width: 20pt, stroke: 2pt + blue ), ) ] ```typ #for i in range(16) { let amount = i * 4pt place(center, dx: amount - 32pt, dy: amount / 8)[A] } ``` #[ #show:blockk #for i in range(16) { let amount = i * 4pt place(center, dx: amount - 32pt, dy: amount / 8)[A] } ] == 重复内容repeat 重复内容。这在实现自定义索引、引用或大纲时很有用。 ```para repeat(content) -> content ``` ```typ Sign on the dotted line: #box(width: 1fr, repeat[.]) #set text(10pt) #v(8pt, weak: true) #align(right)[ Berlin, the 22nd of December, 2022 ] ``` #[ #show:blockk Sign on the dotted line: #box(width: 1fr, repeat[.]) #set text(10pt) #v(8pt, weak: true) #align(right)[ Berlin, the 22nd of December, 2022 ] ] == 旋转rotate 按给定角度旋转元素。 ```para rotate( // 旋转角 set angle, // 旋转原点,默认情况下,原点是旋转元素的中心。旋转元素的左下角与基线保持对齐,将原点设置为 bottom + left。 set origin: alignment2d alignment, content, ) -> content ``` ```typ #stack( dir: ltr, spacing: 1fr, ..range(16) .map(i => rotate(24deg * i)[X]), ) ``` #[ #show:blockk #stack( dir: ltr, spacing: 1fr, ..range(16) .map(i => rotate(24deg * i)[X]), ) ] ```typ #rotate(-1.571rad)[Space!] ``` #[ #show:blockk #rotate(-1.571rad)[Space!] ] ```typ #set text(spacing: 8pt) #let square = square.with(width: 8pt) #box(square()) #box(rotate(30deg, origin: center, square())) #box(rotate(30deg, origin: top + left, square())) #box(rotate(30deg, origin: bottom + right, square())) ``` #[ #show:blockk #set text(spacing: 8pt) #let square = square.with(width: 8pt) #box(square()) #box(rotate(30deg, origin: center, square())) #box(rotate(30deg, origin: top + left, square())) #box(rotate(30deg, origin: bottom + right, square())) ] == 水平/垂直排列stack 水平或垂直排列内容和间距。stack沿轴放置项目列表,每个项目之间的间距可选。 ```para stack( // 方向:ltr rtl ttb btt set dir: direction, // 间距 set spacing: none relative length fraction, ..relative length fraction content, ) -> content ``` ```typ #stack( dir: ttb, rect(width: 40pt), rect(width: 120pt), rect(width: 90pt), ) ``` #[ #show:blockk #stack( dir: ttb, rect(width: 40pt), rect(width: 120pt), rect(width: 90pt), ) ] == 内容放缩scale 在不影响布局的情况下缩放内容。缩放功能允许在不影响布局的情况下缩放和镜像内容。 ```para scale( // 水平放缩因子,如果为负,水平镜像 set x: ratio, // 垂直放缩因子,如果为负,垂直镜像 set y: ratio, // 放缩原点 set origin: alignment2d alignment, content, ) -> content ``` ```typ #set align(center) #scale(x: -100%)[This is mirrored.] ``` #[ #show:blockk #set align(center) #scale(x: -100%)[This is mirrored.] ] ```typ A#box(scale(75%)[A])A \ B#box(scale(75%, origin: bottom + left)[B])B ``` #[ #show:blockk A#box(scale(75%)[A])A \ B#box(scale(75%, origin: bottom + left)[B])B ] == 定理terms <terms> 术语的使用及其描述。垂直显示一系列术语及其描述。当描述跨越多行时,他们使用悬挂缩进来传达视觉层次结构。 #parbreak() 语法糖:以/开始一行,后跟术语、:和描述,创建术语列表项。 ```para terms( // false:项目以术语列表间距隔开。true:改用正常行距。这使得术语列表更紧凑 set tight: boolean, // 分隔符 set separator: content, // 缩进 set indent: length, // 悬挂缩进 set hanging-indent: length, // 间距 set spacing: auto relative length fraction, ..content array, ) -> content ``` ```typ / Ligature: A merged glyph. / Kerning: A spacing adjustment between two adjacent letters. ``` #[ #show:blockk / Ligature: A merged glyph. / Kerning: A spacing adjustment between two adjacent letters. ] ```typ #set terms(separator: [: ]) / Colon: A nice separator symbol. ``` #[ #show:blockk #set terms(separator: [: ]) / Colon: A nice separator symbol. ] ```typ #set terms(separator: h(2cm,weak:true)) / Colon: A nice separator symbol. ``` #[ #show:blockk #set terms(separator: h(2cm,weak:true)) / Colon: A nice separator symbol. ] ```typ #set terms(hanging-indent: 0pt) / Term: This term list does not make use of hanging indents. ``` #[ #show:blockk #set terms(hanging-indent: 0pt) / Term: This term list does not make use of hanging indents. ] ```typ #for year, product in ( "1978": "TeX", "1984": "LaTeX", "2019": "Typst", ) [/ #product: Born in #year.] ``` #[ #show:blockk #for (year, product) in ( "1978": "TeX", "1984": "LaTeX", "2019": "Typst", ) [/ #product: Born in #year.] ] = 可视化 目前Typst还不支持绘制图表! == 直线line 绘制直线 ```para line( set start: array, set end: none array, set length: relative length, set angle: angle, set stroke: length color stroke, ) -> content ``` ```typ #set page(height: 100pt) #line(length: 100%) #line(end: (50%, 5%)) #line(length: 100%, stroke: 2pt + red) ``` #[ #show:blockk #line(length: 100%) #line(end: (50%, 5%)) #line(length: 100%, stroke: 2pt + red) ] == 矩形rect 绘制矩形 ```para rect( // 宽 set width: auto relative length, // 高 set height: auto relative length, // 内部填充 // 设置填充时,默认stroke失效。要创建同时具有填充和描边的矩形,您必须同时配置两者。 set fill: none color, // 圆圈格式 // none 不使用描边 auto 1pt黑色描边 set stroke: none auto length color stroke, // 边框弧度 set radius: relative length dictionary, // 内边距 set inset: relative length dictionary, // 外边距 set outset: relative length dictionary, set none content, ) -> content ``` ```typ // Without content. #rect(width: 35%, height: 30pt) // With content. #rect[ Automatically sized \ to fit the content. ] ``` #[ #show:blockk // Without content. #rect(width: 35%, height: 30pt) // With content. #rect[ Automatically sized \ to fit the content. ] ] ```typ #rect(fill: blue) #stack( dir: ltr, spacing: 1fr, rect(stroke: red), rect(stroke: 2pt), rect(stroke: 2pt + red), ) #set rect(stroke: 4pt) #rect( radius: ( left: 5pt, top-right: 20pt, bottom-right: 10pt, ), stroke: ( left: red, top: yellow, right: green, bottom: blue, ), ) #rect(inset: 0pt)[Tight] ``` #[ #show:blockk #rect(fill: blue) #stack( dir: ltr, spacing: 1fr, rect(stroke: red), rect(stroke: 2pt), rect(stroke: 2pt + red), ) #set rect(stroke: 4pt) #rect( radius: ( left: 5pt, top-right: 20pt, bottom-right: 10pt, ), stroke: ( left: red, top: yellow, right: green, bottom: blue, ), ) #rect(inset: 0pt)[Tight] ] == 正方形square 正方形,参数解释同上 ```para square( set size: auto length, set width: auto relative length, set height: auto relative length, set fill: none color, set stroke: none auto length color dictionary stroke, set radius: relative length dictionary, set inset: relative length dictionary, set outset: relative length dictionary, set none content, ) -> content ``` ```typ // Without content. #square(size: 40pt) // With content. #square[ Automatically \ sized to fit. ] ``` #[ #show:blockk // Without content. #square(size: 40pt) // With content. #square[ Automatically \ sized to fit. ] ] == 圆形circle 绘制带有内容的圆圈 ```para circle( // 圆半径,与weight和height互斥 set radius: length, // 相对于父容器的宽度,互斥 set width: auto relative length, // 相对于父容器的高度,互斥 set height: auto relative length, // 内部填充 set fill: none color, // 圆圈格式 set stroke: none auto length color stroke, // 内边距 set inset: relative length dictionary, // 外边距 set outset: relative length dictionary, set none content, ) -> content ``` ```typ // Without content. #circle(radius: 25pt) // With content. #circle[ #set align(center + horizon) Automatically \ sized to fit. ] ``` #[ #show:blockk // Without content. #circle(radius: 25pt) // With content. #circle[ #set align(center + horizon) Automatically \ sized to fit. ] ] == 路径path 使用路径绘制图形,通过点列表绘制,曲线为贝塞尔曲线 (v0.2新增) ```para path( // 如何填充路径 fill: none | color, // 路径格式设置 stroke: none | auto | length | color | stroke, // 是否闭合路径。该曲线将考虑相邻的控制点。如果想用一条直线结束,只需添加一个与起点相同的最后一个点。 closed: boolean, // 路径顶点设置,可以用三种方式定义: // - 给定线或多边形函数的常规点。 // - 两个点的数组,第一个是顶点,第二个是控制点。控制点相对于顶点表示,镜像得到第二个控制点。给定的控制点是影响进入该顶点的曲线的点(即使是第一个点)。镜像控制点影响从该顶点出来的曲线。 // - 三个点的数组,第一个是顶点,下一个是控制点(分别是曲线进出的控制点) ..array, ) -> content ``` ```typ #path( fill: blue.lighten(80%), stroke: blue, closed: true, (0pt, 50pt), (100%, 50pt), ((50%, 0pt), (40pt, 0pt)), ) ``` #[ #show:blockk #path( fill: blue.lighten(80%), stroke: blue, closed: true, (0pt, 50pt), (100%, 50pt), ((50%, 0pt), (40pt, 0pt)), ) ] == 多边形polgon 一个封闭的多边形。多边形由其角点定义并自动闭合。 ```para polygon( // 如何填充多边形。目前所有的多边形都是根据non-zero winding rule填充的。 set fill: none color, // 多边形边界格式设置 set stroke: none length color stroke, // 多边形的顶点。每个点都指定为两个相对长度的数组。 ..array, ) -> content ``` ```typ #polygon( fill: red, stroke: 2pt + black, (0pt, 0pt), (50%, 0pt), (50%, 4cm), (20%, 4cm), ) ``` #[ #show:blockk #polygon( fill: red, stroke: 2pt + black, (0pt, 0pt), (50%, 0pt), (50%, 4cm), (20%, 4cm), ) ] == 椭圆ellipse 绘制椭圆,参数同上 ```para ellipse( set width: auto relative length, set height: auto relative length, set fill: none color, set stroke: none auto length color stroke, set inset: relative length dictionary, set outset: relative length dictionary, set none content, ) -> content ``` ```typ // Without content. #ellipse(width: 35%, height: 30pt) // With content. #ellipse[ #set align(center) Automatically sized \ to fit the content. ] ``` #[ #show:blockk // Without content. #ellipse(width: 35%, height: 30pt) // With content. #ellipse[ #set align(center) Automatically sized \ to fit the content. ] ] == 图片image 参考之前章节 @image 的描述 = Meta 文档结构化、内省和元数据配置。在这里,可以找到构建文档并与该结构交互的函数。这包括章节标题和图表、书目管理、交叉引用等。 此外,此类别描述了 Typst 内省功能:使用计数器功能,您可以访问和操作页面、部分、图形和方程式计数器或创建自定义计数器。查询功能让您可以搜索文档中的元素,以构建图表列表或显示当前章节标题的标题等内容。 == 文献库导入bibliography 导入参考文献库 #parbreak() 可以通过使用以下两种格式之一的参考书目文件的路径调用此函数来创建新的参考书目: - Hayagriva `.yml` \ Hayagriva 是一种新的参考书目文件格式,专为与 Typst 一起使用而设计。 - BibLaTeX `.bib` 只要在文档中的某处添加参考书目,就可以开始使用引用语法 (`@key`) 或显式调用citation函数 (`#cite("key")`) 来引用内容。参考书目将仅显示文档中引用的作品的条目。 ```para bibliography( // 路径 path: string, // 设置参考文献 set title: none auto content, // 设置引用格式 当前支持: apa author-date ieee mla // v0.1版本"author-date"和"author-title"改名为"chicago-author-date"和"chicago-author-title" set style: string, ) -> content ``` ```typ This was already noted by pirates long ago. @arrgh Multiple sources say ... #cite("arrgh", "netwok"). #bibliography("works.bib") ``` == 文献引用cite <cite> 引用参考书目中的作品。在开始引用之前,您需要在文档的某处添加参考书目。 ```para cite( // 标识应在参考书目中引用的元素的引用键。参考语法仅支持单个键。 ..string, // 引文的补充,例如页码或章节编号。在参考语法中,可以在方括号中添加补充: set none content, // 引文是否应包括括号。 set brackets: boolean, // 引用样式 numerical alphanumerical chicago-author-date chicago-notes chicago-author-title keys // v0.1版本"author-date"和"author-title"改名为"chicago-author-date"和"chicago-author-title" set style: auto string, ) -> content ``` ```typ This was already noted by pirates long ago. @arrgh Multiple sources say ... #cite("arrgh", "netwok"). #bibliography("works.bib") ``` ```typ This has been proven over and over again. @distress[p.~7] #bibliography("works.bib") ``` ```typ #set cite(brackets: false) @netwok follow these methods in their work ... #bibliography( "works.bib", style: "author-date", ) ``` ```typ #set cite(style: "alphanumerical") Alphanumerical references. @netwok #bibliography("works.bib") ``` == 文献引用ref <ref> 对标签或参考书目的引用。引用函数生成对标签的文本引用。例如,对标题的引用将产生一个适当的字符串,例如“Section 1”,用于对第一个标题的引用。参考文献也是指向相应元素的链接。 参考语法也可用于引用参考书目。 ```para ref( label, set supplement: none auto content function, ) -> content ``` ```typ #set heading(numbering: "1.") #set math.equation(numbering: "(1)") = Introduction <intro> Recent developments in typesetting software have rekindled hope in previously frustrated researchers. @distress As shown in @results, we ... = Results <results> We discuss our approach in comparison with others. == Performance <perf> @slow demonstrates what slow software looks like. $ O(n) = 2^n $ <slow> #bibliography("works.bib") ``` ```typ #set heading(numbering: "1.") #set ref(supplement: it => { if it.func() == heading { "Chapter" } else { "Thing" } }) = Introduction <intro> In @intro, we see how to turn Sections into Chapters. And in @intro[Part], it is done manually. ``` == 图片figure 见之前章节 @image 描述 == 脚注footnote 使用脚注,可以在当前页面提供额外的标记与参考。脚注将会插入一个上标数字,用于链接到底部的注释。注释在文档中是按顺序编号的,并且可以跨越多个页面。 下文描述了如何自定义脚注列表中的条目外观。脚注是以普通的上标实现的,因此可以基于`super`函数自定义规则。 ```typ Check the docs for more details. #footnote[https://typst.app/docs] ``` #[ #show:blockk Check the docs for more details. #footnote[https://typst.app/docs] ] 脚注会自动以上标的形式依附在前面的单词。即使在编标记前面还有空格。如果有强制使用空格的地方,可以使用字符`#" "`或者显示声明水平间距`#h()`。 ```para footnote( // 如何编号 // 默认情况下,脚注编号是连续的。如果需要自定义每页的脚注编号,可以在每页开头设置脚注`counter` numbering: string | function, content, ) -> content ``` ```typ #set footnote(numbering: "*") Footnotes: #footnote[Star], #footnote[Dagger] ``` #[ #show:blockk #set footnote(numbering: "*") Footnotes: #footnote[Star], #footnote[Dagger] ] === `footnote.entry` 自定义脚注列表中的条目。 此函数不能直接调用。但是可以用于设置和显示规则以自定义脚注列表。 此文档编写中,发现该函数只有在文章开头定义才会生效,原因未知! ```para footnote.entry( // 脚注内容,他的位置可以用于确定counter状态 note: content, // 设置脚注与正文之间的分隔符 // 默认:#line(length: 30%, stroke: 0.5pt) separator: content, // 正文与分隔符之间的间距 // Default: 1em clearance: length, // 脚注之间的间距 // Default: 0.5em // gap: length, // 脚注缩进 // Default: 1em indent: length, ) -> content ``` ```typ #show footnote.entry: set text(red) My footnote listing #footnote[It's down here] has red text! ``` #[ #show:blockk #show footnote.entry: set text(blue) My footnote listing #footnote[It's down here] has red text! ] ```typ #show footnote.entry: it => { let loc = it.note.location() numbering( "1: ", ..counter(footnote).at(loc), ) it.note.body } Customized #footnote[Hello] listing #footnote[World! 🌏] ``` #[ #show:blockk #show footnote.entry: it => { let loc = it.note.location() numbering( "1: ", ..counter(footnote).at(loc), ) it.note.body } Customized #footnote[Hello] listing #footnote[World! 🌏] ] ```typ #set footnote.entry( separator: repeat[.] ) Testing a different separator. #footnote[ Unconventional, but maybe not that bad? ] ``` #[ #show:blockk #set footnote.entry( separator: repeat[.] ) Testing a different separator. #footnote[ Unconventional, but maybe not that bad? ] ] ```typ #set footnote.entry(clearance: 3em) Footnotes also need ... #footnote[ ... some space to breathe. ] ``` #[ #show:blockk #set footnote.entry(clearance: 3em) Footnotes also need ... #footnote[ ... some space to breathe. ] ] ```typ #set footnote.entry(gap: 0.8em) Footnotes: #footnote[Spaced], #footnote[Apart] ``` #[ #show:blockk #set footnote.entry(gap: 0.8em) Footnotes: #footnote[Spaced], #footnote[Apart] ] ```typ #set footnote.entry(indent: 0em) Footnotes: #footnote[No], #footnote[Indent] ``` #[ #show:blockk #set footnote.entry(indent: 0em) Footnotes: #footnote[No], #footnote[Indent] ] == 标题heading 章节标题。通过使用标题,可以将文档组织成多个部分。每个标题都有一个级别,从一级开始,向上无界。此级别指示以下内容(部分、小节等)的逻辑作用。顶级标题表示文档的顶级部分(不是文档的标题)。 Typst 可以自动为您的标题编号。要启用编号,请指定您希望如何使用编号模式或功能对标题进行编号。 除了编号之外,Typst 还可以自动为您生成所有标题的大纲。要从此大纲中排除一个或多个标题,您可以将 outlined 参数设置为 false。 语法糖:通过以一个或多个\=开始一行,后跟一个空格来创建。等号的数量决定了标题的逻辑嵌套深度。 ```para heading( // 标题深度 set level: integer, // 编号格式 set numbering: nonestringfunction, // 是否在目录显示 set outlined: boolean, content, ) -> content ``` ```typ #set heading(numbering: "1.a)") = Introduction In recent years, ... == Preliminaries To start, ... ``` ```typ #set heading(numbering: "1.a.") = A section == A subsection === A sub-subsection ``` ```typ #outline() #heading[Normal] This is a normal heading. #heading(outlined: false)[Hidden] This heading does not appear in the outline. ``` == 布局Layout 对当前外部容器大小(如果none则设置页面)进行修改(宽度和高度)#parbreak() 给定函数必须接受单一参数,也即高和宽使用字典的形式传递。 ```typ #let text = lorem(30) #layout(size => style(styles => [ #let (height,) = measure( block(width: size.width, text), styles, ) This text is #height high with the current page width: \ #text ])) ``` #[ #show:blockk #let text = lorem(30) #layout(size => style(styles => [ #let (height,) = measure( block(width: size.width, text), styles, ) This text is #height high with the current page width: \ #text ])) ] 如果布局调用放置在宽度为 800pt、高度为 400pt 的框内,则指定的函数将被赋予参数(宽度:800pt,高度:400pt)。如果它直接放在页面中,它会收到页面的尺寸减去边距。这在与测量结合时最有用。 #parbreak() 您还可以使用此函数将比率解析为固定长度。如果您正在构建自己的布局抽象,这可能会派上用场。 ```typ #layout(size => { let half = 50% * size.width [Half a page is #half wide.] }) ``` #[ #show:blockk #layout(size => { let half = 50% * size.width [Half a page is #half wide.] }) ] 请注意,如果页面宽度或高度之一分别为自动,则此函数将提供无限宽度或高度。 ```para 用外部容器的大小来调用的函数。它的返回值显示在文档中。 容器的尺寸是以字典的形式给出的,有宽度和高度两个键。 布局返回的内容每次出现在文档中时,都会调用这个函数一次。这使得生成的内容有可能取决于它所在的容器的大小。 layout(function) -> content ``` == 编号numbering 编号定义应如何将数字序列显示为内容。它通过模式字符串或任意函数定义。编号模式由计数符号、它们的前缀和一个后缀组成,实际数字被替换为计数符号。前缀和后缀按原样重复。 ```para numbering( // 定义编号。计数符号是 1、a、A、i、I 和 *。在给定的情况下,它们被序列中的数字替换。 // *字符表示应使用符号进行计数,顺序为*、†、‡、§、¶、‖。如果项目超过六项​​,则使用多个符号表示数量。 numbering: string function, // 要应用编号的数字。必须是积极的。 // 如果编号是一种模式并且给出的数字多于计数符号,则重复最后一个计数符号及其前缀。 numbers: ..integer, ) -> any ``` ```typ #numbering("1.1)", 1, 2, 3) \ #numbering("1.a.i", 1, 2) \ #numbering("I – 1", 12, 2) \ #numbering( (..nums) => nums .pos() .map(str) .join(".") + ")", 1, 2, 3, ) ``` #[ #show:blockk #numbering("1.1)", 1, 2, 3) \ #numbering("1.a.i", 1, 2) \ #numbering("I – 1", 12, 2) \ #numbering( (..nums) => nums .pos() .map(str) .join(".") + ")", 1, 2, 3, ) ] == 链接link <link> 超链接 link 函数使其位置主体参数可点击并将其链接到 dest 参数指定的目的地。 默认情况下,链接的样式与普通文本没有任何不同。但是,您可以使用显示规则轻松应用您选择的样式。 语法糖:以 http:// 或 https:// 开头的文本会自动变成链接。 ```para link( // 指向目的地 // 要链接到网页,dest 应该是一个有效的 URL 字符串。 // 要链接到文档的另一部分,dest 可以采用以下两种形式之一:locate函数或具有整数类型的页面键和长度类型的 x 和 y 坐标的字典。页数从一页开始,坐标相对于页面的左上角。 dest: string dictionary location, // 链接的显示内容。 body: content, ) -> content ``` ```typ #show link: underline https://example.com \ #link("https://example.com") \ #link("https://example.com")[ See example.com ] ``` #[ #show:blockk #show link: underline https://example.com \ #link("https://example.com") \ #link("https://example.com")[ See example.com ] ] ```typ #link("mailto:<EMAIL>") \ #link((page: 1, x: 0pt, y: 0pt))[ Go to top ] ``` #[ #show:blockk #link("mailto:<EMAIL>") \ #link((page: 1, x: 0pt, y: 0pt))[ Go to top ] ] == 访问locate 提供对文档内容位置的访问。与queries、counters、state和links结合使用很有用。 ```para locate(function) -> content ``` ```typ #locate(loc => [ My locatation: \ #loc.position()! ]) ``` #[ #show:blockk #locate(loc => [ My locatation: \ #loc.position()! ]) ] === methods ```para // 返回当前页码。不会返回此位置的页面计数器的值,而是返回真实的页码(从一开始)。 // 如果想知道页面计数器的值,请改用 counter(page).at(loc)。 value.page() -> integer // 返回包含页码和此位置的 x、y 位置的字典。页码从 1 开始,坐标从页面的左上角开始测量。 // 只需要页码,请改用 page(),因为它允许 Typst 跳过不必要的工作。 value.position() -> dictionary ``` == 大纲outline 生成大纲/目录,此函数生成文档中所有标题的列表,直到给定深度。 元素的编号和页码将显示在大纲中及其标题或标题旁边。 ```para outline( // 设置目录标题,none表示无目录标题 set title: none auto content, // 设置包含在大纲中的元素类型 set target: label function selector // 显示标题的最大深度 set depth: none integer, // 是否缩进副标题以将其编号的开头与其父母的标题对齐。这仅在设置标题编号时有效。 set indent: boolean, // 标题和页码之间的空间。可以设置为 none 以禁用填充。默认是重复[.]。 set fill: none content, ) -> content ``` ```typ #outline() = Introduction #lorem(5) = Prior work #lorem(10) ``` ```typ #set heading(numbering: "1.a.") #outline( title: [Contents (Automatic)], indent: auto, ) #outline( title: [Contents (Length)], indent: 2em, ) #outline( title: [Contents (Function)], indent: n => [→ ] * n, ) = About ACME Corp. == History === Origins #lorem(10) == Products #lorem(10) ``` #h(2em)通过设置target参数,大纲可用于生成除标题之外的其他类型元素的列表。在下面的示例中,我们通过将 target 设置为`figure.where(kind: image)` 来列出所有包含图像的图形。我们也可以将其设置为仅图形,但列表中还将包括包含表格或其他材料的图形。 ```typ #outline( title: [List of Figures], target: figure.where(kind: image), ) #figure( image("tiger.jpg"), caption: [A nice figure!], ) ``` ```typ #outline( title: [List of Tables], target: figure.where(kind: table), ) #figure( table( columns: 4, [t], [1], [2], [3], [y], [0.3], [0.7], [0.5], ), caption: [Experiment results], ) ``` ```typ #set heading(numbering: "1.") #outline(depth: 2) = Yes Top-level section. == Still Subsection. === Nope Not included. ``` ```typ #outline(fill: line(length: 100%)) = A New Beginning ``` === outline.entry function 大纲元素有几个自定义的选项,比如它的标题和缩进参数。然而,如果需要的话,可以通过`outline.entry`元素对大纲的外观和风格有更多的控制。 显示大纲中的每个条目行,包括对大纲元素的引用、其页码以及两者之间的填充内容。 该元素旨在与显示规则一起使用来控制大纲的效果。 ```para outline.entry( // 大纲的嵌套登记 level: integer, // 该条目引用的元素。其位置将通过location方法提供,并且可以linked。 element: content, // 在大纲中的条目中,取代被提及的元素而显示的内容。对于一个标题,这将是它的编号,然后是标题的名称。 body: content, // 用于填充元素轮廓与其页码之间空间的内容(由该条目所在的轮廓元素定义)。如果没有,则在该间隙中插入空白空间。请注意,当使用显示规则覆盖大纲条目时,建议将填充内容包装在具有分数宽度的框中。例如,box(width: 1fr, Repeat[-]) 将精确显示填补特定空白所需的多个 - 字符。 // 简而言之就是制表符 fill: none content, // 此条目链接到的元素的页码,采用引用页面的编号集进行格式化。 page: content, ) -> content ``` ```typ #set heading(numbering: "1.") #show outline.entry.where( level: 1 ): it => { v(12pt, weak: true) strong(it) } #outline(indent: auto) = Introduction = Background == History == State of the Art = Analysis == Setup ``` == 计数器counter count页面、元素等。使用counter func,可以访问和修改页面、标题、图表等的计数器。此外,您可以为其他要计数的事物定义自定义计数器。 === 显示counter 要显示heading counter的当前值,可以调用counter func并将key设置为heading,然后调用counter的display method。要查看任何输出,您还必须启用heading number。 display 函数可选地接受一个参数,告诉它如何格式化计数器。 ```typ #set heading(numbering: "1.") = Introduction Some text here. = Background The current value is: #counter(heading).display() Or in roman numerals: #counter(heading).display("I") ``` === 修改counter 要修改counter,可以使用 step 和 update 方法: - step 方法将counter的值增加 1。因为counter可以有多个级别(在节、小节等的标题的情况下),所以 step 方法可以选择使用级别参数。如果给定,则counter在给定深度步进。 - update 方法允许您任意修改counter。可以给它一个整数(或多个级别的倍数)。为了获得更大的灵活性,您还可以为其提供一个获取当前值并返回新值的函数。 ```typ #set heading(numbering: "1.") = Introduction #counter(heading).step() = Background #counter(heading).update(3) #counter(heading).update(n => n * 2) = Analysis Let's skip 7.1. #counter(heading).step(level: 2) == Analysis Still at #counter(heading).display(). ``` === 如何步进 (v0.1新增) 当您定义和使用自定义counter时,一般情况下,您应该先step counter然后display it。这样,计数器的step可以取决于它步进的元素。如果您正在为定理编写一个计数器,那么您的定理定义将首先包括计数器步骤,然后才显示计数器和定理的内容。#parbreak() ```typ #let c = counter("theorem") #let theorem(it) = block[ #c.step() *Theorem #c.display():* #it ] #theorem[$1 = 1$] #theorem[$2 < 3$] ``` #[ #show:blockk #let c = counter("theorem") #let theorem(it) = block[ #c.step() *Theorem #c.display():* #it ] #theorem[$1 = 1$] #theorem[$2 < 3$] ] #h(2em)机理解释:heading counter的更新取决于heading的层级。通过在heading之前设置heading的step,当到二级heading时,我们可以将step从`1`修正为`1.1`。如果我们在heading之后使用step,那么程序不会知道step的值。这是因为counters必须在计数元素之前step,#strong[并且从0开始]。 === 页面计数器pagecounter pagecounter是特殊的。它会在每个分页符处自动步进。但与其他counter一样,也可以手动步进。例如,您可以为序言使用罗马页码,然后为主要内容切换为阿拉伯文页码并将pagecounter重置为 1。 ```typ #set page(numbering: "(i)") = Preface The preface is numbered with roman numerals. #set page(numbering: "1 / 1") #counter(page).update(1) = Main text Here, the counter is reset to one. We also display both the current page and total number of pages in Arabic numbers. ``` === 自定义counters 自定义counter,使用字符串作为key调用counter函数。 ```typ #let mine = counter("mycounter") #mine.display() \ #mine.step() #mine.display() \ #mine.update(c => c * 3) #mine.display() \ ``` #[ #show:blockk #let mine = counter("mycounter") #mine.display() \ #mine.step() #mine.display() \ #mine.update(c => c * 3) #mine.display() \ ] === time travel Counters can travel through time! You can find out the final value of the counter before it is reached and even determine what the value was at any particular location in the document. ```typ #let mine = counter("mycounter") = Values #locate(loc => { let start-val = mine.at(loc) let elements = query(<intro>, loc) let intro-val = mine.at( elements.first().location() ) let final-val = mine.final(loc) [Starts as: #start-val \ Value at intro is: #intro-val \ Final value is: #final-val \ ] }) #mine.update(n => n + 3) = Introduction <intro> #lorem(10) #mine.step() #mine.step() ``` 上述代码做了如下几件事: - 调用`loacte`函数获取当前位置。然后将该位置传递给counter。at 方法总是返回一个数组,因为计数器可以有多个级别。由于计数器从 1 开始,因此第一个值为 (1,)。 - 查询文档中所有带有 <intro> 标签的元素。结果是一个数组,从中提取第一个元素的位置。然后我们在该位置查找计数器的值。计数器的第一次更新将其设置为 1 + 3 = 4。因此在介绍标题处,该值为 (4,)。 - 最后,在counter上调用 final 方法。它告诉我们在文档末尾counter的值是多少。还需要给它一个位置来证明我们在一个 locate 调用中,但哪个并不重要。标题之后是对 step() 的两次调用,因此最终值为 (6,)。 ```para counter(key: string | label | function) -> counter ``` === Methods ```para // 显示当前counter值 value.display(string | function) -> content // 将计数器的值增加一。更新将在返回内容插入文档的位置生效。如果您不将输出放入文档中,则什么也不会发生!例如,如果您编写 let _ = counter(page).step(),就会出现这种情况。 value.step(level: integer) -> content // 更新计数器的值 value.update(integer | array | function) -> content // 获取给定位置的计数器值。始终返回一个整数数组,即使计数器只有一个数字。 value.at(location) -> array // 获取文档末尾的计数器值。始终返回一个整数数组,即使计数器只有一个数字。 value.final(location) -> array ``` == 查找query 在文档中查找元素。query功能使您可以在文档中搜索特定类型或具有特定标签的元素。 要使用它,您首先需要使用 locate 函数检索当前文档位置。然后您可以决定是否要查找所有元素,仅查找该位置之前的元素,还是仅查找该位置之后的元素。 === 查找元素find elements 在下面的示例中,我们创建了一个自定义页眉,以小写大写形式显示文本“Typst Academy”和当前部分标题。在第一页上,节标题被省略,因为标题在第一个节标题之前。 为了实现这种布局,我们调用 locate 然后查询当前位置之后的所有标题。在这种情况下,我们传递给 locate 的函数被调用两次:每页调用一次。 - 在第一页上,查询当前位置之前的所有标题会产生一个空数组:没有以前的标题。我们检查这种情况,然后只显示“Typst Academy”。 - 对于第二页,我们从查询结果中检索最后一个元素。这是当前位置之前的最新标题,因此,它是我们当前所在部分的标题。我们通过 body 字段访问其内容并将其显示在“Typst Academy”旁边。 ```typ #set page(header: locate(loc => { let elems = query( selector(heading).before(loc), loc, ) let academy = smallcaps[ Typst Academy ] if elems == () { align(right, academy) } else { let body = elems.last().body academy + h(1fr) + emph(body) } })) = Introduction #lorem(23) = Background #lorem(30) = Analysis #lorem(15) ``` ```para query( // heading figure equation reference label target: label function, location, ) -> content ``` 为了解决您的所有查询,Typst 多次评估和布局文档的各个部分。但是,不能保证您的查询实际上可以完全解决。如果您不小心,查询可能会影响自身——导致结果永远不稳定。 在下面的示例中,我们查询文档中的所有标题。然后我们生成尽可能多的标题。一开始,只有一个标题,名为 Real。这样count为1,生成一个Fake heading。 Typst 看到查询的结果已经改变并再次处理它。这次,count 为 2,生成了两个 Fake headings。这种情况一直在继续。正如我们所见,输出有五个标题。这是因为 Typst 在五次尝试后就放弃了。 一般来说,你应该尽量不要写影响自己的查询。同样的警告也适用于其他内省功能,如计数器和状态。 ```typ = Real #locate(loc => { let elems = query(heading, loc) let count = elems.len() count * [= Fake] }) ``` == 文档document 文档的根元素及其元数据。所有文档都自动包装在文档元素中。该元素的主要用途是在设置规则中使用它来指定文档元数据。 使用此功能设置的元数据不会在文档中呈现。相反,它嵌入在已编译的 PDF 文件中。 ```para document( // 设置文档标题 set title: none string, // 文档作者 set author: string array, ) -> content ``` = 计算 Typst因为支持函数,所以支持数值的计算和处理。这些函数是calc module的组成,默认情况下是不会导入的。除了如下的函数以外,calc还定义了常量`pi`、`e`、`inf`、`nan`。#parbreak() ```para // 计算给定数的绝对值 abs(integer | float | length | angle | ratio | fraction) -> any // 计算sin值 当使用整数或浮点数调用时,它们将被解释为弧度。 sin(integer | float | angle) -> float // 计算cos值 当使用整数或浮点数调用时,它们将被解释为弧度。 cos(integer | float | angle) -> float // 计算tan值 当使用整数或浮点数调用时,它们将被解释为弧度。 tan(integer | float | angle) -> float // 计算arccos值 acos(integer | float) -> angle // 计算arcsin值 asin(integer | float) -> angle // 计算arctan值 atan(integer | float) -> angle // 计算角度的双曲正弦值 当使用整数或浮点数调用时,它们将被解释为弧度 sinh(integer | float | angle) -> float // 计算角度的双曲余弦值 当使用整数或浮点数调用时,它们将被解释为弧度 cosh(integer | float | angle) -> float // 计算角度的双曲正切值 当使用整数或浮点数调用时,它们将被解释为弧度 tanh(integer | float | angle) -> float // 计算对数 如果未指定底数,则以 10 为底数计算对数。 base:底数 log(integer | float,base: float,) -> float // 最大值 max(..any) -> any // 最小值 min(..any) -> any // 计算二次式系数 binom(integer,integer,) -> integer // 阶乘 fact(integer) -> integer // 求两个数的模 mod(dividend: integer | float,divisor: integer | float,) -> integer | float // 同上,v0.3新增用于替换mod rem(dividend: integer | float,divisor: integer | float,) -> integer | float // 返回数字的整数部分。如果数字已经是整数,则返回原样。 trunc(integer float) -> integer // 返回数字的小数部分。如果数字是整数,则返回 0。 fract(integer float) -> integerfloat // 指数计算 pow(base: integer | float,exponent: integer | float,) -> integer | float // 判断整数是否为奇数 odd(integer) -> boolean // 判断整数是否为偶数 even(integer) -> boolean // 将数字舍入到最接近的整数。可以指定小数位数。 round(integer | float,digits: integer,) -> integer | float // 将数字向下取整 floor(integer | float) -> integer // 将数字向上取整。如果数字已经是整数,则返回原样。 ceil(integer | float) -> integer // 计算两个整数的最小公倍数。 lcm(integer,integer,) -> integer // 计算一个排列。 perm(integer,integer,) -> integer // 平方根 sqrt(integer | float) -> float // 将数字夹在最大值与最小值之间? clamp(integer | float,integer | float,integer | float,) -> integer | float ``` ```typ #calc.abs(-5) \ #calc.abs(5pt - 2cm) \ #calc.abs(2fr) \ #calc.sqrt(16) \ #calc.sqrt(2.5) \ #calc.pow(2, 3) \ #calc.log(100) \ #calc.rem(20, 6) \ #calc.rem(1.75, 0.5) \ #calc.fact(5) \ #calc.fract(-3.1)\ #calc.lcm(96, 13) \ #calc.perm(10, 5)\ #calc.trunc(3) \ #calc.trunc(-3.7) \ #calc.trunc(15.9) \ #calc.clamp(5, 0, 4) ``` #[ #show:blockk #calc.abs(-5) \ #calc.abs(5pt - 2cm) \ #calc.abs(2fr) \ #calc.sqrt(16) \ #calc.sqrt(2.5) \ #calc.pow(2, 3) \ #calc.log(100) \ #calc.rem(20, 6) \ #calc.rem(1.75, 0.5) \ #calc.fact(5) \ #calc.fract(-3.1)\ #calc.lcm(96, 13) \ #calc.perm(10, 5)\ #calc.trunc(3) \ #calc.trunc(-3.7) \ #calc.trunc(15.9) \ #calc.clamp(5, 0, 4) ] ```typ #calc.sin(1.5) \ #calc.sin(90deg) \ #calc.cos(90deg) \ #calc.cos(1.5) \ #calc.cos(90deg) \ #calc.tan(1.5) \ #calc.tan(90deg) #calc.acos(0) \ #calc.acos(1) \ #calc.asin(0) \ #calc.asin(1) \ #calc.atan(0) \ #calc.atan(1) \ #calc.sinh(0) \ #calc.sinh(45deg) \ #calc.cosh(0) \ #calc.cosh(45deg) \ #calc.tanh(0) \ #calc.tanh(45deg) \ ``` #[ #show:blockk #calc.sin(1.5) \ #calc.sin(90deg) \ #calc.cos(90deg) \ #calc.cos(1.5) \ #calc.cos(90deg) \ #calc.tan(1.5) \ #calc.tan(90deg) #calc.acos(0) \ #calc.acos(1) \ #calc.asin(0) \ #calc.asin(1) \ #calc.atan(0) \ #calc.atan(1) \ #calc.sinh(0) \ #calc.sinh(45deg) \ #calc.cosh(0) \ #calc.cosh(45deg) \ #calc.tanh(0) \ #calc.tanh(45deg) \ ] ```typ #calc.max(1, -3, -5, 20, 3, 6) \ #calc.max("typst", "in", "beta") #calc.min(1, -3, -5, 20, 3, 6) \ #calc.min("typst", "in", "beta") \ #calc.odd(4) \ #calc.odd(5) \ #range(10).filter(calc.odd) \ #calc.even(4) \ #calc.even(5) \ #range(10).filter(calc.even) \ #calc.round(3.1415, digits: 2) \ #calc.floor(500.1) \ #calc.ceil(500.1) \ ``` #[ #show:blockk #calc.max(1, -3, -5, 20, 3, 6) \ #calc.max("typst", "in", "beta") #calc.min(1, -3, -5, 20, 3, 6) \ #calc.min("typst", "in", "beta") \ #calc.odd(4) \ #calc.odd(5) \ #range(10).filter(calc.odd) \ #calc.even(4) \ #calc.even(5) \ #range(10).filter(calc.even) \ #calc.round(3.1415, digits: 2) \ #calc.floor(500.1) \ #calc.ceil(500.1) \ ] = Construct Typst支持不同类型值的构造和转换。 == int 将值转换为整数 - 布尔值转换为0或1 - 浮点数向下取整 - 字符串以10为基数解析 ```para int(boolean | integer | float | string) -> integer ``` ```typ #int(false) \ #int(true) \ #int(2.7) \ #{ int("27") + int("4") } ``` #[ #show:blockk #int(false) \ #int(true) \ #int(2.7) \ #{ int("27") + int("4") } ] == float 将值转为浮点数 - 布尔值转为0.0或1.0 - 整数向下取整为64位浮点数 - 字符串以 10 为基数解析为最接近的 64 位浮点数。支持指数符号。 ```para float(boolean | integer | float | string) -> float ``` ```typ #float(false) \ #float(true) \ #float(4) \ #float("2.7") \ #float("1e5") ``` #[ #show:blockk #float(false) \ #float(true) \ #float(4) \ #float("2.7") \ #float("1e5") ] == range 创建一个由数字序列组成的数组。如果你只传递一个位置参数,它被解释为范围的结束。如果你传递两个,它们描述了范围的开始和结束。 ```para range( // 起始,包含当前位置 start: integer, // 结束,不包含当前位置 end: integer, // 步长 step: integer, ) -> array ``` ```typ #range(5) \ #range(2, 5) \ #range(20, step: 4) \ #range(21, step: 4) \ #range(5, 2, step: -1) ``` #[ #show:blockk #range(5) \ #range(2, 5) \ #range(20, step: 4) \ #range(21, step: 4) \ #range(5, 2, step: -1) ] == regex 从字符串创建正则表达式。结果可用作show 规则选择器,或者string方法(find,split,replace)。 ```para regex(string) -> regex ``` ```typ // Works with show rules. #show regex("\d+"): set text(red) The numbers 1 to 10. // Works with string methods. #("a,b;c" .split(regex("[,;]"))) ``` #[ #show:blockk #show regex("\d+"): set text(red) The numbers 1 to 10. #("a,b;c" .split(regex("[,;]"))) ] == cmyk 见之前章节 @cmyk 描述。 == RGB 见之前章节 @rgb 描述 == luma 见之前章节 @luma 描述 == string 见之前章节 @string 描述 == Label <label> 从字符串创建label。将label插入到内容中会将其附加到最近的不是空格的前一个元素。然后,可以通过标签引用该元素并设置其样式。 语法糖:可以通过将其名称括在尖括号中来创建标签。这适用于标记和代码。 ```para label(string) -> label ``` ```typ #show <a>: set text(blue) #show label("b"): set text(red) Heading <a> *Strong* #label("b") ``` #[ #show:blockk #show <a>: set text(blue) #show label("b"): set text(red) Heading <a> \ *Strong* #label("b") ] == symbol 见之前章节 @symbol 描述 = 导入文件 从外部读取数据文件 == csv 从 CSV 文件中读取结构化数据。 CSV 文件将被读取并解析为一个二维字符串数组:CSV 文件中的每一行将表示为一个字符串数组,所有行将被收集到一个数组中。标题行不会被删除。 ```para csv( // csv路径 path:string, // 分隔符 delimiter: string, ) -> array ``` ```typ #let results = csv("data.csv") #table( columns: 2, [*Condition*], [*Result*], ..results.flatten(), ) ``` // #[ // #show:blockk // #let results = csv("data.csv") // #table( // columns: 2, // [*Condition*], [*Result*], // ..results.flatten(), // ) // ] == json 从 JSON 文件中读取结构化数据。 该文件必须包含有效的 JSON 对象或数组。 JSON 对象将被转换为 Typst 字典,JSON 数组将被转换为 Typst 数组。字符串和布尔值将被转换为 Typst 等价物,null 将被转换为 none,数字将被转换为浮点数或整数,具体取决于它们是否为整数。该函数返回字典或数组,具体取决于 JSON 文件。 ```para json(path: string) -> array dictionary ``` ```typ #let forecast(day) = block[ #box(square( width: 2cm, inset: 8pt, fill: if day.weather == "sunny" { yellow } else { aqua }, align( bottom + right, strong(day.weather), ), )) #h(6pt) #set text(22pt, baseline: -8pt) #day.temperature °#day.unit ] #forecast(json("monday.json")) #forecast(json("tuesday.json")) ``` // #[ // #show:blockk // #let forecast(day) = block[ // #box(square( // width: 2cm, // inset: 8pt, // fill: if day.weather == "sunny" { // yellow // } else { // aqua // }, // align( // bottom + right, // strong(day.weather), // ), // )) // #h(6pt) // #set text(22pt, baseline: -8pt) // #day.temperature °#day.unit // ] // #forecast(json("monday.json")) // #forecast(json("tuesday.json")) // ] == plain text 读取文本文件并返回字符串 ```para read(path: string) -> string ``` ```typ #let text = read("data.html") An example for a HTML file:\ #raw(text, lang: "html") ``` // #[ // #show:blockk // #let text = read("data.html") // An example for a HTML file:\ // #raw(text, lang: "html") // ] == toml 从 TOML 文件中读取结构化数据。 该文件必须包含有效的 TOML 表。 TOML 表将转换为 Typst 字典,TOML 数组将转换为 Typst 数组。字符串和布尔值将被转换为 Typst 等价物,数字将被转换为浮点数或整数,具体取决于它们是否为整数。目前,日期时间将被转换为字符串,因为 Typst 还没有内置的日期时间。 示例中的 TOML 文件包含一个表,其中包含键标题、版本和作者。 ```para toml(string) -> dictionary ``` ```typ #let details = toml("details.toml") Title: #details.title \ Version: #details.version \ Authors: #(details.authors .join(", ", last: " and ")) ``` == xml 从 XML 文件中读取结构化数据。XML 文件被解析为字典和字符串数组。 XML 节点可以是元素或字符串。元素表示为具有以下键的字典: - tag:作为字符串的元素名称。 - attrs:元素属性的字典,作为字符串。 - children:元素的子节点数组。 示例中的 XML 文件包含一个带有多个article tags的root news tag。每篇文章都有title, author, and content tag.。content tag包含一个或多个段落,表示为 p 标签。 ```para xml(path: string) -> array ``` ```typ #let findChild(elem, tag) = { elem.children .find(e => "tag" in e and e.tag == tag) } #let article(elem) = { let title = findChild(elem, "title") let author = findChild(elem, "author") let pars = findChild(elem, "content") heading(title.children.first()) text(10pt, weight: "medium")[ Published by #author.children.first() ] for p in pars.children { if (type(p) == "dictionary") { parbreak() p.children.first() } } } #let data = xml("example.xml") #for child in data.first().children { if (type(child) == "dictionary") { article(child) } } ``` // #[ // #show:blockk // #let findChild(elem, tag) = { // elem.children // .find(e => "tag" in e and e.tag == tag) // } // #let article(elem) = { // let title = findChild(elem, "title") // let author = findChild(elem, "author") // let pars = findChild(elem, "content") // heading(title.children.first()) // text(10pt, weight: "medium")[ // Published by // #author.children.first() // ] // for p in pars.children { // if (type(p) == "dictionary") { // parbreak() // p.children.first() // } // } // } // #let data = xml("example.xml") // #for child in data.first().children { // if (type(child) == "dictionary") { // article(child) // } // } // ] == yaml 从 YAML 文件中读取结构化数据。该文件必须包含有效的 YAML 对象或数组。 YAML 映射将转换为 Typst 字典,YAML 序列将转换为 Typst 数组。字符串和布尔值将被转换为 Typst 等价物,空值(null、~ 或空``)将被转换为无,数字将被转换为浮点数或整数,具体取决于它们是否为整数。请注意,不是字符串的映射键会导致条目被丢弃。自定义 YAML 标签将被忽略,但加载的值仍然存在。该函数返回字典或值或数组,具体取决于 YAML 文件。 ```para yaml(path: string) -> arrayvaluedictionary ``` ```typ #let bookshelf(contents) = { for author, works in contents { author for work in works [ - #work.title (#work.published) ] } } #bookshelf(yaml("scifi-authors.yaml")) ``` = Foundations == Assert 如果不满足条件,则失败并出现错误。不在文档中产生任何输出。 ```para assert( // 判断语句 condition: boolean, // 报错信息 message: nonestring, ) -> ``` ```typ #assert(1 < 2, message: "math broke") ``` #[ #show:blockk #assert(1 < 2, message: "math broke") ] == Evaluate 将字符串评估为 Typst 代码。 ```para eval( source: string ) -> any ``` ```typ #eval("1 + 1") \ #eval("(1, 2, 3, 4)").len() \ #eval("[*Strong text*]") ``` #[ #show:blockk #eval("1 + 1") \ #eval("(1, 2, 3, 4)").len() \ #eval("[*Strong text*]") ] == Panic 报错 ```para panic( ..any ) -> ``` ```typ #panic("this is wrong") ``` == Representation 以文本形式输出想要的字符串。当插入到内容中时,大多数值都显示为具有语法突出显示的等宽表示形式。例外情况是无、整数、浮点数、字符串、内容和函数。 ```para repr(any) -> string ``` ```typ #none vs #repr(none) \ #"hello" vs #repr("hello") \ #(1, 2) vs #repr((1, 2)) \ #[*Hi*] vs #repr([*Hi*]) ``` #[ #show:blockk #none vs #repr(none) \ #"hello" vs #repr("hello") \ #(1, 2) vs #repr((1, 2)) \ #[*Hi*] vs #repr([*Hi*]) ] == Type 返回值类型 ```para type(any) -> string ``` ```typ #type(12) \ #type(14.7) \ #type("hello") \ #type(none) \ #type([Hi]) \ #type(x => x + 1) ``` #[ #show:blockk #type(12) \ #type(14.7) \ #type("hello") \ #type(none) \ #type([Hi]) \ #type(x => x + 1) ] #pagebreak() #[ #import "symm.typ":* #set page( paper:"a4", margin: ( top:2mm, bottom:2mm, left:2mm, right:2mm ), numbering: none, header: none, ) #set text(size:18pt) #set box(baseline:40%,fill:luma(230),height: 1.6em,inset:0.5em,outset:2pt,radius:5pt) #let arr=() #for (ii,i) in symm.keys().enumerate() [ #if type(symm.at(i)) == "dictionary" { for (jj,j) in symm.at(i).keys().enumerate() [ #if type(symm.at(i).at(j)) == "dictionary" { for (kk,k) in symm.at(i).at(j).keys().enumerate() [ #if type(symm.at(i).at(j).at(k))=="dictionary" { for (mm,m) in symm.at(i).at(j).at(k).keys().enumerate() [ #if type(symm.at(i).at(j).at(k).at(m))=="dictionary" { for (nn,n) in symm.at(i).at(j).at(k).at(m).keys().enumerate() [ #if symm.at(i).at(j).at(k).at(m).keys().at(nn) == "o" [ #arr.push(align(center+horizon)[#box[#symm.at(i).at(j).at(k).at(m).at(n)] \ #text(size:10pt)[#symm.keys().at(ii)\.#symm.at(i).keys().at(jj)\.#symm.at(i).at(j).keys().at(kk)\.#symm.at(i).at(j).at(k).keys().at(mm)]]) ] else [ #arr.push(align(center+horizon)[#box[#symm.at(i).at(j).at(k).at(m).at(n)] \ #text(size:10pt)[#symm.keys().at(ii)\.#symm.at(i).keys().at(jj)\.#symm.at(i).at(j).keys().at(kk)\.#symm.at(i).at(j).at(k).keys().at(mm)\.#symm.at(i).at(j).at(k).at(m).keys().at(nn)]]) ] ] } else [ #if symm.at(i).at(j).at(k).keys().at(mm) == "o" [ #arr.push(align(center+horizon)[#box[#symm.at(i).at(j).at(k).at(m)] \ #text(size:10pt)[#symm.keys().at(ii)\.#symm.at(i).keys().at(jj)\.#symm.at(i).at(j).keys().at(kk)]]) ] else [ #arr.push(align(center+horizon)[#box[#symm.at(i).at(j).at(k).at(m)] \ #text(size:10pt)[#symm.keys().at(ii)\.#symm.at(i).keys().at(jj)\.#symm.at(i).at(j).keys().at(kk)\.#symm.at(i).at(j).at(k).keys().at(mm)]]) ] ] ] } else [ #if symm.at(i).at(j).keys().at(kk) == "o" [ #arr.push(align(center+horizon)[#box[#symm.at(i).at(j).at(k)] \ #text(size:10pt)[#symm.keys().at(ii)\.#symm.at(i).keys().at(jj)]]) ] else [ #arr.push(align(center+horizon)[#box[#symm.at(i).at(j).at(k)] \ #text(size:10pt)[#symm.keys().at(ii)\.#symm.at(i).keys().at(jj)\.#symm.at(i).at(j).keys().at(kk)]]) ] ] ] } else [ #if symm.at(i).keys().at(jj) == "o" [ #arr.push(align(center+horizon)[#box[#symm.at(i).at(j)] \ #text(size:10pt)[#symm.keys().at(ii)]]) ] else [ #arr.push(align(center+horizon)[#box[#symm.at(i).at(j)] \ #text(size:10pt)[#symm.keys().at(ii)\.#symm.at(i).keys().at(jj)]]) ] ] ] } else [ #arr.push(align(center+horizon)[#box[#symm.at(i)] \ #text(size:10pt)[#symm.keys().at(ii)]]) ] ] #table( columns: (1fr,1fr,1fr,1fr,1fr,1fr), stroke:gray+1.0pt, align:horizon, ..arr ) ]
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/软件分析/hw/2100012990-郭子荀-软分第二次作业.typ
typst
#import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark #import "../../template.typ": * #show: note.with( title: "作业12", author: "YHTQ", date: datetime.today().display(), logo: none, withOutlined : false, withTitle : false, withHeadingNumbering: false ) = 1. 将三个抽象域分别记作: #let termPP = ``` term{x > 0} ``` #let termP = ``` term{x >= 0} ``` #let termN = ``` term{x < 0} ``` #let term = ``` term ``` - 自然数:#termP - 负数:#termN - 未知:#term 则加法计算规则包括: - $termP + termP: termP$ - $termN + termN: termN$ - $termP + termN: term$ - $termN + termP: term$ - $\_ + term: term$ - $term + \_: term$ 乘法规则包括: - $termP * termP: termP$ - $termN * termN: termP$ - $termP * termN: term$ - $termN * termP: term$ - $\_ * term: term$ - $term * \_: term$ 考虑 $3 * (-3) = -9$,在该抽象域下只能得到: $ (3: termP) * (-3: termN) = -9: term $ 然而事实上在更精确的抽象域下可以得到: $ (3: termPP) * (-3: termN) = -9: termN $
https://github.com/refparo/24xs-zh
https://raw.githubusercontent.com/refparo/24xs-zh/master/adventure1-bakery.typ
typst
#set document( title: "24XS 微型单人冒险:面包房", author: ("<EMAIL>", "Paro") ) #include "rules1.typ" #import "common.typ": * #show: typ-24xs #adventure-page( [ *冒险*:有一群拇指大的小人生活在一座老面包房的房椽木里,而你是他们之一。夜幕降临,轮到你离开房椽去寻找烤好的食物来喂饱你的族人了。\ *选或者编 2 个技能*:格斗,调查,导航,盗窃,欺骗,攀爬,发明,运动,潜行,说服,真菌学,生态学,木工,害虫防治,历史,烘焙。 ], random-table( [烤好的食物通常放在……], [藏在墙里的加固保险箱], [店面前的玻璃盒子], [密闭性不好的冷库], [柜台后的木箱], [恐怖而闹鬼的地下室], [每晚各不相同的地点], ), random-table( [保护着面包房的是……], [一只坏脾气的大猫], [店面前的玻璃盒子], [一群敌对的拇指人], [AI 控制的安保系统], [极其警觉的保安], [一个非常想念蛋糕的幽灵], ), random-table( [你要解决……], [各种不同的捕虫陷阱], [爬满虫子的隧道迷宫], [因管道泄漏而上涨的水位], [储藏室里居住的老鼠], [一把结实的锁和藏起来的钥匙], [路途中一段危险的攀爬], ), )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/rivet/0.1.0/docs/schema.typ
typst
Apache License 2.0
/// Loads a schema from a file or a raw block. /// This function returns a dictionary of structures /// /// Supported formats: #schema.valid-extensions.map(e => raw("." + e)).join(", ") /// - path-or-schema (str, raw, dictionary): If it is a string, defines the path to load. \ /// If it is a raw block, its content is directly parsed (the block's language will define the format to use) \ /// If it is a dictionary, it directly defines the schema structure /// -> dictionary #let load(path-or-schema) = {} /// Renders the given schema /// This functions /// - schema (dictionary): A schema dictionary, as returned by #doc-ref("schema.load") /// - config (auto, dictionary): The configuration parameters, as returned by #doc-ref("config.config") /// - width (ratio, length): The width of the generated figure #let render(schema, config: auto, width: 100%) = {}
https://github.com/alberto-lazari/computer-science
https://raw.githubusercontent.com/alberto-lazari/computer-science/main/advanced-topics-cs/module-3/trustworthy-ai.typ
typst
When put into the broader trustworthy AI horizon, the paper contributions have some interesting improvements over some of the main topics of the subject. When considering the _Assessment List for Trustworthy AI_ (ALTAI) the greatest improvements can be seen mostly on: - *Requirement \#1*: Human Agency and Oversight - *Requirement \#3*: Privacy and Data Governance - *Requirement \#4*: Transparency == Privacy and Data Governance This is another rock-solid assumption in the paper: the model has to be private. As with interpretability, it proved that a model can have comparable security results, but with great levels of accuracy and still keeping the interpretability. In this case LLM is not the first model to consider this aspect, nor the best, but a virtuous example that privacy can be treated seriously, without giving up on performance. == Transparency This is probably the most important point the paper revolves around. It starts pointing out that no other model ever considered to find a trade-off between privacy and accuracy, but with the premise that the system should be interpretable and explainable. When compared with other, already existing models, LLM proved to reach similar results, but with the added feature of being simple and explainable, by design. \ This is a great starting point for modern, next-generation models, that could incorporate such a model, or the philosophy behind it, allowing all new models to be easily understandable. == Human Agency and Oversight Being transparent and easily explainable, the LLM model is easier than more obscure alternatives to be managed and supervised by a human. When talking about oversight especially, being able to explain clearly the reasoning behind specific choices of the AI is important and a great advantage to have. It is not that easy to intervene and change the AI system manually, though probably possible by tuning the linear maps weights to avoid particular answers (maybe toward bias) or make some classes more precisely identifiable. == Other requirements Regarding the other requirements it's difficult to say whether it improves or not. It mostly depends on actual implementations and real applications. Topics like diversity, bias, safety or accountability were not addressed by the paper, because they were outside its scope. The proposal is a generic model, but a simple and clear one, thus it may be able to improve some aspects, given it is used and implemented well.
https://github.com/alberto-lazari/cv
https://raw.githubusercontent.com/alberto-lazari/cv/main/common.typ
typst
#import "@preview/brilliant-cv:2.0.1": cv, cvSection, cvEntry, cvHonor, cvSkill, hBar #let metadata = toml("/metadata.toml") #let cv = cv.with(metadata) #let section(text) = { cvSection(text, letters: text.split("").len() - 2, metadata: metadata) v(.2em) } #let modules(lang: metadata.language, ..args) = { for module in args.pos() { include { "modules_" + lang + "/" + module + ".typ" } v(.5em) } } // Better entry function #let entry( location: none, description: none, tags: (), ..args ) = { if tags.len() > 0 { description = { description // Separate description from tags v(-.3em) } } cvEntry( location: location, description: description, tags: tags, metadata: metadata, ..args ) v(-.5em) } #let honor(..args) = { v(eval(metadata.layout.at("before_entry_skip"))) cvHonor(metadata: metadata, ..args) } #let skill(type: none, info: ()) = { v(eval(metadata.layout.at("before_entry_skip"))) type = { set text(.9em) set par(leading: .5em) type } info = { set align(horizon) let spacing = .4em info.join([#h(spacing) | #h(spacing)]) } cvSkill(type: type, info: info) }
https://github.com/0x1B05/algorithm-journey
https://raw.githubusercontent.com/0x1B05/algorithm-journey/main/practice/note/content/前缀信息.typ
typst
#import "../template.typ": * #pagebreak() = 构建前缀信息的技巧-解决子数组相关问题 解决如下问题,时间复杂度O(n) == #link( "https://leetcode.cn/problems/range-sum-query-immutable/description/", )[题目1: 子数组范围求和] 给定一个整数数组 `nums`,处理以下类型的多个查询: - 计算索引 `left` 和 `right` (包含 `left` 和 `right`)之间的 `nums` 元素的 和 ,其中 `left` <= `right` - 实现 `NumArray` 类: - `NumArray(int[] nums)` 使用数组 `nums` 初始化对象 - `int sumRange(int i, int j)` 返回数组 `nums` 中索引 `left` 和 `right` 之间的元素的 总和 ,包含 `left` 和 `right` 两点(也就是 `nums[left] + nums[left + 1] + ... + nums[right]` ) #example("Example")[ 输入: ``` ["NumArray", "sumRange", "sumRange", "sumRange"] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] ``` 输出: ``` [null, 1, -1, -3] ``` 解释: ```java NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3) numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1)) numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1)) ``` ] == #link( "https://www.nowcoder.com/practice/36fb0fd3c656480c92b569258a1223d5", )[题目2 : 未排序数组中累加和为给定值的最长子数组长度 ] 给定一个无序数组`arr`, 其中元素可正、可负、可0。给定一个整数`k`,求`arr`所有子数组中累加和为`k`的最长子数组长度 输入描述: 第一行两个整数`N`, `k`。`N`表示数组长度,`k`的定义已在题目描述中给出 第二行`N`个整数表示数组内的数 输出描述: 输出一个整数表示答案 #example("Example")[ 输入: ``` 5 0 1 -2 1 1 1 ``` 输出: ``` 3 ``` ] #tip("Tip")[ - $1⩽N⩽10^5$ - $−10^9⩽k⩽10^9$ - $−100⩽"arr"_i⩽100$ ] == #link( "https://leetcode.cn/problems/subarray-sum-equals-k/", )[ 题目3: 和为 `aim` 的子数组 ] 构建 前缀和 出现的次数。返回 无序数组中 累加和为给定值的 子数组数量 #code(caption: [ 题目3: 和为 `aim` 的子数组 ])[ ```java public class Code03_Code03_NumberOfSubarraySumEqualsAim { public static int subarraySum(int[] nums, int aim) { HashMap<Integer, Integer> map = new HashMap<>(); // 0这个前缀和,在没有任何数字的时候,已经有1次了 map.put(0, 1); int ans = 0; for (int i = 0, sum = 0; i < nums.length; i++) { // sum : 0...i前缀和 sum += nums[i]; ans += map.getOrDefault(sum - aim, 0); map.put(sum, map.getOrDefault(sum, 0) + 1); } return ans; } } ``` ] == #link( "https://www.nowcoder.com/practice/545544c060804eceaed0bb84fcd992fb", )[ 题目4: 正数与负数个数相等的最长子数组 ] 构建 前缀和 最早出现的位置。返回 无序数组中 正数和负数个数相等的 最长子数组长度 #code( caption: [ 题目4: 正数与负数个数相等的最长子数组 ], )[ ```java public class Code04_PositivesEqualsNegtivesLongestSubarray { public static int MAXN = 100001; public static int n; public static int[] arr = new int[MAXN]; public static HashMap<Integer, Integer> map = new HashMap<>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer in = new StreamTokenizer(br); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); while (in.nextToken() != StreamTokenizer.TT_EOF) { n = (int) in.nval; for (int i = 0, num; i < n; i++) { in.nextToken(); num = (int) in.nval; arr[i] = num != 0 ? (num > 0 ? 1 : -1) : 0; } out.println(compute()); } out.flush(); out.close(); br.close(); } public static int compute() { map.clear(); map.put(0, -1); int ans = 0; for (int i = 0, sum = 0; i < n; i++) { sum += arr[i]; if (map.containsKey(sum)) { ans = Math.max(ans, i - map.get(sum)); } else { map.put(sum, i); } } return ans; } } ``` ] == #link( "https://leetcode.cn/problems/longest-well-performing-interval/", )[ 题目5: 表现良好时间段的最大长度 ] 构建 前缀和 最早出现的位置。表现良好的最长时间段问题 #code(caption: [ 题目5: 表现良好时间段的最大长度 ])[ ```java public class Code05_LongestWellPerformingInterval { public static int longestWPI(int[] hours) { // 某个前缀和,最早出现的位置 HashMap<Integer, Integer> map = new HashMap<>(); // 0这个前缀和,最早出现在-1,一个数也没有的时候 map.put(0, -1); int ans = 0; for (int i = 0, sum = 0; i < hours.length; i++) { sum += hours[i] > 8 ? 1 : -1; if (sum > 0) { ans = i + 1; } else { // sum <= 0 if (map.containsKey(sum - 1)) { ans = Math.max(ans, i - map.get(sum - 1)); } } if (!map.containsKey(sum)) { map.put(sum, i); } } return ans; } } ``` ] == 题目6 : 构建 前缀和余数 最晚出现的位置。移除的最短子数组长度,使得剩余元素的累加和能被p整除 == 题目7 : 构建 前缀奇偶状态 最早出现的位置。每个元音包含偶数次的 最长子串长度
https://github.com/maxgraw/bachelor
https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/6-evaluation/0-index.typ
typst
In diesem Kapitel widmet sich die Arbeit der Evaluation des entwickelten Prototyps einer Augmented Reality Konstruktionsumgebung für Möbelsysteme. == Zielsetzung #include "./goal.typ" == Methodik #include "./method.typ" == Ergebnisse #include "./result.typ" == Diskussion #include "discussion.typ"
https://github.com/fredguth/abnt-typst
https://raw.githubusercontent.com/fredguth/abnt-typst/main/templates/pos.typ
typst
// #import "../_config.typ": metadados, estilo, h1, h2, h3, h4, base, hdisplay, hficha, pagina_branca // {% comment %} - Elementos pós-textuais // -- Referências (obrigatório) // -- Glossário (opcional) // -- Apêndice (opcional) // -- Anexo (opcional) // -- Índice (opcional) // {% endcomment %} #pagebreak(to: "odd") // Referências (obrigatório)============================= // ABNT NBR 14724:2011 §4.2.3.1 - Referências // Elemento obrigatório. Elaboradas conforme a ABNT NBR 6023 #bibliography("../referencias.bib") // #pagina_branca() // Glossário (opcional)================================== // Apêndices (opcional)================================== // Índice Remissivo (opcional)=========================== // ABNT NBR 14724:2011 §4.2.3.5 - Índice Remissivo // 4.2.3.5 Índice // Elemento opcional. Elaborado conforme a ABNT NBR 6034. // Colofão (opcional)================================== // ABNT nem menciona Colofão
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cheq/0.1.0/examples/custom-styles.typ
typst
Apache License 2.0
#import "@preview/cheq:0.1.0": checklist #set page(width: auto, height: auto, margin: 2em) #show: checklist.with(fill: luma(95%), stroke: blue, radius: .2em) = Solar System Exploration, 1950s – 1960s - [ ] Mercury - [x] Venus - [x] Earth (Orbit/Moon) - [x] Mars - [ ] Jupiter - [ ] Saturn - [ ] Uranus - [ ] Neptune - [ ] Comet Haley #show: checklist.with(unchecked: sym.ballot, checked: sym.ballot.x) = Solar System Exploration, 1950s – 1960s - [ ] Mercury - [x] Venus - [x] Earth (Orbit/Moon) - [x] Mars - [ ] Jupiter - [ ] Saturn - [ ] Uranus - [ ] Neptune - [ ] Comet Haley
https://github.com/KireinaHoro/research-plan
https://raw.githubusercontent.com/KireinaHoro/research-plan/master/infk-doctoral-plan/manual.typ
typst
#import "@preview/tidy:0.3.0" #import "infk-doctoral-plan.typ" #let docs = tidy.parse-module( read("infk-doctoral-plan.typ"), name: "D-INFK Doctoral Plan Template", scope: (mod: infk-doctoral-plan), preamble: "import mod: *;" ) #show link: underline #set page(footer: align(center, counter(page).display("1"))) #tidy.show-module(docs)
https://github.com/tingerrr/chiral-thesis-fhe
https://raw.githubusercontent.com/tingerrr/chiral-thesis-fhe/main/README.md
markdown
# chiral-thesis-fhe This is a thesis template for the [University of Applied Sciences Erfurt][fhe] (FHE). It provides scaffolding for a [Typst] project which can be used to write a bachelor's thesis, mastere's thesis, or simple a report in the style mandated by the university. The template package provides scaffolding and defaults in both German, but may later be extended to english. The default thesis scaffold contains 5 common chapters with some lorem and examples for figures, tables and other useful features. Lastly, it contains a README.md detailing the structure and explaining how to add and remove optional parts of the document. ## Exmaple TODO ## TODO The following tasks remain before publishing on Typst Universe. - [x] Get into a workable state - [ ] Separate styles into optional and mandatory styles for easier picking and chosing - [ ] Provide more common defaults - [ ] Fix anti-matter and use it again - [ ] Provide better error messages on incorrect inputs - [x] Ensure abstracts are part of the PDF outline by using unstyled headings - [ ] Document package API and template README.md - [ ] Add metadata for post document checking (no remaining todos, correct layout choices) - [ ] Correctly separate fonts and resources or implement resources in Typst - [ ] Passthrough values to `set document` ## Documentation The documentation for this package can be viewed in the [manual]. A changelog is curated [here][changelog] and the initialized project contains a [README][template-readme] explaining how to get started. ## Contribution To contribute, simply open an issue to discuss a possible feature or problem that needs fixing. If you found an obvious bug, feel free to open a PR directly. PRs will automatically run regression tests, but for rapid local development consider installing some of the tools listed below. ### Tools - `typst` 0.11.0 to compile examples, docs and tests - `just` to run the recipes used for development and testing - `oxipng` for running the `doc` recipe - `typst-test` to run regression tests ## Etymology The default looks of the word and LaTeX templates are fairly LaTeX-typical in appearance. The non-descriptive "chiral" is a word play on this being the mirrored partner to the LaTeX template, as well as on the last letter of LaTeX being the greek letter chi. [fhe]: https://fh-erfurt.de/ [typst]: https://typst.app/home [manual]: ./docs/manual.pdf [changelog]: ./CHANGELOG.md [template-readme]: ./template/README.md
https://github.com/i-am-wololo/cours
https://raw.githubusercontent.com/i-am-wololo/cours/master/main/parties_i23/arithmetique.typ
typst
#import "../templates.typ": * #title("Arithmetique") = Les groupes quotient de $ZZ$ continuation du chapitre des groupes // TODO: mettre un lien vers les groupes == Divisibilite, nombres premiers #definition(title:"divisibilite")[ soit $a,b$ deux nombres, on dit que $a$ divise $b$ ou que $a$ est diviseur de $b$ ou encore que $b$ est multiple de $a$ si et seulement si $ exists c in ZZ a c = b $ a etant le diviseur, c etant le quotient, b etant le nombre] = Les anneaux $ZZ\/ZZ n$ == Structure d'anneaux L'ensemble $ZZ$ est muni de deux lois de composition interne, l' addition et la multiplication dont les proprietes lui confere une structure d'anneaux une structure d'anneaux #definition(title:"anneaux")[on appelle anneau tout triplet $(A, +, *)$ ou $+$ et $*$ sont des lois de composition interne dite d'addition et de multiplication qui satisfient les proprietes suivantes: - $(A, +)$ est un groupe commutatif dont l'element neutre est 0 - $(A, *)$ est un groupe associatif dont l'element neutre est 1 ] = Les theoremes de Gauss, Euler et Fernat
https://github.com/typst-community/guidelines
https://raw.githubusercontent.com/typst-community/guidelines/main/src/chapters/style/expression-blocks.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/src/util.typ": * #import mantys: * == Expression Blocks Prefer implicit block expression values over explicit `return`. #do-dont[ ```typc let if-none(var, default) = if var == none { default } else { var } ``` ][ ```typc // useless return let if-none(var, default) = if var == none { return default } else { return var } ``` ] Prefer assignment of expression block expressions over mutation of existing delcarations. #do-dont[ ```typc let x = if var { 0 } else { 1 } ``` ][ ```typc let x if var { x = 0 } else { x = 1 } ``` ] == Expression Blocks Prefer implicit block expression values over explicit `return`. #do-dont[ ```typc let if-none(var, default) = if var == none { default } else { var } ``` ][ ```typc // useless return let if-none(var, default) = if var == none { return default } else { return var } ``` ] Prefer assignment of expression block expressions over mutation of existing delcarations. #do-dont[ ```typc let x = if var { 0 } else { 1 } ``` ][ ```typc let x if var { x = 0 } else { x = 1 } ``` ]
https://github.com/YDX-2147483647/typst-pointless-size
https://raw.githubusercontent.com/YDX-2147483647/typst-pointless-size/main/zihao.typ
typst
MIT License
#let size_to_pt = ( (8, 5pt), (7, 5.5pt), (-6, 6.5pt), (6, 7.5pt), (-5, 9pt), (5, 10.5pt), (-4, 12pt), (4, 14pt), (-3, 15pt), (3, 16pt), (-2, 18pt), (2, 22pt), (-1, 24pt), (1, 26pt), ("-0", 36pt), (0, 42pt), ) #let zh(size, overrides: ()) = { let rules = (..overrides, ..size_to_pt) let rule = rules.find(((s, p)) => s == size) if rule != none { rule.at(1) } else { panic("expected a valid size (zìhào), found " + repr(size) + ". (All valid sizes: " + rules.map(r => repr(r.at(0))).join(", ") + ".)") } } #let zihao(size, overrides: ()) = { body => { set text(size: zh(size, overrides: overrides)) body } }
https://github.com/sofianedjerbi/Resume
https://raw.githubusercontent.com/sofianedjerbi/Resume/main/metadata.typ
typst
Apache License 2.0
// NOTICE: Copy this file to your root folder. /* Personal Information */ #let firstName = "Sofiane" #let lastName = "Djerbi" #let personalInfo = ( phone: "+33 695 800 269", email: "<EMAIL>", linkedin: "sofianedjerbi", //custom-1: (icon: "", text: "example", link: "https://example.com"), //gitlab: "mintyfrankie", //orcid: "0000-0000-0000-0000", //researchgate: "John-Doe", //extraInfo: "", ) /* Language-specific */ // Add your own languages while the keys must match the varLanguage variable #let headerQuoteInternational = ( "": [5+ years AWS-certified Cloud Professional seeking full-time role in Geneva, starting from now.], "en": [5+ years AWS-certified Cloud Professional seeking full-time role in Geneva, starting from now.], "fr": [5+ ans d'expérience et certifié AWS, recherche un poste dans le domaine du Cloud à Genève. Disponible immédiatement.], ) #let cvFooterInternational = ( "": "Curriculum vitae", "en": "Curriculum vitae", "fr": "Résumé", ) #let letterFooterInternational = ( "": "Cover Letter", "en": "Cover Letter", "fr": "Lettre de motivation", ) #let nonLatinOverwriteInfo = ( "customFont": "Heiti SC", "firstName": "王道尔", "lastName": "", // submit an issue if you think other variables should be in this array ) /* Layout Setting */ #let awesomeColor = "skyblue" // Optional: skyblue, red, nephritis, concrete, darknight #let profilePhoto = "../src/avatar.png" // Leave blank if profil photo is not needed #let varLanguage = "fr" #let varEntrySocietyFirst = false // Decide if you want to put your company in bold or your position in bold #let varDisplayLogo = true // Decide if you want to display organisation logo or not #let ifAIInjection = false // Decide if you want to inject AI prompt or not #let keywordsInjectionList = ( "AWS", "Azure", "GCP", "EC2", "S3", "Lambda", "DynamoDB", "RDS", "CloudFormation", "Kubernetes", "Docker", "Terraform", "Ansible", "Jenkins", "GitLab CI/CD", "Python", "Java", "Kotlin", "JavaScript", "TypeScript", "Go", "Rust", "C++", "Node.js", "React", "Spring Boot", "Django", "Flask", "MongoDB", "PostgreSQL", "Redis", "Elasticsearch", "Git", "GitHub", "Bitbucket", "Jira", "Microservices", "RESTful APIs", "GraphQL", "SQL", "NoSQL", "Tableau", "Power BI", "Prometheus", "Grafana", "ELK Stack", "Agile", "Scrum", "CI/CD", "DevOps", "Serverless", "Containerization", "Infrastructure as Code", "Linux", "Unix", "Bash", "PowerShell", "Machine Learning", "Big Data", "Data Analytics", "Cloud-native", "Scalability", "High Availability", "Continuous Integration", "Continuous Deployment", "Microservices Architecture", "Event-Driven Architecture" )
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/06-fourier-series/04-adding-fouriers.typ
typst
#import "../../utils/core.typ": * == Суммирование рядов Фурье #ticket[Суммирование рядов по Чезаро. <NAME>. Свойства.] #def[ Рассмотрим ряд $sum_(k = 0)^oo a_k$ и положим $A_n := sum_(k = 0)^n a_k$. Будем говорить, что $S$ --- сумма ряда по Чезаро, если $S = lim_(n -> oo) (A_0 + A_1 + ... + A_n)/(n + 1)$. Обозначается $(c) (sum a_k)$. ] #example[ Рассмотрим ряд $sum_(n = 0)^oo (-1)^n$, который расходится. Однако его сумма по Чезаро равна $1/2$: $ A_n = cases(1\, n = 2k, 0\, n = 2k + 1) ==> alpha_n = (1 + 0 + 1 + 0 + ... + A_n)/(n + 1) = cases( 1/2\, n = 2k + 1, (k + 1)/(2k + 1)\, n = 2k ) --> 1/2. $ ] #props[ 1. Если сходится ряд, то он сходится к своей сумме по Чезаро. 2. Суммирование по Чезаро линейно. 3. Если ряд сходится по Чезаро, то $a_n = o(n)$. ] #proof[ 1. Теорема Штольца. 2. Просто расписать. 3. $ alpha_n = (A_0 + ... + A_(n - 1) + A_n)/(n + 1) = n/(n + 1) dot (A_0 + ... + A_(n - 1) + A_n)/n = n/(n + 1) (alpha_(n - 1) + A_n/n) ==> \ ==> A_n = n underbrace(((n + 1)/n dot alpha_n - alpha_(n - 1)), --> 1 dot S - S = 0) = o(n) ==> \ ==> a_n = n underbrace((A_n/n - A_(n - 1)/(n - 1) (n - 1)/n), --> 0 - 0 dot 1 = 0) = o(n) $ ] #notice[ $ alpha_n = (A_0 + A_1 + ... + A_n)/(n + 1) = sum_(k = 0)^n (1 - k/(n + 1)) a_k. $ Доказывается по индукции. ] #th(name: "Харди")[ Если ряд сходится по Чезаро, и $a_n = O(1/n)$ (можно даже если $a_n >= -c/n$ --- достаточно подпереть ряд с одной стороны), то он сходится. ] #proof[ Без доказательства. ] #notice[ Есть и другие способы считать суммы расходящихся рядов. Например, $ lim_(t -> 1-) sum_(n = 1)^oo a_n t^n. $ ] #example[ Рассмотрим следующий ряд: $ 1/2 + sum_(k = 1)^oo cos k x. $ Он расходится, так как члены ряда не стремятся к нулю. Пусть $D_n (t)$ --- его частичная сумма, а $ Phi_n (t) := (D_0 (t) + D_1 (t) + ... + D_n (t))/(n + 1). $ Такая штука называется _ядром Фейера_. Рассмотрим несколько свойств этой штуки в нашем примере: 1. $Phi_n$ --- непрерывная четная $2pi$-периодическая функция. 2. $Phi_n (0) = (n + 1)/2$. 3. $1/pi integral_(-pi)^pi Phi_n (t) dif t = 1$, так как у $D_i$ интеграл $pi$. В силу четности, $1/pi integral_0^pi Phi_n (t) dif t = 1/2$. 4. При $t != 2pi m$, $ Phi_n (t) = (sin^2 (n + 1)/2 t)/(2(n + 1) sin^2 t/2). $ Действительно, $ sum_(k = 0)^n (sin^2 t/2) D_n (t) = sum_(k = 0)^n 1/2 sin(k + 1/2) t dot sin t/2 = 1/4 sum_(k = 0)^n (cos k t - cos (k + 1) t) = 1/4 underbrace((1 - cos (n + 1) t), 2 sin^2 (n + 1)/2 t). $ 5. $Phi_n (t) > 0$ по предыдущему свойству. 6. $lim_(n -> oo) max_(delta <= t <= pi) Phi_n (t) = 0$. Доказательство: $ Phi_n (t) <= 1/(2(n + 1) sin^2 (delta/2)) --> 0. $ Значит, если $t != 2pi m$, то $("c") (1/2 + sum_(k = 1)^oo cos k t) = 0$. ]
https://github.com/storopoli/Bayesian-Statistics
https://raw.githubusercontent.com/storopoli/Bayesian-Statistics/main/slides/01-bayesian_statistics.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "@preview/polylux:0.3.1": * #import themes.clean: * #import "utils.typ": * #import "@preview/cetz:0.1.2": * #new-section-slide("Bayesian Statistics") #slide(title: "Recommended References")[ #text(size: 18pt)[ - #cite(<gelman2013bayesian>, form: "prose") - Chapter 1: Probability and inference - #cite(<mcelreath2020statistical>, form: "prose") - Chapter 1: The Golem of Prague - #cite(<gelman2020regression>, form: "prose") - Chapter 3: Some basic methods in mathematics and probability - #cite(<khanBayesianLearningRule2021>, form: "prose") - *Probability*: - A great textbook - #cite(<bertsekasIntroductionProbability2nd2008>, form: "prose") - Also a great textbook (skip the frequentist part) - #cite(<dekkingModernIntroductionProbability2010>, form: "prose") - Bayesian point-of-view and also a philosophical approach - #cite(<jaynesProbabilityTheoryLogic2003>, form: "prose") - Bayesian point-of-view with a simple and playful approach - #cite(<kurtBayesianStatisticsFun2019>, form: "prose") - Philosophical approach not so focused on mathematical rigor - #cite(<diaconisTenGreatIdeas2019>, form: "prose") ] ] #focus-slide(background: julia-purple)[ #quote( block: true, attribution: [<NAME>], )[Inside every nonBayesian there is a Bayesian struggling to get out] ] #focus-slide(background: julia-purple)[ #align(center)[#image("images/memes/frequentists-vs-bayesians.png")] ] #slide(title: [What is Bayesian Statistics?])[ #v(2em) Bayesian statistics is a *data analysis approach based on Bayes' theorem* where available knowledge about the parameters of a statistical model is updated with the information of observed data. @gelman2013bayesian. #v(2em) Previous knowledge is expressed as a *prior* distribution and combined with the observed data in the form of a *likelihood* function to generate a *posterior* distribution. #v(2em) The posterior can also be used to make predictions about future events. ] #slide(title: [What changes from Frequentist Statistics?])[ #text(size: 16pt)[ - *Flexibility* - probabilistic building blocks to construct a model #footnote[like LEGO]: - Probabilistic conjectures about parameters: - Prior - Likelihood - Better *uncertainty* treatment: - Coherence - Propagation - We don't use _"if we sampled infinite times from a population that we do not observe..."_ - No *$p$-values*: - All statistical intuitions makes *sense* - 95\% certainty that $θ$'s parameter value is between $x$ and $y$ - Almost *impossible* to perform $p$-hacking ] ] #slide(title: [A little bit more formal])[ - Bayesian Statistics uses probabilistic statements: - one or more parameters $θ$ - unobserved data $tilde(y)$ - These statements are conditioned on the observed values of $y$: - $P(θ | y)$ - $P(tilde(y) | y)$ - We also, implicitly, condition on the observed data from any covariate $x$ ] #slide(title: [Definition of Bayesian Statistics])[ #v(4em) The use of Bayes theorem as the procedure to *estimate parameters of interest $θ$ or unobserved data $tilde(y)$*. @gelman2013bayesian ] #slide(title: [PROBABILITY DOES NOT EXIST! #footnote[#cite(<definettiTheoryProbability1974>, form: "prose")]])[ #side-by-side(columns: (4fr, 1fr))[ #v(3em) - Yes, probability does not exist ... - Or even better, probability as a physical quantity, objective chance, *does NOT exist* - if we disregard objetive chance _nothing is lost_ - The math of inductive rationality remains *exactly the same* ][ #image("images/persons/finetti.jpg") ] ] #slide(title: [PROBABILITY DOES NOT EXIST! #footnote[#cite(<definettiTheoryProbability1974>, form: "prose")]])[ #side-by-side(columns: (3fr, 2fr))[ - Consider flipping a biased coin - The trials are considered independent and, as a result, have an important property: *the order does not matter* - The frequency is considered a *sufficient statistic* - Saying that order does not matter or saying that the only thing that matters is frequency are two ways of saying the same thing - We say that the probability is *invariant under permutations* ][ #align(center)[ #canvas( length: 0.65cm, { import draw: * set-style( mark: (fill: black, size: 0.3), stroke: (thickness: 2pt), radius: 1, ) circle((0, 0)) arc( (1, 0), start: 0deg, delta: 180deg, mode: "PIE", fill: julia-green, ) arc( (-1, 0), start: 180deg, delta: 180deg, mode: "PIE", fill: julia-red, ) content((0, 0.5), [#align(center)[#text(fill: white, size: 14pt)[H]]]) content( (0, -0.5), [#align(center)[#text(fill: white, size: 14pt)[T]]], ) line((0, -1), (-3.5, -5)) content((-2.5, -3))[#text(size: 14pt)[$0.5$]] line((0, -1), (3.5, -5)) content((2.5, -3))[#text(size: 14pt)[$0.5$]] circle((-3.5, -6), fill: julia-green) content( (-3.5, -6), [#align(center)[#text(fill: white, size: 14pt)[H]]], ) line((-3.5, -7), (-5, -11)) content((-5, -9))[#text(size: 14pt)[$0.5$]] line((-3.5, -7), (-2, -11)) content((-2, -9))[#text(size: 14pt)[$0.5$]] circle((3.5, -6), fill: julia-red) content( (3.5, -6), [#align(center)[#text(fill: white, size: 14pt)[T]]], ) line((3.5, -7), (2, -11)) content((2, -9))[#text(size: 14pt)[$0.5$]] line((3.5, -7), (5, -11)) content((5, -9))[#text(size: 14pt)[$0.5$]] circle((-5, -12), fill: julia-green) content( (-5, -12), [#align(center)[#text(fill: white, size: 14pt)[H]]], ) circle((-2, -12), fill: julia-red) content( (-2, -12), [#align(center)[#text(fill: white, size: 14pt)[T]]], ) circle((2, -12), fill: julia-green) content((2, -12), [#align(center)[#text(fill: white, size: 14pt)[H]]]) circle((5, -12), fill: julia-red) content((5, -12), [#align(center)[#text(fill: white, size: 14pt)[T]]]) }, ) ] ] ] #slide(title: [Probability Interpretations])[ - *Objective* - frequency in the long run for an event: - $P("rain") = "days that rained" / "total days"$ - $P("me being elected president") = 0$ (never occurred) #v(2em) - *Subjective* - degrees of belief in an event: - $P("rain") = "degree of belief that will rain"$ - $P("me being elected president") = 10^(-10)$ (highly unlikely) ] #slide(title: [What is Probability?])[ We define $A$ is an event and $P(A)$ the probability of event $A$. $P(A)$ has to be between $0$ and $1$, where higher values defines higher probability of $A$ happening. $ P(A) &∈ RR \ P(A) &∈ [0,1] \ 0 <= &P(A) <= 1 $ ] #slide(title: [Probability Axioms #footnote[#cite(<kolmogorovFoundationsTheoryProbability1933>, form: "prose")]])[ #side-by-side(columns: (4fr, 1fr))[ - *Non-negativity*: For every $A$: $P(A) >= 0$ #v(2em) - *Additivity*: For every two _mutually exclusive_ $A$ and $B$: $P(A) = 1 - P(B) "and" P(B) = 1 - P(A)$ #v(2em) - *Normalization*: The probability of all possible events $A_1, A_2, dots$ must sum up to $1$: $sum_(n ∈ NN) A_n = 1$ ][ #image("images/persons/kolmogorov.jpg") ] ] #slide(title: [Sample Space])[ #v(3em) - Discrete: $Θ = {1, 2, dots}$ #v(3em) - Continuous: $Θ ∈ (-oo, oo)$ ] #slide(title: [Discrete Sample Space])[ 8 planets in our solar system: - Mercury: ☿ - Venus: ♀ - Earth: ♁ - Mars: ♂ - Jupiter: ♃ - Saturn: ♄ - Uranus: ♅ - Neptune: ♆ ] #slide(title: [Discrete Sample Space])[ #side-by-side[ #align(center)[ #canvas( length: 0.5cm, { import draw: * set-style( mark: (fill: black, size: 0.3), stroke: (thickness: 2pt), radius: 1, ) content((0, 0))[#text(size: 18pt, fill: white)[placeholder]] content((0, -2))[#text(size: 18pt)[ The planet has a magnetic field ]] content((0, -6))[#text(size: 18pt)[ The planet has moon(s) ]] content((0, -10))[#text(size: 18pt)[ The planet has a magnetic field _and_ moon(s) ]] content((0, -14))[#text(size: 18pt)[ The planet has a magnetic field _or_ moon(s) ]] content((0, -18))[#text(size: 18pt)[ The planet does _not_ have a magnetic field ]] }, ) ] ][ #align(center)[ #canvas( length: 0.5cm, { import draw: * set-style( mark: (fill: black, size: 0.3), stroke: (thickness: 2pt), radius: 1, ) content((0, 0))[#text(size: 18pt)[$θ ∈ E_1$]] circle((-7, -2)) content((-7, -2))[#text(size: 18pt)[☿]] circle((-5, -2), fill: julia-purple) content((-5, -2))[#text(size: 18pt, fill: white)[♀]] circle((-3, -2), fill: julia-purple) content((-3, -2))[#text(size: 18pt, fill: white)[♁]] circle((-1, -2)) content((-1, -2))[#text(size: 18pt)[♂]] circle((1, -2), fill: julia-purple) content((1, -2))[#text(size: 18pt, fill: white)[♃]] circle((3, -2), fill: julia-purple) content((3, -2))[#text(size: 18pt, fill: white)[♄]] circle((5, -2), fill: julia-purple) content((5, -2))[#text(size: 18pt, fill: white)[♅]] circle((7, -2), fill: julia-purple) content((7, -2))[#text(size: 18pt, fill: white)[♆]] content((0, -4))[#text(size: 18pt)[$θ ∈ E_2$]] circle((-7, -6)) content((-7, -6))[#text(size: 18pt)[☿]] circle((-5, -6)) content((-5, -6))[#text(size: 18pt)[♀]] circle((-3, -6), fill: julia-purple) content((-3, -6))[#text(size: 18pt, fill: white)[♁]] circle((-1, -6), fill: julia-purple) content((-1, -6))[#text(size: 18pt, fill: white)[♂]] circle((1, -6), fill: julia-purple) content((1, -6))[#text(size: 18pt, fill: white)[♃]] circle((3, -6), fill: julia-purple) content((3, -6))[#text(size: 18pt, fill: white)[♄]] circle((5, -6), fill: julia-purple) content((5, -6))[#text(size: 18pt, fill: white)[♅]] circle((7, -6), fill: julia-purple) content((7, -6))[#text(size: 18pt, fill: white)[♆]] content((0, -8))[#text(size: 18pt)[$θ ∈ E_1 sect E_2$]] circle((-7, -10)) content((-7, -10))[#text(size: 18pt)[☿]] circle((-5, -10)) content((-5, -10))[#text(size: 18pt)[♀]] circle((-3, -10), fill: julia-purple) content((-3, -10))[#text(size: 18pt, fill: white)[♁]] circle((-1, -10)) content((-1, -10))[#text(size: 18pt)[♂]] circle((1, -10), fill: julia-purple) content((1, -10))[#text(size: 18pt, fill: white)[♃]] circle((3, -10), fill: julia-purple) content((3, -10))[#text(size: 18pt, fill: white)[♄]] circle((5, -10), fill: julia-purple) content((5, -10))[#text(size: 18pt, fill: white)[♅]] circle((7, -10), fill: julia-purple) content((7, -10))[#text(size: 18pt, fill: white)[♆]] content((0, -12))[#text(size: 18pt)[$θ ∈ E_1 union E_2$]] circle((-7, -14)) content((-7, -14))[#text(size: 18pt)[☿]] circle((-5, -14), fill: julia-purple) content((-5, -14))[#text(size: 18pt, fill: white)[♀]] circle((-3, -14), fill: julia-purple) content((-3, -14))[#text(size: 18pt, fill: white)[♁]] circle((-1, -14), fill: julia-purple) content((-1, -14))[#text(size: 18pt, fill: white)[♂]] circle((1, -14), fill: julia-purple) content((1, -14))[#text(size: 18pt, fill: white)[♃]] circle((3, -14), fill: julia-purple) content((3, -14))[#text(size: 18pt, fill: white)[♄]] circle((5, -14), fill: julia-purple) content((5, -14))[#text(size: 18pt, fill: white)[♅]] circle((7, -14), fill: julia-purple) content((7, -14))[#text(size: 18pt, fill: white)[♆]] content((0, -16))[#text(size: 18pt)[$θ ∈ not E_1$]] circle((-7, -18), fill: julia-purple) content((-7, -18))[#text(size: 18pt, fill: white)[☿]] circle((-5, -18)) content((-5, -18))[#text(size: 18pt)[♀]] circle((-3, -18)) content((-3, -18))[#text(size: 18pt)[♁]] circle((-1, -18), fill: julia-purple) content((-1, -18))[#text(size: 18pt, fill: white)[♂]] circle((1, -18)) content((1, -18))[#text(size: 18pt)[♃]] circle((3, -18)) content((3, -18))[#text(size: 18pt)[♄]] circle((5, -18)) content((5, -18))[#text(size: 18pt)[♅]] circle((7, -18)) content((7, -18))[#text(size: 18pt)[♆]] }, ) ] ] ] #slide(title: [Continuous Sample Space])[ #side-by-side[ #align(center)[ #canvas( length: 0.5cm, { import draw: * set-style(mark: (fill: black, size: 0.3), stroke: (thickness: 2pt)) content((0, 0))[#text(size: 18pt, fill: white)[placeholder]] content((0, -2))[#text(size: 18pt)[ The distance is less than five centimeters ]] content((0, -6))[#text(size: 18pt)[ The distance is between three and seven centimeters ]] content((0, -10))[#text(size: 18pt)[ The distance is less than five centimeters \ _and_ between three and seven centimeters ]] content((0, -14))[#text(size: 18pt)[ The distance is less than five centimeters \ _or_ between three and seven centimeters ]] content((0, -18))[#text(size: 18pt)[ The distance is _not_ less than five centimeters ]] }, ) ] ][ #align(center)[ #canvas( length: 0.5cm, { import draw: * set-style( mark: (start: "|", end: "|", fill: black, size: 1), stroke: (thickness: 4pt), ) content((0, 0))[#text(size: 18pt)[$θ ∈ E_1$]] line((-7, -2), (7, -2)) line((-7, -2), (-1, -2), stroke: julia-purple + 6pt) content((0, -4))[#text(size: 18pt)[$θ ∈ E_2$]] line((-7, -6), (7, -6)) line((-3, -6), (1, -6), stroke: julia-purple + 6pt) content((0, -8))[#text(size: 18pt)[$θ ∈ E_1 sect E_2$]] line((-7, -10), (7, -10)) line((-3, -10), (-1, -10), stroke: julia-purple + 6pt) content((0, -12))[#text(size: 18pt)[$θ ∈ E_1 union E_2$]] line((-7, -14), (7, -14)) line((-7, -14), (1, -14), stroke: julia-purple + 6pt) content((0, -16))[#text(size: 18pt)[$θ ∈ not E_1$]] line((-7, -18), (7, -18)) line((-1, -18), (7, -18), stroke: julia-purple + 6pt) }, ) ] ] ] #slide(title: [Discrete versus Continuous Parameters])[ #text(size: 18pt)[ Everything that has been exposed here was under the assumption that the parameters are discrete. This was done with the intent to provide an intuition what is probability. Not always we work with discrete parameters. Parameters can be continuous, such as: age, height, weight etc. But don't despair! All probability rules and axioms are valid also for continuous parameters. The only thing we have to do is to change all s $sum$ for integrals $∫$. For example, the third axiom of *Normalization* for _continuous_ random variables becomes: $ ∫_(x ∈ X) p(x) dif x = 1 $ ] ] #slide(title: [Conditional Probability])[ Probability of an event occurring in case another has occurred or not. The notation we use is $P(A | B)$, that read as "the probability of observing $A$ given that we already observed $B$". $ P(A | B) & = "number of elements in A and B" / "number of elements in B" \ P(A | B) &= P(A sect B) / P(B) $ assuming that $P(B) > 0$}. ] #slide(title: [Example of Conditional Probability -- Poker Texas Hold'em])[ - *Sample Space*: $52$ cards in a deck, $13$ types of cards and $4$ types of suits. - $P(A)$: Probability of being dealt an Ace $(4 / 52 = 1 / 13)$ - $P(K)$: Probability of being dealt a King $(4 / 52 = 1 / 13)$ - $P(A | K)$: Probability of being dealt an Ace, given that you have already a King $(4 / 51 ≈ 0.078)$ - $P(K | A)$: Probability of being dealt a King, given that you have already an Ace $(4 / 51 ≈ 0.078)$ ] #slide(title: [Caution! Not always $P(A | B) = P(B | A)$])[ In the previous example we have the symmetry $P(A | K) = P(K | A)$, *but not always this is true* #footnote[ More specific, if the basal rates $P(A)$ and $P(B)$ aren't equal, the symmetry is broken $P(A | B) ≠ P(B | A)$ ] #text(size: 14pt)[ The Pope is catholic: - $P("pope")$: Probability of some random person being the Pope, something really small, 1 in 8 billion $(1 / (8 dot 10^9))$ - $P("catholic")$: Probability of some random person being catholic, 1.34 billion in 8 billion $(1.34 / 8 ≈ 0.17)$ - $P("catholic" | "pope")$: Probability of the Pope being catholic $(999 / 1000 = 0.999)$ - $P("pope" | "catholic")$: Probability of a catholic person being the Pope $(1 / (1.34 dot 10^9) dot 0.999 ≈ 7.46 dot 10^(-10))$ ] - #text(size: 22pt)[*Hence*: $P("catholic" | "pope") ≠ P("pope" | "catholic")$] ] #slide(title: [Joint Probability])[ Probability of two or more events occurring. The notation we use is $P(A, B)$, that read as "the probability of observing $A$ and also observing $B$". $ P(A, B) &= "number of elements in A or B" \ P(A, B) &= P(A union B) \ P(A, B) &= P(B, A) $ ] #slide(title: [Example of Joint Probability -- Revisiting Poker Texas Hold'em])[ #text(size: 17pt)[ - *Sample Space*: $52$ cards in a deck, $13$ types of cards and $4$ types of suits. - $P(A)$: Probability of being dealt an Ace $(4 / 52 = 1 / 13)$ - $P(K)$: Probability of being dealt a King $(4 / 52 = 1 / 13)$ - $P(A | K)$: Probability of being dealt an Ace, given that you have already a King $(4 / 51 ≈ 0.078)$ - $P(K | A)$: Probability of being dealt a King, given that you have already an Ace $(4 / 51 ≈ 0.078)$ - $P(A, K)$: Probability of being dealt an Ace _and_ being dealt a King $ P(A, K) &= P(K, A) \ P(A) dot P(K | A) &= P(K) dot P(A | K) \ 1 / 13 dot 4 / 51 &= 1 / 13 dot 4 / 51 \ &≈ 0.006 $ ] ] #slide(title: [Visualization of Joint Probability versus Conditional Probability])[ #figure( image( "images/probability/joint_vs_conditional_probability.svg", height: 80%, ), caption: [$P(X,Y)$ versus $P(X | Y=-0.75)$], ) ] #slide(title: [Product Rule of Probability #footnote[also called the Product Rule of Probability.]])[ #v(2em) We can decompose a joint probability $P(A,B)$ into the product of two probabilities: #v(2em) $ P(A,B) &= P(B,A) \ P(A) dot P(B | A) &= P(B) dot P(A | B) $ ] #slide(title: [Who was <NAME>?])[ #side-by-side(columns: (4fr, 1fr))[ #text(size: 17pt)[ - *<NAME>* (1701 - 1761) was a statistician, philosopher and Presbyterian minister who is known for formulating a specific case of the theorem that bears his name: Bayes' theorem. - Bayes never published what would become his most famous accomplishment; his notes were edited and published posthumously by his friend *<NAME>*. - The theorem official name is *Bayes-Price-Laplace*, because *Bayes* was the first to discover, *Price* got his notes, transcribed into mathematical notation, and read to the Royal Society of London, and *Laplace* independently rediscovered the theorem without having previous contact in the end of the XVIII century in France while using probability for statistical inference with census data in the Napoleonic era. ] ][ #image("images/persons/thomas_bayes.png") ] ] #slide(title: [Bayes Theorem])[ Tells us how to "invert" conditional probability: #v(3em) $ P(A | B) = (P(A) dot P(B | A)) / P(B) $ ] #slide(title: [Bayes' Theorem Proof])[ Remember the following probability identity: #text(size: 18pt)[ $ P(A,B) &= P(B,A) \ P(A) dot P(B | A) &= P(B) dot P(A | B) $ OK, now divide everything by $P(B)$: $ (P(A) dot P(B | A)) / P(B) &= (P(B) dot P(A | B)) / P(B) \ (P(A) dot P(B | A)) / P(B) &= P(A | B) \ P(A | B) &= (P(A) dot P(B | A)) / P(B) $ ] ] #slide(title: [A Probability Textbook Classic #footnote[Adapted from: #link( "https://www.yudkowsky.net/rational/bayes", )[Yudkowski - _An Intuitive Explanation of Bayes' Theorem_]]])[ #text(size: 15pt)[ How accurate is a *breast cancer* test? - 1% of women have *breast cancer* (Prevalence) - 80% of mammograms detect *breast cancer* (True Positive) - 9.6% of mammograms detect *breast cancer* when there is no incidence (False Positive) $ P(C | +) &= (P(+ | C) dot P(C)) / P(+) \ P(C | +) &= (P(+ | C) dot P(C)) / (P(+ | C) dot P(C) + P( + | not C ) dot P(not C)) \ P(C | +) &= (0.8 dot 0.01) / (0.8 dot 0.01 + 0.096 dot 0.99) \ P(C | +) &≈ 0.0776 $ ] ] #slide(title: [Why Bayes' Theorem is Important?])[ We can invert the conditional probability: $ P("hypothesis" | "data") = (P("data" | "hypothesis") dot P( "hypothesis" )) / P("data") $ #v(2em) But isn't this the $p$-value? #align(center)[#text(size: 24pt, fill: julia-red)[NO!]] ] #slide(title: [What are $p$-values?])[ #v(2em) $p$-value is the probability of obtaining results at least as extreme as the observed, given that the null hypothesis $H_0$ is true: #v(2em) $ P(D | H_0) $ ] #slide(title: [What $p$-value is *not*!])[ #align(center)[#image("images/memes/pvalue.jpg", height: 80%)] ] #slide(title: [What $p$-value is *not*!])[ #text(size: 18pt)[ - *$p$-value is not the probability of the null hypothesis* - #text(fill: julia-red)[No!] - Infamous confusion between $P(D | H_0)$ and $P(H_0 | D)$. - To get $P(H_0 | D)$ you need Bayesian statistics. - *$p$-value is not the probability of data being generated at random* - #text(fill: julia-red)[No again!] - We haven't stated nothing about randomness. - *$p$-value measures the effect size of a statistical test* - Also #text(fill: julia-red)[no]... $p$-value does not say anything about effect sizes. - Just about if the observed data diverge of the expected under the null hypothesis. - Besides, $p$-values can be hacked in several ways @head2015extent. ] ] #slide(title: [The relationship between $p$-value and $H_0$])[ To find out about any $p$-value, *find out what $H_0$ is behind it*. It's definition will never change, since it is always $P(D | H_0)$: - *$t$-test*: $P(D | "the difference between the groups is zero")$ - *ANOVA*: $P(D | "there is no difference between groups")$ - *Regression*: $P(D | "coefficient has a null value")$ - *Shapiro-Wilk*: $P(D | "population is distributed as a Normal distribution")$ ] #slide(title: [What are Confidence Intervals?])[ #side-by-side(columns: (4fr, 1fr))[ #v(2em) #quote( block: true, attribution: [ #cite(<neyman1937outline>, form: "prose") the "father" of confidence intervals ], )[ A confidence interval of X% for a parameter is an interval $(a, b)$ generated by a repeated sampling procedure has probability X% of containing the true value of the parameter, for all possible values of the parameter. ] ][ #image("images/persons/neyman.jpg") ] ] #slide(title: [What are Confidence Intervals?])[ #text(size: 18pt)[ Say you performed a statistical analysis to compare the efficacy of a public policy between two groups and you obtain a difference between the mean of these groups. You can express this difference as a confidence interval. Often we choose 95% confidence. In other words, 95% is _not_ the probability of obtaining data such that the estimate of the true parameter is contained in the interval that we obtained, it is the *probability of obtaining data such that, if we compute another confidence interval in the same way, it contains the true parameter*. The interval that we got in this particular instance is irrelevant and might as well be thrown away. #text(fill: julia-red)[ Doesn't say anything about you *target population*, but about you *sample* in an insane process of *infinite sampling* ... ] ] ] #slide(title: [Confidence Intervals versus Posterior Intervals])[ #align(center)[ #canvas( length: 0.9cm, { plot.plot( size: (16, 9), x-label: $θ$, y-label: none, x-tick-step: 5, y-tick-step: 0.25, x-min: -0.1, x-max: 4, y-min: -0.01, y-max: 1.5, { plot.add(domain: (0.02, 4), samples: 200, x => lognormal(x, 0, 2)) plot.add( domain: (0.25950495026507125, 3.8534910373715427), samples: 200, style: plot.palette.blue, hypograph: true, // label: "50% Posterior", // FIXME: depends on unreleased cetz 2.0.0 x => lognormal(x, 0, 2), ) plot.add( domain: (0.001, 0.09), samples: 50, style: ( stroke: julia-red + 2pt, mark: (start: "|", end: "|", fill: julia-red, size: 0.05), ), // mark: "o", // mark-size: 0.4, // label: "MLE", // FIXME: depends on unreleased cetz 2.0.0 x => 1.4739034450607542, ) }, ) }, ) ] ] #focus-slide(background: julia-purple)[ #align(center)[#image("images/memes/assumptions-vs-reality.jpg")] ] #slide(title: [But why I never see stats without $p$-values?])[ #side-by-side(columns: (4fr, 1fr))[ #text(size: 17pt)[ We cannot understand $p$-values if we do no not comprehend its origins and historical trajectory. The first mention of $p$-values was made by the statistician <NAME> in 1925: #quote( block: true, attribution: [ #cite(<fisher1925statistical>, form: "prose") ], )[ $p$-value is a measure of evidence against the null hypothesis ] - To quantify the strength of the evidence against the null hypothesis, Fisher defended "$p<0.05$ as the standard level to conclude that there is evidence against the tested hypothesis" - "We should not be off-track if we draw a conventional line at 0.05" ] ][ #image("images/persons/fisher.jpg") ] ] #slide(title: [$p = 0.06$])[ - Since $p$-value is a probability, it is also a continuous measure. #v(2em) - There is no reason for us to differentiate $p = 0.049$ against $p = 0.051$. #v(2em) - <NAME>, a psychologist said "surely, God loves the $.06$ nearly as much as the $.05$" @rosnow1989statistical. ] #slide(title: [ But why I never heard about Bayesian statistics? #footnote[ _inverse probability_ was how Bayes' theorem was called in the beginning of the 20th century. ] ])[ #side-by-side(columns: (4fr, 1fr))[ #v(3em) #quote( block: true, attribution: [ #cite(<fisher1925statistical>, form: "prose") ], )[ ... it will be sufficient ... to reaffirm my personal conviction ... that the theory of inverse probability is founded upon an error, and must be wholly rejected. ] ][ #image("images/persons/fisher.jpg") ] ] #slide(title: [ Inside every nonBayesian, there is a Bayesian struggling to get out #footnote[ quote from <NAME>. ] ])[ #side-by-side(columns: (4fr, 1fr))[ #v(2em) - In his final year of life, Fisher published a paper @fisherExamplesBayesMethod1962 examining the possibilities of Bayesian methods, but with the prior probabilities being determined experimentally. #v(2em) - Some authors speculate @jaynesProbabilityTheoryLogic2003 that if Fisher were alive today, he would probably be a Bayesian. ][ #image("images/persons/fisher.jpg") ] ] #slide(title: [Bayes' Theorem as an Inference Engine])[ #text(size: 13pt)[ Now that you know what is probability and Bayes' theorem, I will propose the following: $ underbrace(P(θ | y), "Posterior") = (overbrace(P(y | θ), "Likelihood") dot overbrace(P(θ), "Prior")) / underbrace(P(y), "Normalizing Constant") $ - $θ$ -- parameter(s) of interest - $y$ -- observed data - *Priori*: prior probability of the parameter(s) value(s) - *Likelihood*: probability of the observed data given the parameter(s) value(s) - *Posterior*: posterior probability of the parameter(s) value(s) after we observed data $y$ - *Normalizing Constant* #footnote[sometimes also called _evidence_.]: $P(y)$ does not make any intuitive sense. This probability is transformed and can be interpreted as something that only exists so that the result $P(y | θ) P(θ)$ be constrained between $0$ and $1$ -- a valid probability. ] ] #slide(title: [Bayes' Theorem as an Inference Engine])[ Bayesian statistics allows us to *quantify directly the uncertainty* related to the value of one or more parameters of our model given the observed data. #v(1em) This is the *main feature* of Bayesian statistics, since we are estimating directly $P(θ | y)$ using Bayes' theorem. #v(1em) The resulting estimate is totally intuitive: simply quantifies the uncertainty that we have about the value of one or more parameters given the data, model assumptions (likelihood) and the prior probability of these parameter's values. ] // typstfmt::off #slide(title: [Bayesian vs Frequentist Stats])[ #table( columns: (auto, auto, auto), inset: 10pt, align: (left + horizon, center + horizon, center + horizon), [], [#text(fill: julia-blue)[Bayesian Statistics]], [#text(fill: julia-red)[Frequentist Statistics]], [*Data*], [Fixed -- Non-random], [Uncertain -- Random], [*Parameters*], [Uncertain -- Random], [Fixed -- Non-random], [*Inference*], [Uncertainty regarding the parameter value], [Uncertainty regarding the sampling process from an infinite population], [*Probability*], [Subjective], [Objective (but with several model assumptions)], [*Uncertainty*], [Posterior Interval -- $P(θ | y)$], [Confidence Interval -- $P(y | θ)$], ) ] // typstfmt::on #slide(title: [Advantages of Bayesian Statistics])[ - Natural approach to express uncertainty - Ability to incorporate previous information - Higher model flexibility - Full posterior distribution of the parameters - Natural propagation of uncertainty #v(2em) *Main disadvantage*: Slow model fitting procedure ] #slide(title: [The beginning of the end of Frequentist Statistics])[ #text(size: 18pt)[ - Know that you are in a very special moment in history of great changes in statistics - I believe that frequentist statistics, specially the way we qualify evidence and hypotheses with $p$-values will transform in a "significant" #footnote[pun intended ...] way. - 8 years ago, the _American Statistical Association_ (ASA) published a declaration about $p$-values @Wasserstein2016. It states exactly what we exposed here: The main concepts of the null hypothesis significant testing and, in particular $p$-values, cannot provide what researchers demand of them. Despite what says several textbooks, learning materials and published content, $p$-values below $0.05$ doesn't "prove" anything. Not, on the other way around, $p$-values higher than $0.05$ refute anything. - ASA statement has more than 4.700 citations with relevant impact. ] ] #slide(title: [The beginning of the end of Frequentist Statistics])[ #text(size: 17pt)[ - An international symposium was promoted in 2017 which originated an open-access special edition of _The American Statistician_ dedicated to practical ways to abandon $p < 0.05$ @wassersteinMovingWorld052019. - Soon there were more attempts and claims. In September 2017, _Nature Human Behaviour_ published an editorial proposing that the $p$-value's significance level be decreased from $0.05$ to $0.005$ @benjaminRedefineStatisticalSignificance2018. Several authors, including highly important and influential statisticians argued that this simple step would help to tackle the replication crisis problem in science, that many believe be the main consequence of the abusive use of $p$-values @Ioannidis2019. - Furthermore, many went a step ahead and suggested that science banish once for all $p$-values @ItTimeTalk2019 @lakensJustifyYourAlpha2018. Many suggest (including myself) that the main tool of statistical inference be Bayesian statistics @amrheinScientistsRiseStatistical2019 @Goodman1180 @vandeschootBayesianStatisticsModelling2021. ] ] #focus-slide(background: julia-purple)[ #align(center)[#image("images/memes/stats-phil.png")] ]
https://github.com/AxiomOfChoices/Typst
https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Courses/Math%2018_745%20-%20Lie%20Groups%20and%20Lie%20Algebras/Assignments/Assignment%204.typ
typst
#import "/Templates/generic.typ": latex, header #import "@preview/ctheorems:1.1.0": * #import "/Templates/math.typ": * #import "/Templates/assignment.typ": * #show: doc => header(title: "Assignment 4", name: "<NAME>", doc) #let lecture = counter("lecture") #lecture.step() #let update_lecture = () => { lecture.step() counter(heading).update(0) } #let bonus_problem = { pagebreak() block(text([*Bonus Exercise*], size: 17pt)) } #show: latex #let NumberingAfter(doc) = { let level = 1 set heading( numbering: (..numbers) => if numbers.pos().len() <= level { return context numbering( "1.1", lecture.get().first(), ..numbers, ) }, supplement: "Exercise", ) show heading: it => { if (it.numbering == none) { return it } if (it.level > 1) { return text(it, size: 14pt) } let numbers = counter(heading).at(it.location()) let display-number = numbering(it.numbering, ..numbers) let body = it.body // if (numbers.last() > 1) { pagebreak(weak: true) // } block(text([*#body #display-number*], size: 17pt)) } doc }; #show: thmrules #let col(x, clr) = text(fill: clr)[$#x$] #let bar(el) = $overline(#el)$ #show: NumberingAfter #set enum(numbering: "(a)") *Sources consulted* \ Classmates: <NAME>. \ Texts: Class Notes. #update_lecture() #update_lecture() #update_lecture() #update_lecture() #update_lecture() #update_lecture() #update_lecture() = Exercise == Statement Let $G$ be an Algebraic group and, $H$ be an algebraic subgroup of $G$. Let $N_G (H) = {g in G | g H g^(-1) seq H }$ be the normalizer of $H$ in $G$. Prove that it is an algerbraic subgroup, whos Lie algerba is $N_(frak(g)) (frak(h))$, whose $frak(g) = Lie G, frak(h) = Lie H$. == Solution Let $C_G$ be the polynomials that define $G$ and $C_H$ be the polynomials that define $H$, then we define the polynomial set $C'$ by $ C' = { (det g)^(deg p) p((g x adj g)/(det g)): p in C_H, x in H} $ where $adj g$ is the adjugate of $g$, which is equal to $g^(-1) det (g)$, and is polynomially dependent on $g$. It is easy to see then, that the elements of $C'$ are indeed polynomials, for any rational terms of $det g$ are cancelled out by the $(det g)^(deg p)$ up front. We then have that $ N_G (H) = {g in Gl_n : q(g) = 0, p(g) = 0, forall q in C_G, p in C'}. $ To check the second statement we check when $1 + epsilon X in N_G (H)$, we get that for each $h in H$ we have $ (1 + epsilon X) h (1 + epsilon X)^(-1) = (1 + epsilon X) h (1 - epsilon X) = h + epsilon (X h - h X) $ thus $1 + epsilon X in Lie N_G (H)$ if and only if $h^(-1) X h - X in Lie H$ or otherwise said $X in frak(n)_(frak(g)) frak(h)$. = Question == Statement Let $frak(g) in sl_2 (FF)$ with $char FF != 2$. Let $frak(h) = FF mat(0,1;0,0)$. This is a maximal nilpotent subalgebra, but not a Cartan subalgebra. == Solution This is a subalgebra of dimension $1$, if it was not a maximal nilpotent subalgebra, then $sl_2$ would contain a 2 dimensional nilpotent subalgebra $frak(h)'$. Any other basis vector of $frak(h)'$ is of the form $ x = mat(a,0;b,-a) $ but then we have $ [x,mat(0,1;0,0)] = mat(a,0;b,-a) mat(0, 1;0, 0) - mat(0, 1;0, 0) mat(a,0;b,-a) = mat(0, a; 0, b) - mat(b, -a;0, 0) = mat(-b, 2a; 0, b) $ so since it it is a 2 dimensional Lie algebra we must assume that $b = 0$ as otherwise we can span the whole space. Then if $b = 0$ and $a != 0$ then $[frak(h)', frak(h)] = frak(h)$ so the algebra is not nilpotent. Thus $frak(h)$ is indeed maximal nilpotent. However, we have $frak(n)_(frak(g)) frak(h) != frak(h)$ because we have $ [ mat(1,0;0,-1), mat(0,1;0,0) ] = mat(1,0;0,-1) mat(0,1;0,0) - mat(0,1;0,0) mat(1,0;0,-1) = mat(0, 1;0, 0) - mat(0, -1;0, 0) = mat(0, 2;0, 0) $ and so $mat(1,0;0,-1)$ is in $frak(n)_(frak(g)) frak(h)$ but is not in $frak(h)$. = Question == Statement Let $frak(g)$ be a 3 dimensional Lie algebra of rank 1, then we showed in class that $frak(g) = FF h plus.circle V$ where $dim V = 2$ and $[h,V] seq V$. Show that in this case $frak(g)$ is isomorphic to one of the following lie algebras with basis $h,a,b$. + $[h,a] = a, [h,b] = a + b, [a,b] = 0$ + $[h,a] = a, [h,b] = lambda b, lambda != 0, [a,b] = 0$ + $[h,a] = a, [h,b] = -b, lambda != 0, [a,b] = h$ == Solution We use the generalized root space decomposition, $frak(g) = frak(h) plus.circle (plus.circle.big_(lambda in frak(h)^*) frak(g)_((lambda))^frak(h))$, here since $frak(h) = FF h$ then the roots $lambda$ are just scalars defined by $h |-> lambda$. We can clearly see in this decomposition that $V = plus.circle.big_(lambda in frak(h)^*) frak(g)_((lambda))^frak(h)$, thus the root decomposition is equivalent to the decomposition of $V$ into generalized eigenspaces of $ad h$. Now as a linear transformation, up to a change of basis, it has one of the two forms $ ad h tilde.eq mat(lambda, 1; 0, lambda), wide ad h tilde.eq mat(lambda_1, 0; 0, lambda_2). $ We now treat the cases one by one. In the first case, we have $[h,a] = lambda a$ and $[h, b] = lambda b + a$. Now if $lambda = 0$ then we have $[h, a] = 0$ and so $a in frak(n)_frak(h) frak(g)$ contradicting that $frak(h) = frak(n)_frak(h) frak(g)$. Hence let us that $lambda != 0$, then changing basis to $ h' = 1/lambda h, a' = a/lambda, b' = b $ we get $ [h', a'] = a/lambda = a', wide [h', b'] = 1/lambda [h, b] = 1/lambda (lambda b + a) = b' + a', $ now we assume that we already did this change of basis, we want to ask what are the possible values of $[a,b]$. Now we have $a,b in frak(g)_((1))^(frak(h))$ and so from the root decomposition we have that $[a,b] in frak(g)_((2))^(frak(h))$ which only contains $0$ by construction so we must have $[a,b] = 0$ and so this exactly matches $(a)$. Now for the second case, we again can assume that $lambda_1,lambda_2 != 0$ so we may replace $h$ by $h' = 1/lambda_1 h$ to get $ [h', a] = 1/lambda_1 [h, a] = a, wide [h', b] = 1/lambda_1 [h, b] = lambda_2/lambda_1 b. $ Now defining $lambda = lambda_2/lambda_1$ and noting that $lambda != 0$, we have $a in frak(g)_((1))^(frak(h))$ and $b in frak(g)_((lambda))^(frak(h))$ then we have $[a,b] in frak(g)_((lambda + 1))^(frak(h))$ so we now get two cases. If $lambda != -1$, then we have $lambda + 1 != 0,1,lambda$ so $[a,b] = 0$, this matches exactly case (b). If $lambda = -1$ then $lambda + 1 = 0$ so we can have $[a,b] != c h$ for some non-zero constant $c$. Replacing $a$ with $a' = a/c$ we get $ [h,a'] = 1/c a = a', wide [h,b] = -b, wide [a',b] = 1/c [a,b] = h, $ which exactly matches case (c). = Question == Statement Show that all Lie algebras from (a) and (b) solvable and find conditions of their isomorphism. Show that (c) is isomorphic to $sl_2 (FF)$ and that it is not solvable. == Solution Let $frak(g)_a$ be a model of the Lie algebra from (a), we have that $ frak(g)_a^1 = [frak(g)_a, frak(g)_a] = V $ and $[V,V] = 0$ so $frak(g)_a$ is indeed solvable. Similarly let $frak(g)_(b, lambda)$ be a model of the Lie algebra from (b), we have that $ frak(g)_(b,lambda)^1 = [frak(g)_(b,lambda), frak(g)_(b,lambda) ] = V $ and again $[V,V] = 0$ so $frak(g)_(b,lambda)$ is solvable. Now $frak(g)_a$ and $frak(g)_(b,lambda)$ are never isomorphic because under any isomorphism we must have $frak(h) seq frak(g)_a$ map onto $frak(h) seq frak(g)_(b,lambda)$ and yet $ad h$ in $frak(g)_a$ is never a scalar multiple of $ad h$ in $frak(g)_(b, lambda)$ in any basis, so an isomorphism can never exist. Now we also know that for $lambda != lambda'$ if $frak(g)_(b, lambda) iso frak(g)_(b, lambda')$ then we must have $ c mat(1, 0; 0, lambda) tilde.eq mat(1, 0; 0, lambda') $ for some constant $c$. It is easy to see that this is only possible if $c = 1$ and $lambda = lambda'$ or if $c = lambda' = 1/lambda$ and so for this isomorphism exists exactly when $lambda lambda' = 1$. Finally let $frak(g)_c$ be a model for (c), then set $ tilde(h) = mat(1,0;0,-1), tilde(e) = mat(0,1;0,0), tilde(f) = mat(0,0;1,0) $ to be a basis for $sl_2 (FF)$. We note that $ [tilde(h), tilde(e)] = 2 tilde(e), [tilde(h), tilde(f)] = -2 tilde(f), [tilde(e), tilde(f)] = tilde(h), $ so the mapping $h -> tilde(h)/2, a -> tilde(e)/sqrt(2), b -> tilde(f)/sqrt(2)$ defines an isomorphism. Then $frak(g)_c$ is clearly not solvable and hence not isomorphic to the other two. #update_lecture() = Question == Statement Show that if $A$ and $B$ are commuting nilpotent operators on a vector space over a field of characteristic $0$ then $ e^(A + B) = e^A e^B. $ == Solution We have by definition $ e^(A + B) = sum_(i = 0)^N (A + B)^i/(i!) $ where $N$ is such that $A^N B^(N-i) = 0$ for all $i <= N$ (such always exists since you can take twice the max of their nilpotent degree). Now since $A$ and $B$ commute we know that $(A + B)^i = sum_(k=0)^i binom(i,k) A^k B^(k-i)$ and so we have $ e^(A + B) &= sum_(i = 0)^N (A + B)^i/(i!) = sum_(i = 0)^N 1/(i!) sum_(k=0)^i binom(i,k) A^k B^(i-k) = sum_(i = 0)^N 1/(i!) sum_(k=0)^i i!/(k! (i-k)!) A^k B^(i-k) \ &= sum_(i = 0)^N sum_(k=0)^i 1/(k! (i-k)!) A^k B^(i-k) $ on the other hand we have $ e^A e^B = sum_(i = 0)^N A^i/(i!) sum_(j = 0)^N B^j/(j!) = sum_(i = 0)^N sum_(j = 0)^N 1/(i! j!) A^i B^j $ then for $i + j >= N$ this sum the terms are zero by assumption so we have $ e^A e^B = sum_(i = 0)^N sum_(j = 0)^(N - i) 1/(i! j!) A^i B^j $ now notice that we are summing over all integers $i,j >= 0$ with $i + j <= N$ exactly once. This is also exactly what we are doing in the sum $ e^(A + B) = sum_(i = 0)^N sum_(k=0)^i 1/(k! (i-k)!) A^k B^(i-k) $ and so we get $e^(A + B) = e^(A) e^B$. = Question == Statement Let $frak(g)$ be an arbitrary algebra over a field $FF$ of characteristic $0$, and let $D$ be a derivation of the algebra $frak(g)$. Show that if $D$ is a nilpotent operator then $e^D$ is an automorphism of the algebra $frak(g)$. == Solution First we will prove a small lemma #lemma[ Let $D$ be a derivation of an algebra $frak(g)$, we have $ D^n (a b) = sum_(i=0)^n binom(n,i) D^i (a) D^(n - i) (b) $ ] #proof[ We prove by induction, this is clearly true for $n = 1$. Now we have $ D^(n+1) (a b) &= D(D^n (a b)) = D(sum_(i=0)^n binom(n,i) D^i (a) D^(n - i) (b)) = sum_(i=0)^n binom(n,i) D(D^i (a) D^(n - i) (b)) \ &= sum_(i=0)^n binom(n,i) D(D^i (a) D^(n - i) (b)) = sum_(i=0)^n binom(n,i) (D^(i+1) (a) D^(n - i) (b) + D^(i) (a) D^(n - i + 1) (b)) \ &= sum_(i=0)^n binom(n,i) (D^(i+1) (a) D^(n - i) (b)) + sum_(i=0)^n binom(n,i) (D^(i) (a) D^(n - i + 1) (b)) \ &= sum_(i=1)^(n+1) binom(n,i-1) (D^(i) (a) D^(n - i + 1) (b)) + sum_(i=0)^n binom(n,i) (D^(i) (a) D^(n - i + 1) (b)) \ &= D^(n+1) (a) b + a D^(n+1) (b) + sum_(i=1)^n (binom(n,i-1) + binom(n,i)) (D^(i) (a) D^(n - i + 1) (b)) \ &= D^(n+1) (a) b + a D^(n+1) (b) + sum_(i=1)^n (binom(n+1,i) (D^(i) (a) D^(n - i + 1) (b)) \ &= sum_(i=0)^(n+1) binom(n+1,i) D^(i) (a) D^(n - i + 1) (b) $ ] Let us now check that $e^D$ is indeed a morphism of algebras. We have $ e^D (a b) &= sum_(i=0)^N (D^i (a b))/i! = sum_(i=0)^N sum_(k=0)^i binom(i,k) D^(k) (a) D^(i-k) (b) 1/i! \ &= sum_(i=0)^N sum_(k=0)^i 1/(k! (i-k)!) D^(k) (a) D^(i-k) (b) $ and we also have $ e^D (a) e^D (b) &= sum_(i=0)^N (D^i (a))/i! sum_(j = 0)^N (D^j (b))/j! &= sum_(i=0)^N sum_(j = 0)^N 1/(i! j!)(D^i (a)) (D^j (b)) $ and so by the exact same argument as for the previous question, these two are equal. To show it is an automorphism, we simply recall that its inverse is $e^(-D)$ by the previous question. = Question == Statement Recall that $ (d f)|_(x = a) (b) = d/(d t)|_(t=0) f(a + t b). $ Show that $(d f)|_(x = 0)$ is a linear operator on $FF^m$ with the matrix $((partial f_i)/(partial x_j) (a))_(i,j)$ == Solution The fact that $(d f)|_(x = 0)$ is linear is by definition, to compute the matrix we set $b = e_j$ and check $ (d f)|_(x = 0) (e_j) &= d/(d t)|_(t = 0) f(a + t e_j) = (d/(d t)|_(t = 0) f_1 (a + t e_j), ..., d/(d t)|_(t = 0) f_m (a + t e_j)) \ &= (partial_(x_j) f_1|_(x = a), partial_(x_j) f_2|_(x = a), ..., partial_(x_j) f_m|_(x = a)) $ and so the $i$-th component is given by $partial_(x_j) f_i|_(x = a)$ which is exactly what we wanted. #[ #pb() #set heading(numbering: none) #heading("Bonus Problem") ] == Statement + Show that if $F$ is a polynomial in $m$ indeterminents such that $F(f_1,...,f_m)$ is identically zero then $det((partial f_i)/(partial x_j))$ is identically 0. + Given algebraically independent polynomials in $y_1,...,y_m$ in $FF[x_1,...,x_m]$, show that the field extension $FF(x_1, ..., x_m) supset.eq F(y_1,...,y_m)$ is finite, in the sense that each $x_i$ satisfies a non-zero polynomial equation over $FF(y_1,...,y_m)$. + For each $i = 1,2,...,m$ take a polynomial equation satisfied by $x_i$ over $FF(f_1,...,f_m)$ and clear the denominators to get a polynomial over $FF[f_1,...,f_m]$ and let $p_i (f_1,...,f_m)$ be the leading coefficient of this polynomial. Show that the set of points $ {y in FF^m | p_i (y) != 0 "for" i = 1,2,...,m} $ is contained in $f(FF^m)$. == Solution + Since $ F(f_1,...,f_m) = 0 $ then we have by chain rule $ partial_(x_i) F(f_1,...,f_m) = sum_j (partial F)/(partial f_j) (partial f_j)/(partial x_i) = 0 $ so the matrix-covector product has $ (partial F)/(partial f_j) (partial f_j)/(partial x_i) = 0. $ Now at any point we have either $(partial F)/(partial f_j) = 0$ or the image of $(partial f_j)/(partial x_i)$ is contained in the kernel of $(partial F)/(partial f_j)$. We thus have $ FF^m = (sect.big_(j) V((partial F)/(partial f_j))) union V(det (partial f_j)/(partial x_i)), $ but as union of Zariski closed sets one of these sets must equal the entirety of $FF^m$. Now this cannot be $ sect.big_(j) V((partial F)/(partial f_j)) $ as at least one polynomial here is non-trivial if $F$ is not constant (I am assuming that $F != 0$), hence $FF^m = V(det (partial f_j)/(partial x_i))$. + Clearly $FF(y_1,...,y_m)$ has transcendence degree $m$ and thus if $FF(x_1,...,x_m)$ was not a finite extension it would have transcendence degree at least $m + 1$. But clearly it also has transcendence degree $m$ so it is a finite extension. + Construct $p_i (f_1,...,f_m)$ as in the question, let $y in FF^m$ be such that $p_i (y) != 0$ for $i = 1,2,...,m}$, then we can define the homomorphism $ G : FF[f_1,...,f_m] &-> FF\ f_i &|-> y_i $ and so since $p_i (y)$ are non-zero then we get that $p_i$ gets mapped to a non-zero element of $FF$, and thus $G(p_i)$ is invertible. We can thus define an extension $ tilde(G) : FF[f_1,...,f_m, p_1^(-1),...,p_m^(-1)] -> FF. $ Now inside the ring $FF[f_1,...,f_m, p_1^(-1),...,p_m^(-1)]$ we can divide the polynomial solved by $x_i$ by its leading coefficient to get a monic polynomial, making $x_i$ integral. Since we assumed that $FF$ is algebraically closed and noting that $FF[x_1,...,x_m]$ is an integral extension of $FF[f_1,...,f_m, p_1^(-1),...,p_m^(-1)]$ we thus get another extension of $G$, $ ov(G) : FF[x_1,...,x_m] -> FF. $ Now by construction we have that the tuple $ (ov(G)(x_1),...,ov(G)(x_n)) $ is such that $ f_i (ov(G)(x_1),...,ov(G)(x_n)) = y_u $ so we get that $ f(ov(G)(x_1),...,ov(G)(x_n)) = y $ and so indeed $y$ is in $f(FF^m)$. Finally we note that ${y in FF^m | p_i (y) != 0 "for" i = 1,2,...,m}$ is a Zariski open set and thus $f(FF^m)$ contains a Zariski open set. = Question == Statement Let $frak(g) = sl_2 (RR)$. Show that $frak(h)_1 = RR mat(1, 0;0, -1)$ and $frak(h)_2 = RR mat(0, 1;-1, 0)$ are Cartan subalgebras of $frak(g)$, but they are not conjugate by any automorphism of $frak(g)$. == Solution We already know from class that $frak(h)_1$ is Cartan so we only check $frak(h)_2$. Now $frak(h)_2$ is clearly nilpotent, so we check $frak(n)_frak(h)_2 frak(g)$. For any $mat(a,b;c,-a)$ we have $ [mat(a,b;c,-a), mat(0,1;-1,0)] &= mat(a,b;c,-a) mat(0,1;-1,0) - mat(0,1;-1,0) mat(a,b;c,-a) = mat(-b,a;a,c) - mat(c,-a;-a,-b) \ &= mat(-b-c, 2 a; 2a, b+c) $ which is never in $frak(h)_2$ unless it is equal to zero, in which case $a = 0$ and $b + c = 0$ and hence $frak(n)_frak(h)_2 frak(g) = frak(h)_2$. Now to see that they are not conjugate by any automorphism, we recall that $frak(h)_1$ has two weight spaces, with weights $2,-2$. On the other hand we can compute for $frak(h)_2$, $ (ad mat(0, 1; -1, 0)) mat(a, b; c, -a) = mat(b+c,-2a;-2a,-b-c) $ so if it is in an eigenspace we have $ b + c = lambda a, - 2 a = lambda b, - 2 a = lambda c $ for some $lambda$. From this we immediately get $c = b$ so $ 2 b = lambda a, - 2 a = lambda b $ so $ 2 b = lambda^2/(-2) b. $ now if $b = 0$ then we get $a = 0$ and so no weight space there, on the other hand if $b != 0$ then $ -4 = lambda^2 $ so $lambda = 2 i$. Thus $frak(h)_2$ has no decomposition into a real weight space, so it cannot be conjugate to $frak(h)_1$ by a real automorphism.
https://github.com/yy01zz02/profile-template
https://raw.githubusercontent.com/yy01zz02/profile-template/main/src/english.typ
typst
MIT License
// import from template #import "../template/template.typ": *; #show: template; #set text( size: 12pt, font: "Centaur" ) #init( name: "<NAME>", pic_path : "", ) #info( color: rgb(0, 0, 0), ( icon: "/img/fa/fa-home.svg", link: "https://zhangsan.io/", content: "https://zhangsan.io/" ), ( icon: fa_github, link: "https://github.com/NorthSecond", content: "NorthSecond" ), ( icon: fa_email, link: "mailto:San%20Zhang<<EMAIL>>", content: "<EMAIL>", ), ( icon: fa_phone, link: "tel:+86 133 3333 3333", content: "+86 133 3333 3333", ), ) #resume_section("Education") #resume_item( "XXX University", "Master of Engineering", "Computer Science and Technology", "2024.09 -- 2027.07" ) #resume_item( "XXXX University", "Bachelor of Engineering", "Software Engineering", "2020.09 -- 2024.06" ) #resume_section("Publications") - [CVPR 2024]*You*, #lorem(5), and #lorem(1). "#lorem(10)" Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition. 2024. - [CVPR 2023]*You*, #lorem(5), and #lorem(1). "#lorem(10)" Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition. 2023. #resume_section([Selected Projects]) #resume_item( lorem(5), "Computer Architecture", lorem(8), "2023.12 -- 2026.11" ) #resume_desc( "Description", lorem(32) ) #resume_desc( "Contribution", lorem(24) ) #resume_desc( "Achievement", lorem(12) ) #resume_section([Experience]) #resume_item( lorem(8), "Student Assistant", lorem(3), "2021.11 -- 2024.06" ) #resume_desc( "Description", lorem(24) ) #resume_section([Competitions and Awards]) #resume_desc( "Professional Skills Competition", lorem(8) ) #resume_desc( "Scholarship", lorem(24) ) #resume_desc( "Other Administrative Awards", lorem(12) ) #resume_section([Skills and Interests]) #resume_desc( "Programming Languages", [Proficient in C/C++; familiar with Rust, Python; have experience in Java, SQL, Matlab, TypeScript, Golang and some other languages.] ) #resume_desc( "Development Tools", [Proficient in Git, Docker, Kubernetes, familiar with Jenkins, Travis CI, Circle CI, etc.] ) #resume_desc( "Interests", [Machine Learning, Computer Vision, Compiler, System Programming, etc.] )
https://github.com/noahjutz/CV
https://raw.githubusercontent.com/noahjutz/CV/main/chip.typ
typst
#let chip(body) = box( inset: (x: 8pt, y: 6pt), radius: 4pt, stroke: gray, body ) #let chips(..body) = { for c in body.pos() { chip(c) h(4pt) } }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/cjk-latin-spacing_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Issue #2538 #set text(cjk-latin-spacing: auto) abc字 abc字#linebreak() abc字#linebreak() 母 abc字\ 母
https://github.com/danilasar/physics-laba1
https://raw.githubusercontent.com/danilasar/physics-laba1/master/main.typ
typst
#import "conf.typ" : conf #show: conf.with( title: [], type: "referat", info: (:), settings: ( title_page: ( enabled: false ), contents_page: ( enabled: false ) ) ) = ЛАБОРАТОРНАЯ РАБОТА №1 / Наименование работ: Изучение электростатического поля методом электролитической ванны. / Цель работы: / Принадлежности: + Волновой генератор + Делитель, состоящий из магазинов сопротивлений + Листы бумаги + Электролитическая ванна + Стеклянный стол + Металлический зонд с лампой + Осциллограф / Рабочая формула: $ frac(phi(x), phi_0) = frac(ln frac(x, l - x) + ln frac(l - a, a), 2 ln frac(l - a, a)) $
https://github.com/jneug/typst-finite
https://raw.githubusercontent.com/jneug/typst-finite/main/manual.typ
typst
MIT License
#import "@local/mantys:0.1.0": * #import "@local/tidy:0.2.0" #import "@preview/cetz:0.1.1" #import "finite.typ" #import "util.typ" #show "CETZ": a => package[CeTZ] #let cetz-cmd = cmd.with(module:"cetz") #let cetz-cmd- = cmd-.with(module:"cetz") #show: mantys.with( ..toml("typst.toml"), title: align(center, finite.automaton(( q0: (q1:none), q1: (q2:none), q2: (q3:none), q3: (q4:none), q4: (q5:none), q5: none, ), style: ( q0: (label: "F"), q1: (label: "I"), q2: (label: "N"), q3: (label: "I"), q4: (label: "T"), q5: (label: "E") ))), date: datetime.today(), abstract: [ FINITE is a Typst package to draw transition diagrams for finite automata (finite state machines) with the power of CETZ. The package provides new elements for manually drawing states and transitions on any CETZ canvas, but also comes with commands to quickly create automata from a transition table. ], examples-scope: ( cetz: cetz, finite: finite, util: util, automaton: finite.automaton ) ) #let show-module(name, scope: (:), outlined: false) = tidy-module( read(name + ".typ"), name: name, show-outline: outlined, include-examples-scope: true, extract-headings: 3, tidy: tidy ) = Usage == Load from package repository (Typst 0.6.0 and later) For Typst 0.6.0 and later, the package can be imported from the _preview_ repository: #codesnippet[```typ #import "@preview/finite:0.3.0": automaton ```] Alternatively, the package can be downloaded and saved into the system dependent local package repository. Either download the current release from GitHub#footnote[#link("https://github.com/jneug/typst-finite")] and unpack the archive into your system dependent local repository folder#footnote[#link("https://github.com/typst/packages#local-packages")] or clone it directly: #codesnippet[```shell-unix-generic git clone https://github.com/jneug/typst-finite.git finite/0.3.0 ```] In either case, make sure the files are placed in a subfolder with the correct version number: `finite/0.3.0` After installing the package, just import it inside your `typ` file: #codesnippet[```typ #import "@local/finite:0.3.0": automaton ```] == Dependencies FINITE loads #link("https://github.com/johannes-wolf/typst-canvas")[CETZ] and the utility package #link("https://github.com/jneug/typst-tools4typst")[#package[t4t]] from the `preview` package repository. The dependencies will be downloaded by Typst automatically on first compilation. = Drawing automata FINITE helps you draw transition diagrams for finite automata in your Typst documents, using the power of CETZ. To draw an automaton, simply import #cmd[automaton] from FINITE and use it like this: #example[```typ #automaton(( q0: (q1:0, q0:"0,1"), q1: (q0:(0,1), q2:"0"), q2: none, )) ```] As you can see, an automaton ist defined by a dictionary of dictionaries. The keys of the top-level dictionary are the names of states to draw. The second-level dictionaries have the names of connected states as keys and transition labels as values. In the example above, the states `q0`, `q1` and `q2` are defined. `q0` is connected to `q1` and has a loop to itself. `q1` transitions to `q2` and back to `q0`. #cmd-[automaton] selected the first state in the dictionary (in this case `q0`) to be the initiat state and the last (`q2`) to be a final state. See @aut-specs for more details on how to specify automatons. To modify how the transition diagram is displayed, #cmd-[automaton] accepts a set of options: #example(breakable:true)[```typ #automaton( ( q0: (q1:0, q0:"0,1"), q1: (q0:(0,1), q2:"0"), q2: (), ), initial: "q1", final: ("q0", "q2"), labels:( q2: "FIN" ), style:( state: (fill: luma(248), stroke:luma(120)), transition: (stroke: (dash:"dashed")), q0-q0: (anchor:top+left), q1: (initial:top), q1-q2: (stroke: 2pt + red) ) ) ```] For larger automatons, the states can be arranged in different ways: #example(breakable:true)[```typ #let aut = (:) #for i in range(10) { let name = "q"+str(i) aut.insert(name, (:)) if i < 9 { aut.at(name).insert("q" + str(i + 1), none) } } #automaton( aut, layout: finite.layout.circular.with(offset: 45deg), style: ( transition: (curve: 0), q0: (initial: top+left) ) ) ```] See @using-layout for more details about layouts. == Specifing finite automata <aut-specs> Most of FINITEs commands expect a finite automaton specification ("spec" in short) as the first argument. These specifications are dictionaries defining the elements of the automaton. If an automaton has only one final state, the spec can simply be a transition table. In other cases, the specification can explicitly define the various elements. A specification can have these elements: ```typc ( transitions: (...), states: (...), inputs: (...), initial: "...", final: (...) ) ``` - `transitions` is a dictionary of dictionary in the format: ```typc ( state1: (input1, input2, ...), state2: (input1, input2, ...), ... ) ``` - `states` is an optional array with the names of all states. The keys of `transitions` are used by default. - `inputs` is an optional array with all input values. The inputs found in `transitions` are used by default. - `initial` is an optional name of the initial state. The first value in `states` is used by default. - `final` is an optional array of final states. The last value in `states` is used by default. The utility function #cmd(module:"util")[to-spec] can be used to create a full spec from a parital dictionary by filling in the missing values with the defaults. == Command reference #show-module("cmd") == Styling the output As common in CETZ, you can pass general styles for states and transitions to the #cetz-cmd-[set-style] function within a call to #cetz-cmd-[canvas]. The elements functions #cmd-[state] and #cmd-[transition] (see below) can take their respective styling options as arguments, to style individual elements. #cmd[automaton] takes a #arg[style] argument that passes the given style to the above functions. The example below sets a background and stroke color for all states and draws transitions with a dashed style. Additionally, the state `q1` has the arrow indicating an initial state drawn from above instead from the left. The transition from `q1` to `q2` is highlighted in red. #example(breakable:true)[```typ #automaton( ( q0: (q1:0, q0:"0,1"), q1: (q0:(0,1), q2:"0"), q2: (), ), initial: "q1", final: ("q0", "q2"), style:( state: (fill: luma(248), stroke:luma(120)), transition: (stroke: (dash:"dashed")), q1: (initial:top), q1-q2: (stroke: 2pt + red) ) ) ```] Every state can be accessed by its name and every transition is named with its initial and end state joined with a dash (`-`). The supported styling options (and their defaults) are as follows: - states: / #arg(fill: auto): Background fill for states. / #arg(stroke: auto): Stroke for state borders. / #arg(radius: .6): Radius of the states circle. - `label`: / #arg(text: auto): State label. / #arg(size: auto): Initial text size for the labels (will be modified to fit the label into the states circle). - transitions / #arg(curve: 1.0): "Curviness" of transitions. Set to #value(0) to get straight lines. / #arg(stroke: auto): Stroke for transitions. - `label`: / #arg(text: ""): Transition label. / #arg(size: 1em): Size for label text. / #arg(color: auto): Color for label text. / #arg(pos: .5): Position on the transition, between #value(0) and #value(1). #value(0) sets the text at the start, #value(1) at the end of the transition. / #arg(dist: .33): Distance of the label from the transition. / #arg(angle: auto): Angle of the label text. #value(auto) will set the angle based on the transitions direction. == Using #cmd-(module:"cetz")[canvas] The above commands use custom CETZ elements to draw states and transitions. For complex automata, the functions in the #module[draw] module can be used inside a call to #cetz-cmd-[canvas]. #example(breakable:true)[``` #cetz.canvas({ import cetz.draw: set-style import finite.draw: state, transition state((0,0), "q0", initial:true) state((2,1), "q1") state((4,-1), "q2", final:true) state((rel:(0, -3), to:"q1.bottom"), "trap", label:"TRAP", anchor:"top-left") transition("q0", "q1", inputs:(0,1)) transition("q1", "q2", inputs:(0)) transition("q1", "trap", inputs:(1), curve:-1) transition("q2", "trap", inputs:(0,1)) transition("trap", "trap", inputs:(0,1)) }) ```] === Element functions #show-module("draw") === Anchors States have the common anchors (like `top`, `top-left` ...), transitions have a `initial`, `end`, `center` and `label` anchors. These can be used to add elements to an automaton: #example(breakable:true)[``` #cetz.canvas({ import cetz.draw: circle, line, place-marks, content import finite.draw: state, transition state((0,0), "q0") state((4,0), "q1", final:true) transition("q0", "q1", label:$epsilon$) circle("q0.top-right", radius:.4em, stroke:none, fill:black) let magenta-stroke = 2pt+rgb("#dc41f1") circle("q0-q1.label", radius:.5em, stroke:magenta-stroke) place-marks( line( name: "q0-arrow", (rel:(.6,.6), to:"q1.top-right"), (rel:(.15,.15), to:"q1.top-right"), stroke:magenta-stroke ), (mark:">", pos:1, stroke:magenta-stroke) ) content( (rel:(0,.25), to:"q0-arrow.start"), text(fill:rgb("#dc41f1"), [*very important state*]) ) }) ```] == Layouts <using-layout> Layouts can be used to move states to new positions within a call to #cetz-cmd-[canvas]. They act similar to CETZ groups and have their own transform. Any other elements than states will keep their original coordinates, but be translated by the layout, if necessary. FINITE ships with a bunch of layouts, to accomodate different scenarios. === Available layouts <available-layouts> #show-module("layout") === Using layouts Layouts are elements themselves. This means, they have a coordinate to be moved on the canvas and they can have anchors. Using layouts allows you to quickly create complex automata, without the need to pick each states coordinate by hand. #example(breakable:true)[``` #cetz.canvas({ import cetz.draw: set-style import finite.draw: * set-style(state: (radius: .4)) layout.grid( (0,0), name:"grid", columns:3, { set-style(state: (fill: green.lighten(80%))) for s in range(6) { state((), "a" + str(s)) } }) layout.linear( (rel:(2,0), to:"grid.right"), dir: bottom, anchor: "center", { set-style(state: (fill: blue.lighten(80%))) for s in range(4) { state((), "b" + str(s)) } }) state((rel: (0, -1.4), to:"grid.bottom"), "TRAP", fill:red.lighten(80%)) transition("a0", "TRAP", curve:-1) transition("b2", "TRAP") transition("a5", "b0") transition("a5", "b2", curve:-1) }) ```] === Creating custom layouts <creating-layout> There are two ways to create custom layouts. Using the #cmd(module:"layout")[custom] layout or building your own from the ground up. ==== Using #cmd(module:"layout")[custom] The `custom` layout passes information about states to a #arg[positions] function, that computes a dictionary with new coordinates for all states. The `custom` layout will then place the states at the given locations and handle any other elements other than states. The position function gets passed the CETZ context, a dictionary of state names and matching radii (for drawing the states circle) and the list of #cmd-[state] elements. This example arranges the states in a wave: #example(breakable:true)[``` #let wave-layout = finite.layout.custom.with( positions: (ctx, radii, states) => { let (i, at) = (0, 0) let pos = (:) for (name, r) in radii { at += r pos.insert(name, (at, 1.2 * calc.sin(i))) i += 1 at += r + .4 } return pos } ) #let aut = (:) #for i in range(8) { aut.insert("q"+str(i), none) } #automaton( aut, layout: wave-layout, style: ( state: (radius: .4), q2: (radius: .8), q6: (radius: .8) ) ) ```] ==== Creating a layout element Layout are elements and are similar to CETZ's groups. A layout takes an array of elements and computes a new positions for each state in the list. To create a layout, FINITE provides a base element that can be extended. A basic layout can look like this: #sourcecode[```typc #let my-layout( position, name: none, anchor: "left", body ) = { // Layouts always need to have a name. // If none was provided, we create one. if is.n(name) { name = "layout" + body.map((e) => e.at("name", default:"")).join("-") } // Get the base layout element let layout = base(position, name, anchor, body) // We need to supply a function to compute new locations for the elements. layout.children = (ctx) => { let elements = () for element in elements { // states have a custom "radius" key if "radius" in element { // Change the position of the state element.coordinates = ((rel:(.6,0)),) } elements.push(element) } elements } return (layout,) } ```] == Utility functions #show-module("util", outlined: true) == Doing other stuff with FINITE Since transition diagrams are effectvely graphs, FINITE could also be used to draw graph structures: #example[``` #cetz.canvas({ import cetz.draw: set-style import finite.draw: state, transitions state((0,0), "A") state((3,1), "B") state((4,-2), "C") state((1,-3), "D") state((6,1), "E") transitions(( A: (B: 1.2), B: (C: .5, E: 2.3), C: (B: .8, D: 1.4, E: 4.5), D: (A: 1.8), E: (:) ), C-E: (curve: -1.2)) }) ```] = Showcase // #example[``` // #finite.automaton(( // q0: (q1: 0, q2: 0), // q2: (q3: 1, q4: 0), // q4: (q2: 0, q5: 0, q6: 0), // q6: (q7: 1), // q1: (q3: 1, q4: 0), // q3: (q1: 1, q5: 1, q6: 1), // q5: (q7: 1), // q7: () // ), // layout: finite.layout.group.with(grouping: ( // ("q0",), // ("q1", "q2", "q3", "q4", "q5", "q6"), // ("q7",) // ), // spacing: 2, // layout: ( // finite.layout.linear, // finite.layout.grid.with(columns:3, spacing:2.6), // finite.layout.linear // ) // ), // style: ( // transition: (curve: 0), // q1-q3: (curve:1), // q3-q1: (curve:1), // q2-q4: (curve:1), // q4-q2: (curve:1), // q1-q4: (label: (pos:.75)), // q2-q3: (label: (pos:.75, dist:-.33)), // q3-q6: (label: (pos:.75)), // q4-q5: (label: (pos:.75, dist:-.33)) // ) // ) // ```]
https://github.com/Mc-Zen/tidy
https://raw.githubusercontent.com/Mc-Zen/tidy/main/tests/test_testing.typ
typst
MIT License
#import "/src/tidy.typ": * #{ let code = ``` /// >>> 2 == 2 /// >>> ("e", 2) == ("e", 2) /// >>> eq(1+1, 2) /// >>> ne(2+1, 2) /// >>> approx(calc.sin(calc.pi), 0) /// /// >>> 2 == 2 /// >>> eq(2, 2) /// >>> eq((a: 13, b: 21) + (a: 3), (a: 3, b:21)) #let f() ``` let result = show-module(parse-module(code.text)) } // disable tests #{ let code = ``` /// >>> 2 == 3 #let f() ``` let result = show-module(parse-module(code.text), enable-tests: false) }
https://github.com/ad-si/invoice-maker
https://raw.githubusercontent.com/ad-si/invoice-maker/master/tests.typ
typst
ISC License
#import "invoice-maker.typ": * #{ // add-zeros() assert.eq(add-zeros(1.234), "1.23") assert.eq(add-zeros(1.2), "1.20") } #{// verify-iban() let iban-tests = ( ("DE", "DE44 5001 0517 5407 3249 31", true), ("DE", "DE89 3704 0044 0532 0130 00", true), ("DE", "DE44 5001 0517 5407 3249 3X", false), ("DE", "DE91 2100 0418 4502 0005 1332", false), ("DE", "DE14 2004 1010 0505 0001 3M02 606", false), ("DE", "DE14 2004 1010 0505 0001 3M02 6067", false), ("GB", "GB82 WEST 1234 5698 7654 32", true), ("GB", "GB29 NWBK 6016 1331 9268 19", true), ("GB", "GB93 0076 2011 6238 5295", false), ("GB", "GB93 0076 2011 6238 5295 7", false), ("GB", "GB82 WEST 1234 5698 7654 322", false), // 1 char too long ("GB", "1GB91 2100 0418 4502 0005 1332", false), ) for (country, iban, expected-result) in iban-tests { assert.eq( verify-iban(country, iban), expected-result, message: "IBAN '" + iban + "' should be " + if expected-result { "valid" } else { "invalid" } + " for " + country ) } } #{//parse-date assert.eq( parse-date("2024-03-27"), datetime(year: 2024, month: 03, day: 27), ) }
https://github.com/Jollywatt/typst-fletcher
https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/edge-decorations/test.typ
typst
MIT License
#set page(width: auto, height: auto, margin: 1em) #import "/src/exports.typ" as fletcher: diagram, node, edge #diagram(spacing: 4em, $ A edge(<->, "wave") & B edge(<->, "zigzag") & C edge(<->, "coil") $) #diagram(spacing: (2em, 3em), $ e^- edge("dr", "-<|-") & & & & & edge("dl", "-|>-") e^+ \ & edge("wave") & edge(gamma, "wave", bend: #80deg) edge("wave", bend: #(-80deg)) & edge("wave") \ e^+ edge("ur", "-|>-") & & & & & edge("ul", "-<|-") e^- \ $) #diagram(spacing: (1cm, 0mm), $ A edge(~>) & B \ A edge(<~) & B \ A edge("<~>") & B \ A edge(">~<") & B \ $)
https://github.com/rabotaem-incorporated/probability-theory-notes
https://raw.githubusercontent.com/rabotaem-incorporated/probability-theory-notes/master/sections/01-elementary/!sec.typ
typst
= Элементарная теория вероятностей #include "01-experiment-probability-model.typ" #include "02-limit-theorems.typ"
https://github.com/FilipSolich/CV-Template
https://raw.githubusercontent.com/FilipSolich/CV-Template/main/template.typ
typst
The Unlicense
#let chip(body, txColor: black, bgColor: white) = { box(fill: bgColor, stroke: black, radius: 15%, inset: 5pt)[#text(fill: txColor)[#body]] } #let double_chip(data) = { ( box(stroke: black, radius: (left: 15%), inset: 5pt)[#data.at(0)], box(stroke: black, radius: (right: 15%), inset: 5pt)[#data.at(1)] ).join() } #let split_chip(body1, body2, txColor: (black, black), bgColor: (white, white)) = { ( box( stroke: (left: black, top: black, bottom: black), radius: (left: 15%), fill: bgColor.at(0), inset: (left: 5pt, top: 5pt, bottom: 5pt) )[#text(fill: txColor.at(0))[#body1]], box( stroke: (right: black, top: black, bottom: black), radius: (right: 15%), fill: bgColor.at(1), inset: (right: 5pt, top: 5pt, bottom: 5pt) )[#text(fill: txColor.at(0))[#body2]] ).join() } #let chips = ( go: chip(bgColor: rgb("#6AD7E5"))[Go], python: split_chip(bgColor: (blue, yellow))[Pyt][hon], cpp: chip(txColor: white, bgColor: rgb("#0080CD"))[C++], c: chip(txColor: white, bgColor: rgb("#5B6ABE"))[C], django: chip(txColor: white, bgColor: rgb("#0F3D2D"))[Django], fastapi: chip(txColor: white, bgColor: rgb("#009485"))[FastAPI], jquery: chip(txColor: white, bgColor: rgb("#0769AD"))[jQuery], postgres: chip(bgColor: rgb("#699ECA"))[PostgreSQL], mongo: chip(txColor: white, bgColor: rgb("#023430"))[MongoDB], rabbitmq: chip(bgColor: rgb("#FF6600"))[RabbitMQ], redis: chip(txColor: white, bgColor: rgb("#D9271B"))[Redis], grpc: chip(txColor: white, bgColor: rgb("#244C5A"))[gRPC], docker: chip(bgColor: rgb("#0092E6"))[Docker], ci: chip()[CI], github: chip(txColor: white, bgColor: black)[GitHub], ) #let CV(lang, personalInfo, languages, jobs, education, projects, certifications) = { set document( title: [#personalInfo.name - CV], author: personalInfo.name, ) set page(paper: "a4", margin: 2cm) set text(font: "Carlito", size: 12pt, lang: lang) let secondary = rgb("#828282") let experienceTitle(body) = [ #text(size: 1.25em)[*#body*] ] let chips(data) = [ #data.join(h(3pt)) ] let date(dateFrom, dateTo: none) = [ #set text(secondary) #box(baseline: 0.15em, image("icons/calendar.svg", height: 1em)) #text(dateFrom) #if dateTo != none { text("- "+dateTo) } ] let link(icon, link) = ( align(center)[#box(image(icon, height: 1.5em))], text(baseline: 0.35em, link) ) let links(data) = [ #let d = data.map(l => link(l.icon, l.link)).flatten() #table(columns: 2, stroke: none, ..d) ] let langs(data) = [ #underline(offset: 0.25em)[= #data.title] #v(5pt) #data.langs.map(d => double_chip(d)).join(linebreak()) ] let job(data) = [ #experienceTitle[#data.title]\ #if data.keys().contains("company") [ *#data.company*\ ] #if data.keys().contains("description") { data.description } #if data.keys().contains("chips") { v(-5pt) chips(data.chips) } #linebreak() #date(data.dateFrom, dateTo: data.dateTo) ] let project(data) = [ #experienceTitle[#data.title]\ #data.link\ #data.description #v(-5pt) #chips(data.chips) ] let certification(data) = [ #experienceTitle[#data.title]\ *#data.issuer*\ #date(data.date) ] let experience(data, func) = [ #grid(columns:(2.2fr, 13fr), { if data.keys().contains("logo") { box(inset: (top: -5pt))[#image(data.logo, height: 2.8em)] } }, { func(data) }) ] let experiences(title, func, data) = [ #underline(offset: 0.25em)[= #title] #v(5pt) #data.map(dt => experience(dt, func)).join(v(5pt)) ] // Page 1 grid(rows: (1fr, 9fr), { text(size: 2.5em)[*#personalInfo.degrees.join(" ") #personalInfo.name*] linebreak() if sys.inputs.at("jobTitle", default: "") != "" { text(secondary, size: 1.7em)[*#sys.inputs.jobTitle*] } line(length: 100%) },{ grid(columns: (1.8fr, 3.5fr), { image(personalInfo.photo, width: 80%) links(personalInfo.links) langs(languages) },{ experiences(jobs.title, job, jobs.jobs) } ) } ) // Page 2 grid(columns: (1.8fr, 3.5fr), { },{ experiences(education.title, job, education.education) experiences(projects.title, project, projects.projects) experiences(certifications.title, certification, certifications.certs) } ) }
https://github.com/maxgraw/bachelor
https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/3-state/0-index.typ
typst
Das folgende Kapitel widmet sich dem aktuellen Stand der Technik im Bereich der Augmented Reality. Es werden zunächst aktuelle Studien und Anwendungen vorgestellt. Anschließend wird die WebXR-Technologie mit anderen AR-Plattformen verglichen und abschließend werden verschiedene aktuelle WebXR-Frameworks vorgestellt. == Aktuelle Studien <current-studies-chapter> #include "current-studies.typ" == Anwendungen <applications-chapter> #include "applications.typ" == WebXR im Vergleich zu anderen AR-Plattformen #include "ar-comparison.typ" == WebXR Frameworks <webxr-frameworks-chapter> #include "webxr-frameworks.typ"
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/sections/PianificazioneSprint/OttavoSprint.typ
typst
MIT License
#import "../../functions.typ": glossary === Ottavo #glossary[sprint] *Inizio*: Venerdì 12/01/2024 *Fine*: Giovedì 18/01/2024 *Obiettivi dello #glossary[sprint]*: - Terminare la revisione in stile #glossary[walkthrough] delle _Norme di Progetto v1.0_; - Terminare la stesura ed effettuare la revisione in stile #glossary[walkthrough] del _Piano di Progetto v1.0_: - Aggiornare pianificazione e preventivo pertinenti allo #glossary[sprint] 8 e inserire il consuntivo pertinente allo #glossary[sprint] 7; - Aggiungere pianificazione e preventivo degli #glossary[sprint] 9 e 10, come parte della pianificazione a breve termine; - Inserire il nuovo preventivo nella sezione dedicata alla suddivisione delle ore per ruolo nel periodo di tempo che precede ogni revisione, riportando le modifiche decise e approvate dal team nel corso dello #glossary[sprint] appena concluso; - Realizzare automazione per la creazione di tabelle e grafici pertinenti ai preventivi, in modo simile a quanto precedentemente realizzato per i consuntivi. - Incorporare il nuovo BAC (Budget At Completion) all'interno del _Piano di Qualifica v1.0_ e terminarne la revisione in stile #glossary[walkthrough]: - Evidenziare l'adattamento del team alla scarsità di ore da Amministratore e Analista con il nuovo preventivo a partire dallo #glossary[sprint] 7 (incluso). - Terminare la revisione in stile #glossary[walkthrough] dell'_Analisi dei Requisiti v1.0_; - Apportare le modifiche consigliate dalla Proponente al #glossary[PoC] (visualizzazione di tabelle contenenti i dati grezzi generati dai simulatori di sensori e filtraggio dei dati) in vista della demo prevista per la prima revisione #glossary[RTB]\; - Terminare la preparazione della presentazione e la stesura della _Lettera di Presentazione_ in vista della revisione #glossary[RTB]\; - Candidatura alla revisione #glossary[RTB].
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/par_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test that paragraph spacing loses against block spacing. // TODO #set block(spacing: 100pt) #show table: set block(above: 5pt, below: 5pt) Hello #table(columns: 4, fill: (x, y) => if calc.odd(x + y) { silver })[A][B][C][D]
https://github.com/Error-418-SWE/Documenti
https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/3%20-%20PB/Documentazione%20esterna/Verbali/24-03-15/24-03-15.typ
typst
#import "/template.typ": * #show: project.with( date: "15/03/24", subTitle: "Aggiornamento sullo stato dei lavori", docType: "verbale", authors: ( "<NAME>", ), missingMembers: ( "<NAME>", ), externalParticipants : ( (name: "<NAME>", role: "Referente aziendale"), ), timeStart: "14:05", timeEnd: "14:35", location: "Zoom", ); = Ordine del giorno - Presentazione MVP; - Presentazione dei pattern; - Presentazione codice; - Pianificazione meeting futuri. == Presentazione MVP Sono state presentate al Proponente le funzionalità implementate finora nell'MVP, quali: - configurazione iniziale dell'ambiente; - importazione da database di zone, bin e prodotti; - lista delle zone presenti; - lista dei prodotti presenti; - ispezione dei prodotti, bin e zone; - creazione di una zona; - lista degli ordini di movimentazione; - risincronizzazione dell'ambiente; - reimpostazione dell'ambiente. Il Proponente è risultato soddisfatto ed entusiasta dei progressi raggiunti con l'MVP, ed ha evidenziato una buona usabilità e interfaccia grafica del software. == Presentazione dei pattern Sono stati presentati i principali design pattern implementati finora, ponendo particolare attenzione ai Data Mapper e ai Repository che hanno consentito la realizzazione di una logica del software indipendente dalla struttura dei dati grezzi. == Presentazione codice Su richiesta del Proponente, è stato mostrato il codice del software. Si sono discussi vari dubbi e trovate soluzioni: - si è deciso di avere un caricamento totale dei dati sin dall'inizio e non parziale: il Proponente ha approvato questa scelta, suggerendo di concentrarsi sulla realizzazione dei requisiti concordati e di considerare i problemi legati alla performance solo nel momento in cui si presentano; - il caricamento dei dati da database avviene tramite Server Action, per sfruttare al meglio le tecnologie scelte; - la simulazione delle API deve avvenire tramite il classico fetch, come suggerito anche dal Proponente. == Pianificazione meeting futuri Durante l'incontro non è stata decisa una data precisa per il prossimo meeting, che verrà stabilita in seguito tramite contatto mail.
https://github.com/tiankaima/typst-notes
https://raw.githubusercontent.com/tiankaima/typst-notes/master/2bc0c8-2024_spring_TA/hw16_17.typ
typst
#set text( font: ("linux libertine", "Source Han Serif SC", "Source Han Serif"), size: 10pt, ) #show math.equation: it => text(size: 10pt, math.display(it)) #let dcases(..args) = { let dargs = args.pos().map(it => math.display(it)) math.cases(..dargs) } #show image: it => align(center, it) #show heading.where(level: 3): it => highlight(it) #let Real = "Re" #let Imaginary = "Im" #set page( header: context [ #h(1fr) #if counter(page).get().first() > 1 [ *Homework 16 Ans* ] ], footer: context [ #let headings = query(selector(heading.where(level: 2)).before(here())) #if headings.len() > 0 { text(size: 8pt, headings.last().body) } #h(1fr) #counter(page).display( "1/1", both: true, ) ], ) #align(center)[ = Homework 16 Ans 2024 Spring 数学分析 B2 Ma. ] == 6.12 Ans === 1(3) $ integral_2^(+oo) (dif x) / (x^u ln x) $ + $u<=1$, then $1/(x^u ln x)>=1/(x ln x)$, we have: $ integral_2^(+oo) (dif x) / (x^u ln x) >= integral_2^(+oo) (dif x) / (x ln x) = lim_(t->+oo) ln ln t = +oo $ + $u>1$, since $ln x$ is strictly increasing, we have: $ integral_2^(+oo) (dif x) / (x^u ln x) <= integral_2^(+oo) (dif x) / (x^u ln 2) < +oo $ Or more generally, since $1/(ln x) -> 0 quad (x->+oo)$, and $integral_2^(+oo) (dif x)/(x^u)<+oo$, with Dirchelet (Page 301, Theorem 13.7), we can show that: $ integral_2^(+oo) (dif x) / (x^u ln x) < +oo $ So the integral converges for $u>1$. === 1(5) $ integral_0^(+oo) (sin^2 x) / (x^alpha (1+x)) dif x $ First split the integral into two parts: $ I = I_1 + I_2 =integral_0^1 (sin^2 x) / (x^alpha (1+x)) dif x + integral_1^(+oo) (sin^2 x) / (x^alpha (1+x)) dif x $ // Note than when $I=integral_0^(+oo)dif x$ converges, a necessary & sufficient condition is that both $I_1=integral_0^1 dif x$ and $I_2=integral_1^(+oo)dif x$ converge. (This differs from splitting into, say $I_1=integral_0^(+oo) f_1 dif x$ and $I_2=integral_0^(+oo) f_2 dif x$, where the in-convergance of $I$ is not guaranteed by the convergance of $I_1$ and $I_2$, or vice versa.) + We start by discussing $I_1$: $ (sin^2 x) / (x^alpha (1+x)) tilde x^2 / x^alpha = x^(2-alpha) $ So integral $I_1 = integral_0^1 (sin^2 x)/(x^alpha (1+x))$ and $integral_0^1 1/(x^(alpha - 2))$ have the same convergance, and the latter converges if $alpha - 2 < 1$, i.e. $alpha < 3$. + The second part $I_2$ requires some techniques. + Let's first show the case for $alpha>0$: $ integral_1^(+oo) (sin^2 x) / (x^alpha (1+x)) dif x = 1 / 2 integral_1^(+oo) (1-cos x) / (x^alpha (1+x)) = 1 / 2( integral_1^(+oo)1 / (2x^alpha (1+x)) dif x-integral_1^(+oo) (cos 2x) / (2x^alpha (1+x)) dif x ) = 1 / 2 (I_3 + I_4) $ // This is what I meant by in-convergance of $I_1, I_2$ can't deduce the in-convergance of $I$, luckily in this case we can prove both are under $alpha >=0$ It's trivial to prove $I_3$ converges with $alpha >0$. For $I_4$, since $integral_1^A cos 2x dif x$ is always bounded, $1/(x^alpha (1+x))$ is strictly decreasing, with Dirchelet, we can show that $I_4$ converges for $alpha >=0$. + With $alpha=0$: $I_3=integral_1^(+oo)1/(1+x)dif x$ no longer converges, but $I_4$ remains convergent, so $I_2$ diverges for $alpha=0$ + Then there's the case for $alpha<0$: $ integral_1^(+oo) (sin^2 x) / (x^alpha (1+x)) dif x >= integral_1^(+oo) (sin^2 x) / (1+x) dif x -> +oo $ Thus $I_2$ diverges for $alpha<0$. To sum up, $I$ converges for $0<alpha<3$. === 1(6) $ integral_0^(+oo) ln(1+x^2) / x^alpha dif x $ The idea is shared: $ I= I_1 + I_2 = integral_0^1 ln(1+x^2) / x^alpha dif x + integral_1^(+oo) ln(1+x^2) / x^alpha dif x $ + For $I_1$, as $x->0$: $ ln(1+x^2) / x^alpha tilde x^2 / x^alpha = x^(2-alpha) $ So $I_1$ converges if $2-alpha > -1$, i.e. $alpha < 3$. + For $I_2$, the key is to use *logrithm is smaller than any power function when $x->+oo$*, so for $alpha> 1$ $ 0<(ln (1+x^2)) / x^alpha <= x^((alpha-1) / 2) / x^alpha = 1 / x^((alpha+1) / 2) $ We can show $I_2$ is convergent, for $alpha<=1$, use simple inequality: $ ln(1+x^2) / x^alpha >= 1 / x^alpha >0 $ Thus $I_2$ diverges for $alpha<=1$. To sum up, $I$ converges for $1<alpha<3$. === 2(2) $ integral_0^(+oo) e^(-alpha x) sin(beta x) dif x $ + When $0<alpha_0<=alpha<+oo$: $ abs(e^(-alpha x) sin(beta x))<=e^(-alpha_0 x) $ With the fact that $integral_1^(+oo)e^(-alpha_0 x)dif x$ is convergent and Weierstrass M-test, we can show that $integral_0^(+oo)e^(-alpha x) sin(beta x) dif x$ uniformly converges. + When $0<alpha<+oo$, except for $beta=0$ (which is a trivial case), we can show that $ integral_0^(+oo)e^(-alpha x) sin(beta x) dif x $ doesn't uniformly converges (with Q3). For this question, we can actually calculate the integral: $ integral e^(-alpha x) sin(beta x) = integral Imaginary(e^(-alpha x) dot e^(i beta x)) = Imaginary(integral e^(-alpha + i beta x)) = Imaginary(-1/(-alpha + i beta)) = - Imaginary(-alpha - i beta) / (alpha^2-beta^2) = beta / (alpha^2 - beta^2) $ This would provide the same result as above. === 2(4) $ integral_1^(+oo) (ln (1+x^2)) / (x^alpha) dif x quad (1< alpha<+oo) $ This depends on Q4 as well. As shown in Q1(6), $integral_1^(+oo) (ln (1+x^2)) / (x^alpha)$ converges on $alpha>1$, but not $alpha=1$. So the integral is *not* uniformly convergent. === 2(5) $ integral_1^(+oo) e^(-alpha x) (cos x) / x^p dif x quad (0<=alpha<+oo, p>0) $ Given that $abs(e^(-alpha x)) <=1 quad forall 1<x<+oo space.quad 0<=alpha <+oo$ is decreasing and strictly bounded, we now proof $integral_1^(+oo) (cos x)/x^p dif x$ is uniformly convergent (with respect to $alpha$), which is to say we just need to prove its convergance. With these two facts, we can show that the integral is uniformly convergent using Abel's Theorem. + For $p>1$: Given $abs(integral_1^A cos x)<2$ and $1/x^p arrow.br 0$, using Dirchelet, we can show that $integral_1^(+oo) (cos x) / x^p dif x$ converges. + For $0<p<=1$, use integrate by parts: $ integral_1^(+oo) (cos x) / x^p dif x = [(sin x) / x^p]_1^(+oo) + p integral_1^(+oo) (sin x) / x^(p+1) dif x $ That turns the discussion from $p in (0,1]$ to $p+1 in (1,2]$, as above. + Another much faster solution for this: Consider splitting $x$ based on $cos x < 0$ or $cos x >0$: $ integral_1^(+oo) (cos x) / (x^p) = integral_1^(pi / 2) (cos x) / (x^p) + sum_(n=1)^oo integral_(pi / 2 + ( n-1 ) pi)^(pi / 2 + n pi) (cos x) / (x^p) $ This is a alternating series, after this step, don't use Mean Value Theorem for integrals, which you have no control of $xi_n$ over $[pi/2+(n-1)pi, pi/2+n pi]$. Instead, for each nearby interval, subtract them directly, then one would have: $ integral_(pi / 2+(n-1)pi)^(pi / 2+n pi) (cos x) / (x^p) + (cos (x+pi)) / ((x+pi)^p) >0 $ So the alternating series have a decreasing absolute value, and the integral converges. Thus for $p>0$, the integral uniformly converges. === 2(6) $ integral_0^(+oo) (sin(x^2)) / (1+x^p) dif x quad (0<=p<+oo) $ Same as above, we just prove $integral_0^(+oo) sin(x^2) dif x <+oo$, alongside the fact that $1/(1+x^p) arrow.br quad (p>0)$ (also bounded), this would enough to show uniformly convergent with Abel's Theorem. To save some time, we use the same method as above, to turn the integral to a alternating series. However directly invoking the mothod won't work: $ integral_0^(+oo) sin(x^2) = sum_(n=0)^(+oo) integral_(sqrt(n pi))^(sqrt((n+1) pi)) sin(x^2) $ Consider substitute $x^2 -> u$: $ integral_0^(+oo) sin(x^2) dif x &= integral_0^(+oo) (sin x) / (2 sqrt(x)) dif x\ &= sum_(n=0)^(+oo) integral_(n pi)^((n+1) pi) sin(x) / (2 sqrt(x)) dif x $ With the same idea, we subtract the nearby intervals: $ &quad integral_(n pi)^((n+1) pi) sin(x) / (2 sqrt(x)) dif x + integral_((n+1) pi)^(( n+2 ) pi) sin(x) / (2 sqrt(x)) dif x \ &=integral_(n pi)^((n+1) pi) sin(x) / (2 sqrt(x)) - sin(x) / (2 sqrt(x+pi)) dif x\ & > 0 $ (skipping some details.) Thus the integral converges, and uniformly converges for $p>0$. === 3 If $f(x,u)$ is continous on $a<=x<+oo, alpha<=u<=beta$. For every $u in [alpha, beta)$, integral $integral_a^(+oo) f(x,u) dif x$ converges, but not when $u=beta$, which is to say $integral_a^(+oo) f(x, beta) dif x$. Prove that $integral_a^(+oo)f(x,u) dif x$ mustn't be uniformly convergent on $[alpha, beta)$. As scary it might seems, this isn't that hard to prove. Using contradiction, let's first say $integral_a^(+oo)f(x,u) dif x$ is uniformly convergent on $[alpha, beta)$, then $forall epsilon > 0, exists X > a, forall A_1,A_2 > X &$ $ & abs(integral_(A_1)^(A_2) f(x,u) dif x)<epsilon / 2 quad forall u in [alpha, beta) $ (Cauchy Criterion for uniform convergent) Given $f(x,u)$ 's continoutiy on $[a,+oo)times[alpha, beta]$, $u->beta^-$, we have: $ forall epsilon' > 0, exists delta_u>0, forall u in (beta - delta_u, beta) quad abs(f(x,u) - f(x,beta))<epsilon' $ Take $epsilon' = epsilon/(2 (A_2 - A_1))$, then we have $ abs(integral_(A_1)^A_2 f(x,beta) dif x) &<= abs(integral_(A_1)^(A_2) f(x,u) dif x) + abs(integral_(A_1)^(A_2) f(x,beta) - f(x, u) dif x)\ &= epsilon / 2 + epsilon / (2 (A_2 - A_1)) dot (A_2 -A_1) < epsilon $ This is contradictory to $integral_a^(+oo) f(x, beta)$'s divergance, thus the original assumption is wrong, and $integral_a^(+oo) f(x,u) dif x$ mustn't be uniformly convergent on $[alpha, beta)$. == 6.14 Ans === 6 Prove that $F(alpha):=integral_0^(+oo) (cos x)/(1+(x + alpha)^2)$ is continous and differentiable on $alpha in [0, +oo)$. - Continuity: $ abs((cos x)/(1+(x+alpha)^2)) <= 1 / (1+x^2) quad x,alpha >=0 $ Since $integral_0^(+oo) 1/(1+x^2)$ is convergent, based on Weierstrass, we know that $F(alpha)$ is unifromly convergent on $[0,+oo)$, thus $F(alpha)$ is continous. - Differentiable: $ diff / (diff alpha) ((cos x) / (1+(x+alpha)^2)) = cos x dot (- (2 (x+a)) / ((1+(x+alpha)^2)^2)) $ Control the sizes: $ abs(diff/(diff alpha) ((cos x)/(1+(x+alpha)^2))) <= 2 dot (x+a) / (1+(x+alpha)^2)^2 $ Below is a solution I copied from someone's homework $ integral_0^(+oo) 2 dot (x+a) / (1+(x+alpha)^2)^2 dif x = 2 integral_a^(+oo) x / ( 1+x^2 )^2 dif x = integral_sqrt(a)^(+oo) (dif u) / (1+u)^2 <integral_0^(+oo) (dif u) / (1+u)^2 <+oo $ Based on Weierstrass, we know $integral_0^(+oo) (diff)/(diff alpha)((cos x)/(1+(x+alpha)^2)) dif x$ is uniformly convergent, thus $F(alpha)$ is differentiable on $[0,+oo)$. Note: *THIS IS WRONG*. To use Weierstrass, one would have to strictly construct a $abs(f(x,u))<g(x), forall u$, otherwise it's still pointwise than uniform. Quick way to do fix this is by comparing $(x+a)/((1+(x+a)^2)^2)$ with $x/(1+x^2)^2$, note that $x/(1+x^2)^2$ is strictly decreasing at $x>1$, so the correct way to do so is just: $ integral_1^(+oo) 2 dot (x+a) / (1+(x+alpha)^2)^2 dif x < 2 dot integral_1^(+oo) x / (1+x^2)^2 dif x $ The range for $alpha$ isn't changed here, only the starting point of the integral, unifromly convergance holds. For proof, recall: uniformly convergent $<=>$ $ lim_(A->+oo) sup_(u in [alpha, beta]) abs(integral_A^(+oo) f(x,u) dif x) = 0 $ Or if one could figure it out, use inequality like this: $ 2 dot (x+a) / (1+(x+alpha)^2)^2 <= 2 dot (x+a) / (1+(x+alpha)^4) <= 3 / (1+(x+alpha)^3) <= 3 / (1+x^3) $ The following inequality is used here: $ 3+3(x+alpha)^4>=2(x+alpha)^4+4(x+alpha)>=2(x+alpha^4)+2(x+alpha)=2(x+alpha)(1+(x+alpha)^3) $ === 7(2) $ integral_0^(+oo) (1-e^(-a x)) / (x e^x) dif x $ $ integral_0^(+oo) (1-e^(-a x)) / (x e^x) dif x &= integral_0^(+oo) (e^(-1 dot x) - e^((-a -1) x)) / (x)dif x\ &=integral_0^(+oo) dif x integral_(-a-1)^(-1) e^(k x) dif k $ $ &phi(k) = integral_0^(+oo) e^(k x) dif x = -1 / k quad k <= k_0 < 0 \ $ Consider that: $e^(k x) <= e^(k_0 x)$, also $integral_0^(+oo) e^(k_0 x) <+oo$. $phi(k)$ is uniformly convergent on $[-a-1, -1]$, thus: $ integral_0^(+oo) (1-e^(-a x)) / (x e^x) dif x &= integral_0^(+oo) dif x integral_(-a-1)^(-1) e^(k x) dif k\ &= integral_(-a-1)^(-1) phi(k) dif k\ &= [-ln (-k)]_(k=-a-1)^(k=-1) = ln(a+1) $ === 7(5) $ integral_0^(+oo) (arctan a x) / (x (1+x^2)) dif x $ $ (arctan a x) / (x (1+x^2)) &= 1 / (x (1+x^2)) arctan x u |_(u = 0)^(u=a) \ &=integral_0^a 1 / ((1+u^2 x^2)(1+x^2)) dif u $ $ phi(u) = integral_0^(+oo) 1 / ((1+u^2 x^2)(1+x^2)) dif x $ Consider $1 / ((1+u^2 x^2)(1+x^2)) <= 1/(1+x^2)$. With Weierstrass, $phi(u)$ is uniformly convergent on $[0,a]$, thus: $ integral_0^(+oo) dif x integral_0^a 1 / ((1+u^2 x^2)(1+x^2)) dif u = integral_0^(+a) dif u integral_0^(+oo) 1 / (( 1+u^2 x^2 )(1+x^2)) dif x $ $ integral_0^(+oo) 1 / ((1+u^2 x^2)( 1+x^2 )) dif x &= - u^2 / (1-u^2) integral_0^(+oo) 1 / (1+u^2x^2) dif x + 1 / (1-u^2) integral_0^(+oo) 1 / (1+x^2) dif x\ &= - u / (1-u^2) arctan u x|_0^(+oo) + 1 / (1-u^2) arctan x|_0^(+oo) \ &= pi / 2(-u / (1-u^2) + 1 / (1-u^2))\ &= pi / 2 1 / (1+u) $ So the original intergral becomes: $ integral_0^a 1 / (1+u) dif u = pi / 2 ln(a+1) $ === 7(6) $ integral_0^(+oo) [e^(-(a^2\/x^2))- e^(-(b^2\/ x^2))] dif x $ Wihtout substituting variables, after a few tries, you can see it's impossible to make the form. $ &(diff) / (diff u) e^(-u^2\/x^2) = -(2u) / x^2 e^(-u^2\/x^2)\ &(diff) / (diff u) (1 / u e^(-u^2\/x^2)) = (-(2u) \/ x^2 dot e^(-u^2\/x^2)dot u-e^(-u^2\/x^2)) / (u^2) \ &(diff) / (diff u) (u e^(-u^2\/x^2)) = e^(-u^2\/x^2) - 2u^2 / x^2 e^(-u^2\/x^2) $ Consider substitute $1\/x -> y$: $ &integral_(oo)^0 [e^(-a^2 y^2)-e^(-b^2 y^2)] (dif y) / (y^2)\ &=integral_0^(+oo) [e^(-a^2 y^2) - e^(-b^2 y^2)] / (-y^2) dif y\ $ $ (diff) / (diff v) e^(-v dot y^2) = -y^2 dot e^(-v dot y^2) $ $ [e^(-a^2 y^2) - e^(-b^2 y^2)] / (-y^2) = integral_b^a e^(-v y^2) dif v $ $ phi(v) = integral_0^(+oo) e^(-v y^2) dif y = sqrt(pi) / (2 sqrt(v)) $ $ e^(-v y^2) <= e^(-b y^2) quad forall v in [a,b] $ $ integral_0^(+oo) [e^(-a^2 y^2) - e^(-b^2 y^2)] / (-y^2) dif y = integral_(a^2)^(b^2) phi(v) dif v = sqrt(pi) dot (b-a) $ === 8(1) $ &quad integral_(-oo)^(+oo) x / (sigma sqrt(2 pi)) exp(-1/2 ((x-a)/sigma)^2) dif x \ &=integral_(-oo)^(+oo) (x+a) / (sigma sqrt(2 pi)) exp(-1/2 ((x)/sigma)^2) dif x\ &=integral_(-oo)^(+oo) x / (sigma sqrt(2 pi)) exp(-1/2 ((x)/sigma)^2) dif x + integral_(-oo)^(+oo) a / (sigma sqrt(2 pi)) exp(-1/2 ((x)/sigma)^2) dif x\ &= 0 + a / (sigma sqrt(2pi)) integral_(-oo)^(+oo) exp(-1/2 ((x)/sigma)^2) dif x\ &= a $ This is the expectation of the normal distribution, which is its mean. === 8(3) $ integral_0^(+oo) (sin a x cos b x) / x dif x &= integral_0^(+oo) (sin (a+b)x + sin(a-b)x) / (2x) dif x\ &=dcases( 1/2(pi/2 + pi/2) &= pi/2 quad & a!=b, 1/2(pi/2 + 0) &= pi/4 quad &a=b, ) $ *Note:* $ integral_0^(+oo) (sin A x) / x dif x = dcases( integral_0^(+oo) (sin A x)/(A x) dif (A x) = pi/2 quad& A!=0, 0 quad& A = 0 ) $ === 8(6) $ integral_0^(+oo) (sin^4 x) / (x^2) dif x &= integral_0^(+oo) 1 / x^2 (sin^2 x-1 / 4sin^2 2x) dif x\ &=integral_0^(+oo) ((sin^2 x) / x^2 - (sin^2 2x) / (2x)^2) dif x\ &=integral_0^(+oo) (sin^2 x) / x^2 dif x - 1 / 2 integral_0^(+oo) (sin^2 2x) / (2x)^2 dif (2x)\ &=1 / 2integral_0^(+oo) (sin^2 x) / x^2 dif x\ &=1 / 2integral_o^(+oo) sin^2 x dif (-1 / x)\ &=1 / 2[-(sin^2 x) / x |_0^(+oo) - integral_0^(+oo)2 / x sin x cos x dif x]\ &=1 / 2 integral_0^(+oo) (sin 2x) / (2x) dif (2x)\ &=pi / 4 $
https://github.com/PuntitOwO/template-informe-practica-fcfm
https://raw.githubusercontent.com/PuntitOwO/template-informe-practica-fcfm/main/README.md
markdown
MIT License
# Template Informe de práctica profesional DCC FCFM > [Typst](https://typst.app) es software relativamente nuevo que está creciendo muy rápidamente. Por esto, no puedo asegurar retrocompatibilidad entre versiones del template. Puedes ver un ejemplo de documento en [example.pdf](example.pdf). Esta es una modificación de mi template original para [propuesta e informe de memoria](https://github.com/PuntitOwO/template-informe-memoria-fcfm). ## Ejemplo de uso ```typ #import "conf.typ": conf, pronombre #show: conf.with( titulo: "El Título de mi Práctica", autor: (nombre: "Estudiante DCC", pronombre: pronombre.el), supervisor: (nombre: "Supervisora Empresa", pronombre: pronombre.ella), ) ... el resto del documento empieza aquí ... ``` Puedes ver un ejemplo más completo en [example.typ](example.typ). Para aprender la sintáxis de Typst existe la [documentación oficial](https://typst.app/docs). ## Parámetros de configuración La función `conf` recibe los siguientes parámetros: | Parámetro | Descripción | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `titulo` | El título de la práctica | | `autor` | Diccionario* con Nombre completo de estudiante y pronombre | | `practica` | 1 o 2 dependiendo de si es la primera o segunda práctica. | | `codigo` | Colocar el código del ramo de práctica. (CC4901 para práctica I, CC5901 para práctica II.) | | `ingenieria` | Colocar el nombre de la carrera. | | `correo` | Colocar el correo de autor. | | `telefono` | Colocar el número de teléfono de autor. | | `periodo` | Período en que se realizó la práctica. Por ejemplo: 'Diciembre 2022 - Enero 2023'. | | `empresa` | Nombre de la empresa. | | `supervisor` | Diccionario* con Nombre y pronombre del supervisor | | `correo-supervisor` | Colocar el correo de supervisor. | | `telefono-supervisor` | Colocar el número de teléfono de supervisor. | | `fecha` | Fecha en que se entrega el informe. Por defecto se usa la fecha actual. | | `espaciado_titulo` | espacio extra que rodea al título y al nombre en la portada, 1fr es lo mismo que el resto de espacios, 2fr es el doble, 0.5fr es la mitad, etc. | *Nota: El diccionario debe contener los campos `nombre` y `pronombre` con el nombre completo y pronombre de la persona. El pronombre puede ser `pronombre.el`, `pronombre.ella` o `pronombre.elle` y para usarse debe ser importado con `#import "conf.typ": pronombre`. Ver [example.typ](example.typ) para un ejemplo de uso. ## Cómo usar el template ### Opción 1: Usar el template de forma local [Instalar Typst CLI](https://github.com/typst/typst#installation), clonar el repositorio y trabajar de manera local en un editor. Adicionalmente, puedes instalar un [LSP](https://github.com/nvarner/typst-lsp). ### Opción 2: Usar en la app web Esta opción no se recomienda del todo, ya que no siempre estará actualizada con la última versión del template. 1. Crear cuenta o iniciar sesión en [Typst.app](https://typst.app/) 2. Abrir el siguiente [Proyecto](https://typst.app/project/rsxXr837gOiym7xg84m3e4) 3. En el [Dashboard](https://typst.app/) podrás ver el proyecto "Template Prácticas DCC FCFM" en la sección "Shared with me". Puedes presionar el botón `Duplicate` (aparece al posicionar el mouse sobre el proyecto) para crear una copia del proyecto en tu cuenta. ## Changelog ### v1.1.1 * Se ajusta el estilo de citas a `"council-of-science-editors"`, esto deja las citas contiguas como `[1, 2]` o `[1-3]` * Se arregla error en la tabla de contenido cuando se añade bibliografía. [(Issue #2)](https://github.com/PuntitOwO/template-informe-practica-fcfm/issues/2) * Se encapsula *workaround* de fecha para evitar estropear nombres como "Augusto". [(Issue #3)](https://github.com/PuntitOwO/template-informe-practica-fcfm/issues/3) ### v1.1.0 * Se actualizan los márgenes de página y la enumeración de páginas antes del inicio del contenido. ### v1.0.1 * Se añade el texto en negrita a las entradas principales de la tabla de contenido. ### v1.0.0 * Primera versión
https://github.com/fabian1409/typst-iaik-thesis-template
https://raw.githubusercontent.com/fabian1409/typst-iaik-thesis-template/master/template/thesis.typ
typst
#import "@local/iaik-thesis:0.1.0": * #show: thesis.with( title: "Title and\nSubtitle\nof the Thesis", author: "<NAME>, BSc", curriculum: "Computer Science", supervisors: ( "Firstname Lastname, academic degrees of first supervisor", "Firstname Lastname, academic degrees of next supervisor", ), acknowledgments: [ I want to take this opportunity to thank my supervisors, especially <NAME>, who answered countless questions and gave me valuable feedback during the last year. Furthermore, I want to thank <NAME>, who inspired me to take on this topic and helped me when I was stuck with a particular problem or design choice during development. Finally, I want to thank everyone who supported me during my studies and while working on this thesis. ], abstract: [ #lorem(100) #v(10pt) *Keywords.* #h(8pt) #("Broad keyword", "Keyword", "Specific keyword", "Another specific keyword").join([ $dot$ ]) ], abstract_de: [ #lorem(100) #v(10pt) *Schlagwörter.* #h(8pt) #("Broad keyword", "Keyword", "Specific keyword", "Another specific keyword").join([ $dot$ ]) ], acronyms: ( "NN": "Neural Network", "OS": "Operating System", "BIOS": "Basic Input/Output System", ), ) = Introduction <introduction> #lorem(200) *Outline.* #lorem(30) = Background <background> #lorem(200) #pagebreak() #lorem(200) = Conclusion <conclusion> #lorem(200) = Showcase This is how to cite references #cite(<doe2024dummy>). This is how to refernce labels @introduction, @equation, @table, @code, @image This is how to use acronyms #acr("NN"). == Code === Listing #listing( ```rust fn main() { println!("Hello World!"); } ```, caption: "Rust Hello World", label: <code> ) === Inline This is some inline code ```rust println!("Hello World!")```. == Lists Numbered list: + First + Second + Third Bullet list: - First - Second - Third = Figures #lorem(30) == Images #figure(image("figures/logo.svg", width: 30%), caption: "Logo") <image> == Tables #figure( table( columns: 2, [*Amount*], [*Name*], [360], [Foo], [250], [Bar Baz], ), caption: "Table example" ) <table> == Math $ "sum" &= sum_(i=1)^n i \ t_(n+1) &= t_n + 1/2 * a^2 $ <equation> #bibliography("thesis.bib")
https://github.com/fenjalien/metro
https://raw.githubusercontent.com/fenjalien/metro/main/tests/num/bracket-negative-numbers/test.typ
typst
Apache License 2.0
#import "/src/lib.typ": num, metro-setup #set page(width: auto, height: auto) #num(-15673) #num(-15673, bracket-negative-numbers: true)
https://github.com/Skimmeroni/Appunti
https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Statistica4AI/Stats4AI_notes.typ
typst
Creative Commons Zero v1.0 Universal
#set text( font: "Gentium Plus", size: 10pt, lang: "en" ) #set page( paper: "a4", header: align(right)[_Advanced Foundations of Statistics for AI_], numbering: "1" ) #set par( justify: true ) #set heading( numbering: "1." ) #import "Stats4AI_definitions.typ": * #show: thmrules.with(qed-symbol: $square$) #show par: set block(spacing: 0.55em) #outline(indent: auto) #pagebreak() = Introduction == Statistics #include "Introduction/Statistics.typ" == Probability #include "Introduction/Probability.typ" == Discrete Random Variables #include "Introduction/DiscreteRV.typ"
https://github.com/ludwig-austermann/typst-idwtet
https://raw.githubusercontent.com/ludwig-austermann/typst-idwtet/main/examples/demo.typ
typst
MIT License
#import "../idwtet.typ" #show: idwtet.init.with(eval-scope: ( funarray: ( value: {import "@preview/funarray:0.2.0"; funarray}, code: "import \"@preview/funarray:0.2.0\"" ), )) #set page(width: 16.5cm, height: auto, margin: 0.5cm) = idwtet (I Dont Wanna Type Everything Twice) A package which allows correct example demonstration, e.g. of typst packages. A `typst-ex` raw code language is defined via a show rule, which makes ````typst ```typst-ex === Hello World today is the #datetime.today() ``` ```` to generate: ```typst-ex === Hello World today is the #datetime.today() ``` The inner text is then evaluated via content mode. Similarly, we can use ````typst ```typst-ex-code #for c in range(9) { box(rect(fill: color.mix( (red, 12.5% * c), (green, 100% - 12.5% * c) ))) } ``` ```` to create: ```typst-ex-code for c in range(101) { box(height: 20pt, width: 100% / 101, fill: color.mix( (red, 1% * c), (green, 100% - 1% * c) )) } ``` by evaluating in code mode. Ultimately, using placeholders, also packages, files and variables can be loaded inside the examples, in order to create something like this: ```typst-ex-code %funarray% let numbers = (1, "not prime", 2, "prime", 3, "prime", 4, "not prime", 5, "prime") let (primes, non-primes) = funarray.partition-map( funarray.chunks(numbers, 2), // transforms (a,b,c,d,e) to ((a,b), (c,d), (e,)) x => x.at(1) == "prime", // partition criterion x => x.at(0) // map of each group ) [Of the numbers 1 to 5, the primes are #primes.] ```
https://github.com/drupol/ipc2023
https://raw.githubusercontent.com/drupol/ipc2023/main/src/ipc2023/nix-summary.typ
typst
#import "imports/preamble.typ": * #focus-slide[ #set align(center + horizon) #set text(size: 2em, fill: white, font: "Virgil 3 YOFF") What is Nix? #pdfpc.speaker-note(```md Now that the theory is done, I guess you can all answer the question right? ```) ] #slide(title: "Summary", new-section: "Nix")[ #set align(center + horizon) #uncover("1-")[ #line(length: 100%, stroke: 1pt + rgb("#eeeeee")) Nix is a set of concepts and tools to manage software and configuration in a reproducible way. #line(length: 100%, stroke: 1pt + rgb("#eeeeee")) ] #set align(left + horizon) #uncover("2-")[1. Package manager] #uncover("3-")[2. Programming language] #uncover("4-")[3. Software builder] #uncover("5-")[4. Configuration management tool] #pdfpc.speaker-note(```md As we have seen, Nix is multiple things and if I had to give a summary, it would be the following: Nix is an idea regrouping multiple abstracted concepts and concrete tools: - Nix is a package manager, - Nix is a programming language, - Nix is a software builder, - Nix is a configuration management tool. ```) ] #focus-slide[ #set align(center + horizon) #set text(size:1.8em, fill: white, font: "Virgil 3 YOFF") Is Nix complex? #pdfpc.speaker-note(```md Well, that's a good question, I think it's quite subjective and let me make my point... While it's true that working with Nix is different from coding in PHP, it's really about adopting a new perspective. For those who have some experience with functional programming, getting the hang of Nix shouldn't be too challenging. In fact, understanding Nix could only enhance your PHP development skills. To share a personal anecdote and if I had to give you a comparison with my experience, learning Nix has been quite fast even if there are still many things I don't understand. However, I still find it difficult sometimes because I don't have much knowledge in functional programming... even if I tend to improve that part lately. ```) ] #focus-slide(background-color: rgb("#111111"))[ #set align(center + horizon) #set text(size: .2em) #figure( image("../../resources/screenshots/Screenshot_20231016_134841.png"), caption: [ #link("https://main.elk.zone/vmst.io/@libreivan/111243015119696215")[https://main.elk.zone/vmst.io/@libreivan/111243015119696215] ] ) #pdfpc.speaker-note(```md Usually, I end up like Ivan on this screenshot: "WHY THIS IS NOT WORKING, I'M DOING IT EXACTLY LIKE IN THE DOCUMENTATION!"... And then.... Ah...Oh... it was just a missing semicolon... Ok the theory is done now, we can move on to the practice. I've been making a couple of pre-recorded demos that I will comment live, they are made in the context of PHP development. We'll start with the basics and gradually ramp up to more complex Nix use cases. ```) ]
https://github.com/gldraphael/typst-resume
https://raw.githubusercontent.com/gldraphael/typst-resume/main/style.typ
typst
#let body-font = "New Computer Modern" #let heading-font = "New Computer Modern Sans" #let theme-color = rgb("#1155cc")
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/spacing_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test ignored vs non-ignored spaces. $f (x), f(x)$ \ $[a|b], [a | b]$ \ $a"is"b, a "is" b$
https://github.com/almarzn/portfolio
https://raw.githubusercontent.com/almarzn/portfolio/main/templates/typst/.template/presentation.typ
typst
#import "@preview/fontawesome:0.1.0": * #import "@preview/splash:0.3.0": tailwind #let presentation-section( presentation, links ) = block( )[ #presentation #set par(linebreaks: "simple") #stack( dir: ltr, spacing: 6pt, ..links.map(el => link( el.url, block( inset: 6pt, fill: tailwind.slate-100, radius: 2pt, grid( columns: (18pt, auto), fa-icon(el.icon, fa-set: "Brands"), box(el.text) ) ) )) ) ]
https://github.com/yukukotani/typst-coins-thesis
https://raw.githubusercontent.com/yukukotani/typst-coins-thesis/main/main.typ
typst
Apache License 2.0
#import "template.typ": * #show: project.with( title: "筑波大学情報科学類の卒業論文テンプレート", author: "<NAME>", advisor: "セリヌンティウス", major: "パソコン主専攻", year: "2023", ) #abstract[ この文書は筑波大学情報学群情報科学類の卒業研究論文のサンプルである。このファイルを書き換えて、このサンプルと同様の書式の論文を作成できる。 本サンプルはGitHubリポジトリ @repo-typst-coins-thesis で配布されている。 ] #outline(indent: auto, fill: box(width: 1fr, repeat[.])) // start page number #set page(numbering: "1", number-align: center) #counter(page).update(1) = いろいろな例 ここでは、論文の表紙および本体の記述方法について述べる。 == 表 表を描画する例を @figure_table に示す。 #figure( table( columns: 2, [*西暦*], [*和暦*], [2023年], [令和5年], [2024年], [令和6年], ), caption: [表の例], ) <figure_table> == 脚注 本テンプレートはTypst #footnote[https://typst.app/] 用に作られている。 #heading(numbering: none)[謝辞] ありがとうございます #[ #set text(lang: "en") #bibliography(title: "参考文献", style:"ieee", "bib.yaml") ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/new-cm-svg_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set text(font: "New Computer Modern") #image("/assets/files/diagram.svg")
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/flywheel/identify.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator #import notebookinator: * #import themes.radial.components: * #show: create-body-entry.with( title: "Identify: Launcher Rebuild", type: "identify", date: datetime(year: 2023, month: 11, day: 28), author: "<NAME>", witness: "<NAME>", ) At our last tournament we were very unhappy with the performance of our catapult. It wasn't able to shoot the triballs far enough to cross the barrier, forcing us to consistently play the offensive side of the field. We want to redesign our shooting mechanism to be able to shoot across the field, in order to score triballs directly from the match load bar. This will make it easy for our alliance partner to play on the offensive side of the field. #image("./identify.svg") = Design Constraints Our design must be: - Shorter than the elevation bar - Only use 1 motor = Design Goals We want our new design to be able to shoot the triballs all the way across the field from the match load bar.
https://github.com/typst-community/valkyrie
https://raw.githubusercontent.com/typst-community/valkyrie/main/tests/assertions/comparative/test.typ
typst
Other
#import "/src/lib.typ" as z #import "/tests/utility.typ": * #show: show-rule.with(); #let soft-parse = z.parse.with(ctx: z.z-ctx(soft-error: true)) = Assertions/Comparative == z.assert.min #let min-number-schema(val) = z.number(assertions: (z.assert.min(val),)) #{ soft-parse(5, min-number-schema(4)) == 5 }\ #{ soft-parse(5, min-number-schema(5)) == 5 }\ #{ soft-parse(5, min-number-schema(6)) == none } == z.assert.max #let max-number-schema(val) = z.number(assertions: (z.assert.max(val),)) #{ soft-parse(5, max-number-schema(4)) == none }\ #{ soft-parse(5, max-number-schema(5)) == 5 }\ #{ soft-parse(5, max-number-schema(6)) == 5 } == z.assert.eq #let eq-number-schema(val) = z.number(assertions: (z.assert.eq(val),)) #{ soft-parse(5, eq-number-schema(4)) == none }\ #{ soft-parse(5, eq-number-schema(5)) == 5 }\ #{ soft-parse(5, eq-number-schema(6)) == none }
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/内省/here/here.typ
typst
#image("image.png") #image("image2.png")
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/perf/long.typ
typst
Apache License 2.0
#set page(height: auto) #set par(justify: true) #for i in range(5000) [ #lorem(10) #parbreak() ]
https://github.com/tibs245/template-typst-CV
https://raw.githubusercontent.com/tibs245/template-typst-CV/main/main.typ
typst
#import "template.typ": * #let skills = ( "langages": ( Typescript: ( name: "Typescript", icon: image("icons/typescript.svg", height: 1.4em) ), Javascript: ( name: "Javascript", icon: image("icons/javascript.svg", height: 1.4em) ), PHP: ( name: "PHP 5+", icon: image("icons/php.svg", height: 1em), iconInset: 0.2em), Rust: ( name: "Rust", icon: image("icons/rust.svg", height: 1.4em) ), Bash: ( name: "Bash", icon: image("icons/bash.svg", height: 1.4em) ), Powershell: ( name: "Powershell", icon: image("icons/powershell.svg", height: 1.4em) ), Python: ( name: "Python", icon: image("icons/python.svg", height: 1.4em) ), ), "front-end": ( ReactJS: ( name: "ReactJS", icon: image("icons/react-js.svg", height: 1.4em) ), VueJS3: ( name: "VueJS 3", icon: image("icons/vue-js.svg", height: 1.4em) ), VueJS2: ( name: "VueJS 2", icon: image("icons/vue-js.svg", height: 1.4em) ), Angular: ( name: "Angular 2+", icon: image("icons/angular.svg", height: 1.4em)), ReactNative: ( name: "ReactNative", icon: image("icons/react-js.svg", height: 1.4em) ), Tailwind: ( name: "Tailwind", icon: image("icons/tailwind.svg", height: 0.8em), iconInset: 0.25em), ChakraUI: ( name: "ChakraUI", icon: image("icons/chakra-ui.svg", height: 1.4em)), Pinia: ( name: "Pinia", icon: image("icons/pinia.svg", height: 1.4em)), ), "back-end": ( NodeJS: ( name: "NodeJS", icon: image("icons/nodejs.svg", height: 1.4em) ), Symfony: ( name: "Symfony", icon: image("icons/symfony.svg", height: 1.4em) ), Laravel: ( name: "Laravel", icon: image("icons/laravel.svg", height: 1.4em) ), Deno: (name: "Deno", icon: image("icons/deno.svg"), height: 1.4em), Java: (name: "Java", icon: image("icons/java.svg"), height: 1.4em), ), "test": ( Jest: ( name: "Jest", icon: image("icons/jest.svg", height: 1.4em) ), Cypress: ( name: "Cypress", icon: image("icons/cypress.svg", height: 1.2em), iconInset: 0.3em ), FakerJS: ( name: "FakerJS", icon: image("icons/fakerjs.svg", height: 1.4em) ), ), Outils: ( VSCode: (name: "VSCode", icon: image("icons/vscode.svg", height: 1.1em), iconInset: 0.1em), NextJS: (name: "nextJS", icon: image("icons/next-js.svg", height: 1.1em), iconInset: 0.1em), ViteJS: (name: "VitejS", icon: image("icons/vitejs.svg", height: 1.1em), iconInset: 0.1em), Nuxt: (name: "Nuxt", icon: image("icons/nuxt.svg", height: 1.1em), iconInset: 0.1em), Tauri: (name: "Tauri", icon: image("icons/tauri.svg", height: 1.1em), iconInset: 0.1em), Storybook: (name: "Storybook", icon: image("icons/storybook.svg", height: 1.1em), iconInset: 0.1em), Ansible: (name: "Ansible", icon: image("icons/ansible.svg", height: 1.1em), iconInset: 0.1em), ), "Organisation": ( Scrum: (name: "Scrum", icon: image("icons/scrum.svg", height: 1.4em)), Kanban: (name: "Kanban", icon: image("icons/kanban.svg", height: 1em), iconInset: 0.25em), Gitlab: (name: "Gitlab", icon: image("icons/gitlab.svg", height: 1.4em)), Jira: (name: "Jira", icon: image("icons/jira.svg", height: 1.4em)), ), "DevOPS": ( Gitlabcicd: (name: "Gitlab CI/CD", icon: image("icons/gitlab.svg", height: 1.4em)), Jenkins: (name: "Jenkins", icon: image("icons/jenkins.svg", height: 1.4em)), Docker: (name: "Docker", icon: image("icons/docker.svg", height: 1.4em)), ELK: (name: "ELK", icon: image("icons/elk.svg", height: 1.4em)), ), "OS": ( Linux: (name: "Linux (Ubuntu / Fedora)", icon: image("icons/tux.svg", height: 1.4em)), Windows: (name: "Windows", icon: image("icons/windows.svg", height: 1.4em)), Android: (name: "Android", icon: image("icons/android.svg", height: 1.4em)), ), "Cloud": ( AWS: (name: "AWS", icon: image("icons/aws.svg", height: 0.8em), iconInset: 0.4em), "Google Cloud": (name: "Google Cloud", icon: image("icons/google-cloud.svg", height: 1.4em)), OVH: (name: "OVH", icon: image("icons/ovh.svg", height: 1em), iconInset: 0.25em), ), "SGBD": ( PostgreSQL: (name: "PostgreSQL", icon: image("icons/postgresql.svg", height: 0.8em), iconInset: 0.4em), MySQL: (name: "MySQL", icon: image("icons/mysql.svg", height: 0.8em), iconInset: 0.4em), Firestore: (name: "Firestore", icon: image("icons/firestore.svg", height: 1.4em)), MongoDB: (name: "MongoDB", icon: image("icons/mongodb.svg", height: 1em)), ElasticSearch: (name: "ElasticSearch", icon: image("icons/elasticsearch.svg", height: 1em)), Kafka: (name: "Kafka", icon: image("icons/kafka.svg", height: 1em)), RabbitMQ: (name: "RabbitMQ", icon: image("icons/rabbitmq.svg", height: 1em)), ) ); // It's to choose skills easiers #let skillsValues = skills.values().join() // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( title: "DOSSIER DE COMPÉTENCES", author: yaml("author.yml"), skills: skills ) = EXPÉRIENCES PROFESSIONNELLES #mission( [BearStudio <bearstudio>], role: "Développeur Senior", beginingDate: "juin 2021", endDate: "décembre 2022", duration: "1,5an", contexte: [ Le BearStudio avait besoin d'un développeur supplémentaire pour développer leurs projets. J'ai partager mon expérience, encadrer des juniors et rempli mes missions en autonomie a la fois en interne et en régie pour #link(<magnolia>, [Magnolia]). ], missions: [ - #linkLabel([Mission en régie de 7 mois chez Magnolia], <magnolia>) - Développement projets ReactJS / TypeScript - Développement application tablette avec React Native - Développement extension Boondmanager avec NextJS / ReactJS / TypeScript - Conception des projets et mise en place des types TS de bases - Migration d'un projet Angular a React - Mise en place de bonne pratique pour renforcer la sécurité des projets - Suivi projets interne développé par des juniors - Développement thème Wordpress avec intégration stripe personnalisé - Renfort développement fonctions API JAVA - Installation du réseau de l'entreprise ], skillsConcerned: ( skillsValues.Typescript, skillsValues.ReactJS, skillsValues.NextJS, skillsValues.VueJS3, skillsValues.ReactNative, skillsValues.PHP, skillsValues.NodeJS, skillsValues.MySQL, skillsValues.Gitlabcicd, skillsValues.Docker, skillsValues.Storybook ) ) #mission( [Magnolia.fr <magnolia>], role: "Lead Dev en régie 4/5 jours semaine", beginingDate: "mars 2022", endDate: "décembre 2022", duration: "9mois", contexte: [ #link(<bearstudio>, [Au sein du BearStudio]), j'ai fait une prestation de 9 mois en régis chez Magnolia de 4 à 5 jours/semaine. Suite au départs des Lead-dev ainsi de la loi lemoine qui augmente les opportunités du marché de Magnolia.fr. J'ai eu l'occasion d'intervenir avant de remplacé le lead-dev front. De cette manière j'ai participé à faire grandir l'équipe afin de répondre aux besoins métiers dans un moment important de leur développement. ], missions: [ - Remplacement des tech lead suite à leurs départs - Gestion projet interne pour automatiser et suivre les résiliations de contrats (Scrum) - Suivi de la qualité du projet - VueJS 3 - PHP symfony - Amélioration / Maintien du site vitrine - Amélioration SEO - Modification sur le formulaire de comparaison - Amélioration de la robustesse du site lors de forte influence - Mise en place de l'amélioration de la Définition of Done des projets - Mise en place des CI / CD des projets - Dockerisation des projets pour réduire le temps d'installation et l'uniformisation des environnements des développements - Etude de la MAJ de Gitlab de la v9 à la v13 - Mise en place de Cloudwatch sur les logs des APIs ], skillsConcerned: ( skillsValues.Javascript, skillsValues.Typescript, skillsValues.VueJS3, skillsValues.VueJS2, skillsValues.ViteJS, skillsValues.PHP, skillsValues.Symfony, skillsValues.MySQL, skillsValues.Gitlabcicd, skillsValues.Docker, skillsValues.Jira, skillsValues.Scrum, skillsValues.AWS ) ) #mission( [Sweeflow], role: "Co-Fondateur / Principal développeur", beginingDate: "Janvier 2020", endDate: "juin 2021", duration: "6 mois", contexte: [ J'ai souhaité lancer un produit avec un associé. Ce produit consistait à améliorer au mieux les flux d'entreprise. Et donc facilité les gestions de tâches au quotidien et de diminuer les étapes manuelle. Pour cela j'ai développé un POC en VueJS2 et Nuxt avec un back en NodeJS/Express lié à un Firestore. Pour des raisons d'une stratégie commercial pas assez élaboré dans les temps. J'ai souhaitez quitter le navire avant d'avoir trop de risque de m'endetter. ], missions: [ - Création d'un projet VueJS (2) - Utilisation de Google Cloud et de son service Cloud Run - API en microservice NodeJS - Déploiement automatique et suivi de qualité de code via Gitlab - Formation / Suivi projet du développement (1 développeur junior) - Utilisation de Firebase ], skillsConcerned: ( skillsValues.Javascript, skillsValues.Typescript, skillsValues.Gitlabcicd, skillsValues.Docker, skillsValues.VueJS2, skillsValues.Nuxt, skillsValues.NodeJS, skillsValues.Firestore, skillsValues.at("Google Cloud"), ) ) #mission( [SII ROUEN <SII>], role: "Ingénieur Etudes & Développements", beginingDate: "mai 2018", endDate: "décembre 2020", duration: "1 an", contexte: [ #link(<bearstudio>, [Au sein du BearStudio]), j'ai fait une prestation de 9 mois en régis chez Magnolia de 4 à 5 jours/semaine. Suite au départs des Lead-dev ainsi de la loi lemoine qui augmente les opportunités du marché de Magnolia.fr. J'ai eu l'occasion d'intervenir avant de remplacé le lead-dev front. De cette manière j'ai participé à faire grandir l'équipe afin de répondre aux besoins métiers dans un moment important de leur développement. ], missions: [ - #linkLabel([Mission en régie 1 an chez SFR], <sfr>) - #linkLabel([Mission en régie 1 an chez Orange], <orange>) - Animation d’une conférence sur la sécurité « by design » (Avril 2019) - Animation d’un Mob Programming en 2018 - Création d’une offre de service - Présention DevOPS - Démonstration d'une solution à partir de Gitlab et ses outils de pipeline pour automatiser la chaîne d'intégration et de déploiement (CI/CD) continu sur un projet JavaScript basique. - Intégration des outils d'analyse de code - Vérification des packages - Sécurisation des données de production dans les "variables secrètes" de Gitlab - Cloisonnement par Docker - Déploiement automatique et sécurisation des accès ], skillsConcerned: ( skillsValues.Javascript, skillsValues.Typescript, skillsValues.Gitlabcicd, skillsValues.Docker, skillsValues.Scrum, ) ) #mission( [SFR <sfr>], role: "Ingénieur Etudes & Développements", beginingDate: "septembre 2019", endDate: "décembre 2020", duration: "+1 an", contexte: [ #link(<SII>, [Au sein du SII]), j'ai fait une prestation de 15 mois en régis chez SFR de 5 jours/semaine. Ma mission été essentiellement plus de l'ordre réseau et gestion de projet. Le développement étant moins présent sur cette mission. _(\~3mois de PHP)_ Elle été pour moi l'occasion d'avoir un poste différent qui correspond à ma polyvalence et de progresser sur la gestion de projet. ], missions: [ - Projet :Migration d'un serveur RADIUS - Prise de connaissance de l'actuel - Création maquette pour la migration - Étude des prix matériel et humain pour la migration - Étude de l'impact sur le réseau de la migration - Mise en place des procédures logiciel / matériel et réseau - Mise en application de la procédure logiciel - Suivi du projet - Création de la documentation - Mise en place d’un outil d’observabilité (ELK) pour le nouveau service radius - Projet : Migration API SOAP JAVA à PHP pour assurer une meilleure maintenabilité - Étude de faisabilité - Développement de la nouvelle API ], skillsConcerned: ( skillsValues.PHP, skillsValues.Java, skillsValues.Docker, skillsValues.ElasticSearch, skillsValues.ELK, skillsValues.Linux, ) ) #mission( [Orange <orange>], role: "Développeur FullStack", beginingDate: "mai 2018", endDate: "décembre 2020", duration: "1 an", contexte: [ #link(<SII>, [Au sein du SII]), j'ai fait une prestation de 1 an en régis chez Orange de 5 jours/semaine. Orange utilise une application de plus de 10ans qui à évoluer grâce au développement qu'un de ses managers à entreprit pour facilité son travail. Avec le temps, tout les managers utilises cette application. Des ajouts de fonctionnalités importantes étant souhaités par les managers. Il ont eu pour souhait de prendre un prestataire afin d'assurer le développement de ces derniers et d'assurer sa maintenabilité. L'enjeu était d'utiliser le code ancien tout en adoptant une structure moderne sur les nouvelles fonctionnalités. ], missions: [ - Développement de l’application WEB en VueJS et PHP (Zend Framework) - Création de services web « API REST PHP » consommé par le front en VueJS - Synchronisation de fichiers XLS avec la base de données - Modules de synchronisations BDD <-> Flux CFT - Génération de fichiers géoJson _(liaison des communes pour l’organisation Orange avec l’INSEE)_ - Intégration d'une application moderne en VueJS2 sur une application existante. - Création d’une carte interactive avec Leaflet - Système de gestion des techniciens - Système de gestion des plannings - Système de gestion des zones de couvertures - Système d’administration - Utilisation du thème Vuetify - Gestion de mise en cache des données _(Vuex, maintenant appelé Pinia)_ - Rédaction documentations techniques - Rédaction guide utilisateur - Formation d’un ingénieur sur VueJS2 - Maintenance et création d’un composant - Principe de la séparation de l’application Client / Serveur - Utilisation des services - Utilisation de Vuex (Store local) ], skillsConcerned: ( skillsValues.Javascript, skillsValues.VueJS2, skillsValues.Pinia, skillsValues.PHP ) ) #mission( [Ofelias <ofelias>], role: "Ingénieur DevOPS", beginingDate: "Août 2017", endDate: "janvier 2018", duration: "6 mois", contexte: [ Ofélias été une entreprise de sous-traitance de support informatique afin de permettre au PME d'avoir un support IT pour un coût moins élever qu'avec un salarié à plein temps chez eux. Cela se traduit aussi avec beaucoup d'intervention qui se ressemble. Donc dans l'optique de réduire encore les coûts des parcs informatiques sous leurs responsabilités. Il ont fait appel à moi afin d'automatisé les tâches répétitive. De plus cela leur à permis de répondre à quelques besoins de développement de leurs clients ], missions: [ - Optimisation des processus de maintenance client - Apporter une culture de l’automatisation - Optimiser le temps de travail des techniciens d’Ofelias. - Automatisation des tâches via des scripts Powershell - Modifier et traiter des fichiers Excel - Création d’une application interne en Angular 4 et NodeJS permettant la traçabilité des activités des techniciens - Hébergement de l’application sous Linux Debian, Apache, Node JS - Création et modification d’extension WordPress en PHP \ - Mise en Réseau pour Normandie WebSchool - Analyse de l’état de l’art en vue de la création du Système d’Information sous Windows Server, Hyper V, Active Directory et via les problématiques de Mappage Réseaux - Création d’un serveur interne, de 3 réseaux distincts (réseaux Élèves, Professeurs & Administration), de 3 bornes Wi-Fi et d’un portail de connexion - Mise en place du pare feu via PfSense - Configuration du réseau intranet (Mappage Réseaux) - Mise en place des règles de sécurité via PfSense, Active Directory. ], skillsConcerned: ( skillsValues.Typescript, skillsValues.Angular, skillsValues.PHP, skillsValues.NodeJS, skillsValues.Linux, skillsValues.Windows, skillsValues.Powershell ) ) #mission( veryLong: true, [Bearstudio 2015 <bearstudio2015>], role: "Co-Fondateur - Développeur FullStack - DevOPS", beginingDate: "Novembre 2015", endDate: "Mai 2017", duration: "1 an et 7 mois", contexte: [ Suite à la rencontre avec mes associés. J'ai eu l'occasion de co-fondé le Bearstudio. *Son but :* Apporté une équipe technique pour les entreprises et projets qui souhaites développer une solution numérique. Mes casquettes été multiple. Et nous avons beaucoup d'enjeux puisque nous avons plusieurs projets développer en même temps afin de sécurisé le développement de l'entreprise. #set list(indent: 2em) - 60% Développement Full-Stack - 30% DevOps / Sysadmin - 10% Entreprenariat Cette expérience m'a apporté beaucoup. Nous avons commencé à 3 et lorsque je suis parti nous étions 5. Après plus d'un an. J'ai eu le souhaits de découvrir les stuctures plus traditionnel lorsque j'ai eu l'occasion afin d'affiner ma vision du monde de l'entreprise. #linkLabel([Vous pouvez aussi voir dans ce CV que je suis revenu pendant +1 ans en 2022], <bearstudio>) ], missions: [ #block(breakable: false, [ - *Interne* - *Enjeu :* Développer les outils internes afin de développeur en interne éfficacement et rapidement. - Au niveau de l’équipe : 5 collaborateurs graphistes, intégrateurs et développeurs. - Mise en place des Intégrations continu avec Jenkins - Administration et maintenance sous Linux Debian de la quinzaine de VM installées sur les serveurs physiques avec un système Proxmox - Déploiement de masse avec Ansible - Monitoring des 120 services hébergés via Shinken (dérivé de Nagios) - Vérification de la qualité de développement à partir des merges request ]) \ - *Assystem* - #linkLabel([Développement en régie 4 jours/semaines chez Assystem], <assystem>) #block(breakable: false, [ - *Projet METIGATE* - *Enjeu :* Optimiser la météo-dépendance d’une entreprise. - Création de l’importation des données publiques météo dans la base de données - Serveur RabbitMQ gérant 3 services indépendants afin d’importer cette donnée - Implication de 4VM ainsi que d’une importante chaîne d’automatisation via Jenkins - Maintenance de leur API en Java, MySQL, Docker - Optimisation des performances de l’API - Développement de leur projet « WeatherToAction » sous Angular JS - Suivi & Conseil au long du développement de leur application - Monitoring et exploitation des logs de leurs applications - Installations automatisées de leurs services via Ansible ]) \ #block(breakable: false, [ - *Projet MARCHE-PRIVE* - *Enjeu :* Optimiser le site E-commerce de la société Marché-Privé qui a pour objectif de créer le contact entre l’artisan et le client. - Migration de serveurs (Linux Debian) et d’applications web - Audit de l’état de l’art (Logiciel Proxmox) et mise en place des nouvelles configurations logicielles - Réinstallation de Proxmox et de 3 nouvelles VM - Refontes de leurs règles « iptables » (règles de pare-feu) - Installation des services de production via PHP, Apache et MySQL - Mise à jour des scripts de backup et de reports via logwatch - Consultation sur les aspects Développement et Système en PHP (symfony 3, Twig), Apache, MySQL ]) \ #block(breakable: false, [ - *Projet POWERTRAFFIC* - *Enjeu :* Développement d’une application permettant de proposer des solutions de monitoring de leur visibilité internet, en utilisant des API Google. - Formation des développeurs de Powertraffic sur les activités de développement et de déploiement de l‘application - Consultation sur les aspects Développement en PHP, Apache, MySQL - Utilisations des API externes (API SemRush) ]) \ #block(breakable: false, [ - *Projet HOLIBAG* - *Enjeu :* Consigner ses affaires personnelles auprès des commerçants en un laps de temps réduit : moins de 72 heures. - Audit de l’état de l’art en API Python v2 - Première version de leur application front sous Angular JS et Pug ]) ], skillsConcerned: ( skillsValues.Javascript, skillsValues.Angular, skillsValues.Gitlab, skillsValues.Jenkins, skillsValues.Docker, skillsValues.ElasticSearch, skillsValues.PHP, skillsValues.Symfony, skillsValues.MySQL, skillsValues.Kanban, skillsValues.Scrum, skillsValues.RabbitMQ, skillsValues.Python, skillsValues.Linux, skillsValues.Ansible ) ) #mission( [Assystem <assystem>], role: "Développeur Front-end", beginingDate: "Février 2016", endDate: "Mai 2016", duration: "4 mois", contexte: [ #link(<bearstudio2015>, [Au sein du BearStudio]), j'ai fait une prestation de 4 mois en régis chez Assystem de 4 jours/semaine. Nous avions des compétences en AngularJS et Assystem avais des enjeu lors de la conception d'une application avec ce langages récent. J'ai donc participé au début de ce projet en tant que prestation. Le but de ce projet étant la création d’applications sur la qualité nucléaire afin d’optimiser les enjeux de sécurité et d’intégrité des données ], missions: [ - Supervision de l’architecture AngularJS afin d’organiser le projet - Formation des stagiaires et des collaborateurs en Angular JS - Livraison de la première version ], skillsConcerned: ( skillsValues.Javascript, skillsValues.Angular, ) ) #mission( veryLong: true, [Bonus <bonus>], role: "Développeur Front-end", beginingDate: "Mai 1995", endDate: "Présent", duration: "28 ans", contexte: [ Je suis un grand passionné de l'informatique depuis toujours. De plus j'ai une activité d'auto-entrepreneur depuis le début de ma vie active. Cela inclut des petites activités annexes pour des missions et pour le loisir. Je les inclus ici afin de vous permettre d'avoir un visu ], missions: [ - *Passtauri* _Début en mai 2023_ - Projet libre avec Tauri utilisant Rust et NextJS - Versionning sur github : #link("https://github.com/tibs245/passtauri") - Utilisation de Rust - Chiffrage / Déchiffrage des mots de passe via GPG - *Formations* _(En tant que intervenant)_ - Cours Docker chez SUPINFO en 2019 et 2020 - Cours sur le déploiement automatique _(Ansible, Puppet, Chef)_ en 2019 et 2020 - Cours sur ReactJS et NextJS chez NeedForSchool en 2023 - *Hébergement et maintien d'un serveur familliale* _Depuis 2016_ - Hébergement mail (D'où le kolombo.fr) - Hébergement de plusieurs services internes dont Gitlab et Nextcloud - *Développement et hébergement de quelques applications WEB* - Via missions freelance courtes - *Electronique* - Système de lumière avec un éclairage bande LED avec des ESP8266 que j'ai pour but d'upgrade avec des LED (ws2812b) combiné à des ESP32 pour diminuer légèrement la consommation de veille et donc recharger moins souvent les batteries. - Le but étant de mettre de l'éclairage sur des meubles en hauteur sans prises et ne pas avoir de câble apparent - Même système très utile pour les décorations de Noël - La partie ESP32 n'a jamais pu être finalisé parce que je souhaites une vrai app avec #link("https://github.com/BearStudio/start-ui-native", [Start-UI Native]) sur lequel j'ai participer à l'implémenté le Bluetooth mais le framework graphique a des problème de performance depuis +1ans - Pédagogie pour enfants avec un Microbit - Intéraction entre application React Native et un Microbit - Système de caméra surveillance avec un Raspberry pi et des caméra Eye toy play - Automatisation de taches avec Automate et Ntag215 - Impression 3D (J'ai eu une imprimante Artillery 3D Sidewinder 2ans) qui m'a servi essentiellement à imprimer des choses pour les autres - Concernant les Raspberry Pi j'ai tout les modeles, ils m'ont servi à faire des proxys, des systèmes multimédia pour diffuser de la musique via le WIFI (avant le chrome cast audio), à faire du monitoring et à connecter des imprimantes aux wifis. - Capteur de profondeur avec des ultrasons - Début de projets de détection d'humidité / température / CO² dans les pièces. Pas encore sorti de ma tête ], skillsConcerned: ( skillsValues.Javascript, skillsValues.Typescript, skillsValues.Deno, skillsValues.ReactJS, skillsValues.NextJS, skillsValues.Cypress, skillsValues.ReactNative, skillsValues.Rust, skillsValues.PHP, skillsValues.Linux, skillsValues.Docker, skillsValues.Ansible ) ) = Formations et Langues - 2015 – Analyste développeur à l’Exia Cesi – Mont-Saint-Aignan - 2013 – Bac professionnel SEN _(Système Électronique et Numérique)_ au lycée GRIEU à Rouen Anglais technique : lu et écrit
https://github.com/Tran-Thu-Le/typst-collection
https://raw.githubusercontent.com/Tran-Thu-Le/typst-collection/main/multi-files-reference/main.typ
typst
#import "multi-ref.typ" = How to cite references on multiple files For the current version of Typst (05/06/2024), one cannot cite references on different Typst files. This folder show you how to hack this using file name `multi-ref.typ`. In the following, you can see that the references were displayed properly. #include "file1.typ" #include "file2.typ" #bibliography("ref.bib")
https://github.com/jneug/typst-nassi
https://raw.githubusercontent.com/jneug/typst-nassi/main/tests/template.typ
typst
MIT License
#import "src/nassi.typ" #nassi.diagram({ nassi.elements.process("Hello World") })
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/radial/components/tournament.typ
typst
The Unlicense
#import "../colors.typ": * /// A Series of tables displaying match data from a tournament. Useful for tournament analysis entries. /// - ..matches (dictionary): A list of all of the matches at the tournament. /// Each dictionary must contain the following fields: /// - match (string) The name of the match /// - red-alliance `<dictionary>` The red alliance /// - teams `<array>` /// - score `<integer>` /// - blue-alliance `<dictionary>` The blue alliance /// - teams `<array>` /// - score `<integer>` /// - won `<boolean>` Whether you won the match /// - auton `<boolean>` Whether you got the autonomous bonus /// - awp `<boolean>` Whether you scored the autonomous win point /// - notes `<content>` Any additional notes you have about the match /// -> content #let tournament(..matches) = { for match in matches.pos() { let color = if match.won { green } else { red } let cell = rect.with(fill: color.lighten(80%), width: 100%, height: 30pt) let header-cell = cell.with(fill: color, height: 20pt) let alliance-info(alliance: none) = { cell[ #grid( columns: (1fr, 1fr), [ #alliance.teams.at(0) \ #alliance.teams.at(1) \ ], [ #set text(size: 15pt) #set align(horizon + center) #alliance.score ], ) ] } let bool-icon(input) = { cell[ #set align(horizon + center) #if input { image("../icons/check.svg", width: 1.5em) } else { image("../icons/x.svg", width: 1.5em) } ] } box( grid( columns: (1fr, 1fr, 1fr, 1fr, 1fr), header-cell(radius: (top-left: 1.5pt))[*Match*], header-cell[*Red Alliance*], header-cell[*Blue Alliance*], header-cell[*Auton Bonus*], header-cell(radius: (top-right: 1.5pt))[*AWP*], cell[#match.match], alliance-info(alliance: match.red-alliance), alliance-info(alliance: match.blue-alliance), bool-icon(match.auton), bool-icon(match.awp), ), ) if not match.at("notes", default: none) == none [ === Notes #match.notes ] else [ ] } }
https://github.com/Wuvist/typstnotes
https://raw.githubusercontent.com/Wuvist/typstnotes/main/README.md
markdown
# Typst notes some random staff to make writing typst paper easier * `pandoc_tpl.typ` Make pandoc convert ipynb to typst nicer ```bash pandoc -t typst --template=pandoc_tpl.typ --extract-media ./media test.ipynb -o test.typ ```
https://github.com/Error-418-SWE/Documenti
https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/3%20-%20PB/Documentazione%20interna/Verbali/24-04-07/24-04-07.typ
typst
#import "/template.typ": * #show: project.with( date: "07/04/24", subTitle: "Meeting di retrospettiva e pianificazione", docType: "verbale", authors: ( "<NAME>", ), timeStart: "15:10", timeEnd: "16:00", ); = Ordine del giorno - Valutazione del progresso generale; - Analisi retrospettiva; - Candidatura per sostenere il primo colloquio della Product Baseline; - Predisposizione della presentazione per primo colloquio della Product Baseline; - Pianificazione. = Valutazione del progresso generale Lo Sprint 22 si conclude con il completamento dei task pianificati, rispecchiando quanto impostato all'interno dello Sprint Backlog. == #adr In data 03/04/24 il #cardin ha espresso giudizio positivo in merito all'espansione apportata al documento #adr_v, ritenendo comprese le mancanze individuate nella versione del documento consegnato in RTB, e la sua espansione soddisfacente. Tale risultato ha permesso al gruppo di procedere alla candidatura per il colloquio della Product Baseline. Il documento, pertanto, è ritenuto concluso nella sua interezza e non sarà oggetto di ulteriori modifiche di carattere contenutistico. == #st Il documento #st_v è stato redatto nella sua interezza. In particolare: - riorganizzata la struttura della sezione _Tecnologie_; - correzione titolo sezione _DataRepository Pattern_. Il documento, a seguito delle modifiche apportate, è ritenuto concluso e non sarà oggetto di ulteriori modifiche di carattere contenutistico. == #pdq A seguito dell'aggiornamento della versione di Typst, è stata ridefinita la struttura delle tabelle presenti all'interno del documento #pdq, le quali presentavano errori di formattazione. Le metriche di qualità sono state aggiornate, in particolare: - aggiornamento dei grafici delle metriche per lo Sprint 22; - aggiornamento della dashboard con i dati sullo Sprint 22. == #pdp Il documento #pdp è stato aggiornato con le informazioni relative allo Sprint 22, in particolare: - redazione preventivo Sprint 22; - redazione consuntivo Sprint 22. == #ndp La revisione del documento di #ndp è stata completata, in particolare i paragrafi: - Transition process; - Integration process; - Implementation process; - Quality management process; - Verification process; - Validation process. Il documento, per quanto ritenuto concluso con la redazione dei paragrafi derivanti dallo standard ISO/IEC 12207:2017 e la loro revisione, sarà oggetto di un ulteriore controllo di conformità prima della consegna. = Analisi retrospettiva Lo Sprint 22 è terminato con il raggiungimento della totalità degli obiettivi prefissati. Il rendimento positivo dello Sprint è sostenuto dalle principali metriche esposte dal #pdq_v: - CPI di progetto a 1.00, che rappresenta un avanzamento positivo del progetto, con valore superiore alla soglia di accettabilità; - EAC diminuisce passando da € 13.010,59 a € 12.992,10 rientrando ampiamente nel budget previsto; - $"SEV" >= "SPV"$, come testimoniato anche dalla metrica CPI, che indica un avanzamento positivo del progetto. == Keep doing Il gruppo, ormai prossimo alla conclusione del progetto, ha raggiunto, come anche espresso dalle retrospettive precedenti, una soddisfacente capacità di lavoro in modalità asincrona. Il gruppo è altresì soddisfatto del feedback ricevuto dal #cardin in merito al documento #adr_v, che ha permesso di procedere con la candidatura per il colloquio della Product Baseline. == Improvements === Criticità evidenziate *P01*: A seguito delle festività pasquali (Pasqua e Pasquetta), si è rilevato un leggero calo del rendimento produttivo del gruppo. Tale rallentamento però, non ha compromesso il raggiungimento degli obiettivi prefissati, pertanto non è ritenuto necessario intervenire con azioni correttive. == Candidatura per sostenere il primo colloquio della Product Baseline A seguito di: - valutazione positiva del #cardin in merito al documento #adr_v; - approvazione da parte del Proponente del MVP prodotto in data 26/03/24; - redazione completata del documento #st_v. Il gruppo si è candidato in data 04/04/24 per sostenere il primo colloquio della Product Baseline, fissato per mercoledì 10/04/24 alle ore 8:40. == Predisposizione della presentazione per primo colloquio della Product Baseline Durante il meeting è stata oggetto di discussione la predisposizione della presentazione per il primo colloquio della Product Baseline. La presentazione sarà strutturata in modo da esporre i principali punti del documento #st_v, in particolare: - introduzione; - tecnologie utilizzate; - architettura implementativa (e design pattern); - architettura di deployment. Individuati gli argomenti principali, il gruppo si è suddiviso i compiti per la redazione della presentazione, valutando i tempi necessari per trattare i diversi argomenti in relazione alla durata limitata del colloquio. Nelle date 08/04/2024 e 09/04/2024 verranno eseguite le prove generali della presentazione. == Pianificazione #let table-json(data) = { let keys = data.at(0).keys() table( align: left, columns: keys.len(), ..keys, ..data.map( row => keys.map( key => row.at(key, default: [n/a]) ) ).flatten() ) } #figure(caption: [Task pianificate per lo Sprint 23.], table-json(json("tasks.json")) )
https://github.com/SkytAsul/fletchart
https://raw.githubusercontent.com/SkytAsul/fletchart/main/examples/declarative.typ
typst
#import "../src/lib.typ" as fletchart #import fletchart.elements: action, condition, choice, input-output, process #import fletchart.declarative: fc-declarative #fc-declarative({ let actionA = action("a", "A", fill: color.fuchsia) let actionB = action("b", "B", destination: actionA) let actionC = action("c", "C", destination: "a") let actionD = action("d", "D", type: input-output) condition("x", "X", choice(actionC), choice(actionB), choice(actionD)) actionC actionB actionA actionD }, elements-style-override: (process.name: (fill: color.orange)), debug: true)
https://github.com/rlpundit/typst
https://raw.githubusercontent.com/rlpundit/typst/main/Typst/en-Report/chaps/chpt2.typ
typst
MIT License
/* --------------------------------- DO NOT EDIT -------------------------------- */ #import "../Class.typ": * #show: report.with(isAbstract: false) #chap(chap2) // Chapter 2 #set page(header: smallcaps(title) + h(1fr) + emph(chap2) + line(length: 100%)) /* ------------------------------------------------------------------------------ */ == Introduction <chp:chap2> #lorem(32) == Section 1 #lorem(16) === Subsection 1.1 #lorem(64) === Subsection 1.2 #lorem(64) == Section 2 #lorem(16) === Subsection 2.1 #lorem(64) === Subsection 2.2 #lorem(64) == Conclusion #lorem(32)
https://github.com/Personal-Data-Acquisition/PDA_paperwork
https://raw.githubusercontent.com/Personal-Data-Acquisition/PDA_paperwork/main/SDA/sda.typ
typst
= Software Design and Architecture Document (SDA) #strong[Authors:] <NAME>, <NAME>, <NAME>, <NAME> #strong[DATE:] 2023-12-03 == Introduction This document establishes the software and hardware architecture for a personal data acquisition system. Selecting the correct architecture improves development velocity and enables more robust functionality by having systems that support each other. Cohesive Software Architecture is particularly important for this project as our workflow has contributors split into two sub teams which are developing a frontend and backend that must communicate. In addition to that, designing an appropriate hardware architecture will reduce development costs and help our product find its place in the market. == Architectural Goals and Principles Our hardware and software architectures have the primary goal of being synergistic with each other and possessing libraries that interface with each other. Because our project covers layers ranging from hardware to a website, connection throughout the stack is critical. Additionally, as we work through the prototyping stage our architecture will practice modularity to be able to add new sensor hardware as we expand the capabilities of the product. Our architecture does not need to prioritize scalability as the final objective is only to develop a prototype. == System Overview #figure([#box(width: 300.0pt, image("SystemOverview.png"));], caption: [ image ] ) == Architectural Patterns Controller Responder: This pattern is useful as our hardware SBC can act as the controller which has a single responder in the user webpage. This pattern would help cache data generated by the controller to provide a seamless experience to the user in the face of latency issues. Additionally, the ability to access data in the responder without affecting the controller will allow for computation in an environment separate from the hardware board. Event Sourcing: This pattern works especially well with real-time data, which is what this project is all about. Our hardware controller can act as the producer and broadcast its data to a web server which will act as the event source for an y users that want to query the server and consume that data. The fail-safety of this design is also important to this project as data acquisition environments, such as racing or aeronautics, often cause damage to the controller while still requiring data to be accessible. == Component Descriptions #strong[Sensors:] Hardware components that acquire the raw data, such as accelerometers o r GPS devices. #strong[Microcontroller:] Small computer that is responsible for coordinating the sensors and collecting their data to be broadcast to the web server. #strong[Web server:] Acts as the intermediary between the user and the physical acquisition device. Communicates with the board, composed of the microcontroller and its sensors, to collect data which it then relays to the user interface when queried. #strong[User interface:] An HTTP webpage that requests data from the web server to present in useful ways to the user. == Data Management Sensor readings are transmitted over canbus in JSON format. Data is stored in a relational database on the Raspberry Pi. RESTful API endpoints are provided for CRUD operations on data. == Interface Definitions There will be a user interface to collect data from each sensor and display it to the user. There will be interactions to get event logs from each sensor, and to clear the event logs. The user interface will be hosted on a web server, which users will connect to over with their browser over HTTP. API endpoints for the web interface include: - `GET /data`: Returns a list of collected data from personal devices. \ - `GET /sensors`: Returns a list of sensor configurations. \ - `POST /data`: Allows the addition of new data. \ - `PUT /data/{id}`: Updates data with a specified ID. \ - `PUT /sensors/{id}`: Configure a sensor with a specific ID. \ - `DELETE /data/{id}`: Deletes data with a specified ID. == Considerations === Security The primary data security risk in this project is data loss due to physical conditions of the board. This includes both permanent damage through the elements or impacts as well as location preventing broadcast to the web server. A caching system on both the board and in the web server is the approach that will be used to mitigate this risk. The data security risks due to bad actors in this project are minimal as the data being processed is kinematic information. Regardless, our web server will require password authentication to access the RSA encrypted data. === Performance There are two primary performance concerns of the product. The first is the resolution of our data and how quickly we can poll our sensors, for which the current target is acquiring 10 data points per second. We plan to achieve this metric by screening hardware before they are implemented into the design to ensure it can meet this desired performance. The second concern is with the stability of the connection between the user interface and the board’s raw data. We plan to create a web server that will be able to cache the data produced by the board and present to the user at will to mitigate this concern. === Maintenance and Support Once the prototype is complete, maintenance and development will be inherited by <NAME>, the company partner for this project. The company has a background in aeronautics, competitive motor racing, and computer assisted physics, all of which are relevant to the project area. Their experience with the common end users of personal data acquisition devices makes them very capable of supporting users through the life cycle of the product. == Deployment Strategy As the ultimate objective for this project is to develop a prototype PCB that hosts a local webserver as a user interface, there is only deployment in a development environment. == Testing Strategy === Software (SBC side) Testing User testing will be done to ensure users can understand and use the interface effectively. These tests should be focused on confirming that functional requirements are met. Integration testing will be done with mock data until microcontrollers and sensors are operational. Further tests will be conducted when hardware is more complete. === Firmware Testing Our firmware testing methodology will make heavy usage of mocks for many of the hardware components so we tests can be run on development machines instead of on the embedded systems. A Red Green refactoring/testing cycle will ensure we always know the tests we write are both useful and logically possible to fail. Writing any tests that cannot fail would end up being dead or uncalled code. Many of the usual tests that would be prevalent for ensuring good memory management will be unnecessary from our use of the rust language. This along with the built in `rust-docs` will allow us to even use our tests as examples where needed as part of our documentation. Integration testing will mostly be handled as mocked interfaces replicating the physical hardware that will be required to collect the data. Further tests can added as needed should more sensors be added to the project at a later point in time. == Glossary - SBC: Single Board Computer - Rust: A modern compiled and memory safe language - PCB: Printed Circuit Board
https://github.com/LDemetrios/TypstParserCombinators
https://raw.githubusercontent.com/LDemetrios/TypstParserCombinators/master/release-combinators.typ
typst
// Utility functions (mostly clojure-core rewritten) #let force(x) = if (type(x) == dictionary and x.at("very-special-key") == "delay") { (x.data)() } else { x } #let delay(x) = (very-special-key: "delay", data: x) #let comp(f, g) = it => f(g(it)) #let partial(f, ..x) = (..y) => f(..x, ..y) #let cons(x, y) = (x, ..y) #let conj(x, y) = (..x, y) #let apply(f, ..args, argsColl) = f(..args, ..argsColl) #let constantly(x) = (..y) => x #let stringify(..values) = for v in values.pos() { v } #let reduce(f, coll) = { if coll.len() == 0 { f() } else if coll.len() == 1 { coll.at(0) } else { let x = coll.at(0) let i = 1 while i < coll.len() { x = f(x, coll.at(i)) i += 1 } x } } #let reduce_v(f, val, coll) = { let x = val let i = 0 while i < coll.len() { x = f(x, coll.at(i)) i += 1 } x } // Basic result manipulations #let result(value, tail) = (valid: true, value: value, tail: tail) #let fail-r = (valid: false, value: none, tail: none) #let map-result(f) = res => if res.valid { (valid: true, value: f(res.value), tail: res.tail) } else { res } // Simple parsers #let noparse(value) = s => (valid: true, value: value, tail: s) #let char-p(predicate) = s => { if (s.len() > 0 and predicate(s.first())) { (valid: true, value: s.first(), tail: s.slice(1)) } else { fail-r } } #let char-list(list) = s => { if (s.len() > 0 and s.first() in list) { (valid: true, value: s.first(), tail: s.slice(1)) } else { fail-r } } #let char-not-p(predicate) = s => { if (s.len() > 0 and not predicate(s.first())) { (valid: true, value: s.first(), tail: s.slice(1)) } else { fail-r } } #let char-not-list(list) = s => { if (s.len() > 0 and (s.first() not in list)) { (valid: true, value: s.first(), tail: s.slice(1)) } else { fail-r } } #let exactly(s) = inp => { if (inp.starts-with(s)) { (valid: true, value: s, tail: inp.slice(s.len())) } else { fail-r } } #let exactly-as(s, v) = inp => { if (inp.starts-with(s)) { (valid: true, value: v, tail: inp.slice(s.len())) } else { fail-r } } // Basic combinators #let combine(f, a, b) = s => { let ar = force(a)(s) if ar.valid { let br = force(b)(ar.tail) if br.valid { (valid: true, value: f(ar.value, br.value), tail: br.tail) } else { br } } else { ar } } #let either(a, b) = s => { let ar = force(a)(s) if ar.valid { ar } else { force(b)(s) } } #let map-p(f, parser) = s => { let pre-res = parser(s) if pre-res.valid { (valid: true, value: f(pre-res.value), tail: pre-res.tail) } else { pre-res } } // Ignoring #let ignored = "abracadabra" #let ignore(parser) = s => { let pre-res = parser(s) if pre-res.valid { (valid: true, value: ignored, tail: pre-res.tail) } else { pre-res } } #let iconj(coll, value) = if (value == ignored) { coll } else { conj(coll, value) } // Sequences #let seq(..parsers) = s => { let still-valid = true let return-value = () let remainder = s for parser in parsers.pos() { if still-valid { let next = force(parser)(remainder) if next.valid { remainder = next.tail if (next.value != ignored) { return-value.push(next.value) } } else { still-valid = false } } } if still-valid { (valid: true, value: return-value, tail: remainder) } else { fail-r } } /*reduce_v(partial(combine, iconj), noparse(()), parsers.pos())*/ #let seqf(f, ..parsers) = s => { let pre-res = seq(..parsers)(s) if pre-res.valid { (valid: true, value: f(..pre-res.value), tail: pre-res.tail) } else { pre-res } } #let seqn(n, ..parsers) = s => { let pre-res = seq(..parsers)(s) if pre-res.valid { (valid: true, value: pre-res.value.at(n), tail: pre-res.tail) } else { pre-res } } // Grammar constructions #let or-p(parser, ..parsers) = s => { let res = parser(s) for p in parsers.pos() { if not res.valid { res = p(s) } } res } #let opt(parser) = s => { let res = parser(s) if res.valid { res } else { (valid: true, value: none, tail: s) } } #let star(parser) = s => { let coll = () let rem = s let res = parser(s) while res.valid { coll.push(res.value) rem = res.tail res = parser(rem) } result(coll, rem) } #let plus(parser) = s => { let res = parser(s) if res.valid { let rem = res.tail let coll = () while res.valid { coll.push(res.value) rem = res.tail res = parser(rem) } (valid: true, value: coll, tail: rem) } else { fail-r } } // Representations #let stringifing(parser) = s => { let res = parser(s) if res.valid { (valid: true, value: stringify(..res.value), tail: res.tail) } else { fail-r } } #let whole_parser(parser) = s => { let res = parser(s) if not res.valid { "Couldn't parse: " + s } else if "" != res.tail { "Remained: " + res.tail } else { res.value } } #let char-regex-p(reg) = char-p(it => it.match(regex(reg)) != none) #let skip(s) = inp => { if inp.starts-with(s) { (valid: true, value: ignored, tail: inp.slice(s.len())) } else { fail-r } } #let regex-p(rgx, func: (it)=>it.text) = s => { let match-res = s.match(regex("(" + rgx + ").*")) if match-res == none or match-res.start != 0 { fail-r } else { let captured = match-res.captures.at(0).match(regex(rgx)) (valid:true, value:func(captured), tail:s.slice(captured.text.len())) } }
https://github.com/tiankaima/typst-notes
https://raw.githubusercontent.com/tiankaima/typst-notes/master/5891a0-2024_gaokao_math/main.typ
typst
#set text( font: ("linux libertine", "Source Han Serif SC", "Source Han Serif"), size: 10pt, ) #set page(height: 1100pt) == 思路 以下讨论中, 我们使用如下记号: 原数列 ${a_1, a_2, ..., a_(4m+2)}$ 去除两个数 $a_i, a_j$ 之后*分拆*结果为: $ {a^((1))_1, a^((1))_2,a^((1))_3,a^((1))_4},{a^((2))_1, a^((2))_2,a^((2))_3,a^((2))_4}, ... $ 考虑所有的 $(i,j)$ 取法共 $ C_(4m+2)^2=((4m+2)(4m+1))/2=8m^2+6m+1 $ 种, 我们按照以下方法讨论其中符合条件的 $(i,j)$ 总数的一个下界. - $1-$等差 考虑分拆结果所有数列均为 $1-$等差的情况, 这个情况可以简化到一个形如这样的*基础问题*: $ {a_1, a_2, ..., a_6} $ 我们在 (1) 中已经说明, 上面的取法共有三种, 分别是 $(1,2), (1,6), (5,6)$. 将这个问题推广到一般的 $4m+2$ 长度的数列, 我们可以将 $4m+2$ 拆分成 $4 dot k_1 + 6 + 4 dot k_2$, 大致如下: $ // &#rect(width: 160pt, height: 20pt) && #rect(width: 120pt, height: 20pt) && #rect(width: 160pt, height: 20pt)\ &{a^((1))_1, a^((1))_2, ... space ..., a^((1))_(4k_1)} &&{a^((2))_1, a^((2))_2, ... a^((2))_6} && { a^((3))_1, a^((3))_2, ... space ..., a^((3))_(4k_2) } $ 其中前 $4 dot k_1$ 显然能分拆成 $k_1$ 组 $1-$ 等差数列, 后 $k_2$ 组同理, 只需要在 ${a^((2))_1, a^((2))_2, ... a^((2))_6}$ 中找到 $(i,j)$ 即可. 在这样一个 $mod 4$ 的等价关系下, 我们认为 $(5,6)$ 的取法与 $(1,2)$ 重复, 所以在每个分拆中有两个不重复的结果. 这样的分拆共 $m$ 种, 所以这种情况下的取法至少 $2m$ 种. - $2-$等差 正如上面讨论的, 这里的*基础问题*变为讨论 ${a_1, a_2, ..., a_10}$, 一般的分拆为: $ {a^((1))_1, a^((1))_2, ... space ..., a^((1))_(4k_1)}, {a^((2))_1, a^((2))_2, ... a^((2))_10}, { a^((3))_1, a^((3))_2, ... space ..., a^((3))_(4k_2) } $ 在这里, ${a_1, ... a_10}$ 中合理的 $(i,j)$ 取法包含 $(1,2), (1,10), (2,9), (9,10)$, 考虑到我们在 $1-$ 等价的情况下已经讨论了 $(1,2)$ 和 $(9,10)$, 为避免重复计数, 我们舍弃所有 $abs(j-i)<7$ 的 $(i,j)$, 每种分拆中有 $2$ 种取法. 共 $m-1$ 种分拆, 所以这种情况下的取法共 $2(m-1)$ 种. #rect(width: 100%, stroke: 0.04em, inset: 1em)[ 为了避免重复计数, 我们在这里应该立刻澄清两件事情: - 在每个讨论组中, 除去*基础问题*的组, 其余两侧的数并不是总以 $k-$等差来分拆的, 事实上他们总是以 $1-$等差进行分拆的, 显然这样的分拆总是存在的. - 考虑到我们实际上只讨论 $(i,j)$ 的组合, 而不是讨论分拆的组合, 我们在 $k-$ 分拆的讨论组中只讨论满足 $abs(j-i)>=4k-1$ 的 $(i,j)$, 同时在 $k-$分拆的讨论组中, *基础问题*的长度是 $4k+2$, 所以也总是有 $abs(j-i)<=4k+1<4k+3=4(k+1)-1$, 因此我们在讨论 $k-$分拆的情况下, 不会重复计数. ] - $k-$等差 我们把上面的讨论一般化到 $k-$等差 ($k>=2$), 考虑 $k-$等差的*基础问题* ${a_1, a_2, ..., a_(4k+2)}$, 我们将其拆成 $k-$组长度为 $4$ 或 $5$ 的 $k-$等差数列: $ &{a_1, a_(k+1), a_(2k+1), a_(3k+1), a_(4k+1)}\ &{a_2, a_(k+2), a_(2k+2), a_(3k+2), a_(4k+2)}\ &{a_3, a_(k+3), a_(2k+3), a_(3k+3)}\ &{a_4, a_(k+4), a_(2k+4), a_(3k+4)}\ &{a_5, a_(k+5), a_(2k+5), a_(3k+5)}\ &... $ 所以至少以下 $(i,j)$ 是可行的: $ (1, 4k+2), (2, 4k+1), (1,2), (4k+1, 4k+2) $ 正如上面讨论的一样, 我们舍去后两个情况, 那么每个分拆中有 $2$ 种取法, 共 $m-k+1$ 种分拆, 所以这种情况下的取法共 $2(m-k+1)$ 种. 综上, 我们对符合条件的 $(i,j)$ 一个下界的估计是: $ sum_(k=1)^(m) 2(m-k+1) = m(m+1) >= 1 / 8 (8m^2+6m+1) = m^2+3 / 4m+1 / 8 quad m>=1 $ 得证.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/gentle-clues/0.6.0/gentle-clues.typ
typst
Apache License 2.0
// gentle-clues // Title dict for all supported languages #let title_dict = ( abstract: ( de: "Einführung", en: "Abstract", fr: "Résumé", es: "Resumen" ), info: ( de: "Info", en: "Info", fr: "Info", es: "Info" ), question: ( de: "Frage", en: "Question", fr: "Question", es: "Pregunta" ), memo: ( de: "Merke", en: "Memorize", fr: "À retenir", es: "Recordatorio" ), task: ( de: "Aufgabe", en: "Task", fr: "Tâche", es: "Tarea" ), conclusion: ( de: "Zusammenfassung", en: "Conclusion", fr: "Conclusion", es: "Conclusión" ), tip: ( de: "Tipp", en: "Tip", fr: "Conseil", es: "Consejo" ), success: ( de: "Erledigt", en: "Success", fr: "Succès", es: "Éxito" ), warning: ( de: "Achtung", en: "Warning", fr: "Avertissement", es: "Advertencia" ), error: ( de: "Fehler", en: "Error", fr: "Erreur", es: "Error" ), example: ( de: "Beispiel", en: "Example", fr: "Exemple", es: "Ejemplo" ), quote: ( de: "Zitat", en: "Quote", fr: "Citation", es: "Cita" ), ) // Global states #let gc_header-title-lang = state("lang", "en") // Keep for compatible reasons without underscore till 1.0.0 #let __gc_clues_breakable = state("breakable", false) #let __gc_clues_headless = state("headless", false) #let __gc_clue_width = state("clue-width", auto) #let __gc_header_inset = state("header-inset", 0.5em) #let __gc_content_inset = state("content-inset", 1em) #let __gc_border_radius = state("border-radius", 2pt) #let __gc_border_width = state("border-width", 0.5pt) #let __gc_stroke_width = state("stroke-width", 2pt) #let __gc_task-counter = counter("gc-task-counter") #let gc_enable-task-counter = state("gc-task-counter", true) // Keep for compatible reasons without underscore till 1.0.0 /* Config Init */ #let gentle-clues( lang: "en", breakable: false, headless: false, header-inset: 0.5em, // default-title: auto, // string or none // default-icon: emoji.magnify.l, // file or symbol // default-color: navy, // color profile name width: auto, // length stroke-width: 2pt, border-radius: 2pt, // length border-width: 0.5pt, // length content-inset: 1em, // length show-task-counter: false, // [bool] body ) = { // Check language assert( type(lang) == str, message: "The lang parameter needs to be of type string." ); assert( lang == "en" or lang == "de" or lang == "es" or lang == "fr", message: "The defined language is not supported yet." ) // Update title to lang parameter gc_header-title-lang.update(lang) // keep without underscore for compatible reasons // Update breakability __gc_clues_breakable.update(breakable); // Update clues width __gc_clue_width.update(width); // Update headless state __gc_clues_headless.update(headless); // Update header inset __gc_header_inset.update(header-inset); // Update border radius __gc_border_radius.update(border-radius); // Update border width __gc_border_width.update(border-width); // Update stroke width __gc_stroke_width.update(stroke-width); // Update content inset __gc_content_inset.update(content-inset); // Update if task counter should be shown gc_enable-task-counter.update(show-task-counter); body } // Helper #let if-auto-then(val,ret) = { if (val == auto){ ret } else { val } } #let get_base_color(val) = { if (type(_color) == color) { val } } #let get_colors(base_color) = { return (base_color, base_color.lighten(85%), base_color.lighten(70%)) } /* Basic gentle-clue (clue) template */ #let clue( content, title: auto, // string or none icon: emoji.magnify.l, // file or symbol _color: navy, // color width: auto, // length radius: auto, // length border-width: auto, // length content-inset: auto, // length header-inset: auto, // length breakable: auto, ) = { locate(loc => { // Set default color: let _stroke-color = luma(70); let _bg-color = _stroke-color.lighten(85%); let _border-color = _bg-color.darken(10%); // gray.lighten(20%); let _border-width = if-auto-then(border-width, __gc_border_width.at(loc)); let _border-radius = if-auto-then(radius, __gc_border_radius.at(loc)) let _stroke-width = if-auto-then(auto, __gc_stroke_width.at(loc)) let _clip-content = true // setting bg and stroke color from color argument // TODO: refactor if (type(_color) == color) { _stroke-color = _color; _bg-color = _color.lighten(85%); _border-color = _bg-color.darken(10%); } else if (type(_color) == dictionary) { if (_color.keys().contains("stroke")) { assert(type(_color.stroke) == color, message: "stroke must be of type color"); _stroke-color = _color.stroke; } if (_color.keys().contains("bg")) { assert(type(_color.bg) == color, message: "bg must be of type color"); _bg-color = _color.bg; _border-color = _bg-color.darken(10%); } if (_color.keys().contains("border")) { assert(type(_color.border) == color, message: "border must be of type color"); _border-color = _color.border; } } else if (type(_color) == gradient) { _stroke-color = _color; _bg-color = _color; } else { panic("No valid color type. Use a gradient, color, or specify a dict with (stroke, bg)"); } // Disable Heading numbering for those headings set heading(numbering: none, outlined: false, supplement: "Box") // Header Part let header = rect( fill: _bg-color, width: 100%, radius: (top-right: _border-radius), inset: if-auto-then(header-inset, __gc_header_inset.at(loc)), stroke: (right: _border-width + _bg-color ) )[ #grid( columns: (auto, auto), gutter: 1em, box(height: 1em)[ #if type(icon) == "symbol" { text(1em,icon) } else { image(icon, fit: "contain") } ], align(left + horizon,strong(title)) ) ] // Content-Box let content-box(content) = block( breakable: if-auto-then(breakable, __gc_clues_breakable.at(loc)), width: 100%, fill: white, inset: if-auto-then(content-inset, __gc_content_inset.at(loc)), radius: ( top-left: 0pt, bottom-left: 0pt, top-right: if (title != none){0pt} else {_border-radius}, rest: _border-radius ), )[#content] // Wrapper-Block block( breakable: if-auto-then(breakable, __gc_clues_breakable.at(loc)), width: if-auto-then(width, __gc_clue_width.at(loc)), inset: (left: 1pt), radius: (right: _border-radius, left: 0pt), stroke: ( left: (thickness: _stroke-width, paint: _stroke-color, cap: "butt"), top: if (title != none){_border-width + _bg-color} else {_border-width + _border-color}, rest: _border-width + _border-color, ), clip: _clip-content, )[ #set align(start) #stack(dir: ttb, if __gc_clues_headless.at(loc) == false and title != none { header }, content-box(content) ) ] // block end }) } // Helpers for predefined gentle clues #let get_title_for(clue) = { assert.eq(type(clue),str); locate(loc => { let lang = gc_header-title-lang.at(loc) return title_dict.at(clue).at(lang) }) } #let increment_task_counter() = { locate(loc => { if (gc_enable-task-counter.at(loc) == true){ __gc_task-counter.step() } }) } #let get_task_number() = { locate(loc => { if (gc_enable-task-counter.at(loc) == true){ " " + __gc_task-counter.display() } }) } // Predefined gentle clues /* info */ #let info(title: auto, icon: "assets/info.svg", ..args) = clue( _color: rgb(29, 144, 208), // blue title: if (title != auto) { title } else { get_title_for("info") }, icon: icon, ..args ) /* success */ #let success(title: auto, icon: "assets/checkbox.svg", ..args) = clue( _color: rgb(102, 174, 62), // green title: if (title != auto) { title } else { get_title_for("success") }, icon: icon, ..args ) /* warning */ #let warning(title: auto, icon: "assets/warning.svg", ..args) = clue( _color: rgb(255, 145, 0), // orange title: if (title != auto) { title } else { get_title_for("warning") }, icon: icon, ..args ) /* error */ #let error(title: auto, icon: "assets/crossmark.svg", ..args) = clue( _color: rgb(237, 32, 84), // red title: if (title != auto) { title } else { get_title_for("error") }, icon: icon, ..args ) /* task */ #let task(title: auto, icon: "assets/task.svg", ..args) = { increment_task_counter() clue( _color: maroon, // purple rgb(158, 84, 159) title: if (title != auto) { title } else { get_title_for("task") + get_task_number()}, icon: icon, ..args ) } /* tip */ #let tip(title: auto, icon: "assets/tip.svg", ..args) = clue( _color: rgb(0, 191, 165), // teal title: if (title != auto) { title } else { get_title_for("tip") }, icon: icon, ..args ) /* abstract */ #let abstract(title: auto, icon: "assets/abstract.svg", ..args) = clue( _color: olive, // rgb(124, 77, 255), // kind of purple title: if (title != auto) { title } else { get_title_for("abstract") }, icon: icon, ..args ) /* conclusion */ #let conclusion(title: auto, icon: "assets/lightbulb.svg", ..args) = clue( _color: rgb(255, 201, 23), // yellow title: if (title != auto) { title } else { get_title_for("conclusion") }, icon: icon, ..args ) /* memorize */ #let memo(title: auto, icon: "assets/excl.svg", ..args) = clue( _color: rgb(255, 82, 82), // kind of red title: if (title != auto) { title } else { get_title_for("memo") }, icon: icon, ..args ) /* question */ #let question(title: auto, icon: "assets/questionmark.svg", ..args) = clue( _color: rgb("#7ba10a"), // greenish title: if (title != auto) { title } else { get_title_for("question") }, icon: icon, ..args ) /* quote */ // TODO: add source field. #let quote(title: auto, icon: "assets/quote.svg", ..args) = clue( _color: eastern, title: if (title != auto) { title } else { get_title_for("quote") }, icon: icon, ..args ) /* example */ #let example(title: auto, icon: "assets/example.svg", ..args) = clue( _color: orange, title: if (title != auto) { title } else { get_title_for("example") }, icon: icon, ..args )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-4DC0.typ
typst
Apache License 2.0
#let data = ( ("HEXAGRAM FOR THE CREATIVE HEAVEN", "So", 0), ("HEXAGRAM FOR THE RECEPTIVE EARTH", "So", 0), ("HEXAGRAM FOR DIFFICULTY AT THE BEGINNING", "So", 0), ("HEXAGRAM FOR YOUTHFUL FOLLY", "So", 0), ("HEXAGRAM FOR WAITING", "So", 0), ("HEXAGRAM FOR CONFLICT", "So", 0), ("HEXAGRAM FOR THE ARMY", "So", 0), ("HEXAGRAM FOR HOLDING TOGETHER", "So", 0), ("HEXAGRAM FOR SMALL TAMING", "So", 0), ("HEXAGRAM FOR TREADING", "So", 0), ("HEXAGRAM FOR PEACE", "So", 0), ("HEXAGRAM FOR STANDSTILL", "So", 0), ("HEXAGRAM FOR FELLOWSHIP", "So", 0), ("HEXAGRAM FOR GREAT POSSESSION", "So", 0), ("HEXAGRAM FOR MODESTY", "So", 0), ("HEXAGRAM FOR ENTHUSIASM", "So", 0), ("HEXAGRAM FOR FOLLOWING", "So", 0), ("HEXAGRAM FOR WORK ON THE DECAYED", "So", 0), ("HEXAGRAM FOR APPROACH", "So", 0), ("HEXAGRAM FOR CONTEMPLATION", "So", 0), ("HEXAGRAM FOR BITING THROUGH", "So", 0), ("HEXAGRAM FOR GRACE", "So", 0), ("HEXAGRAM FOR SPLITTING APART", "So", 0), ("HEXAGRAM FOR RETURN", "So", 0), ("HEXAGRAM FOR INNOCENCE", "So", 0), ("HEXAGRAM FOR GREAT TAMING", "So", 0), ("HEXAGRAM FOR MOUTH CORNERS", "So", 0), ("HEXAGRAM FOR GREAT PREPONDERANCE", "So", 0), ("HEXAGRAM FOR THE ABYSMAL WATER", "So", 0), ("HEXAGRAM FOR THE CLINGING FIRE", "So", 0), ("HEXAGRAM FOR INFLUENCE", "So", 0), ("HEXAGRAM FOR DURATION", "So", 0), ("HEXAGRAM FOR RETREAT", "So", 0), ("HEXAGRAM FOR GREAT POWER", "So", 0), ("HEXAGRAM FOR PROGRESS", "So", 0), ("HEXAGRAM FOR DARKENING OF THE LIGHT", "So", 0), ("HEXAGRAM FOR THE FAMILY", "So", 0), ("HEXAGRAM FOR OPPOSITION", "So", 0), ("HEXAGRAM FOR OBSTRUCTION", "So", 0), ("HEXAGRAM FOR DELIVERANCE", "So", 0), ("HEXAGRAM FOR DECREASE", "So", 0), ("HEXAGRAM FOR INCREASE", "So", 0), ("HEXAGRAM FOR BREAKTHROUGH", "So", 0), ("HEXAGRAM FOR COMING TO MEET", "So", 0), ("HEXAGRAM FOR GATHERING TOGETHER", "So", 0), ("HEXAGRAM FOR PUSHING UPWARD", "So", 0), ("HEXAGRAM FOR OPPRESSION", "So", 0), ("HEXAGRAM FOR THE WELL", "So", 0), ("HEXAGRAM FOR REVOLUTION", "So", 0), ("HEXAGRAM FOR THE CAULDRON", "So", 0), ("HEXAGRAM FOR THE AROUSING THUNDER", "So", 0), ("HEXAGRAM FOR THE KEEPING STILL MOUNTAIN", "So", 0), ("HEXAGRAM FOR DEVELOPMENT", "So", 0), ("HEXAGRAM FOR THE MARRYING MAIDEN", "So", 0), ("HEXAGRAM FOR ABUNDANCE", "So", 0), ("HEXAGRAM FOR THE WANDERER", "So", 0), ("HEXAGRAM FOR THE GENTLE WIND", "So", 0), ("HEXAGRAM FOR THE JOYOUS LAKE", "So", 0), ("HEXAGRAM FOR DISPERSION", "So", 0), ("HEXAGRAM FOR LIMITATION", "So", 0), ("HEXAGRAM FOR INNER TRUTH", "So", 0), ("HEXAGRAM FOR SMALL PREPONDERANCE", "So", 0), ("HEXAGRAM FOR AFTER COMPLETION", "So", 0), ("HEXAGRAM FOR BEFORE COMPLETION", "So", 0), )
https://github.com/typst-doc-cn/tutorial
https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/intermediate/stateful/q1.typ
typst
Apache License 2.0
#set text(size: 8pt) #let calc-headings(headings) = { let max-page-num = calc.max(..headings.map(it => it.location().page())) let first-headings = (none, ) * max-page-num let last-headings = (none, ) * max-page-num for h in headings { if first-headings.at(h.location().page() - 1) == none { first-headings.at(h.location().page() - 1) = h } last-headings.at(h.location().page() - 1) = h } let res-headings = (none, ) * max-page-num for i in range(res-headings.len()) { res-headings.at(i) = if first-headings.at(i) != none { first-headings.at(i) } else { last-headings.at(i) = last-headings.at( calc.max(0, i - 1), default: none) last-headings.at(i) } } (res-headings, if max-page-num > 0 { last-headings.at(-1) }) } #let get-heading-at-page(loc) = { let (headings, last-heading) = calc-headings( query(heading.where(level: 2), loc)) headings.at(loc.page() - 1, default: last-heading) } #let set-heading(content) = { show heading.where(level: 3): it => { show regex("[\p{hani}\s]+"): underline it } show heading: it => { show regex("KiraKira"): box("★", baseline: -20%) show regex("FuwaFuwa"): box("✎", baseline: -20%) it } set page(header: locate(loc => { set text(size: 5pt); emph(get-heading-at-page(loc)) })) content } #let set-text(content) = { show regex("feat|refactor"): emph content } #show: set-heading #show: set-text #set page(width: 120pt, height: 120pt, margin: (top: 12pt, bottom: 10pt, x: 5pt)) == 雨滴书v0.1.2 === KiraKira 样式改进 feat: 改进了样式。 === FuwaFuwa 脚本改进 feat: 改进了脚本。 == 雨滴书v0.1.1 refactor: 移除了LaTeX。 feat: 删除了一个多余的文件夹。 == 雨滴书v0.1.0 feat: 新建了两个文件夹。
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/经济学原理/hw/hw8.typ
typst
#import "../../template.typ": * #show: note.with( title: "作业8", author: "YHTQ ", date: none, logo: none, withOutlined: false, withTitle: true ) = C #answer[ 边际成本即为新增加的成本,也就是一天的食宿和泡温泉 ] = A 或 B #answer[ 只要边际成本大于平均成本,平均成本就会上升 ] = (1)#answer[ 当 $k = 100$ 时,有 $q = 20l, l = 1/20 q$,成本函数为: $ c = r k + w l = 100 + 1/5 q $ 平均成本函数为: $ c_("average") = c/q = 100/q + 1/5 $ ] (2)#answer[ 边际成本函数为: $ c_(M) = der(c, q) = 1/5 $ 分别带入 $25, 50, 100$,可以求得短期平均成本和短期边际成本: #table( columns: 4, [], [$25$],[$50$],[$100$], [SAC], [$4.2$], [$2.2$], [$1.2$], [SMC], [$0.2$], [$0.2$], [$0.2$] ) ] (3)#align(center,image("image/image4.png", width: 200pt)) (4) 它们在某种意义上的无穷远点相交。 #answer[ 注意到: $ der("SMC", q) = der(c/q, q) = (q der(c, q) - c)/q^2 = (q "SAC" - c)/q^2 = ("SAC" - "SMC")/q $ 换言之,SAC 曲线与 SMC 曲线的交点一定满足 $der("SMC", q) = 0$,而由于平均成本函数往往呈现先降低再升高的趋势,因此导数为零的点往往是最小值点。 ]
https://github.com/sses7757/sustech-graduated-thesis
https://raw.githubusercontent.com/sses7757/sustech-graduated-thesis/main/example.typ
typst
Apache License 2.0
#import "sustech-graduated-thesis/lib.typ": documentclass, indent, notation, fake-par, 字体 #import "sustech-graduated-thesis/utils/math-utils.typ": sfrac, svec // 参考 modern-nju-thesis: // 你首先应该安装 https://github.com/nju-lug/modern-nju-thesis/tree/main/fonts/FangZheng 里的所有字体, // 如果是 Web App 上编辑,你应该手动上传这些字体文件,否则不能正常使用「楷体」和「仿宋」,导致显示错误。 #let ( // 布局函数 twoside, doc, mainmatter, mainmatter-end, appendix, // 页面函数 fonts-display-page, cover, decl-page, abstract, abstract-en, bilingual-bibliography, outline-page, list-of-figures, list-of-tables, notation-page, acknowledgement, ) = documentclass( doctype: "midterm", // proposal, midterm, final // anonymous: true, // 盲审模式 twoside: true, // 双面模式,会加入空白页,便于打印 // fonts: (楷体: ("Times New Roman", "FZKai-Z03S")), // 可自定义字体,先英文字体后中文字体,应传入「宋体」、「黑体」、「楷体」、「仿宋」、「等宽」 // math-font: "XITS Math", // 公式字体,应预先安装在系统中或放在根目录下 // slant-glteq: true, // 公式 <= >= 样式,按照中文格式要求,所有大于等于、小于等于号均替换为对应倾斜等号变体 // arounds: arounds_default, // 公式不加空格的符号,默认值为 mainmatter.arounds_default // math-breakable: false, // 多行公式可否分割到多页 // sep-ref: true, // 是否自动将@ref与其跟随的中文字符分开处理,使用true时应避免含有中文的label或bib info: ( title: ("基于Typst的", "南方科技大学学位论文"), title-en: "SUSTech Thesis Template for Typst", grade: "20XX", student-id: "1234567890", author: "张三", author-en: "<NAME>", department: "某学院", department-en: "XX Department", dept: "某系", dept-en: "XX Department", major: "某专业", major-en: "XX Major", field: "某方向", field-en: "XX Field", supervisor: ("李四", "教授"), supervisor-en: "<NAME>", // supervisor-ii: ("王五", "副教授"), // supervisor-ii-en: "Professor My Supervisor", submit-date: datetime.today(), ), // 参考文献源 bibliography: bibliography.with("example.bib", style: "sustech-graduated-thesis/gb-t-7714-2015-numeric.csl"), ) // 文稿设置 #show: doc // 字体展示测试页 // #fonts-display-page() // 封面页 #cover() // 声明页 #decl-page() // 正文 #set list(indent: 1.1em, marker: ([•], [#text(size: 0.5em, baseline: 0.2em, "■")])) #set enum(numbering: "(1 a)", indent: 0em) #show: mainmatter // 中文摘要 #abstract( keywords: ("我", "就是", "测试用", "关键词") )[ 中文摘要 ] // 英文摘要 #abstract-en( keywords: ("Dummy", "Keywords", "Here", "It Is") )[ English abstract ] // 目录 #outline-page() // 插图目录 #list-of-figures() // 表格目录 #list-of-tables() // 符号表 #notation-page(supplements: ( ([$lambda$], "特征值"), ([$pi$], "圆周率"), ) ) // 重设页码,开始正文 #counter(page).update(1) = 导 论 自动断字测试: #lorem(50) == 列表 === 无序列表 无序列表编号请自行使用`#set list(indent: 1em, marker: (...))`等方式修改符号和缩进。 - 无序列表项一 - 无序列表项二 - 无序子列表项一 - 无序子列表项二 === 有序列表 有序列表编号请自行使用`#set enum(numbering: "(1 a)", indent: 0em)`等方式修改编号和缩进。 + 有序列表项一#lorem(15) + 有序列表项二 + 有序子列表项一 + 有序子列表项二 == 术语 定义新术语,使用`#notation("key", name-en: "English Full Name", name-cn: "中文全称", abbr: "EFN")`,其中`abbr`可不指定以自动生成,`name-en`可以首字母不大写,如#notation("dft", name-en: "density functional theory", name-cn: "密度泛函理论");字母中存在大写的,默认简写为其大写部分,如#notation("bana", name-en: "BA-NAnas", name-cn: "香蕉")。 引用已经定义的术语,使用`#notation("key", full: true|false|none)`,其中键值`key`的大小写不敏感,如#notation("DFT")、#notation("bana", full: none)和#notation("dft", full: true)。 文档中使用`notation`添加的所有术语均会自动出现在符号表中;同一个`key`,之后的定义会覆盖之前的定义。 本模板还提供了快速定义和引用术语的方式,如全称“#notation("qft", "量子场论", "Quantum Field Theory")”(后两个顺序可互换),无键值“#notation("量子力学", "Quantum Mechanics")”。快速引用如@no:qft和@no:qft-full。 == 图表 引用@tbl:timing-tlt,以及@fig:logo,具体参数设置参见Typst文档。引用图表时,表格和图片分别需要加上`tbl:`和`fig:`前缀才能正常显示编号。 #figure( table( columns: 4, stroke: none, table.hline(), [t], [1], [2], [3], table.hline(stroke: .5pt), [y], [0.3s], [0.4s], [0.8s], table.hline(), ), caption: [三线表], ) <timing-tlt> #figure( image("figs/LOGO.png", width: 50%), caption: [图片测试], ) <logo> == 数学公式 可以像Markdown一样写行内公式$x + y$(\$与字符之间没有空格),以及带编号的行间公式(\$与字符之间存在空格或换行): $ phi.alt := (1 + sqrt(5)) / 2 $ <ratio> 默认字体为XITS Math(可在`https://github.com/aliftype/xits/blob/master/XITSMath-Regular.otf`中下载),可按需修改`math-font`选项以改为所需字体,选项接收的参数为*字体名称*而非字体文件的名称,且字体应预先安装在系统中或放在根目录下。引用数学公式需要加上`eqt:`前缀,则由@eqt:ratio,有: $ F_n &= P(n) \ &= floor(1 / sqrt(5) phi.alt^n). $ 我们也可以通过`<->`标签来标识该行间公式不需要编号 $ f(bold(y)/t) <= integral_1^2 x^(-2) dif x, $ <-> 而后续数学公式仍然能正常编号: $ F_n = floor(1 / sqrt(5) phi.alt^n). $ 使用 `<->` 标签配合内部标签实现单独标记: $ F_n &= P(n) \ &= floor(1 / sqrt(5) phi.alt^n). #<final1> $ <-> 测试引用@eqt:final1。注意到默认情况下,多行公式不能分割到多页上,如需改变,修改`math-breakable`选项。 行内公式自动添加空格功能: - 本模板加入了自动在行内公式两端添加空格的功能,如$sin(x)$,该功能会自动避免在符号两端添加空格。修改`arounds`选项以指定哪些符号两端不添加空格。 - 无序和有序列表以及图、表中的行内公式两端也会自动添加。 - 由于Typst本身没有提供类似LaTeX中的`\sfrac`和`\vec`类似的功能(`arrow()`的箭头默认大小对于某些字符过于巨大),因此,本模板在`utils/math-utils.typ`内提供了类似的函数——`sfrac`和`svec`。如$sfrac(A_L, B_d)$而非$A_L \/ B_d$,$svec(N)$而非$arrow(N)$。 == 参考文献 <sec:bib> 可以像这样引用参考文献:图书#[@蒋有绪1998]和会议#[@中国力学学会1990]。 注意事项: - 若引用的key以中文开始,请按照上述写法编写引用。 - 若为全英文引用key,可以使用类似@Jiang1998的写法,无需包裹在content块内部,也不会自动添加不需要的空格,因为本模板的`equate-ref`函数处理了这种情况。该处理同样适用于其他引用,如@eqt:final1引用。 - 若引用的key不以中文开始却含有中文,本模板在`sep-ref = true`的情况下目前*不能*正确处理,会出现错误,请自行修改引用键值或关闭`sep-ref`并全部使用上述写法编写引用。 == 代码块 代码块支持语法高亮。引用时需要加上`lst:`,如@lst:code。 #figure( ```py def add(x, y): return x + y ```, caption:[代码块], ) <code> == 注意事项 - 为了避免不必要的空格,中文内部(包括标点符号)不能换行。 否则就像本行,在第一个句号后加入了额外的空格。 - 为了使得标题后首行文字可以缩进,本模板使用了`#fake-par`,会导致标题行和下一行可能不同页,如@sec:bib,建议使用手动换行“`\`”解决。 - 另外,对于行间公式和有序/无序列表之后马上需要另起一段的,需使用`#fake-par`另起一段,仅使用空行无法另起一段。 - 如需设置全局格式,请在`#show: mainmatter`之前设置,或在设置之后再次应用`#show: mainmatter`,以免模板的某些全局设置失效。 #fake-par 注意事项结束。 == 表格自动填充 Typst提供了完整的文件读取和字符串处理处理功能,可以通过少量脚本代码自动生成表格内容,如@tbl:opt-res所示,该脚本读取了`test.csv`文件,将其奇数行视为不同方法在不同问题上的优化结果的平均值,偶数行视为其上一行的标准差,并统一加粗每一个问题上的最优结果。使用时可以自行参考下面的表格生成代码和`table`等Typst自带函数的语法进行修改和自定义。 #{ import "@preview/oxifmt:0.2.1": strfmt let res-csv = csv("test.csv") let num-format(n, min-val: 0, format: "3E2") = { if format == none { if n == min-val [*#str(n)*] else [#str(n)] } else { let format-main = format.position("E") + 1 let fmt = strfmt("{:." + format.slice(0, format-main) + "}", n) fmt = fmt.replace("E", "E+").replace("E+-", "E-") let p = fmt.position(regex("E[+-][0-9]+")) + 2 let exp-n = strfmt("{:0" + format.slice(format-main) + "}", int(fmt.slice(p))) fmt = fmt.slice(0, p) + exp-n fmt = if fmt.starts-with("-") {fmt} else {"-" + fmt} fmt = fmt.replace("-", "−") if n == min-val [*#fmt*] else [#fmt] } } let parse-row(csv-str, row-idx) = { let row = (table.cell(rowspan: 2)[F#(row-idx + 1)], [Mean]) let means = csv-str.at(row-idx * 2).map(x => eval(x)) let stds = csv-str.at(row-idx * 2 + 1).map(x => eval(x)) let min-mean = calc.min(..means) let min-std = calc.min(..stds) row += means.map(num-format.with(min-val: min-mean)) row += ([Std],) + stds.map(num-format.with(min-val: min-std)) row } let _next-page-state = state("next-page-state", false) show figure: set block(breakable: true) [#figure( table( columns: (0.3fr, 0.7fr,) + (1fr, ) * 6, align: center + horizon, stroke: 0pt, table.hline(stroke: 1pt), table.header( table.cell(colspan: 2)[*函数*], ..range(1, 7).map(x => [方法#x]), ), table.hline(stroke: 0.5pt), ..range(0, int(res-csv.len() / 2)).map(x => parse-row(res-csv, x)).flatten(), table.hline(stroke: 1pt), table.footer(table.cell(colspan: 8, align: right + bottom, context if _next-page-state.get() [] else [续下页#_next-page-state.update(_ => true)] )) ), caption: [表格内容自动生成测试] ) <opt-res> ] } = 正文 <chap:2> == 正文子标题 === 正文子子标题 引用测试@chap:2。公式编号测试: $ phi.alt := (1 + sqrt(5)) / 2 $ <ratio2> 测试引用@eqt:ratio2。 // 中英双语参考文献 // 默认使用 gb-7714-2015-numeric 样式 #bilingual-bibliography(full: true) // 致谢 #acknowledgement[ 感谢modern-nju-thesis模板,感谢SUSTech LaTeX模板。 ] // 附录 #show: appendix = 附录 A == 附录子标题 === 附录子子标题 附录内容,这里也可以加入图片,例如@fig:appendix-img。 #figure( image("figs/LOGO.png", width: 50%), caption: [图片测试], ) <appendix-img> = 附录 B == 附录子标题 === 附录子子标题 公式编号测试: $ phi.alt := (1 + sqrt(5)) / 2 $ <ratio3> 测试引用@eqt:ratio3。 // 正文结束标志,不可缺少 // 这里放在附录后面,使得页码能正确计数 #mainmatter-end()
https://github.com/Tran-Thu-Le/typst-collection
https://raw.githubusercontent.com/Tran-Thu-Le/typst-collection/main/book-cover/simple-book-cover.typ
typst
#let title = align(center)[#text(fill: red, size: 5em, stroke: 1pt+black)[*A book's cover*]] #let subtitle = align(center)[#text(fill: red, size: 3em, stroke: none)[_For creating Typst books_]] #let author = align(right)[#text(fill: blue, size: 2.5em, stroke: none)[By *<NAME>*] #h(4em)] #let year = align(center)[#text(fill: blue, size: 1.5em, stroke: none)[_Vietnam 2023-2024_] #h(4em)] #box( width: 100%, height: 100%, fill: gradient.linear(white, aqua, angle: 130deg), outset: 1em, radius: 1em, stroke: 2pt + gradient.linear(..color.map.viridis,) )[ #v(25%) #title #v(-3em) #subtitle #v(3em) #author #v(1fr) #year ]
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S5/PST/docs/5-VariablesAleatoires/variables-aleatoires.typ
typst
#import "/_settings/typst/template-note.typ": conf #show: doc => conf( title: [ Title ], lesson: "Lesson", chapter: "Chapter", definition: "Definition", col: 1, doc, ) = Généralités sur les variables aléatoires = Variables aléatoires discrètes = Variables aléatoires continues = Propriétés de l'espérance mathématique et la variance
https://github.com/Mc-Zen/zero
https://raw.githubusercontent.com/Mc-Zen/zero/main/src/formatting.typ
typst
MIT License
#import "state.typ": num-state, group-state #import "parsing.typ": * #let sequence-constructor = $$.body.func() /// Creates an equation from a sequence. This function leaves the /// `block` attribute unset. #let make-equation(sequence) = { math.equation(sequence-constructor(sequence)) } #assert.eq(make-equation((sym.minus, [2])).body, $-2$.body) /// Formats a sign. If the sign is the ASCII character "-", the minus /// unicode symbol "−" is returned. Otherwise, "+" is returned but only /// if `positive-sign` is set to true. In all other cases, the result is /// `none`. #let format-sign(sign, positive-sign: false) = { if sign == "-" { return sym.minus } else if sign == "+" and positive-sign { return sym.plus } } #assert.eq(format-sign("-", positive-sign: false), sym.minus) #assert.eq(format-sign("+", positive-sign: false), none) #assert.eq(format-sign("-", positive-sign: true), sym.minus) #assert.eq(format-sign("+", positive-sign: true), sym.plus) #assert.eq(format-sign(none, positive-sign: true), none) /// Inserts group separators (e.g., thousand separators if `group-size` is 3) /// into a sequence of digits. /// - x (str): Input sequence. /// - invert (boolean): If `false`, the separators are inserted counting from /// right-to-left (as customary for integers), if `true`, they are inserted /// from left-to-right (for fractionals). #let insert-group-separators( x, invert: false, threshold: 5, size: 3, separator: sym.space.thin ) = { if x.len() < threshold { return x } if not invert { x = x.rev() } let chunks = x.codepoints().chunks(size) if not invert { chunks = chunks.rev().map(array.rev) } return chunks.intersperse(separator).flatten().join() } #assert.eq(insert-group-separators("123"), "123") #assert.eq(insert-group-separators("1234"), "1234") #assert.eq(insert-group-separators("12345", separator: " "), "12 345") #assert.eq(insert-group-separators("123456", separator: " "), "123 456") #assert.eq(insert-group-separators("1234567", separator: " "), "1 234 567") #assert.eq(insert-group-separators("12345678", separator: " "), "12 345 678") #assert.eq(insert-group-separators("12345678", separator: " ", size: 2), "12 34 56 78") #assert.eq(insert-group-separators("1234", separator: " ", threshold: 3), "1 234") #assert.eq(insert-group-separators("1234", separator: " ", threshold: 3, invert: true), "123 4") #assert.eq(insert-group-separators("1234567", separator: " ", threshold: 3, invert: true), "123 456 7") #assert.eq(insert-group-separators("1234567", separator: " ", size: 2, threshold: 3, invert: true), "12 34 56 7") #let contextual-group(x, invert: false) = { insert-group-separators(x, invert: invert) } /// Takes a sequence of digits and returns a new sequence of length `digits`. /// If the input sequence is too short, a corresponding number of trailing /// zeros is appended. Exceeding inputs are truncated. #let fit-decimals(x, digits) = { let len = x.len() if len == digits or digits == auto { return x } if len < digits { return x + "0" * (digits - len) } if len > digits { return x.slice(0, digits) } } #assert.eq(fit-decimals("345", 3), "345") #assert.eq(fit-decimals("345", 4), "3450") #assert.eq(fit-decimals("345", 2), "34") #let format-integer = it => { // int, group if type(it.group) == dictionary and it.int != none { it.int = insert-group-separators(it.int, ..it.group) } if it.int == "" { it.int = "0" } it.int } #let format-fractional = it => { // frac, group, digits, decimal-separator? let frac = fit-decimals(it.frac, it.digits) if frac.len() == 0 { return none } if type(it.group) == dictionary { frac = insert-group-separators(frac, invert: true, ..it.group) } it.decimal-separator + frac } #let format-comma-number = it => { // sign, int, frac, digits, group, positive-sign let frac = format-fractional((frac: it.frac, group: it.group, digits: it.digits, decimal-separator: it.decimal-separator)) return format-sign(it.sign, positive-sign: it.positive-sign) + format-integer((int: it.int, group: it.group)) + frac } #let format-uncertainty = it => { /// pm, digits, mode, concise, tight let pm = it.pm if pm == none { return () } let is-symmetric = type(pm.first()) != array if is-symmetric { pm = (pm,) } if it.concise { let compact-pm = ( it.mode == "compact" or (it.mode == "compact-separator" and pm.map(x => x.first().trim("0")).all(x => x.len() == 0)) ) if compact-pm { pm = pm.map(x => utility.shift-decimal-left(..x, -it.digits)) it.digits = auto } } pm = pm.map(((int, frac)) => format-comma-number(( sign: none, int: int, frac: frac, digits: it.digits, group: false, positive-sign: false, decimal-separator: it.decimal-separator )) ) if is-symmetric { if it.concise { ("(", pm.first(), ")") } else { ( math.class("normal", none), math.class(if it.tight {"normal"} else {"binary"}, sym.plus.minus), pm.first() ) } } else { ( math.attach( none, t: sym.plus + pm.at(0), b: sym.minus + pm.at(1) ), ) } } #let format-power = it => { /// x, base, product, positive-sign-exponent, tight, if it.exponent == none { return () } let (sign, integer, fractional) = decompose-signed-float-string(it.exponent) let exponent = format-comma-number((sign: sign, int: integer, frac: fractional, digits: auto, group: false, positive-sign: it.positive-sign-exponent, decimal-separator: it.decimal-separator)) let power = math.attach([#it.base], t: [#exponent]) if it.product == none { (power,) } else { ( box(), math.class(if it.tight {"normal"} else {"binary"}, it.product), power ) } } #let show-num-impl = it => { /// sign, int, frac, e, pm, /// digits /// omit-unity-mantissa, uncertainty-mode, positive-sign let omit-mantissa = ( it.omit-unity-mantissa and it.int == "1" and it.frac == "" and it.e != none and it.pm == none and it.digits == 0 ) let concise-uncertainty = it.uncertainty-mode != "separate" let integer = ( sign: it.sign, int: if omit-mantissa { none } else { it.int }, decimal-separator: it.decimal-separator, group: it.group ) let uncertainty = ( pm: it.pm, digits: it.digits, concise: concise-uncertainty, tight: it.tight, mode: it.uncertainty-mode, decimal-separator: it.decimal-separator ) let power = ( exponent: it.e, base: it.base, product: if omit-mantissa {none} else {it.product}, positive-sign-exponent: it.positive-sign-exponent, tight: it.tight, decimal-separator: it.decimal-separator ) let integer-part = ( format-sign(it.sign, positive-sign: it.positive-sign), format-integer(integer), ) let fractional-part = ( format-fractional((frac: it.frac, group: it.group, digits: it.digits, decimal-separator: it.decimal-separator)), ) let uncertainty-part = format-uncertainty(uncertainty) if concise-uncertainty { fractional-part += uncertainty-part uncertainty-part = () } if it.pm != none and it.e != none and not concise-uncertainty { integer-part = ("(",) + integer-part uncertainty-part.push(")") } let result = ( integer-part, fractional-part, uncertainty-part, format-power(power), ) return result }
https://github.com/paugarcia32/CV
https://raw.githubusercontent.com/paugarcia32/CV/main/cv.typ
typst
Apache License 2.0
#import "brilliant-CV/template.typ": * #show: layout #cvHeader(hasPhoto: true, align: left) #autoImport("personalSummary") #autoImport("education") #autoImport("professional") #autoImport("technicalSkills") #autoImport("projects") #autoImport("certificates") #autoImport("event") //#autoImport("publications") #autoImport("skills") #cvFooter()
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S5/PCO/docs/1-Introduction/threadsintroduction.typ
typst
#import "/_settings/typst/template-note.typ": conf #show: doc => conf( title: [ Introcution aux threads ], lesson: "PCO", chapter: "1 - Introduction", definition: "", col: 1, doc, ) = Modèles de délégation == Modèle de délégation (boos-worker model / delegation model) Le modèle de délégation est un modèle de conception qui permet à un objet de déléguer une partie de son comportement à un autre objet. Ce modèle est utilisé pour déléguer des tâches à un autre objet. Il est utilisé pour réutiliser le code. Il est un moyen de réutiliser le code en utilisant la composition. - Un thread principal - Des threads travailleurs #image("/_src/img/docs/image copy 130.png") ```cpp void tachePatron(void *ptr) { boucle infinie { attend une requête switch (requete) { case requeteX: startThread( ... tacheX); break; case requeteY: startThread( ... tacheY); break; ... } } } void tacheX(void *ptr) { exécuter le travail demandé, puis se terminer } void tacheY(void *ptr) { exécuter le travail demandé, puis se terminer } ``` #colbreak() == Modèle pair (peer model) Le modèle pair est un modèle de conception qui permet à un objet de partager une partie de son comportement avec un autre objet. Ce modèle est utilisé pour partager des tâches avec un autre objet. Il est utilisé pour partager des tâches entre deux objets. Il est un moyen de partager des tâches entre deux objets. - Pas de thread principal - Tous égaux - Chacun s'arrange avec ses entrées/sorties #image("/_src/img/docs/image copy 131.png") ```cpp int main() { startThread( ... tache1); startThread( ... tache2); ... signale aux threads qu’ils peuvent commencer à travailler } void tache1() { attend le signal de commencement effectue le traitement, et synchronise avec les autres threads si nécessaire } void tache2() { attend le signal de commencement effectue le traitement, et synchronise avec les autres threads si nécessaire } ``` #colbreak() == Modèle pipeline (pipeline model) Le modèle pipeline est un modèle de conception qui permet à un objet de transmettre une partie de son comportement à un autre objet. Ce modèle est utilisé pour transmettre des tâches à un autre objet. - Appliqué lorsque: - L'application traite une longue chaîne d'entrée; - Le traitement à effectuer sur ces entrées peut être décomposé en sous-tâches (étages de pipeline) au travers desquelles chaque donnée d'entrée doit passer; - Chaque étage peut traiter une donnée différente à chaque instant. - Un thread attend les données du précédent - Et les transmet ensuite au suivant #image("/_src/img/docs/image copy 132.png") ```cpp void etage1() { boucle infinie { récupérer une entrée du programme traiter cette donnée passer le résultat à l’étage suivant } } void etage2() { boucle infinie { récupérer une donnée de l’étage précédent traiter cette donnée passer le résultat à l’étage suivant } } void etageN() { boucle infinie { récupérer une donnée de l’étage précédent traiter cette donnée passer le résultat en sortie du programme } } ``` = Anatomie d'un processus == Propriétés d'un processus - Un code à exécuter - Un espace d'adressage - Une priorité - Un identifiant - Un contexte d'exécution (PC + registres) *Les processus sont gérés par le système d'exploitation.* == Adressage d'un processus #image("/_src/img/docs/image copy 133.png") == Etat et transition d'un processus #table( align: left + horizon, columns: (0.5fr, 1fr), [*Etat*],[*Description*], "Prêt (ready)", "Le processus est prêt à être exécuté. Cas d'un processus nouvellement créé, débloqué ou, d'un ou plusieurs processus occupant le ou les processeurs disponibles", "Elu (running)", "Le processus est en cours d'exécution sur un processeur. Plusieurs processus peuvent être en exécution dans le cas d'une machine multiprocesseur.", "Bloqué (waiting)", "Le processus est en attente sur une synchronisation ou sur la fin d'une opération d'entreé/sortie par exemple.", "Zombie", " Le processus a terminé son exécution, mais son processus parent doit encore récupérer sa valeur de terminaison.", "Terminé", "Le processus a terminé son exécution ou a été annulé (cancelled). Les ressources du processus seront libérées et le processus disparaîtra. Il s'agit d'un pseudo-état." ) = Anatomie d'un thread #rect(fill: gray, width: 100%)[*Un thread est un fil d'exécution dans un processus*] - Les threads d'un même processus se partagent l'espace d'adressage du processus - Ils possèdent: - leur propre pile (stack) - leur propre contexte d'exécution (PC + registres) - Ils ont un cycle de vie semblable à celui d'un processus == En commun processus et thread #table( align: left + horizon, columns: (1fr), [*Processus et thread*], "Processus et Thread", "Possèdent un ID, un ensemble de registres, un état, et une priorité", "Possèdent un bloc d'information", "Partagent des ressources avec les processus parents", "Sont des entités indépendantes, une fois créés", "Les créateurs de processus et thread ont contrôle sur eux", "Peuvent changer leurs attributs après création, et créer de nouvelles ressources", "Ne peuvent accéder aux ressources d'autres threads et processus non reliés" ) == Non commun processus et thread #table( align: left + horizon, columns: (1fr, 1fr), [*Processus*],[*Thread*], "Propre espace d'adressage", "Pas d'espace d'adressage propre", "Les processus parents et enfants doivent utiliser les mécanismes de communication inter-processus", "Les threads d'un même processus communiquent en lisant et modifiant les variables de leur processus", "Les processus enfants n'ont aucun contrôle sur les autres processus enfants", "Les threads d'un processus sont considérés comme des pairs, et peuvent exercer un contrôle sur les autres threads du processus", "Les processus enfants ne peuvent pas exercer de contrôle sur le processus parent", "N'importe quel thread peut exercer un contrôle sur le thread principal, et donc sur le processus entier", )
https://github.com/mkpoli/roremu
https://raw.githubusercontent.com/mkpoli/roremu/master/src/lib.typ
typst
The Unlicense
/// 日本語ダミーテキスト生成 /// /// - words (int): 生成するテキストの長さ(文字数) /// - offset (int): テキストの開始位置(文字数) /// - custom-text (str, none): デフォルト『吾輩は猫である』の代わりに使用する文字列 /// -> str #let roremu(words, offset: 0, custom-text: none) = { let text = if custom-text == none { read("../texts/neko.txt") } else { custom-text } let length = text.clusters().len() let times = calc.div-euclid(offset + words, length) + 1 (text * times).clusters().slice(offset, offset + words).join("") }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/gentle-clues/0.9.0/lib/theme.typ
typst
Apache License 2.0
// theme file for gentle clues // defautl theme #let default = ( info: ( accent-color: rgb(29, 144, 208), // blue icon: "info.svg" ), success: ( accent-color: rgb(102, 174, 62), // green icon:"checkbox.svg" ), warning: ( accent-color: rgb(255, 145, 0), // orange icon:"warning.svg" ), error: ( accent-color: rgb(237, 32, 84), // red icon:"crossmark.svg" ), task: ( accent-color: maroon, icon:"task.svg" ), tip: ( accent-color: rgb(0, 191, 165), // teal icon:"tip.svg" ), abstract: ( accent-color: olive, icon:"abstract.svg" ), conclusion: ( accent-color: rgb(222, 49, 99), icon:"conclusion.svg" ), memo: ( accent-color: rgb(255, 82, 82), // kind of red icon:"excl.svg" ), question: ( accent-color: rgb("#7ba10a"), // greenish icon:"questionmark.svg" ), quote: ( accent-color: eastern, icon:"quote.svg" ), example: ( accent-color: orange, icon:"simple-graph.svg" ), experiment: ( accent-color: orange, icon:"experiment.svg" ), goal: ( accent-color: red, icon:"flag.svg" ), notify: ( accent-color: blue, icon:"bell.svg" ), code: ( accent-color: luma(100), icon:"code.svg" ), idea: ( accent-color: rgb(255, 201, 23), // yellow icon:"lightbulb.svg" ), danger: ( accent-color: rgb(255, 172, 51), // orange icon:"danger.svg" ), )
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/math/cases.typ
typst
// Test case distinction. --- math-cases --- $ f(x, y) := cases( 1 quad &"if" (x dot y)/2 <= 0, 2 &"if" x divides 2, 3 &"if" x in NN, 4 &"else", ) $ --- math-cases-gap --- #set math.cases(gap: 1em) $ x = cases(1, 2) $ --- math-cases-delim --- #set math.cases(delim: sym.angle.l) $ cases(a, b, c) $
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/RT/textsTmp.typ
typst
#import "../style.typ": * #let trojsvatePoOtcenas = [ #lettrine("<NAME>, <NAME>, <NAME>, pomiluj nas. (3x)") #lettrine("Slava Otcju, i Synu, i Svjatomu Duchu. ") #lettrine("I teper' i navse, i naviky-vikiv. Amiň.") #lettrine("Presvjata Trojcjo, pomiluj nas, Hospodî, očisť našy hrichy, Vladyko, odpusť nam našy provîny, Svjatyj, prîjď i vyľič našy slabostî, čerez tvoje imja.") #lettrine("Pane, zmiluj sa. (3x)") #lettrine("Slava Otcju, i Synu, i Svjatomu Duchu. ") #lettrine("I teraz i vždycky i na veky vekov. Amen.") #lettrine("Otče naš, kotryj jes' na nebesach, naj svjatîť sja tvoje imja, naj prîjde tvoje Car'stvo, naj sja ďije tvoja voľa, jak na nebi tak i na zemľi. Chľib naš denno-dennyj daj nam dnes' i odpusť nam našy dovhy, tak jak i my odpuščame svojim dovžnîkam, i ne prîveď nas do pokušiňa, no osloboď nas od lukavoho.") #lettrine("Bo tobi, Otcju, i Synu, i Svjatomu Duchu naležyť Car'stvo, mic' i slava teper' i navse, i naviky-vikiv.") #lettrine("Amiň.") ] #let nacaloPoOtcenasBezKnaza = [ #lettrine("Pane Ježišu Kriste, Bože náš, pre modlitby našich svätých otcov zmiluj sa nad nami.") #lettrine("Amiň.") #lettrine("Slava tobi, Bože naš, slava tobi.") #lettrine("<NAME>j, Poťišateľu i Duchu pravdy, što vsjahdy jes' i všytko vypovňuješ, bohatstvo dobroty, davateľu žyvota, prîjď i perebyvaj v nas i očisť nas od každoj skverny, i spas', Predobryj, našy dušy.") #trojsvatePoOtcenas ] #let nacaloPoOtcenas = [ #note[Sv: ]#lettrine("Naš Boh je blahoslovlenyj v kažďim časi: teper' i navse, i naviky-vikiv.") #note[ak nie je kňaz, prednášaj:] #lettrine("Pane Ježišu Kriste, Bože náš, pre modlitby našich svätých otcov zmiluj sa nad nami.") #lettrine("Amiň.") #lettrine("Slava tobi, Bože naš, slava tobi.") #lettrine("<NAME>j, Poťišateľu i Duchu pravdy, što vsjahdy jes' i všytko vypovňuješ, bohatstvo dobroty, davateľu žyvota, prîjď i perebyvaj v nas i očisť nas od každoj skverny, i spas', Predobryj, našy dušy.") #trojsvatePoOtcenas ] #let nacaloBezKnaza = [ #nacaloPoOtcenasBezKnaza #lettrine("Pane, zmiluj sa.") #primText[(12x)] #lettrine("Sláva Otcu i Synu i Svätému Duchu.") #lettrine("I teraz i vždycky i na veky vekov. Amen.") #lettrine("Poďte, pokloňme sa Kráľovi, nášmu Bohu.") #lettrine("Poďte, pokloňme sa Kristovi, Kráľovi, nášmu Bohu.") #lettrine("Poďte, pokloňme sa a padnime pred samým Pánom, Ježišom Kristom, Kráľom a Bohom naším.") ] #let nacalo = [ #nacaloPoOtcenas #lettrine("Pane, zmiluj sa.") #primText[(12x)] #lettrine("Sláva Otcu i Synu i Svätému Duchu.") #lettrine("I teraz i vždycky i na veky vekov. Amen.") #lettrine("Poďte, pokloňme sa Kráľovi, nášmu Bohu.") #lettrine("Poďte, pokloňme sa Kristovi, Kráľovi, nášmu Bohu.") #lettrine("Poďte, pokloňme sa a padnime pred samým Pánom, Ježišom Kristom, Kráľom a Bohom naším.") ] #let prepustenieSDostojneBezKnaza = [\ == Prepustenie <X> #lettrine("Dôstojné je velebiť teba, Bohorodička, * vždy blažená a nepoškvrnená, Matka nášho Boha.") #lettrine("Čestňijšuju cheruvim i slavňijšuju bez sravnenija serafim, bez istľinija Boha Slova roždšuju, suščuju Bohorodicu ťa veličajem. ") #lettrine("Slava Otcju, i Synu, i Svjatomu Duchu, i teper' i navse, i naviky-vikiv. Amiň. Hospodî, pomîluj (3x). Poblahoslov.") #lettrine("Pane Ježišu Kriste, Bože náš, pre modlitby našich svätých otcov zmiluj sa nad nami.") #lettrine("Amiň.") ] #let prepustenieBezKnaza = [\ == Prepustenie <X> #lettrine("Čestňišu jak cheruvimy i bez miry slavňišu jak serafimy, neporušeno porodîvšu Boha Slovo, tebe, pravdîvu Bohorodîcju, proslavľame. ") #lettrine("Slava Otcju, i Synu, i Svjatomu Duchu, i teper' i navse, i naviky-vikiv. Amiň. Hospodî, pomîluj (3x). Poblahoslov.") #lettrine("Pane Ježišu Kriste, Bože náš, pre modlitby našich svätých otcov zmiluj sa nad nami.") #lettrine("Amiň.") ] #let prepustenieMaleBezKnaza = [\ == Prepustenie <X> #lettrine("Slava Otcju, i Synu, i Svjatomu Duchu, i teper' i navse, i naviky-vikiv. Amiň. Hospodî, pomîluj (3x). Poblahoslov.") #lettrine("Pane Ježišu Kriste, Bože náš, pre modlitby našich svätých otcov zmiluj sa nad nami.") #lettrine("Amiň.") ] #let prepustenie = [\ == Prepustenie <X> #note[Sv: ] #lettrine("Premudrosť!") #note[L: ] #lettrine("Čestňišu jak cheruvimy i bez miry slavňišu jak serafimy, neporušeno porodîvšu Boha Slovo, tebe, pravdîvu Bohorodîcju, proslavľame.") #note[Sv: ] #lettrine("Slava tobi, Christe Bože, naďijo naša, slava tobi.") #note[L: ] #lettrine("Slava Otcju, i Synu, i Svjatomu Duchu, i teper' i navse, i naviky-vikiv. Amiň. Hospodî, pomîluj (3x). Poblahoslov.") #note[Sv: ] #lettrine("Christos, naš pravdîvyj Boh, naj nas na pros'by svojoj Prečistoj Materî, svjatych, slavnych i vsjahdy proslavľanych apostoľiv, blaženoho Prjašivskoho jepiskopa svjaščenomučenîka Pavla i všytkych svjatych pomîluje i spasîť, jak dobryj i čolovikoľubec'.") #note[L: ] #lettrine("Amiň.") ] #let tropar(hlas, podoben, txt) = [ #primText[Tropár (#hlas. hlas#if podoben != none [, #podoben])]: #txt ] #let sit(hlas, podoben, txt) = [ #primText[Sláva: I teraz: #if hlas != none [(#hlas. hlas#if podoben != none [, #podoben]):] ]#txt ] #let stich(hlas, podoben, txt) = [ #primText[#if hlas != none [(#hlas. hlas#if podoben != none [, #podoben]):]] #txt ] #let vers(txt) = [ #pad(left: 20pt)[#primText[Verš:] #txt] ] #let K(txt) = [ #note[Sv:] #txt ] #let L(txt) = [ #note[L:] #txt ] #let prokimen(hlas, txt, v) = [ #primText[Prokimen (#hlas. hlas)]: #txt #vers[#v] ] #let zalm(num) = [ #import "/style.typ": * #set par(first-line-indent: 1em) #subheader[Žalm #num] #include "zalmy/Z"+padNum(num)+".typ" ] #let slavoslovieMale = [ #set par(first-line-indent: 1em) Sláva Bohu na nebi a mier na zemi. V ľuďoch dobrá vôľa. Chválime ťa, velebíme ťa. Klaniame sa ti, oslavujeme ťa. Dobrorečíme ti pre nesmiernu tvoju slávu, Pane a Kráľu nebeský, Bože, Otče, všemohúci Vládca, Pane náš a jednorodený Synu, Ježišu Kriste i Svätý Duchu, Pane Bože. Baránok Boží, Syn Otca, ty, čo snímaš hriechy sveta, zmiluj sa nad nami. Ty, čo snímaš hriechy sveta, prijmi naše modlitby. Ty, čo sedíš po pravici Otcovej, zmiluj sa nad nami. Len ty sám si svätý, ty jediný si Pán, Ježiš Kristus v sláve Boha Otca. Amen. Každý deň ťa budeme velebiť a tvoje meno chváliť navždy a naveky. Pane, bol si naše útočisko z pokolenia na pokolenie. Riekol som: Pane, zmiluj sa nado mnou a uzdrav moju dušu, lebo som sa prehrešil proti tebe. Pane, k tebe sa utiekam. Nauč ma plniť tvoju vôľu, lebo ty si môj Boh. Veď u teba je zdroj života a v tvojom svetle uzrieme svetlo. Svoju milosť daj tým, čo ťa poznajú. Ráč nás, Pane, v tento deň zachrániť od hriechu. Velebíme ťa, Pane, Bože otcov našich. Chválime a oslavujeme tvoje meno na veky. Amen. Preukáž nám, Pane, svoje milosrdenstvo, lebo dúfame v teba. Blahoslavený si, Pane, nauč nás svoje pravdy. Blahoslavený si, Vládca, daj nám porozumieť svojim pravdám. Blahoslavený si, Svätý, osvieť nás svojimi pravdami. Pane, tvoje milosrdenstvo je večné, nepohŕdaj dielom svojich rúk. Tebe patrí chvála, tebe patrí pieseň. Tebe, Otcu i Synu, i Svätému Duchu, patrí sláva teraz i vždycky, i na veky vekov. Amen. ] #let slavoslovieVelke = [ #set par(first-line-indent: 1em) Sláva Bohu na nebi a mier na zemi. V ľuďoch dobrá vôľa. Chválime ťa, velebíme ťa. Klaniame sa ti, oslavujeme ťa. Dobrorečíme ti pre nesmiernu tvoju slávu, Pane a Kráľu nebeský, Bože, Otče, všemohúci Vládca, Pane náš a jednorodený Synu, Ježišu Kriste i Svätý Duchu, Pane Bože. <NAME>, Syn Otca, ty, čo snímaš hriechy sveta, zmiluj sa nad nami. Ty, čo snímaš hriechy sveta, prijmi naše modlitby. Ty, čo sedíš po pravici Otcovej, zmiluj sa nad nami. Len ty sám si svätý, ty jediný si Pán, <NAME> v sláve Boha Otca. Amen. Každý deň ťa budeme velebiť a tvoje meno chváliť navždy a naveky. Pane, bol si naše útočisko z pokolenia na pokolenie. Riekol som: Pane, zmiluj sa nado mnou a uzdrav moju dušu, lebo som sa prehrešil proti tebe. Pane, k tebe sa utiekam. Nauč ma plniť tvoju vôľu, lebo ty si môj Boh. Veď u teba je zdroj života a v tvojom svetle uzrieme svetlo. Svoju milosť daj tým, čo ťa poznajú. Ráč nás, Pane, v tento deň zachrániť od hriechu. Velebíme ťa, Pane, Bože otcov našich. Chválime a oslavujeme tvoje meno na veky. Amen. Preukáž nám, Pane, svoje milosrdenstvo, lebo dúfame v teba. Blahoslavený si, Pane, nauč nás svoje pravdy. Blahoslavený si, Vládca, daj nám porozumieť svojim pravdám. Blahoslavený si, Svätý, osvieť nás svojimi pravdami. Pane, bol si naše útočisko z pokolenia na pokolenie. Riekol som: Pane, zmiluj sa nado mnou a uzdrav moju dušu, lebo som sa prehrešil proti tebe. Pane, k tebe sa utiekam. Nauč ma plniť tvoju vôľu, lebo ty si môj Boh. Veď u teba je zdroj života a v tvojom svetle uzrieme svetlo. Svoju milosť daj tým, čo ťa poznajú. ] #let vKazdomCase = [ V každom čase a v každej chvíli v nebi aj na zemi sa ti klaňajú a teba oslavujú, Bože dobrý, trpezlivý a nesmierne milosrdný. Ty miluješ spravodlivých, zmilúvaš sa nad hriešnymi a všetko voláš k spáse pre prísľub budúceho dobra. Ty sám, Pane, prijmi v tejto hodine aj naše modlitby a nasmeruj náš život k tvojim prikázaniam. Naše duše posväť a telá očisť, myšlienky usmerni, rozum urob rozvážnym a triezvym, osloboď nás od každého zármutku, zla a utrpenia. Okolo nás postav svojich svätých anjelov ako hradbu, aby sme pod ochranou a vedením ich oddielov dosiahli jednotu vo viere a poznanie tvojej nedotknuteľnej slávy, veď ty si požehnaný na veky vekov. Amen. ]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/emphasis-05.typ
typst
Other
// Error: 26 expected star // Error: 26 expected underscore #[_Cannot *be interleaved]
https://github.com/levinion/typst-dlut-templates
https://raw.githubusercontent.com/levinion/typst-dlut-templates/main/templates/util/style.typ
typst
MIT License
#let font_size = ( chu: 42pt, xiao_chu: 36pt, yi: 26pt, xiao_yi: 24pt, er: 22pt, xiao_er: 18pt, san: 16pt, xiao_san: 15pt, si: 14pt, xiao_si: 12pt, wu: 10.5pt, xiao_wu: 9pt, liu: 7.5pt, xiao_liu: 6.5pt, qi: 5.5pt, xiao_qi: 5pt, ) #let font_family = ( songti_bold: ( "Times New Roman", "Source Han Serif SC", "Source Han Serif", "Noto Serif CJK SC", "SimSun", "Songti SC", "STSongti", ), songti: ("Times New Roman", "SimSun"), heiti: ( "Times New Roman", "Source Han Sans SC", "Source Han Sans", "Noto Sans CJK SC", "SimHei", "Heiti SC", "STHeiti", ), huawen_xihei: ( "Times New Roman", "Source Han Sans SC", "Source Han Sans", "Noto Sans CJK SC", "SimHei", "Heiti SC", "STHeiti", ), huawen_xingkai: ("Times New Roman", "STXingkai"), ) #let vspacer(n, size: 12pt)=[ #set text(font: font_family.songti, size: size) #for i in range(0, n + 1){ linebreak(justify: false) } ]