repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/vmysak/modern-cv-typst
https://raw.githubusercontent.com/vmysak/modern-cv-typst/main/src/my-config.typ
typst
Apache License 2.0
#import "@preview/fontawesome:0.2.1": * /** Page Config **/ #let page-margin = (left: 10mm, right: 10mm, top: 10mm, bottom: 5mm) #let main-font = ("DejaVu Sans") #let main-font-size = 10pt #let full-name-font-size = 30pt #let contacts-font-size = 9pt #let roles-padding = 10pt #let contacts-padding = 0pt #let footer-font-size = 8pt /** User Data **/ #let userInfo = ( firstname: "John", lastname: "Doe", fullName: "<NAME>", roles: ("Lead Engineer", "Software Engineer"), urls: ( linkedin: "https://www.linkedin.com/in/", github: "https://github.com/", email: "mailto:", homepage: "https://site.com/johndoeeeeeeeee", ), /** Try to change order and/or comment line :) **/ contacts: ( // homepage: "Home Page", // birth: "March 1 1900", address: "Earth | Remote", email: "<EMAIL>", phone: "(+123) 123 123 32 09", github: "johndoeeeeeeeeex", linkedin: "johndoeeeeeeeeeeeeeeeeeeeeex", ), footer: ("phone", "telegram", "email"), ) /** Color Schemes **/ #let palettes = ( _selected: "sunrise", bluefish: ( regular-color: rgb("#333333"), regular-color-desat: rgb("#666666"), accent-color: rgb("#262F99"), ), forest: ( regular-color: rgb("#022015"), regular-color-desat: rgb("#153328"), accent-color: rgb("#1aa572"), ), sunrise: ( regular-color: rgb("#252020"), regular-color-desat: rgb("#524848"), accent-color: rgb("#b9831e"), ), blackwhite: ( regular-color: rgb("#000000"), regular-color-desat: rgb("#444444"), accent-color: rgb("#000000"), ), ) #let pal = palettes.at(palettes._selected); /** Icons **/ #let icons = ( address: box(fa-icon("home", fill: pal.accent-color)), birth: box(fa-icon("cake", fill: pal.regular-color)), homepage: box(fa-icon("link", fill: pal.regular-color)), linkedin: box(fa-icon("linkedin", fill: rgb("0077b5"))), github: box(fa-icon("github", fill: rgb("#000000"))), phone: box(fa-icon("square-phone", fill: rgb("#588f53"))), email: box(fa-icon("envelope", fill: rgb("#884a45"))), ) #let size90x10 = (left: 9fr, right: 1fr) #let size80x20 = (left: 8fr, right: 2fr) #let size70x30 = (left: 7fr, right: 3fr) #let size60x40 = (left: 6fr, right: 4fr) #let size50x50 = (left: 5fr, right: 5fr) #let size60x40 = (left: 4fr, right: 6fr) #let size30x70 = (left: 3fr, right: 7fr) #let size20x80 = (left: 2fr, right: 8fr) #let size10x90 = (left: 1fr, right: 9fr) #let inset-row(i) = { ( top: if i > 0 { 7pt } else { 0pt }, ) }
https://github.com/Henriquelay/pathsec-checker
https://raw.githubusercontent.com/Henriquelay/pathsec-checker/main/presentation/figures/addition.typ
typst
#import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge, shapes #set page(width: auto, height: auto, margin: (x: 0pt, y: 0pt)) #set text(font: "New Computer Modern") #diagram({ for i in range(1, 11) { let h = "h" + str(i) node((i / 2, 1), h, stroke: 0.5pt, name: label(h), shape: shapes.rect) edge("<->") let e = "e" + str(i) node((i / 2, 0.5), e, stroke: 0.5pt, name: label(e), shape: shapes.pill) edge("<->") let s = "s" + str(i) node((i / 2, 0), s, stroke: 0.5pt, name: label(s), shape: shapes.octagon) } for i in range(1, 10) { edge(label("s" + str(i)), label("s" + str(i + 1)), "<->") } // node((0 / 2, 1), "h11", stroke: 0.5pt, name: "h11", shape: shapes.rect) // edge(auto, <e1>, "<->") node((5.5 / 2, -0.6), "s555", stroke: 0.5pt, name: "s555", shape: shapes.octagon) edge(<s555>, <s6>, "<->") edge(<s5>, <s555>, "<->") })
https://github.com/Rhinemann/mage-hack
https://raw.githubusercontent.com/Rhinemann/mage-hack/main/src/chapters/Character%20Creation.typ
typst
#import "../templates/interior_template.typ": * #show: chapter.with(chapter_name: "Character Creation") = Character Creation #show: columns.with(2, gutter: 1em) #block(breakable: false)[ === Step 0: Get a character sheet TODO. ] #block(breakable: false)[ === Step 1: Choose Distinctions - One for your personality & sleeper life. #quote[Examples: Rebellious Ex-Barista, Insecure Artist...;] - One for your Awakened affiliation. #quote[Examples: Hermetic Adept Major, A Verbena Witch, A NWO Agent...;] - One for your focus. #quote[Examples: High Ritual Magick, Witchcraft, Dominion...;] ] #block(breakable: false)[ === Step 2: Assign Attributes Each attribute defaults to #spec_c.d4 and you have 12 points to step them up. ] Maximum attribute value at character creation is #spec_c.d10. #block(breakable: false)[ === Step 3: Assign Skills Each Skill defaults to #spec_c.d4 and you have 16 points to step up skills. ] Maximum skill value at character creation is #spec_c.d10. #block(breakable: false)[ === Step 4: Spheres You have 6 points to spend on sphere rating, starting on #spec_c.d4, maximum Sphere rating at character creation is #spec_c.d8. ] At least one point must be assigned to Tradition's affinity Sphere, to reflect your training in Tradition's specialty. #block(breakable: false)[ === Step 5: Assign Specialties, Signature Assets, and additional Powers Players have 9 points to spend on these options: ] - One point to buy a Signature Asset; - One point to step up a Signature Asset; - One point to buy a Specialty; - Two points to buy a new Sphere; - Two points to step your Sphere up; - Two points buy a new locked SFX; At character creation Signature Assets may not be larger than #spec_c.d8. #block(breakable: false)[ === Step 6: Assign SFX and Quintessence Pool Write down your SFX. Assign #spec_c.d6 #spec_c.d6 to the Quintessence pool, this is your Quintessence pool size. ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unify/0.1.0/README.md
markdown
Apache License 2.0
# Unify `unify` is a [typst](https://github.com/typst/typst) package simplifying the typesetting of number, (physical) units, and ranges. It is the equivalent to LaTeX's `siunitx`, though not as mature. ## Overview `unify` allows flexible numbers and units, and still mostly gets well typeset results. ```ts #import "@preview/unify:0.1.0": num, unit, range, unit-range $ #num("-1.3+-0.5e-6") $ $ #unit("1.3+1.2-0.3e3", "meter per second squared") $ $ #range("1e-2", "3e5") $ $ #unit-range("1e3", "2e3", "meter per second") $ ``` <img src="examples/overview.jpg" width="200"> ## `num` `num` uses string parsing in order to typeset numbers. They can have the following form: - `-` - `float` or `integer` number - either (`{}` stands for a number) - symmetric uncertainties with `+-{}` - asymmetric uncertainties with `+{}-{}` - exponential notation `e{}` Parentheses are automatically set as necessary. ## `unit` `unit` allows a `num` as the first argument following the same rules. The second argument is the `unit`. If `raw_unit` is set to true, its value will be passed on to the result. Otherwise, the unit should be written in words. Later on, I made a shorthand notation. The value of `space` will be inserted between units if necessary. Units have four possible parts: - `per` forms the inverse of the following unit. - A prefix in the sense of SI. This is added before the unit. - The unit itself. - A postfix like `squared`. This is added after the unit and takes `per` into account. The possible values of the three latter parts are loaded at runtime from `prefixes.csv`, `units.csv`, and `postfixes.csv` (in the library directory). There, you can also add your own units. The formats for the pre- and postfixes are: | pre-/postfix | symbol | | ------------ | ------------ | | milli | upright("m") | and for units: | unit | symbol | space | | ----- | ------------ | ----- | | meter | upright("m") | true | The first column specifies the whole word that will be replaced. This should be unique. The second column represents the string that will be inserted as the unit symbol. For units, the last column describes whether there should be space before the unit (possible values: `true`/`false`, `1`,`0`). This is mostly the cases for degrees and other angle units (e.g. arcseconds). If you think there are units not included that are of interest for other users, you can create an issue or PR. ## `range` `range` takes two `num`s as the first two arguments. If they have the same exponent, it is automatically factorized. The range symbol can be changed with `delimiter`, and the space between the numbers and symbols with `space`. ## `unit_range` `unit_range` is just a combination of `unit` and `range`.
https://github.com/pascalguttmann/typst-template-report-lab
https://raw.githubusercontent.com/pascalguttmann/typst-template-report-lab/main/template/chapter/instruments.typ
typst
MIT License
= Description of Instruments and Methods
https://github.com/flavio20002/typst-orange-template
https://raw.githubusercontent.com/flavio20002/typst-orange-template/main/README.md
markdown
MIT No Attribution
# orange-book A book template inspired by The Legrand Orange Book of Mathias Legrand and Vel https://www.latextemplates.com/template/legrand-orange-book. ## Usage You can use this template in the Typst web app by clicking "Start from template" on the dashboard and searching for `orange-book`. Alternatively, you can use the CLI to kick this project off using the command ``` typst init @preview/orange-book ``` Typst will create a new directory with all the files needed to get you started. ## Configuration This template exports the `book` function with the following named arguments: - `title`: The book's title as content. - `subtitle`: The book's subtitle as content. - `author`: Content or an array of content to specify the author. - `paper-size`: Defaults to `a4`. Specify a [paper size string](https://typst.app/docs/reference/layout/page/#parameters-paper) to change the page format. - `copyright`: Details about the copyright or `none`. - `lowercase-references`: True to have references in lowercase (Eg. table 1.1) The function also accepts a single, positional argument for the body of the book. The template will initialize your package with a sample call to the `book` function in a show rule. If you, however, want to change an existing project to use this template, you can add a show rule like this at the top of your file: ```typ #import "@preview/orange-book:0.1.0": book #show: book.with( title: "Exploring the Physical Manifestation of Humanity’s Subconscious Desires", subtitle: "A Practical Guide", date: "Anno scolastico 2023-2024", author: "<NAME>", mainColor: rgb("#F36619"), lang: "en", cover: image("./background.svg"), imageIndex: image("./orange1.jpg"), listOfFigureTitle: "List of Figures", listOfTableTitle: "List of Tables", supplementChapter: "Chapter", supplementPart: "Part", part_style: 0, copyright: [ Copyright © 2023 <NAME> PUBLISHED BY PUBLISHER #link("https://github.com/flavio20002/typst-orange-template", "TEMPLATE-WEBSITE") Licensed under the Apache 2.0 License (the “License”). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. _First printing, July 2023_ ], lowercase-references: false ) // Your content goes below. ```
https://github.com/mawkler/cv
https://raw.githubusercontent.com/mawkler/cv/main/english.typ
typst
MIT License
#import "cv.typ": cv, experience, skill, list_interests #import "@preview/fontawesome:0.1.0": * #cv( name: "<NAME>", links: ( (link: "mailto:<EMAIL>", icon: fa-at()), (link: "https://github.com/mawkler", display: "mawkler", icon: fa-github()), (link: "https://fosstodon.org/@mawkler", display: "fosstodon.org/@mawkler", icon: fa-mastodon()), (link: "https://linkedin.com/in/melker-ulander/", display: "<NAME>", icon: fa-linkedin()), ), occupation: "Software Engineer", tagline: [Looking for opportunities to work in Rust. Check out what I'm up to #link("https://github.com/mawkler/cv", "my GitHub").], compiled_date: [Compiled: #datetime.today().display()], left_column: [ == Work Experience #experience("images/omegapoint.png")[Software engineering consultant][Omegapoint][2021 --- present][Stockholm] These are the consulting assignments I've worked on so far: - RESTful Go back-end development in Azure/Kubernetes for an energy company. Bicep IaC, CI/CD. - Java microservices in Kubernetes for a veterinary clinic. Main focus on DevOps and CI/CD, as well as "functional Java". - RESTful back-end development with Azure Functions in TypeScript/Node for a heat-pump manufacturer. Primary focus on DDD, security and CI/CD. #experience("images/ericsson.png")[Software developer][Ericsson][2016 --- 2017][Kista, Stockholm] My work as a summer intern during 2016 as well as 2017 involved building tools that simplify the management of radio software databases. During my first summer I worked mainly on a web client written in Angular. During my second summer I worked with text parsing and building a web-server in Python. The work was done in an agile manner in teams of 2--5 people. #experience("images/hello-world.png")[Programming and CAD teacher][Hello World!][2018][Stockholm] Hello World! is a Swedish non-profit association that teaches kids and teenagers digital skills. I taught programming of microcontrollers such as Arduinos using Python, CAD and 3D-printing, as well as Lua programming. My work at Hello World! improved both my pedagogical and leadership skills. It also confirmed to me how much I love teaching. #experience("images/uppsala.png")[Computer science lab teacher][Uppsala University][2017, 2019][Uppsala] I taught and guided students during computer labs in the course Program Design and Data Structures. The labs included many practical parts like Haskell programming, calculating time complexities, proof by induction, etc. During this work I got the chance to improve my pedagogical skills. == Education #experience("images/uppsala.png")[Master Programme in Computer and Information Engineering, 300 c --- Software Engineering Specialization][Uppsala University][2015-2021][Uppsala] Programming, mathematics and problem solving are three basic building blocks of the programme. For instance, I gained experience working in cross-functional teams, creating software requirements as well as product development in an agile manner. #experience("images/wik.png")[Music programme][Wik's Folkhögskola][2014-2015][Uppsala] Music education with focus on musical variety and expression in song writing as well as live performance and music theory. == Interests #list_interests(( "Neovim", "Open source", "Rust", "Tooling", "Music", "Computer games", "Keyboards", "Board games", "Climbing", "Archery", "Snowboarding" )) ], right_column_header: "Programming Skills", languages_header: "Languages", other_technologies_header: "Other Technologies", right_column: [ === Methodologies #skill("Domain-Driven Design", 4) #skill("Agile", 4) #skill("REST", 4) #skill("DevOps", 4) == Spoken Languages #skill("Swedish", 5) #skill("English", 5) #skill("Spanish", 1) == Other Merits - AWS Certified Cloud Practitioner certificate - Driver's license class B since 2015 ], footer_content: [My CV is open-source. If you're curious, its source code is available at #link("https://github.com/mawkler/cv").] )
https://github.com/dariasc/notebook
https://raw.githubusercontent.com/dariasc/notebook/master/main.typ
typst
#import "template.typ": * #show: project #title() #insert("template.h") = Data Structures #insert("ds/hashmap.h") #insert("ds/order_statistic_tree.h") #insert("ds/uf.h") #insert("ds/convex_hull_trick.h") #insert("ds/sparse_table.h") #insert("ds/iterative_segment_tree.h") #insert("ds/lazy_segment_tree.h") #insert("ds/persistent_segment_tree.h") = Number Theory #insert("nt/modpow.h") = Strings #insert("strings/kmp.h") = Graphs #insert("graph/topo_sort.h") #insert("graph/dinic.h")
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fletcher/0.4.4/src/shapes.typ
typst
Apache License 2.0
#import "deps.typ": cetz #import cetz: draw, vector /// The standard rectangle node shape. /// /// A string `"rect"` or the element function `rect` given to /// #the-param[node][shape] are interpreted as this shape. /// /// #diagram( /// node-stroke: green, /// node-fill: green.lighten(90%), /// node((0,0), `rect`, shape: fletcher.shapes.rect) /// ) /// /// - node (dictionary): A node dictionary, containing: /// - `corner-radius` /// - `size` /// - extrude (length): The extrude length. #let rect(node, extrude) = { let r = node.corner-radius let (w, h) = node.size.map(i => i/2 + extrude) draw.rect( (-w, -h), (+w, +h), radius: if r != none { r + extrude }, ) } /// The standard circle node shape. /// /// A string `"cricle"` or the element function `cricle` given to /// #the-param[node][shape] are interpreted as this shape. /// /// #diagram( /// node-stroke: red, /// node-fill: red.lighten(90%), /// node((0,0), `circle`, shape: fletcher.shapes.circle) /// ) /// /// - node (dictionary): A node dictionary, containing: /// - `radius` /// - extrude (length): The extrude length. #let circle(node, extrude) = draw.circle((0, 0), radius: node.radius + extrude) /// An elliptical node shape. /// /// #diagram( /// node-stroke: orange, /// node-fill: orange.lighten(90%), /// node((0,0), `ellipse`, shape: fletcher.shapes.ellipse) /// ) /// /// - node (dictionary): A node dictionary, containing: /// - `node.size` /// - extrude (length): The extrude length. #let ellipse(node, extrude) = { draw.circle( (0, 0), radius: vector.scale(node.size, 0.5).map(x => x + extrude), ) } /// A rhombus node shape. /// /// #diagram( /// node-stroke: purple, /// node-fill: purple.lighten(90%), /// node((0,0), `diamond`, shape: fletcher.shapes.diamond) /// ) /// /// - node (dictionary): A node dictionary, containing: /// - `size` /// - extrude (length): The extrude length. /// - scale (number): Scale factor to increase the node's drawn size (without /// affecting its real size). This is used so the label doesn't poke out. #let diamond(node, extrude, scale: 1.5) = { let (w, h) = node.size let φ = calc.atan2(w/1pt, h/1pt) let x = w/2*scale + extrude/calc.sin(φ) let y = h/2*scale + extrude/calc.cos(φ) draw.line( (-x, 0pt), (0pt, -y), (+x, 0pt), (0pt, +y), close: true, ) } /// A capsule node shape. /// /// #diagram( /// node-stroke: teal, /// node-fill: teal.lighten(90%), /// node((0,0), `pill`, shape: fletcher.shapes.pill) /// ) /// /// - node (dictionary): A node dictionary, containing: /// - `size` /// - extrude (length): The extrude length. #let pill(node, extrude) = { let size = node.size.map(i => i + 2*extrude) draw.rect( vector.scale(size, -0.5), vector.scale(size, +0.5), radius: calc.min(..size)/2, ) } /// A slanted rectangle node shape. /// /// #diagram( /// node-stroke: olive, /// node-fill: olive.lighten(90%), /// node((0,0), `parallelogram`, shape: fletcher.shapes.parallelogram) /// ) /// /// - node (dictionary): A node dictionary, containing: /// - `size` /// - extrude (length): The extrude length. /// - angle (angle): Angle of the slant, `0deg` is a rectangle. Don't set to /// `90deg` unless you want your document to be larger than the solar system. #let parallelogram(node, extrude, angle: 20deg) = { let (w, h) = node.size let (x, y) = (w/2 + extrude*calc.cos(angle), h/2 + extrude) let δ = h/2*calc.tan(angle) let μ = extrude*calc.tan(angle) draw.line( (-x - μ, -y), (+x - δ, -y), (+x + μ, +y), (-x + δ, +y), close: true, ) } /// An (irregular) hexagon node shape. /// /// #diagram( /// node-stroke: aqua, /// node-fill: aqua.lighten(90%), /// node((0,0), `hexagon`, shape: fletcher.shapes.hexagon) /// ) /// /// - node (dictionary): A node dictionary, containing: /// - `size` /// - extrude (length): The extrude length. /// - angle (angle): Half the exterior angle, `0deg` being a rectangle. #let hexagon(node, extrude, angle: 30deg) = { let (w, h) = node.size let (x, y) = (w/2, h/2 + extrude) let δ = y*calc.tan(angle) x += extrude*calc.tan(45deg - angle/2) draw.line( (-x, -y), (+x, -y), (+x + δ, 0pt), (+x, +y), (-x, +y), (-x - δ, 0pt), close: true, ) } /// An pentagonal node shape, like a house. /// /// #diagram( /// node-stroke: eastern, /// node-fill: eastern.lighten(90%), /// node((0,0), `house`, shape: fletcher.shapes.house) /// ) /// /// - node (dictionary): A node dictionary, containing: /// - `size` /// - extrude (length): The extrude length. /// - angle (angle): The slant of the roof. Set to `0deg` for a rectangle, and /// to `90deg` for a document stretching past Pluto. #let house(node, extrude, angle: 10deg) = { let (w, h) = node.size let (x, y) = (w/2 + extrude, h/2 + extrude) let a = h/2 + extrude*calc.tan(45deg - angle/2) let b = h/2 + w/2*calc.tan(angle) + extrude/calc.cos(angle) draw.line( (-x, -y), (-x, a), (0pt, b), (+x, a), (+x, -y), close: true, ) } /// A truncated rectangle node shape. /// /// #diagram( /// node-stroke: maroon, /// node-fill: maroon.lighten(90%), /// node((0,0), `octagon`, shape: fletcher.shapes.octagon) /// ) /// /// - node (dictionary): A node dictionary, containing: /// - `size` /// - extrude (length): The extrude length. /// - truncate (number, length): Size of the truncated corners. A number is /// interpreted as a ratio of the smaller of the node's width or height. #let octagon(node, extrude, truncate: 0.5) = { let (w, h) = node.size let (x, y) = (w/2 + extrude, h/2 + extrude) let d if type(truncate) == length { d = truncate } else { d = truncate*calc.min(w/2, h/2)} d += extrude*0.5857864376 // (1 - calc.tan(calc.pi/8)) draw.line( (-x + d, -y ), (-x , -y + d), (-x , +y - d), (-x + d, +y ), (+x - d, +y ), (+x , +y - d), (+x , -y + d), (+x - d, -y ), close: true, ) }
https://github.com/huyufeifei/grad
https://raw.githubusercontent.com/huyufeifei/grad/master/docs/paper/src/ch5.typ
typst
= 测试 == 功能测试 对VirtIO驱动程序功能的测试分别使用 #link("https://github.com/rcore-os/virtio-drivers/tree/master/examples/riscv")[rCore所提供的riscv架构测试程序] 的 #link("https://github.com/huyufeifei/svdrivers/tree/master/qemu")[改进版本] 和Alien中进行测试。测试代码已在链接中给出。对于Uart16550设备驱动的测试仅在Alien中进行测试。 对于不同设备的功能测试方式分别如下: - *块设备:*对于设备的每一个块,使用一个函数计算出一个对应的均匀分布的数字,对该块的所有字节写入该数字。随后使用一个初始化为0的内存空间缓冲区,向其中读取目标块内的数据。如果所读取到的数据与写入的数据完全相同,则说明该块设备驱动的读写操作功能是正确的。 - *网卡:*对于一个被初始化的网卡,它将不断侦听是否收到了包。如果有新收到的包,就会像系统发送中断标志。因此,在tcp网络协议栈未启用的情况下,使用`ping`命令向qemu模拟器所映射到虚拟机内网卡的端口发送查询命令,开启日志输出并编译后,在Alien虚拟机系统中可以观察到收到网络包带来的中断。输出收到的包内容,为所发出的ping请求包。在tcp网络协议栈启用的情况下,使用`netcat` / `nc`命令对其进行tcp连接的测试,能够看到nc输出tcp连接成功建立的消息。使用`netcat`发送测试数据`"hello"`,并在系统中将收到的数据逆序输出,如果观测到虚拟机输出`"olleh"`,则可以证明驱动程序对网络包的接受和发送功能正确。 - *输入设备:*由于硬件条件限制,对于输入设备只测试了鼠标和键盘的设置。通过在qemu的运行指令里启用鼠标和键盘的VirtIO设备,可以把宿主机的鼠标和键盘输出传入到虚拟机的设备中。使用同一个驱动程序对此两设备进行测试。在初始化之后,将系统焦点聚集于虚拟机的窗口中,随后进行键盘按键、长按或者鼠标点击、移动、滚轮操作,并启用日志输出。对于所有的输入设备操作均能看到在测试程序中输出了接收到的输入事件,说明输入设备驱动的功能正确。 - *Uart16550 串口设备:*串口设备被用于在Alien中与终端进行通信。在没有启用或初始化串口设备时,虚拟机与用户的交互直接经过qemu完成。在使用串口之后,系统向串口输出的内容和会在终端呈现,串口收到的内容会被系统检测到。在初始化串口驱动后使用其输出函数,向终端输出`"uart test"`,结果正确的在终端显示,说明串口驱动正确。 测试的结果,所开发的安全驱动,可以正常操作设备,完成所需的功能。 == 性能测试 通常认为使用底层的C语言的一个优势是其效率更高。而Rust的零成本抽象为其带来了与C/C++类似的性能。使用Rust仅比C++程序慢4-8%@y4,而不安全的C风格Rust速度则与C/C++程序相差无几@redleaf。通过对有较高性能需求的块设备驱动的速度测试,可以展现出使用安全代码编写的设备驱动与不安全代码相比性能变化如何。 以下的测试所使用的环境是: / 中央处理器: 13th Gen Intel(R) Core(TM) i9-13900HX / 操作系统: Windows Subsystem for Linux (WSL) 2 Ubuntu 20.04 / 虚拟机软件:qemu 7.0.0 === 块设备 对块设备的测试采用顺序读写的方式进行。使用的设备大小为20MB。该设备是一个由`dd`命令所创建的文件,每次写入1MB的源于`/dev/zero`的数据,总共执行数量为20次。随后可以在qemu的运行命令中将该20MB的文件作为一个存储设备传递给虚拟机中。测试中分别使用本项目的安全Rust实现的驱动和用于对比的使用了不安全代码的设备驱动对其进行总共200次全盘读写,并记录每次的时间和速度。最后以此计算出两种不同驱动的平均速度和方差。写入时所使用的数据全部为0xFF,而对于读取时的数据未进行任何初始化。200次全盘读写会分为20次进行,每次会读写十倍于整个设备的数据量。这些操作按照块编号由低到高的顺序被执行,并在超出最大空间之后回到0号块继续进行循环。每次读写在开始前后都会读取riscv架构中用于计时的寄存器,将之相减后能够获知该读写操作总共所花费的时钟周期。由于qemu中riscv机器的cpu频率已知,因此通过计算可以获知该计时时长对应多少现实时间。块的大小通过驱动的查询容量功能获取,而非硬编码在测试程序中,可以应对不同大小的设备的测试需要。计时的区域不包括查询块设备大小所耗费的时间。但是会计入循环语句的时间与对驱动程序提供的功能进行函数调用的时间。最后通过计算每次总读写的数据量与耗时之商,可以获知该次操作的实际吞吐量。驱动所提供的查询容量所返回的单位是块。而一块在VirtIO块设备的规定中大小为512字节,因此该返回值与一块的存储大小相乘就是整个设备的容量。为了保证测试结果的精确性,在进行测试时,不对测试机器进行任何其他操作以避免有程序与qemu抢占CPU从而导致测试结果不准确。为提高计算精度,所有数值都被转化为64位浮点数进行运算。每次单次测试出来的结果将会被存入一个数组中,此操作不会被计入所耗费时间。在所有次测试都结束后,对于所获得的每次速度数组,可以进行求平均与求方差的操作,以此减小测例结果中的误差,增大可信度。方差被用于说明设备驱动的运行速度稳定性。 测试所得的原始数据可以在#link("https://github.com/huyufeifei/grad/tree/master/info/test_data")[此链接处]查看,测试所用代码分别在github代码仓库下的`svdrivers/qemu`和`virtio-drivers/example/riscv`文件夹中。测试的结果如下表: #figure( table(columns: (5em, 1fr, 1fr, 1fr, 1fr), stroke: 1pt + black, table.cell(rowspan:2, "操作类型"), table.cell(colspan:2, "安全代码"), table.cell(colspan:2, "不安全代码"), "平均速度", "方差", "平均速度", "方差", "读", "19.86MB/s", "0.027", "19.87MB/s", "0.086", "写", "18.04MB/s", "0.129", "17.40MB/s", "0.038", ), caption: "块设备读写性能", ) 从如上数据中可以看出,使用安全代码实现的VirtIO块设备驱动相比于不安全的设备驱动,在顺序读取操作上速度相差无几,而在顺序写入时,其速度甚至比不安全的实现快了3.6%。 写操作普遍比读操作缓慢,但是差距并不大,只有约2MB/s的差距。读和写操作都接近一个上限,即20MB/s。这个速度很可能是在虚拟环境中使用单处理器对块设备进行读写的速度上限。安全驱动和不安全驱动均接近这个上限,表明在现有应用场景中驱动的性能并没有成为操作的瓶颈。 这些数据说明了在块设备驱动这方面,使用不安全代码并没有显著的速度优势。因此可以放心的使用安全的设备驱动,而不需要担心其可能对性能造成的影响。
https://github.com/HiiGHoVuTi/requin
https://raw.githubusercontent.com/HiiGHoVuTi/requin/main/lang/mon-syn.typ
typst
#import "../lib.typ": * #show heading: heading_fct #import "@preview/gloss-awe:0.0.5": gls #show figure.where(kind: "jkrb_glossary"): it => {it.body} === Prélude // NOTE(Juliette) : le début est extrait de TD Un _monoïde_ est $(M, +)$ est un #gls(entry: "Magma")[magma] associatif unifère, c'est-à-dire un #gls(entry: "Demi-groupe")[demi-groupe] avec un élément neutre. #question(0)[Rappeler pourquoi $Sigma^star$ est un monoïde.] Un _monoïde libre_ sur $A$ est le plus petit monoïde tel que tout élément non neutre admet une unique décomposition comme produit d'éléments de $A$. #question(0)[Montrer que $Sigma^star$ est le monoïde libre sur $Sigma$.] #question(1)[Si $A subset Sigma^star$, $A^star$ est-il le monoïde libre sur $A$ ?] Soit $cal(L) subset.eq Sigma^star$, on définit la _congruence syntaxique_ comme $ forall x,y in Sigma^star, med x eq.triple_L y <==> (forall u, v in Sigma^star, med u x v in cal(L) <=> u y v in cal(L)) $ #question(0)[Montrer que $eq.triple_L$ est une relation d'équivalence.] On note $Sigma^star\/eq.triple_L$ l'ensemble des classes d'équivalence de $eq.triple_L$. #question(1)[Montrer que cet ensemble forme un monoïde.] On l'appelle _monoïde syntaxique_ de $cal(L)$. Un _morphisme de monoïdes_ est une fonction qui préserve la multiplication et le neutre dans un monoïde. #question(1)[Montrer que la projection canonique $pi : Sigma^star -> Sigma^star \/ eq.triple_L$ qui à un mot associe sa classe est un morphisme surjectif.] === Reconnaître un langage On dit qu'un monoïde $cal(M)$ _reconnaît_ un langage $cal(L)$ lorsqu'il existe $A subset.eq cal(M)$ et un morphisme \ $h : Sigma^star -> cal(M)$ tels que $h^(-1) (A) = M$. #question(1)[Montrer que si $cal(M)$ reconnaît $cal(L)$, alors il existe $cal(M')$ sous-monoïde de $cal(M)$ reconnaissant $cal(L)$ avec un morphisme $h'$ surjectif.] #question(2)[Montrer que si $cal(M)$ reconnaît $cal(L)$, il existe un morphisme surjectif de $cal(M)$ dans $Sigma^star \/ eq.triple_L$.] #question(1)[Montrer que $cal(L)$ est reconnu par un monoïde fini si et seulement si $eq.triple_L$ admet un nombre fini de classes.] // TODO(Juliette) : quid des monoïdes infinis ? === Langages rationnels Soit $cal(A) = (Q, Sigma, delta, q_i, F)$ un automate reconnaissant $cal(L)$ un langage rationnel. On pose $R_Q := frak(P)(Q^2)$ l'ensemble des relations binaires sur $Q$ muni de la loi suivante $ r dot s = {(x,z) in Q^2, exists y in Q, x r y and y r z} $ #question(0)[Justifier que $R_Q$ est un monoïde fini.] #question(3)[Montrer que $R_Q$ reconnaît $cal(L)$.] L'engendré par l'image du morphisme témoin dans $R_Q$ est appelé _monoïde des transitions_. On suppose désormais disposer du monoïde syntaxique de $cal(L)$. #question(2)[Donner un automate reconnaissant $cal(L)$ dont les états sont $Sigma^star \/ eq.triple_L$.] #question(1)[En déduire qu'un langage est rationnel si et seulement si il est reconnu par un monoïde fini si et seulement si la congruence syntaxique admet un nombre fini de classes.] === Minimalité Soit $cal(L)$ un langage rationnel, puis $cal(A^star)$ un automate minimal et $cal(M)$ son monoïde syntaxique. #question(3)[Montrer que le monoïde des transitions de $cal(A^star)$ est isomorphe à $cal(M)$.]
https://github.com/tairahikaru/old-typst-japanese
https://raw.githubusercontent.com/tairahikaru/old-typst-japanese/main/otypjp.typ
typst
Other
// otypjp.typ // https://github.com/tairahikaru/old-typst-japanese // This file is distributed under the AGPLv3 // xspcode // from XeLaTeX-ja (https://github.com/h20y6m/xelatexja) by <NAME> (h20y6m) (MIT License) #let kanji_class_allow = ( "\\u{0370}-\\u{04FF}" + "\\u{1F00}-\\u{1FFF}" + "\\u{2000}-\\u{2013}" + "\\u{2016}\\u{2017}" + "\\u{201A}\\u{201B}" + "\\u{201E}-\\u{2024}" + "\\u{2027}-\\u{20AB}" + "\\u{20AD}-\\u{20CF}" + "\\u{2100}-\\u{2121}" + "\\u{2123}-\\u{2328}" + "\\u{232B}-\\u{243F}" + "\\u{2500}-\\u{27BF}" + "\\u{2900}-\\u{29FF}" + "\\u{2B00}-\\u{2BFF}" + "\\u{2460}-\\u{24FF}" + "\\u{2E80}-\\u{2EFF}" + "\\u{3000}\\u{3003}\\u{3004}\\u{3006}\\u{3007}\\u{3013}\\u{3013}\\u{301C}" + "\\u{3020}-\\u{3032}" + "\\u{3036}-\\u{303A}" + "\\u{303C}-\\u{309A}" + "\\u{309F}-\\u{30FA}" + "\\u{30FF}" + "\\u{3190}-\\u{319F}" + "\\u{31F0}-\\u{4DBF}" + "\\u{4E00}-\\u{9FFF}" + "\\u{F900}-\\u{FAFF}" + "\\u{FE10}-\\u{FE1F}" + "\\u{FE30}-\\u{FE6F}" + "\\u{FF00}" + "\\u{FF02}-\\u{FF07}" + "\\u{FF0A}\\u{FF0B}" + "\\u{FF0D}" + "\\u{FF0F}-\\u{FF19}" + "\\u{FF1C}-\\u{FF1E}" + "\\u{FF20}-\\u{FF3A}" + "\\u{FF3C}" + "\\u{FF3E}\\u{FF3F}" + "\\u{FF41}-\\u{FF5A}" + "\\u{FF5C}\\u{FF5E}" + "\\u{FF65}-\\u{FF9D}" + "\\u{FFA0}-\\u{FFEF}" + "\\u{1AFF0}-\\u{1B16F}" + "\\u{1F100}-\\u{1F2FF}" + "\\u{20000}-\\u{3FFFF}" + "\\u{1100}-\\u{11FF}" + "\\u{2F00}-\\u{2FFF}" + "\\u{3100}-\\u{318F}" + "\\u{31A0}-\\u{31EF}" + "\\u{A000}-\\u{A4CF}" + "\\u{A960}-\\u{A97F}" + "\\u{AC00}-\\u{D7FF}" + "\\u{A7}\\u{A8}\\u{B0}\\u{B1}\\u{B4}\\u{B6}\\u{D7}\\u{F7}" + "\\u{FE00}-\\u{FE0F}" + "\\u{E0100}-\\u{E01EF}" + "\\u{3099}\\u{309A}" ) #let kanji_class_inhibit = ( "\\u{00B7}\\u{30FB}\\u{FF1A}\\u{FF1B}" + "\\u{2014}\\u{2015}\\u{2025}\\u{2026}" ) #let kanji_class_preonly = ( "\\u{2018}\\u{201C}\\u{2329}\\u{3008}\\u{300A}\\u{300C}\\u{300E}\\u{3010}\\u{3014}\\u{3016}\\u{3018}\\u{301A}\\u{301D}\\u{FF08}\\u{FF3B}\\u{FF5B}\\u{FF5F}" + "\\u{00A1}\\u{00BF}\\u{20AC}\\u{FF40}\\u{FF62}" ) #let kanji_class_postonly = ( "\\u{2019}\\u{201D}\\u{232A}\\u{3001}\\u{3009}\\u{300B}\\u{300D}\\u{300F}\\u{3011}\\u{3015}\\u{3017}\\u{3019}\\u{301B}\\u{301E}\\u{301F}\\u{FF09}\\u{FF0C}\\u{FF3D}\\u{FF5D}\\u{FF60}" + "\\u{3002}\\u{FF0E}" + "\\u{00AA}\\u{00B2}\\u{00B3}\\u{00B4}\\u{00B9}\\u{00BA}\\u{02D0}\\u{2122}\\u{3005}\\u{3033}\\u{3034}\\u{3035}\\u{303B}\\u{309B}\\u{309C}\\u{309D}\\u{309E}\\u{30FC}\\u{30FD}\\u{30FE}\\u{FF01}\\u{FF1F}\\u{FF61}\\u{FF63}\\u{FF64}\\u{FF9E}\\u{FF9F}" ) #let kanji_class = ( kanji_class_allow + kanji_class_inhibit + kanji_class_preonly + kanji_class_postonly ) #let japanese_class_postallow = ( kanji_class_allow + kanji_class_postonly ) #let japanese_class_preallow = ( kanji_class_allow + kanji_class_preonly ) #let alphabet_class_inhibit = ( "\\u{0021}\\u{0022}\\u{0023}\\u{0024}\\u{0025}\\u{0026}\\u{002A}\\u{002B}\\u{002D}\\u{002F}\\u{003C}\\u{003D}\\u{003E}\\u{003F}\\u{0040}\\u{005C}\\u{005E}\\u{005F}\\u{007B}\\u{007C}\\u{007D}\\u{007E}" ) #let alphabet_class_preonly = ( "\\u{0027}\\u{0029}\\u{002C}\\u{002E}\\u{003A}\\u{003B}\\u{005D}" ) #let alphabet_class_postonly = ( "\\u{0028}\\u{005B}\\u{0060}" ) #let alphabet_class_postallow = ( "^" + "\\u{0020}" + // 空白 kanji_class + alphabet_class_inhibit + alphabet_class_postonly ) #let alphabet_class_preallow = ( "^" + "\\u{0020}" + // 空白 kanji_class + alphabet_class_inhibit + alphabet_class_preonly ) #let insert_char(regex1, regex2, string, function) = { let regexA = regex("["+regex1+"]["+regex2+"]") let regex1 = regex("["+regex1+"]") let position = string.position(regexA) let match = string.find(regexA) let match1 = match.find(regex1) ( string.slice(0, position) + function( match.slice(0, match1.len()), match.slice(match1.len(), match.len()) ) + string.slice(position+match.len(), string.len()) ) } #let insert_xkanjiskip(it) = { let array = () let it = it.text for elem in it.split(" ") { while elem.contains(regex("["+japanese_class_postallow+"]["+alphabet_class_preallow+"]")) { elem = insert_char(japanese_class_postallow, alphabet_class_preallow, elem, (c1, c2) => c1+" "+c2) } while elem.contains(regex("["+alphabet_class_postallow+"]["+japanese_class_preallow+"]")) { elem = insert_char(alphabet_class_postallow, japanese_class_preallow, elem, (c1, c2) => c1+" "+c2) } array.push(elem) } let it = array.join(" ") it } // font #let japanese_class = kanji_class #let japanese_regex = regex("[" + japanese_class + "]") #let alphabet_regex = regex("[^" + japanese_class + "]") #let defaults = ( Cjascale: (0.25 * 13) / (10 * (25.4 / 72)), // 13Q / 10bp jmainfont: "Noto Serif CJK JP", jcodefont: "Noto Sans CJK JP", mainfont: "New Computer Modern", codefont: "DejaVu Sans Mono", emojifont: "Twitter Color Emoji", spacing: 100%, leading-ratio: 0.75, text-edge: true, ) #let conf( Cjascale: defaults.Cjascale, jmainfont: defaults.jmainfont, jcodefont: defaults.jcodefont, mainfont: defaults.mainfont, codefont: defaults.codefont, emojifont: defaults.emojifont, spacing: defaults.spacing, leading-ratio: defaults.leading-ratio, text-edge: defaults.text-edge, state-arg: none, doc, ) = { set text(lang: "ja", region: "JP") // フォント set text(font: ( mainfont, jmainfont, emojifont ), features: ("chws",)) show alphabet_regex: set text( // regexで指定すると別の場所でのfontの指定が上書きされる //font: ( // mainfont, jmainfont, emojifont //), //top-edge: Cjascale * 0.88em, //bottom-edge: Cjascale * 0.12em, lang: "en", // for hyphenation ) show japanese_regex: set text( //font: ( // jmainfont, mainfont, emojifont //), features: ("chws",), kerning: false, size: Cjascale * 1em, //top-edge: 0.88em, //bottom-edge: 0.12em, ) show alphabet_regex: set text( top-edge: Cjascale * 0.88em, bottom-edge: Cjascale * 0.12em, ) if text-edge show japanese_regex: set text( top-edge: 0.88em, bottom-edge: 0.12em, ) if text-edge //set text( // top-edge: Cjascale * 0.88 * 10pt, // bottom-edge: Cjascale * 0.12 * 10pt, //) show raw: set text(font: ( codefont, jcodefont, emojifont ), kerning: false, features:("-chws",)) // 行末スペース対策 set text(spacing: 0%) show regex("[^" + japanese_class + "]+"): set text(spacing: spacing) // 和文欧文間空白 show regex(".*["+japanese_class_postallow+"]["+alphabet_class_preallow+"].*"): it => insert_xkanjiskip(it) show regex(".*["+alphabet_class_postallow+"]["+japanese_class_preallow+"].*"): it => insert_xkanjiskip(it) // 段落 set par( leading: Cjascale * leading-ratio * 1em, justify: true, first-line-indent: Cjascale * 1em, // 最初の段落がインデントされない https://github.com/typst/typst/issues/311 ) if type(state-arg) == "state" { state-arg.update(s => { s.insert("Cjascale", Cjascale) s.insert("leading-ratio", leading-ratio) s.insert("spacing", spacing) s }) } doc } #let tate(content, baseline: -0.1em) = { show regex("[" + japanese_class + "]"): it => { set text( features: ("vert", "vrt2", "vkna", "vchw"), ) set text( features: ("-vkrn",), ) box(rotate(-90deg, origin: center, it)) h(weak:true, 0.0001fr) } show regex("[^" + japanese_class + "]"): set text(baseline: baseline) // rotateのregexより先に show regex(".*["+japanese_class_postallow+"]["+alphabet_class_preallow+"].*"): it => insert_xkanjiskip(it) show regex(".*["+alphabet_class_postallow+"]["+japanese_class_preallow+"].*"): it => insert_xkanjiskip(it) show parbreak: it => { h(1fr); it } show linebreak: it => { h(1fr); it } style(styles => { let size = measure(content, styles) box( width: size.height, height: size.width, { align(right, rotate(90deg, origin: center, content) ) }, ) }) }
https://github.com/typst-community/valkyrie
https://raw.githubusercontent.com/typst-community/valkyrie/main/src/ctx.typ
typst
Other
#let ctx-proto = ( strict: false, soft-error: false, remove-optional-none: false, ) /// This is a utility function for setting contextual flags that are used during validation of objects against schemas. /// /// Currently, the following flags are described within the API: /// / strict: If set, this flag adds the requirement that there are no entries in dictionary types that are not described by the validation schema. /// / soft-error: If set, this flag silences errors from failed validation parses. It is used internally for types that should not error on validation failures. See @@either /// /// - parent (z-ctx, none): Current context (if present), to which contextual /// flags passed in variadic arguments are appended. /// - ..args (arguments): Variadic contextual flags to set. Positional arguments are discarded. /// -> z-ctx #let z-ctx(parent: (:), ..args) = ctx-proto + parent + args.named()
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/docs/tinymist/book.typ
typst
Apache License 2.0
#import "@preview/shiroa:0.1.1": * #show: book #book-meta( title: "Tinymist Docs", description: "The documentation for tinymist service", authors: ("Myriad-Dreamin",), repository-edit: "https://github.com/Myriad-Dreamin/tinymist/edit/main/{path}", language: "en", summary: [ #prefix-chapter("introduction.typ")[Introduction] = Editor Integration #prefix-chapter("configurations.typ")[Common Configurations] - #chapter("frontend/main.typ")[Editor Frontends] - #chapter("frontend/vscode.typ")[VS Cod(e,ium)] - #chapter("frontend/neovim.typ")[NeoVim] - #chapter("frontend/emacs.typ")[Emacs] - #chapter("frontend/sublime-text.typ")[Sublime Text] - #chapter("frontend/helix.typ")[Helix] - #chapter("frontend/zed.typ")[Zed] = Features - #chapter("feature/cli.typ")[Command line interface] - #chapter("guide/completion.typ")[Completion] - #chapter("feature/export.typ")[Exporting Documents] - #chapter("feature/preview.typ")[Document Preview] - #chapter("feature/language.typ")[Other Features] = Service Overview #prefix-chapter("overview.typ")[Overview of Service] - #chapter("principles.typ")[Principles] - #chapter("commands.typ")[Commands System] - #chapter("inputs.typ")[LSP Inputs] - #chapter("type-system.typ")[Type System] = Service Development - #chapter("crate-docs.typ")[Crate Docs] - #chapter("module/lsp.typ")[LSP and CLI] - #chapter("module/query.typ")[Language Queries] - #chapter("module/preview.typ")[Document Preview] ], ) #build-meta(dest-dir: "../../dist/tinymist") #get-book-meta() // re-export page template #import "/typ/templates/page.typ": project #let book-page = project
https://github.com/kfijalkowski1/typst-diff-tool
https://raw.githubusercontent.com/kfijalkowski1/typst-diff-tool/main/typst_ast_parser/data/1_additional_bullet_point/expected_added_bullet_point.typ
typst
#import "@preview/pesha:0.2.0": * #experience( place: "Hot Topic", title: "Retail-sales associate", time: [2004--06], )[ - Top in-store sales associate in seven out of eight quarters - Inventory management - #text(fill: red)[Training and recruiting]#text(fill: green)[ADDED BULLET POINT] #text(fill: green)[- Training and recruiting] #text(fill: green)[- ANOTHER ADDED BULLET POINT] ]
https://github.com/Nenuial/quarto-swissequestrian
https://raw.githubusercontent.com/Nenuial/quarto-swissequestrian/main/_extensions/se-letter/typst-show.typ
typst
$if(lang)$ #set text(lang: "$lang$") $endif$ #show: letter-simple.with( sender: ( name: "$sender.name$", address: "$sender.address$", ), font: "Gilroy", header: [ #place(top + left, dx: 2.5cm, dy: 1.5cm, [ #set text(fill: rgb("#00283c"), size: 8pt) *SWISS EQUESTRIAN*\ #set text(fill: black) Postfach 726, Papiermühlestrasse 40H, CH-3000 Bern 22\ #link("tel:0041313354343", "+41 (0)31 335 43 43"), #link("mailto:<EMAIL>", "<EMAIL>"), #link("https://www.swiss-equestrian.ch", "swiss-equestrian.ch") ]) #place(top + right, image("$logo$", width: 3.2cm), dx: -1.5cm, dy: 1.5cm) $if(department)$ #place(top + right, dx: -2cm, dy: 5.5cm, [ #set text(fill: rgb("#00283c"), size: 14pt) #strong(upper([$department$])) ]) $endif$ ], $if(annexes)$ footer: [$for(annexes)$$annexes$$sep$\ $endfor$], $endif$ $if(annotations)$ annotations: [$annotations$], $endif$ recipient: [ $for(recipient)$ $recipient$ $sep$\ $endfor$ ], $if(reference-signs)$ reference-signs: ( $for(reference-signs/pairs)$ ([$it.key$], [$it.value$]), $endfor$ ), $endif$ $if(signature)$ signature-name: "$signature.name$", signature-title: "$signature.title$", $endif$ date: "$date$", subject: "$subject$", )
https://github.com/dice-punk-press/open-d12
https://raw.githubusercontent.com/dice-punk-press/open-d12/main/src/core-rules.typ
typst
Creative Commons Attribution 4.0 International
#set page( paper: "a4", header: [ #set text(8pt) Open D12 | Core Rules | v0.0.1 #h(1fr)Feedback: https://github.com/dice-punk-press/open-d12/issues ] ) = Open D12 Core Rules == Alpha Release v0.0.1 This is an early release of the core rules. Everything works but we're actively collecting feedback and improving things. There may be big changes to come. Check the feedback link in the top corner for the latest updates or to leave feedback. Thank you, your feedback makes the game better. == Introduction #text(style:"italic")[Open d12 is a rules system for creating table top role playing games. It is not a game in itself but a set of rules that can be used to create a wide variety of games. The rules are designed to be simple and flexible, allowing players and narrators to create and play games in a wide variety of settings and genres. The core rules are minimal but complete. There are number of extensions that can be added to the core rules to create more complex and detailed games. The best way to think of Open d12 is as a set of recipes for creating games where some of the ingredients will need to be decided by the authors.] #outline(indent: auto) #pagebreak() #columns(2)[ == Definitions / Setting: the world in which the game takes place, including the culture, technology, geography and history of the world / Scope: the breadth of roles and activities that the players will be able to take on in the game / d12: a 12 sided die / Narrator: the Narrator is the person who facilitates the game / Characters: players create and take on the role of characters in the game / Skill Group: a skill group represents a set of skills that are related to each other, players invest points into skill groups to represent their characters' abilities / Skill: a skill is a specific ability that a character has, skills are grouped into skill groups / Roll: a roll is the act of rolling a d12 to determine the outcome of an action / Result: the number used to determine the outcome of a roll / Extension: an extension is an additional set of rules that can be added to the core rules / Chances: character's have chances, this is a resource that allows them to avoid serious harm or negative consequences / Fun: in open d12 fun comes from exploring the game world and your character and from failure as well as success #set heading(level: 1, numbering: "1.1") = Basic Equipment Needed - One or more d12s (more recommended) - Paper and something to write with - A copy of the rules = Game Rules To create a game using Open d12 you will need to decide on the following: - The *setting* and *scope* of the game - The *skill groups* and *skills* that will be used when creating characters - Which, if any, extensions you are using - How you will guide players through character creation and playing the game - How you will support the Narrator in facilitating the game == Setting and Scope The *setting* and *scope* inform everything else. Being clear about the setting and scope will help you to make decisions about how to implement the rules and make the game easier to design, facilitate and play. *Example:* _If you pick a steam-punk fantasy world as your setting think about whether the scope of the game will be focused on anyone from that world or focused on the people who crew and maintain the airships that are the primary form of transport._ Broader scopes are not necessarily better. A more focused scope allows for clearer mechanics and story telling. However, it's possible not everyone will want to play a game with a very specific combination of setting and scope. At the end of the day it's import to focus on what you will enjoy creating. == Skill Groups In open d12 characters have a number of *skill groups*. These represent a character's broad areas of expertise. When creating a character players invest points into these *skill groups* to represent their character's abilities. The points invested into a *skill group* typically determine the *skill level* for all of the skills belonging to that group. The minimum value for a *skill group* is one and the maximum value is nine. You may wish to further restrict the maximum value a character can start the game with. A character with 9 in a skill, especially with a *bonus die* will succeed about 90% of the time. It is recommended you have between three and six *skill groups* in your game. The more skill groups you have the more complex your game will be. *Example:* _If you are making a simple 'sword and sorcery' game then you might decide on the following skill groups: Might, Finesse and Knowledge._ == Skills A *skill* is a specific ability that a character might want to perform. *Skills* belong to a *skill group*, with related skills belonging to the same group. A character's *skill level* is typically determined by the number of points they have invested in the *skill group*. It is recommended that each group has the same number of skills and that you have between two and four *skills* in each *skill group*. The more skills you have the greater the chance they wont all be used. However, too few skills can get in the way of players being able to create the characters they want. *Example:* _Building on the simple example above you might decide to have the following skills belonging to the following groups. Might: Attack, Defense. Finesse: Aim, Stealth. Knowledge: Arcana, Lore._ === Specialization To make characters more unique they can specialize in one or more skills. When a character specializes in a skill they gain a *bonus die* when rolling that skill. = Character Creation The basics of character creation involve determining how many points are invested in each *skill group* and if the character is specialized in any *skills*. It is also important for characters to have a name, a description and a background that ties them into the setting. You will need to decide how many points are available for players to invest, how many can be invested into any one skill at the start of the game and how many skills can be specialized in. *Example:* _For our simple 'sword and sorcery' game we might decide that players have 9 points to invest in their character's skill groups and that they can invest a maximum of 6 points into any one group. As skill groups start at 1 this means the maximum starting value for any skill group will be 7. We'll also let players pick 1 skill for their characters to specialize in._ You may want to tie specialization in certain skills to a particular background or profession. This isn't covered in the core rules but there are extensions that go into more detail. = Playing the game == The Narrator The role of the Narrator is to facilitate the game. Their goal is to create a fun, challenging and engaging environment for the players to explore and tell stories in. They have three main responsibilities: *Describe the game world and non-player characters.* The Narrator describes what is happening in the part of the game world the players are interacting with and how it looks, feels, sounds, smells, and tastes. They also describe the actions and appearance of any non-player characters who are present. They also answer questions from the players about the game world and non-player characters, although they may choose to keep some information secret or require a *roll* to reveal certain pieces of information. *Provide just enough direction to move the story forward.* The Narrator provides one or more 'story hooks' to give the player characters a reason to act and provides a source of challenge, story-conflict and tension. The Narrator needs to make characters earn their successes and feel their failures. They also need to prevent characters from getting totally stuck. *Use the game rules (and their own judgement) to determine the outcomes of actions.* The Narrator helps the players to navigate the rules and determines what happens when a roll succeeds or fails. It is important that the Narrator acts fairly and consistently when applying the rules and determining outcomes and that they generally act in the interests of keeping the game fun, challenging and engaging. == The Players The role of the players is to take on the role of a character in the game world. Their goals is to explore the world and their characters by interacting with the game and the rules. Players ask the Narrator questions about the game world and decide what their characters do, say and try. They also decide _how_ their characters try to do things. Players don't have specific responsibilities but it is recommended that they prefer working together to solve problems, have a high level understanding of the rules and their characters and, most importantly, have fun. == Rolls and resolution When a player attempts something uncertain or risky the *Narrator* will ask them to make a *roll* using the *skill* that most closely matches the action they are attempting. The player will roll one or more d12s (based on the *bonuses* and *penalties* involved in the roll) to determine the *result* of the roll. The *result* is compared to the *skill level* of the *character* for the chosen *skill*. A result of equal to or less than the skill level is a *success*, a result higher than the skill level is a *failure*. *Bonus Dice*: If the *roll* involves one or more *bonus dice* then the player rolls a number of d12s equal to one plus the number of bonus dice they have and uses the lowest number on any of the dice as the *result*. *Penalty Dice*: If the *roll* involves one or more *penalty dice* then the player rolls a number of d12s equal to one plus the number of penalty dice they have and use the highest number on any of the dice as the *result*. *Bonus and penalty dice*: *Bonus* and *penalty dice* cancel each other out. For example if a *roll* involves two penalty dice and one bonus die then they player would make the roll with one penalty die. *Neutral Rolls*: If the *roll* has no *bonus* or *penalty dice* then the player rolls a single d12 and uses the *result*. == Determining bonus and penalty dice *Bonus dice* can come from three sources. A character may be *specialized* in a *skill*, granting them a *bonus dice* when rolling that skill. The *Narrator* may grant a *bonus dice* based on the in-game circumstances surrounding the *roll*, for example preparation and planning by the characters or having the right tools for the job. Finally some items or conditions may grant situational *bonus dice*. *Penalty dice* come from the difficulty of a given role, either because the task is inherently difficult or because the specific situation is making things more difficult. The Narrator determines how many *penalty dice* are involved in a given roll. == Danger, threat and chances In the core version of the rules each character has three *chances* to avoid serious harm or negative consequences. Characters are typically given a chance to perform a *roll* to avoid harm. If they fail the *roll* then they lose a *chance*. If they lose all of their *chances* then they are out of the game - this could mean they are dead, captured, unconscious or otherwise unable to continue, depending on the setting. *Characters* do not lose a *chance* every time they fail a roll, only when the *Narrator* determines that it is appropriate. === Regaining chances The *Narrator* may allow characters to regain *chances* by resting, healing or through other in-game actions. == Non-player characters Non player characters are important for making the game world feel alive and can be a good way to provide hints and direction to the players. The *Narrator* creates and controls non-player characters. Non-player characters use the same rules as player characters, they have *skill groups* and *skills* and make *rolls* to determine if their actions are successful. These rolls are made by the *Narrator*. The *Narrator* can decide if these rolls are made in secret or in the open. == Items The core rules do not cover items in detail. However, players and the *Narrator* should consider the following things when dealing with items in the game. As in the real world there should be a limit on the number of items players can carry and use at the same time. If a character is carrying too many items then the *Narrator* may require a *roll* to determine how well they deal with the consequences of being over encumbered. Players should keep track of the items their characters are carrying and using. The *Narrator* may award bonus dice (or penalty dice) for having the right (or wrong) tools for the job. Some things should be impossible or very difficult to do without the right tools. == Opposed rolls and combat If two characters are trying to achieve opposing goals then the *Narrator* may call for an *opposed roll*. In this case both characters make a *roll* and the character with the lowest *result* that is also a *success* wins. Opposed roles may use the same *skill* or different *skills*, depending on the situation. If both characters fail the *roll* then the *Narrator* should resolve the situation in a way that makes sense for the game. === Combat In the core rules combat is a special case of an *opposed roll* where one character (the attacker) is trying to inflict damage on another (the defender) and reduce that defender's *chances* by one. Depending on the situation surrounding the roll the defending character may be able to make a *roll* to avoid the damage. Typically if the defender knows about the attack and is sufficiently mobile then they will be able to make a *roll* to defend themselves. *Example:* _In our simple 'sword and sorcery' example a goblin non player character attacks a player character. Both characters have seen each other and are ready for battle. The Narrator rolls the goblin's attack skill and the player rolls their character's defense skill. If both rolls succeed then the lowest roll 'wins'._ Depending on the scope and setting of the game it may be necessary to decide which skills can and cannot be used to defend against each other. For example, could a _defense_ skill be used to defend against _magic_? = Running the game == Starting the game - Ensure all players understand the basics of the rules and have created their characters - The Narrator and each player establish a *story hook* for that player's character, this gives the character an initial goal or motivation once the game starts - The players and Narrator agree any ground rules for the game (for example, how long the game will last, what types of content and behavior is and isn't appropriate in the game, etc) - The players and Narrator should introduce themselves if they don't already know each other - The Narrator should introduce the setting, describe the state of the world at the start of the game and provide any background knowledge it is reasonable for the characters to start with - When each player character is first introduced give the player a chance to describe their character === Story hooks A story hook is a reason for a character to act. In shorter games the hooks tend to be obvious and immediate, in longer games they may be more subtle and complex. The *Narrator* should provide at least one story hook for each character to give them a reason to act and to provide a source of challenge, story-conflict and tension. == Core gameplay loop 1. The *Narrator* establishes which characters are present in the scene and describes the world around them, including any non-player characters who may be present and what they are doing. 2. The *players* describe what their characters are attempting to do and how they are attempting to do it or ask the *Narrator* questions about the scene. 3. The *Narrator* continues the plot, either by sharing more information with the players or by asking for a roll. If a roll is required the Narrator also determines the skill being used and the difficulty of the roll. 4. The *players* react to this new information and decide what their characters are going to do next, moving the story forward. 5. Start again from 1. == Ending the game The game ends when the players have achieved their goals or lost all of their chances. When the game ends the *Narrator* should provide players with a sense of closure and an opportunity to reflect on the game. For example, they might describe what happens to key non-player characters and how the player characters' actions have impacted the larger game world. ]
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/examples/metropolis.typ
typst
#import "../lib.typ": * #let s = themes.metropolis.register(s, aspect-ratio: "16-9", footer: self => self.info.institution) #let s = (s.methods.info)( self: s, title: [Title], subtitle: [Subtitle], author: [Authors], date: datetime.today(), institution: [Institution], ) #let (init, slides, touying-outline, alert) = utils.methods(s) #show: init #set text(font: "Fira Sans", weight: "light", size: 20pt) #show math.equation: set text(font: "Fira Math") #set strong(delta: 100) #set par(justify: true) #show strong: alert #let (slide, title-slide, new-section-slide, focus-slide) = utils.slides(s) #show: slides = First Section #slide[ A slide without a title but with some *important* information. ] == A long long long long long long long long long long long long long long long long long long long long long long long long Title #slide[ A slide with equation: $ x_(n+1) = (x_n + a/x_n) / 2 $ #lorem(200) ] = Second Section #focus-slide[ Wake up! ] == Simple Animation #slide[ A simple #pause dynamic slide with #alert[alert] #pause text. ] // appendix by freezing last-slide-number #let s = (s.methods.appendix)(self: s) #let (slide,) = utils.slides(s) = Appendix #slide[ Appendix. ]
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas3/2_Utorok.typ
typst
#let V = ( "HV": ( ("", "Krestoobrázno", "Júže vo mňí mnohoobráznyj zmíj, uvíďiv ľínosť k poléznym ďilóm, i manovénijem ko zlým i hóršym preobrazújetsja, pokazúja hrichá sládosť, svojé že hórkoje ďílanije, i soprotívnoje božéstvennym zápovidem. Ťímže i porivájet mjá nrávom, jáko dóbraja, zlája prijimáti lukávym, Christé."), ("", "", "Vsják púť bezzakónija i hrichóvnyj šéstvovav usérdno, ostáviv právyj do koncá, nýňi ko vratóm smértnym priblížichsja, uťisňájem zovú: životá nášeho puťú, Iisúse mój preblahíj, k široťí pokajánija ístinnaho obratív spasí, dážď mí ispravlénije: i préžde smérti, proščénija božéstvennaho spodóbi mjá."), ("", "", "Umertvíchsja hrichí razlíčnymi, i prehrišénij mnóžestvy, i bezmístijem velíkim, ležú mértv, bezpómoščen voístinnu. Jedína že živét nadéžda mojá, jáže k tvojemú blahoutróbiju: mértvym dychánije vkúpi i živót podavája Christé, i umerščvľájaj strásti nás umertvívšyja, ťímže predvarív, víčnyja smérti ischití mja."), ("", "", "Íže máterneje bezčádije, i ótčeje bezhlásije v roždeství tvojém predtéče razrišívyj, mojehó sérdca bezčádije, i duší bezslovésije, razriší molítvami tvojími blahoprijátnymi, k milosérdomu Ótču Sýnu, vsích Vladýci i Bóhu, jehóže jáko slóva úm bezstrástno rodí: i ľubéznaja tomú i hlahólati i tvoríti ukripí mja."), ("", "", "Íže Christú uhotóvav stezí, i šéstvija ispráviv, pred jehóže licém póslan býsť, i mojé sérdce blahošéstvenno tomú pokaží, molítvami tvojími i pomoščmí projavlénnymi: íže nohám jehó čestným dostójin javílsja jesí, nebésnyja mjá zemlí chodíti spodóbi, jéjuže šéstvujut krótkich nózi, da ľubóviju jáko chodátaja počitáju ťá."), ("", "", "Žitijú ánheľskomu porevnovál jesí na zemlí, proróčeskoje soveršénije, i nóvaho zavíta pervomúčeniče, íže súščym pod zemléju pérvyj propovídniče božéstvennaho slóva támo sošéstvija, ot Christá sviďíteľstvovannyj: drúže áhnca, i izbáviteľa, ot vsjákich soblázn vrážijich, i mnohopleténnych iskušénij jehó, tvojehó rabá izbávi krestíteľu Joánne, molítvami tvojími."), ("Bohoródičen", "", "Jáže svíta nezachodímaho óblače, Bohorádovannaja otrokovíce, blahoslovénnaja Maríje, vozsijáj mí svít pokajánija vo ťmí hrichóvnej bezúmno soderžímu: i izbávi moľbámi tvojími ohňá hejénskaho, i ťmý nesvitímyja, i dné nevečérňaho javí pričástnika Ďívo, pribihájuščaho pod króv tvój prečístaja."), ), "S": ( ("", "", "Večérňuju písň prinósim tí Christé, s kadílom i písňmi duchóvnymi, pomíluj spáse dúy náša."), ("", "", "Spasí mja Hóspodi Bóže mój, tý bo vsím jesí spasénije: búrja mjá strastéj smuščájet, i brémja bezzakónija pohružájet mjá. Dážď mí rúku pómošči, i vozvedí mja k svítu pokajánija, jáko jedín blahoutróben i čelovikoľúbec."), ("", "", "Vélija múčenik tvojích Christé síla: vo hrobích bo ležášče dúchi prohóňat, i uprazdníša vrážiju vlásť, víroju Tróičeskoju podvíhšesja o blahočéstiji."), ("Bohoródičen", "", "V ženách svjatája Bohoródice, Máti beznevístnaja, molí, jehóže rodilá jesí, carjá i Bóha, da spasét nás jáko čelovikoľúbec."), ), ) #let P = ( "1": ( ("", "", "Vódy drévle, mánijem božéstvennym, vo jedíno sónmišče sovokupívyj, i razďilívyj móre Izráiľteskim ľúdem, séj Bóh náš preproslávlen jésť: tomú jedínomu poím, jáko proslávisja."), ("", "", "V ľínosti žitijé skončáv, priblížichsja k koncú žitijá mojehó: no samá Prečístaja, poné v posľídneje vrémja, dážď mí umilénije, moľúsja, jáko da pláčusja hórko o bezmírnych mojích prehrišénijich."), ("", "", "Oskvernív bezúmno, júže po óbrazu, krasotú strasťmí plóti mojejá Ďívo, Bóžijaho ustrašíchsja nehodovánija, i užásnaho óhnennaho preščénija: no samá pomíluj mjá pribihájuščaho k tebí."), ("", "", "Koľína preklonív okajánnyj, tvojú prošú pómošč presvjatája Ďívo: no tý uslýši boľáščuju dúšu, i naležáščij óblak pečáli mojejá razorí zaréju tvojích molítv."), ("", "", "Napoítisja bohátno slezámi dážď, brazdám strástnyja mojejá duší, i plód prinestí mi storíčnyj Vladýčice spodóbi, i sérdce mojé vsjákaho vesélija ispólni, da slávľu ťá."), ), "3": ( ("", "", "Íže ot ne súščich vsjá privedýj, slóvom sozidájemaja, soveršájemaja Dúchom, vsederžíteľu výšnij, v ľubví tvojéj utverdí mené."), ("", "", "Sléz túču podážď mí blahája Bohoródice, i sími uhasí strastéj mojích péšč, i vsjákija omýj dušévnyja mojá skvérny."), ("", "", "V bezzakónijich oskverních blahoródije duší prečístaja, i trepéšču isťazánija, jehdá isťážet mjá óbraza dostojánija, Slóvo."), ("", "", "Búrja prehrišénij objémši mjá nýňi, vo hlubinú otčájanija svedé: no dážď mí rúku čístaja, i na pokajánije mjá nastávi."), ("", "", "Izbávi hejénny i vsjákaho ináho preščénija v čás sudá, rabá tvojehó preneporóčnaja, i pričástnika sotvorí Sýna i Bóha tvojehó cárstviju."), ), "4": ( ("", "", "Položíl jesí k nám tvérduju ľubóv Hóspodi, jedinoródnaho bo tvojehó Sýna za ný na smérť dál jesí. Ťímže tí zovém blahodarjášče: sláva síľi tvojéj Hóspodi."), ("", "", "Prijidóša čístaja, bezmístnych ďíl vódy, do okajánnyja mojejá duší. Ťímže pómysly brénija oderžím, vopijú s boľízniju: ne prézri mené Vladýčice rabá tvojehó."), ("", "", "Zvírije mýslenniji, nýňi nemílostivno obydóša mjá, tščáščesja voschítiti neščádno smirénnuju mojú dúšu, vseneporóčnaja: no Sýnom prečístaja sokruší dušetľínnyja čéľusti."), ("", "", "Mílostiva búdi tvojemú rabú Vladýčice, moľúsja, i čájemaho preščénija ľúdi tvojá ischití vsečístaja, da zovém tí blahodarjášče: sláva tebí vsích caríce."), ("", "", "Jehdá v noščí ženích priídet sudíti zemlí, tohdá vo srítenije jehó so svítloju sviščéju blahovolí prečístaja izýti mí, i poklonítisja tohó prišéstviju."), ), "5": ( ("", "", "Na zemlí nevídimyj javílsja jesí, i čelovíkom vóleju sožíl jesí nepostižímyj, i k tebí útreňujušče, vospivájem ťá čelovikoľúbče."), ("", "", "Psí mnózi oderžáša mjá voístinnu, sónm lukávych duchóv obýde mjá: no sích prečístaja sovíty nýňi razorí."), ("", "", "Róv mňí nýňi lukávyj izrýv, vovreščí mja vóň pokušájetsja: no tvojéju desníceju Vladýčice, da vpadét v jámu, júže sotvorí."), ("", "", "Da ne járostiju Sýna tvojehó obličén búdu, vo vrémja prišéstvija jehó, ni hňívom jehó nakažúsja vsepítaja: no spasí mja moľbámi tvojími."), ("", "", "Vížď čístaja némošč, vížď smirénije okajánnyja mojejá duší, i bezplótnych vráh vostánije: i sích vréda izbávi mjá."), ), "6": ( ("", "", "Bézdna posľídňaja hrichóv obýde mjá, i isčezájet dúch mój: no prostrýj Vladýko vysókuju tvojú mýšcu, jáko Petrá mja upráviteľu spasí."), ("", "", "Mánijem vsích ziždíteľa, jehdá chóščet dušá mojá razlučítisja ot plóti, vseneporóčnaja, svobodí mja rukí nenavíďaščich mjá, Bohoródice vsepítaja."), ("", "", "Izsuší mútnyja ríki Bohorodíteľnice, lukávych mojích ďijánij strujámi umilénija, i naprávi k voďí osláby v déň sudá."), ("", "", "Vísi mojú némošč dušévnuju, i umá mojehó nekríposť prečístaja, i plóti nemožénije. ťímže spasí rabá tvojehó: ťá bo sťažách zastúpnicu nepobidímuju."), ("", "", "Strují mňí sléz duchóvnych podážď otrokovíce, ímiže izmýju tínu prehrišénij mojích, i strastéj molvú preneporóčnaja, i skvérny ťilésnyja."), ), "S": ( ("", "Krasoťí ďívstva", "Mílostivaho vo črévi nosívšaja, pribihájuščaho pod króv tvój, i prosjášča ot duší božéstvennuju tvojú pómošč, Vladýčice uščédri, i mílosti spodóbi, jehdá predstánem Vladýce tvári, izbávi čístaja ohňá víčnaho, i vsjákaho osuždénija."), ), "7": ( ("", "", "Préžde óbrazu zlatómu, persídskomu čtílišču, ótrocy ne pokloníšasja, trijé pojúšče posreďí péšči: otcév Bóže blahoslovén jesí."), ("", "", "Izlijášasja na mjá čístaja, prehrišénij vódy do duší mojejá, bézdna že obýde mjá posľídňaja: no sehó izmí trevolnénija."), ("", "", "Okropí mja čístaja, króviju iz rébr roždestvá tvojehó, mnóžestvom mílosti tvojejá: omýj že mjá sléznymi strujámi, i očísti mjá ot vsjákija skvérny."), ("", "", "Sokrušénije mojéj duší, smirénije že sérdcu dážď vsečístaja, jáko da vsjákaho izbávľusja kovárstva, prísno mjá neščádno lovjáščich."), ("", "", "Jáko mílostiva Máti Bóžija, rabý tvojá Vladýčice, mílosti spodóbi, íže víroju Sýnu tvojemú vopijúščyja: otcév Bóže blahoslovén jesí."), ), "8": ( ("", "", "Nesterpímomu ohňú sojedinívšesja, Bohočéstija predstojášče júnoši, plámenem že nevreždéni, božéstvennuju písň pojáchu: blahoslovíte vsjá ďilá Hospódňa Hóspoda, i prevoznosíte vo vsjá víki."), ("", "", "Stríly striľcá sokruší čístaja, deržávoju Sýna tvojehó, i sehó neprávda nýňi da snídet na vérch jehó, da vospojú: vsjá ďilá Hospódňa Hóspoda pójte i prevoznosíte jehó vo víki."), ("", "", "Svítom tvojím ozarí otrokovíce, omračénoje mojé sérdce, i orúžijem svíta svítu dvéri otvérzi mí zovúšču: blahoslovíte vsjá ďilá Hospódňa Hóspoda, pójte i prevoznosíte jehó vo víki."), ("", "", "Usnúv v smérti, ležú vo hróbi otčájanija, no samá mja vozstávi Ďívo, i bódrenno píti spodóbi: blahoslovíte vsjá ďilá Hospódňa Hóspoda, pójte i prevoznosíte jehó vo víki."), ("", "", "Ne prestáj čístaja, moľášči o čtúščich ťá vo umiléniji, izbávitisja sitéj dijávoľskich, Sýnu tvojemú vopijúščich: blahoslovíte vsjá ďilá Hospódňa Hóspoda, pójte i prevoznosíte jehó vo víki."), ), "9": ( ("", "", "V zakóňi síni i pisánij óbraz vídim vírniji: vsják múžeskij pól ložesná razverzája, svját Bóhu: ťím pervoroždénnoje Slóvo, Otcá beznačáľna, Sýna pervoroďáščasja Máteriju neiskusomúžno, veličájem."), ("", "", "Oburevájet strastéj volnénije, i smuščénije skvérnych pomyšlénij dúšu mojú, i lukávych čelovík búrja prísno mjá smuščájet: no jáko čelovikoľubíva Ďívo, oderžímyja núždy vskóri mjá izbávi."), ("", "", "Dušé smirénnaja, otstupí lukávych tvojích ďijánij, i prestáni ot zlóby, i jéže prohňívati Bóha, vosprijimí že usérdno zápovidi jehó: Bohoródicu bo ímaši putí tvojá napravľájuščuju."), ("", "", "Jáko róždšaja vsích Hóspoda, strastéj mjá svobodí, i ľútych hrichóv, i vsehó mja ďíly blahími za mnóhoje milosérdije tvojé obohatí: da rádujasja ľubóviju veličáju ťá vseneporóčnaja."), ("", "", "Približájetsja dušé konéc, pri dvérech sudíšče, otstupí ďíl stúdnych, i prijimísja za blahóje žitijé: ímaši bo pobórnicu Bohoródicu, izbavľájuščuju ťá ot vsjákaho ozloblénija."), ), ) #let U = ( "S1": ( ("", "", "Prišéľstvujušči na zemlí dušé mojá, pokájsja, pérsť bo vo hróbi ne pojét, ni ot prehrišénij izbavľájet. Vozopíj Christú Bóhu: serdcevídče, sohriších tí, préžde dáže ne osúdiši mené, poščadí mjá Bóže i pomíluj mjá."), ("", "", "Dokóľi dušé mojá prebyváješi v sohrišénijich? Dokóľi prijémleši pokajánija otložénije? Prijimí vo umí súd hrjadúščij, vozopíj Christú Bóhu: serdcevídče, sohriších, bezhríšne Hóspodi, pomíluj mjá."), ("Bohoródičen", "", "Priíéžišče i sílo náša Bohoródice, krípkaja pomóščnice míra, molítvami tvojími pokrýj rabý tvojá ot vsjákija núždy, jedína blahoslovénnaja."), ), "S2": ( ("", "", "Na strášňim sudíšči bez sopérnik obličájusja, i bez sviďíteľej osuždájusja: kníhi bo sóvistnyja razhibájutsja, i ďilá sokrovénnaja otkryvájutsja. Préžde dáže úbo vo ónom vsenaródnom pozórišči chóščeši isťazáti, jáže mnóju soďíjannaja, Bóže, očísti mjá, i spasí mja."), ("", "", "Hlubinú sohrišénij mojích tý vísi Hóspodi: dážď mí rúku pómošči jáko Petrú, i spasí mja."), ("Múčeničen", "", "Sijájete víroju presvítlaja svitíla svjatíji, nemoščstvújuščich vráčeve, strastotérpcy prechváľniji: mučítelej bo rán ne ubojástesja, ídoľskoje zločéstije nizložíste, pobídu imúšče nepobidímuju krest ístinnyj."), ("Bohoródičen", "", "Prijimí Vladýčice víroju pritekájuščaho pod króv tvój, i ne voznenavížď mené, nižé prézri blahája pokajánijem moľáščahosja. Prijimí jáže ot úst nedostójnych mojích moľbú, i chodátajstvom tvojím ot sitéj izbávi mjá, da so derznovénijem vopijú ti: rádujsja obrádovannaja."), ), "S3": ( ("", "Krasoťí ďívstva", "Pod króv tvój pribíhše, víroju zovém iz hlubiný dušévnyja: Bohoblažénne proróče i Predtéče, napástej i bíd smuščénija, i nedúhov volnénija utiší, i sújetny sotvorí vrahóv zlochítryja sovíty, prosjá nám vélija mílosti."), ("", "", "Unýnije tvojé dušé okajánnaja, préžde ischóda tvojehó ottrjásši pokajánijem, i s pláčem obratísja zovúšči k nezlóbivomu Iisúsu čelovikoľúbcu: sohriších tí Vladýko, no jáko milosérd spasí mja, molítvami svjatáho Predtéči, íže jedín sýj bezhríšen."), ("Bohoródičen", "", "Nedomýslenno i nepostižímo jésť Vladýčice Bohorádovannaja, jéže soďílannoje o tebí strášnoje Bóžije táinstvo: íbo neobiménnaho začénši rodilá jesí, plótiju obložéna ot prečístych krovéj tvojích: jehóže vsehdá čístaja s Predtéčeju molí, spastísja dušám nášym."), ), "K": ( "P1": ( "1": ( ("", "", "Dívno, slávno tvorjáj čudesá, tý jesí Bóže, bézdnu ozemlenívyj, i kolesnícy potopívyj, i ľúdi spásýj pojúščija tebé, jáko carjú nášemu i Bóhu."), ("", "", "Sámi sebé préžde koncá vírniji pláčim ot vsejá duší: približájetsja ženích, vozžžém ďijánija jákože svítlyja sviščý, jáko da božéstvennyj čertóh ulučím vkúpi."), ("", "", "Pokájavsja drévle Manassíja ot vsejá duší, spasésja: vozopí bo ot sredý úz svjázan ko jedínomu Vladýci. Tomú revnúj dušé, i spaséšisja udób."), ("Múčeničen", "", "Očés sľipotú, rúk lišénije, jazýka urízanije, nóh že otjátije, bédr i mýšcej sokrušénije, preterpíša božéstvenniji stradáľcy, blahodarjášče Iisúsu Christú."), ("Múčeničen", "", "Vračébnica javísja nám ráka moščéj vášich, svjatíji múčenicy vsím vírnym: iz nejáže počerpájem iscilénija, dúš že i ťilés, po dólhu vás čtúščiji prísno."), ("Bohoródičen", "", "Bezsmértija mánnu Christá nosjášči, stámno slovésnaja, hóresti dušetľínnych strastéj izbávi mjá vsepítaja Ďívo: jáko da víroju ťá slavoslóvľu blahočéstno."), ), "2": ( ("", "", "Vódy drévle, mánijem božéstvennym, vo jedíno sónmišče sovokupívyj, i razďilívyj móre Izráiľteskim ľúdem, séj Bóh náš, preproslávlen jésť: tomú jedínomu poím, jáko proslávisja."), ("", "", "Neplódnyja utróby božéstvennoje prozjabénije, plodý mi dobroďítelej prozjabáti, Bóhu molísja, hrichá mojehó razrešája neplódije, i othoňája mrák ot umá mojehó, Hospódeň predtéče."), ("", "", "sólnca slávy vélij, jákože predtekúščaja zvezdá, víroju na zemlí javílsja jesí, zémľu vsjú prosvíščšaho: tohó úbo molí, omračívšujusja dúšu mojú zlými pomyšléňmi prosvitíti Predtéče."), ("", "", "Íže živót súščym vo áďi, Dúchom božéstvennym približájuščsja, predvozvistíl jesí Proróče, mojú umerščvlénnuju dúšu oživí tvojími moľbámi: i jáko ot hróba prehrišénij vozstávi, moľúsja, slávnyj Predtéče."), ("Bohoródičen", "", "So archánhely i ánhely Ďívo, i so svjatými vsími, iz tebé Hóspoda jávľšahosja nám molí, mólimsja, ístinnuju Bohoródicu ispovídajuščym ťá ot bíd izbávitisja."), ), ), "P3": ( "1": ( ("", "", "Neplódnaja dušé i bezčádnaja, sťaží plód blahoslávnyj, veseľáščisja vozopíj: utverdíchsja tobóju Bóže, ňísť svját, ňísť práveden, páče tebé Hóspodi."), ("", "", "Zakón Bóžij otverhóch nesmýslenno, i osuždén býti ímam: i čtó sotvorjú, ne vím. Sudijé právedňijšij, uščédriv spasí mja milosérdijem tvojím."), ("", "", "Vostók čelovikoľúbče sýj vostókov, vozsijáj mí, moľúsja, právdy svít, izymája mjá strastéj omračénija, i ťmý mučénija, mnohomílostive."), ("Múčeničen", "", "Zemlí mýslennyja žítelije, drevesá plodovítaja rájskaja, svjatíji múčenicy, istóčnicy, íže božéstvennuju vódu imúščiji, čáši prolivájuščiji pitijé svjatóje javístesja."), ("Múčeničen", "", "Jedín vo mnóhich ťilesích nráv nosjášče, strastotérpcy múčenicy, ťmý pobidíste vrahá mirodéržca, Tróicu nerazďilímuju propovídajušče."), ("Bohoródičen", "", "Ďívo Máti prečístaja, kájuščymsja nám i ko Christú pritekájuščym, i prehrišénij razrišénije choťáščym prijáti, mílostiva sehó vsím soďílaj vsích Vladýčice."), ), "2": ( ("", "", "Íže ot ne súščich vsjá privedýj, slóvom sozidájemaja, soveršájemaja Dúchom, vsederžíteľu výšnij, v ľubví tvojéj utverdí mené."), ("", "", "Hlás Slóva býv Krestíteľu, hlásy čtúščich ťá k nemú nýňi isprávi, i prehrišénij ostavlénije chodátajstvom tvojím nám podážď."), ("", "", "Sohriších tebí i bezzakónnovach, i ľúťi Spáse prehriších, i dúšu oskverních: sehó rádi moľúsja tí, tvojehó rádi Krestíteľa uščédri mjá."), ("", "", "V pustýni zablúždša slasťmí, pustýnnoje vospitánije i nastávnika nóvych ľudéj moľú ťa Predtéče, k pokajánija putí nastávi mjá."), ("Bohoródičen", "", "So apóstoly, i proróki svjaščénnymi, s múčeniki prečístaja, i s výšnimi sílami Sýna tvojehó molí, uščédriti nás tebé pojúščich."), ), ), "P4": ( "1": ( ("", "", "Priosinénnuju hóru Avvakúm prozrjáše, prečístuju tvojú utróbu čístaja, ťím vzyváše: ot júha priídet Bóh, i svjatýj ot horý priosinénnyja čášči."), ("", "", "Íže istočívyj iz kámene drévle ľúdem nepokorívym Christé, i prerikájuščym, vódu žáždy iscilénija, ot nevlážnyja duší mojejá Bóže, umilénija kápľu izmyvájuščuju mjá istočí."), ("", "", "Vračú boľáščich, sérdca mojehó strásti iscilí blahoutróbnym tvojím manovénijem, pokajánija semú Spáse prilahája plástyr, jáko bláh, božéstvennaho býlija, jáko da víroju slavoslóvľu ťá."), ("Múčeničen", "", "Mílostivno strastonóscy, jáže k ťílu drúžby, rasprjáhše pomyšlénije, múčiti vás choťáščym predáste sámi sebé. Ťímže blížniji ziždíteľu býste drúzi."), ("Múčeničen", "", "Mnohoboľíznennyja strúpy ot mnohovídnych múk podjáste stradáľcy Christóvy, i blahodáť prijáste ot duchóvnych daróv, strastéj nášich prohoňájušče mnohoľítnyja boľízni."), ("Bohoródičen", "", "Mnohoimenítaja Otrokovíce rádujsja, iz nejáže Bóh Slóvo rodísja, ot bezslovésnych nás razrišája, i bezmístnych ďijánij: rádujsja óblače svítlyj, razhoňájuščij óblaki nášeho unýnija."), ), "2": ( ("", "", "Položíl jesí k nám tvérduju ľubóv Hóspodi, jedinoródnaho bo tvojehó Sýna za ný na smérť dál jesí. Ťímže tí zovém blahodarjášče: sláva síľi tvojéj Hóspodi."), ("", "", "Slóva ťá hlás plótiju jávľšahosja súšča, Predtéče Hospódeň moľú, bezslovésnych mjá izbávi ďijánij, slovesý čtúščaho ťá, i po dólhu víroju blažáščaho."), ("", "", "Vozdochní o dušé, i Bóhu ziždíteľu tvojemú vozopíj: sohriších, očísti mjá Christé, i izbávi mjá strášnyja múki, bíd že i skorbéj, moľbámi božéstvennaho Predtéči."), ("", "", "Volnámi mnóhimi ľútych strastéj potopľájema, i búreju ľúťi soderžíma, i prísno pohružájema, Krestíteľu ischití, i k pokajánija pristánišču nastávi mjá."), ("Bohoródičen", "", "Máti Bóžija, Cheruvím prevýššaja, kolesníce, s neveščéstvennymi služíteli, i so svjatými vsími molí Christá, jehóže rodilá jesí vseneporóčnaja, spastí mja otčájannaho."), ), ), "P5": ( "1": ( ("", "", "Útreňujušče vospivájem ťá Slóve, Sýne Bóžij jedinoródne: tvój mír dážď nám, i pomíluj ný pojúščyja ťá, i vírno poklaňájuščyjasja."), ("", "", "Okropív mjá pokajánija issópom, očísti ot skvérn strastéj, da javľúsja tebí číst, jehdá chóščeši Iisúse, sudíti vsjáčeskim, právednym tvojím sudóm."), ("", "", "Rány sohníšasja Spáse preokajánnyja mojejá duší: iscilíteľu boľáščich, i dáteľu blahích, iscilív spasí mja, mnóhija rádi tvojejá mílosti."), ("Múčeničen", "", "Sokrušíšasja sosúdi skudéľniji strastotérpcev na zemlí: no kríposť dušévnaja ukripísja mnóžaje, i prosvitísja Christóvoju síloju."), ("Múčeničen", "", "Prolivájemaja svjatých króv vsjú zémľu osvjátí, i napojí vírnych dúšy, i izsuší jávi sújetstva mútnyja potóki."), ("Bohoródičen", "", "Roždestvóm tvojím oneplódstvila jesí otrokovíce práďidňuju kľátvu: i istočíla jesí nám blahoslovénija ríki, blahoslóvjaščym ťá, i slávjaščym víroju."), ), "2": ( ("", "", "Na zemlí nevídimyj javílsja jesí, i čelovíkom vóleju sožíl jesí nepostižímyj, i k tebí útreňujušče, vospivájem ťá čelovikoľúbče."), ("", "", "Na zemlí jákože ánhel blažénne, s plótiju jávi požíl jesí. Ťímže moľúsja tí: plotskích mudrovánij dúšu mojú svobodí."), ("", "", "Vo hlubinú hrichóvnuju vpádšaho, i slasťmí dúšu oskvernívšaho, i bídstvujuščaho, Hospódeň Predtéče, spasí mja k tebí pribihájuščaho."), ("", "", "Tý prorókov prevýšši javílsja jesí, íbo sám víďil jesí proróče Propovídannaho: jehóže neprestánno molí, prosvitíti dúšy náša."), ("Bohoródičen", "", "Nebés prostránňijši jávľšisja, jéže v ťá vselénijem Slóva Bohorádovannaja, uťisňájuščich mjá hrichóv svobodí."), ), ), "P6": ( "1": ( ("", "", "Hlubiná strastéj vostá na mjá, i búrja protívnych vítrov: no predvarív mjá tý spasí Spáse, i izbávi ot tlí jáko spásl jesí ot zvírja proróka."), ("", "", "Omračíchsja hrichá mhlóju, i ležú neďíjstven vés: íže ujazvívyjsja mené rádi kopijém inohdá, Christé Bóže, uščédri mjá tvojím milosérdijem."), ("", "", "Steňú, i v zlých prebyváju: slezjú, i sudá ne trepéšču, nečúvstvijem boľú: Slóve Bóžij, uščédri mjá i spasí, blahími suďbámi tvojími."), ("Múčeničen", "", "Jákože áhncy ne vopijúšče otňúd, ni slóvo, ni hlás ispuščájušče, vseslávniji stradáľcy, k zakoléniju i ránam privodími býste, Christá vospivájušče."), ("Múčeničen", "", "Zvirém prédani býste na sňíď, morskíja hlubiný pričastístesja rádostnoju dušéju. Ťímže vás Christós, stradáľcy, vincý netľínnymi ukrasí."), ("Bohoródičen", "", "Dvére vírno spasájemych, vratá, ímiže jedín prójde voplóščsja za ný, vratá nám právdy otvérzi, víroju ťá pojúščym."), ), "2": ( ("", "", "Bézdna posľídňaja hrichóv obýde mjá i isčezájet dúch mój: no prostrýj Vladýko vysókuju tvojú mýšcu, jáko Petrá mja upráviteľu spasí."), ("", "", "Vodámi, potóka sládosti, priklónšahosja pod rúku tvojú krestíl jesí: tohó molí, nizposláti mí vódu múdre umilénija, mnóho sohrišívšemu."), ("", "", "Bézdnu milosérdija v ricí Predtéče omýl jesí, prevýsprenňaja nebesá vodámi pokryvájuščaho, Iisúsa čelovikoľúbca: jehóže molí istočíti mí ostavlénije."), ("", "", "Priblížisja cárstvo nebésnoje, pokájtesja, vzyvál jesí Predtéče: jehóže ulučíti spodóbi ľubóviju ťá čtúščich, i pod króv čestnýj pribihájuščich."), ("Bohoródičen", "", "Prečístaja, jáže plóť svojú sozdáteľu vzajím dávši, s výšnimi sílami, i so proróki vsími, apóstoly že i múčeniki, tohó molí uščédriti i spastí mja."), ), ), "P7": ( "1": ( ("", "", "Plámeň orosívyj péščnyj, i ótroki neopalímy spasýj, blahoslovén jesí vo víki, Hóspodi Bóže otéc nášich."), ("", "", "Obnažíchsja ot ríz netľínija, oblekóchsja že v ďilá bezčéstija. Ťímže vopijú ti: Bóže ščédryj, dobroďítelej mjá odéždami prosvití."), ("", "", "Očíma blúdnyma okaľáchsja, i osjazánijem nevozderžánija oskverníchsja, i mérzok bých pred tobóju Iisúse, jáko blúdnaho prijimí mja."), ("Múčeničen", "", "Výšňuju žízň vozľubívše, mnóhija preterpíste boľízni, Christóvy orúžnicy, svitíľnicy božéstvenniji: sehó rádi vírno ublažájemi jesté."), ("Múčeničen", "", "Prosvitívšesja zaréju mučénija, oblistájete mnóžaje sólnca, i vsják mrák bezbóžija othnáste svjatíji múčenicy."), ("Bohoródičen", "", "Jáko róždši vsích soderžíteľa, ot soderžáščaho mráka nevíďinija, i ot hrichá izbávi mjá, Bohoródice čístaja prisnoďívo."), ), "2": ( ("", "", "Trijé ótrocy v peščí Tróicu proobrazívše, preščénije óhnennoje popráša, i pojúšče vopijáchu: blahoslovén jesí Bóže otéc nášich."), ("", "", "Svitíľnik sólnca, dúšu mojú ľínostiju omračénuju ozarí i osľiplénnuju, k pokajánija stezí napravľája mjá, Krestíteľu Christóv Predtéče."), ("", "", "Súdnyj čás pomyšľája, vés ustrašájusja, sležú vo mnóžestvi bezmístnych ďijánij, Krestíteľu Hospódeň, predstáv izbávi mjá ohňá predležáščaho mí."), ("", "", "Predstáteľu životá mojehó, zastúpniče mój Predtéče, ot vrahóv mjá vídimych i nevídimych sochraní, i pokrýj, i cárstvija nebésnaho pričástnika sotvorí."), ("Bohoródičen", "", "Ďívo Bohoródice, Sýna tvojehó molí, so proróki, apóstoly že i múčeniki, búduščija núždy izbáviti ný, tebé čtúščyja prísno."), ), ), "P8": ( "1": ( ("", "", "Ánhelmi nemólčno vo výšnich slávimaho Bóha, nebesá nebés, zemľá, i hóry, i chólmi, i hlubiná, i vés ród čelovíčeskij, písňmi tohó jáko sozdáteľa i izbáviteľa blahoslovíte , i prevoznosíte vo vsjá víki."), ("", "", "Jáko strácha tvojehó ne imích živúščaho v sérdci mojém, vsjú skončách plotskúju slásť bezsóvistnyj, i trepéšču tvojehó sudá vsích carjú: ne vozhnušájsja mené nýňi kájuščahosja."), ("", "", "Na zémľu svjatúju mjá prejtí, mnohomílostive spodóbi, na néjže živút krótcyi, pokajánijem izmýv mjá zemnáho hrichá, íže na zemlí bezhríšno roždéjsja ot Ďívy."), ("Múčeničen", "", "V svojéj vám króvi očervleníšasja nóhi váša, zapinájušče vrahú, i šéstvije k nebésnym tvorjášče prepodóbno, vseslávniji Christá vsích Bóha strastotérpcy."), ("Múčeničen", "", "Sovlekóstesja ko stradánijem usérdno, i k velíkim borénijem, obnažíste vrahá, i v stúd oblekóste: ťímže na nebesích vincenóscy likújete, slávniji strastotérpcy."), ("Bohoródičen", "", "Jákovľu ťá dobrótu, íže krásnyj dobrótoju Hospóď vozľubív, vo tvojé črévo vseneporóčnaja vselísja, čelovíčeskoje suščestvó dobrótami prosvitív, páče umá darováňmi."), ), "2": ( ("", "", "Nesterpímomu ohňú sojedinívšesja, Bohočéstija predstojášče júnoši, plámenem že nevreždéni, božéstvennuju písň pojáchu: blahoslovíte vsjá ďilá Hospódňa Hóspoda, i prevoznosíte vo vsjá víki."), ("", "", "Áhnca Bóžija propovídal jesí, hrichí čelovíkov vzémľuščaho, Joánne božéstvennyj Predtéče: tohó molí brémja razrišíti hrichóv mojích, i spasájemych části spodóbiti mjá."), ("", "", "Péšči plámene horjáščaho, ťmý nesvitímyja kromíšnija izbávi mjá, vo ťmí zlých ďíl vsehó soderžíma, moľú ťa Slóve Bóžij prebeznačáľnyj, slávnaho rádi božéstvennaho Krestíteľa tvojehó."), ("", "", "Pustým dušám i bezplódnym, pokajánijem blahoplódije propovídavyj, Hospódeň božéstvennyj proróče, ternonósnuju dúšu mojú ot vsích slastéj očísti: jáko da vozraščú blahích ďíl klás."), ("Bohoródičen", "", "Jáko Má<NAME>žija, molí so svjatými ánhely i proróki, apóstoly že i múčeniki, bíd že i skorbéj, i búduščich vsích múk izbáviti, tebé Bohoródicu prísno ispovídajuščich."), ), ), "P9": ( "1": ( ("", "", "Blahoslovén Hospóď Bóh Izráilev, vozdvíhnuvyj róh spasénija nám, v domú Davída ótroka svojehó, milosérdija rádi mílosti, v níchže posití nás vostók s vysotý, i naprávil ný jésť na púť míra."), ("", "", "Sé vrémja blahoprijátno, i déň očiščénija: obratítisja voschoščí próčeje, o dušé, tvoríti plodý pokajánija: da ne bezplódnu ťá obrjáščet smértnaja sikíra strášnaja, i jáko smokóvnicu drévňuju posíkši, ohňú támošnemu póslet."), ("", "", "Jákože inohdá bohátyj veseľúsja v sládostech, nemilosérdije mnóhoje imýj k blížnemu, i ohňá ne ustrašájusja neuhasímaho. Ťímže Vladýko, umjahčí mi okamenénije duší, jáko da poné nakonéc milosérdijem prosviščúsja omračénnyj."), ("Múčeničen", "", "Známenavšesja múčenicy božéstvennoju króviju Christóvoju, i známeňmi víroju stráždušče krípko, nevírnyja vrahí nizložíste, i ot prélesti skvérnyja mnóhija ľúdi ischitíste, preminéniji božéstvennymi, prosvitívše svítom Bohorazúmija."), ("Múčeničen", "", "Izoščréni javístesja mečí, sikúšče vrážija opolčénija, božéstvenniji Christóvy múčenicy: i sosúdi vmistívše zarjú svjatýja Tróicy, i svíščnicy sviťáščyja vírnym svít blahočéstija, i Sijóna mýslennaho ístinniji orúžnicy."), ("Bohoródičen", "", "Svitovídna ťá óblaka prorók predzrít, iz nehóže velíkoje sólnce javísja nám Christós Bóh, i prosvití jáže pérvije omračénnyja: tohó umolí blahája, strastéj mojích óblaki othnáti, i svítom božéstvennym prosvitíti."), ), "2": ( ("", "", "V zakóňi síni i pisánij óbraz vídim vírniji, vsják múžeskij pól ložesná razverzája, svját Bóhu: ťím pervoroždénnoje Slóvo, Otcá beznačáľna, Sýna pervoroďáščasja Máteriju neiskusomúžno, veličájem."), ("", "", "V zakónnuju síň priník, zarjú božéstvennyja blahodáti bohátno uzríl jesí, zemnýja koncý múdre prosviščája, i ťmú prohoňája nerazúmija, proróče: sehó rádi ťá čtím."), ("", "", "Jáko múčenik Christóv, jáko božéstvennyj Krestíteľ, jáko pokajánija svitíľnik, i jáko útro blahočéstija, vétchomu chodátaj i nóvomu: obetšávšuju zlóboju smirénnuju mojú dúšu, razumínijem božéstvennym obnovív, prosvití."), ("", "", "V čás užásnyj, v čás strášnyj, v čás osuždénija, osuždájema mjá izbávi múdre, preščénija ždúščaho mjá támo: poslúšajuščaho imíja tvojá moľbý, jákože drúh ženichá, Spasíteľa dúš nášich."), ("Bohoródičen", "", "Jáko Máti Bóžija, jáko Máti iz tebé plótiju róždšahosja Slóva Bóžija čístaja, so bezplótnymi, apóstoly že i proróki, so svjatíteli i múčeniki, tohó molí prísno, umiríti mír, prečístaja Máti Ďívo."), ), ), ), "ST": ( ("", "", "Razsíjannyj mój úm soberí Hóspodi, i oľadeňívšeje sérdce mojé očísti, jáko Petrú dajá mi pokajánije, jáko mytarjú vozdychánije, i jákože bludníci slézy, da vélijim hlásom vzyváju tí: Bóže spasí mja, jáko jedín milosérd i čelovikoľúbec."), ("", "", "Mnóžiceju pínija soďivája, obritóchsja hrichí soveršája, jazýkom úbo pínija viščája, dušéju že nevmístnaja mýšľu: no obojé isprávi Christé Bóže pokajánijem, i pomíluj mjá."), ("Múčeničen", "", "Caréj i mučítelej strách otrínuša Christóvy vóini, i blahoderznovénno, i múžeski tohó ispovídaša, vsjáčeskich Hóspoda Bóha, i carjá nášeho, i móľatsja o dušách nášich."), ("Bohoródičen", "", "Bez símene začalá jesí ot Dúcha svjatáho, i slavoslóvjašče vospivájem ťá: rádujsja presvjatája Ďívo."), ) ) #let L = ( "B": ( ("", "", "Otvérhša Christé, zápoviď tvojú, práotca Adáma iz rajá izhnál jesí: razbójnika že ščédre, ispovídavša ťá na kresťí, vóň vselíl jesí, zovúšča: pomjaní mja Spáse vo cárstviji tvojém."), ("", "", "Žitéjskimi slasťmí oskvernénu priťažách dúšu, k ščedrótam tvojím prichoždú nenačájem vés, i priľížno zovú ti Christé, svíduščemu jedínomu tájnaja: očísti mjá tvojím milosérdijem Hóspodi."), ("", "", "Jáko chodátaj vétchaho i nóvaho býv Božéstvennyj Krestíteľu, obetšávšaho mjá prehrišéňmi obnovív, dážď tvojími moľbámi vsechváľne, chodíti nepretknovénno po stezjám pokajánija, vvoďáščim dóbri vo cárstvo Christóvo."), ("", "", "Pódvihom dóbrym podvizávšesja dóbliji stradáľcy, bezčíslennyja ťmý boľíznej podjáste, i sehó rádi vsích boľízni oblehčájete prísno, i duchóv vreždénija prohónite: ťímže víroju vás svjatíji slávim."), ("", "", "Svít i živót, i vseďíteľ, triipostásnaja jedínica, jáko voístinnu jésť, júže slávim: Otéc bo, i Sýn, i Dúch, jedínica i soderžáščaja vsjá, Vladýka i Hospóď jedín Bóh v trijéch lícach poznavájetsja."), ("", "", "Sohrišájuščaho prísno, i prohňívajuščaho Bóha blaháho, Ďívo Máti uščédri i pokajánija óbrazy jáko blahája, utverdí mja nýňi, jáko da búduščich múk izbíhnuv, vospiváju priľížno otrokovíce, molítvu tvojú."), ) )
https://github.com/imatpot/typst-ascii-ipa
https://raw.githubusercontent.com/imatpot/typst-ascii-ipa/main/src/lib/converters/branner.typ
typst
MIT License
// https://web.archive.org/web/19990209070257/http://weber.u.washington.edu/~yuenren/ASCII_IPA.html // https://en.wikipedia.org/wiki/Comparison_of_ASCII_encodings_of_the_International_Phonetic_Alphabet #let branner-unicode = ( ("&g^", "ˤ"), ("'", "ˈ"), ("(", "̯"), ("(^", "̆"), ("+", "̟"), (",", "ˌ"), (",)", "̩"), (".", "."), (".)", "̚"), ("/", "↗"), ("/)", "ꜛ"), ("1", "̏"), ("13", "᷅"), ("15", "̌"), ("2", "̀"), ("3", "̄"), ("342", "᷈"), ("35", "᷄"), ("3\"", "ʒ"), ("4", "́"), ("5", "̋"), ("51", "̂"), (":", "ː"), (";", "ˑ"), ("<", "̘"), ("=", "̝"), ("=)", "‿"), ("=\"", "̞"), (">", "̙"), ("?", "ʔ"), ("?&", "ʕ"), ("?&-", "ʢ"), ("?-", "ʡ"), ("?\"", "ʢ"), ("@", "ə"), ("B", "ʙ"), ("B\"", "β"), ("E", "ɛ"), ("E&", "ɜ"), ("E\"", "ɞ"), ("G", "ɢ"), ("G$", "ʛ"), ("H", "ʜ"), ("I", "ɪ"), ("L", "ʟ"), ("N", "ɴ"), ("O-", "θ"), ("OE)", "ɶ"), ("P\"", "ɸ"), ("Q&-", "ʢ"), ("R", "ʀ"), ("R%", "ʁ"), ("S", "ʃ"), ("Sx)", "ɧ"), ("U", "ʊ"), ("U)", "̜"), ("U\"", "ɤ"), ("V)", "̥"), ("X", "χ"), ("Y", "ʏ"), ("[", "̪"), ("[]", "̻"), ("\"^", "̈"), ("\\", "↘"), ("\\)", "ꜜ"), ("]", "̺"), ("_", "̠"), ("`", "ʼ"), ("a", "a"), ("a&", "ɐ"), ("a\"", "ɑ"), ("a\"&", "ɒ"), ("ae)", "æ"), ("b", "b"), ("b$", "ɓ"), ("c!", "ǂ"), ("c", "c"), ("c&", "ɔ"), ("c\"", "ç"), ("ci)", "ɕ"), ("d", "d"), ("d$", "ɗ"), ("d-", "ð"), ("dr)", "ɖ"), ("e", "e"), ("e&", "ɘ"), ("f", "f"), ("g", "ɡ"), ("g$", "ɠ"), ("g\"", "ɣ"), ("g^", "ˠ"), ("h", "h"), ("h&", "ɥ"), ("h-", "ħ"), ("h\"", "ɦ"), ("h\")", "̤"), ("h^", "ʰ"), ("i", "i"), ("i-", "ɨ"), ("j", "j"), ("j$", "ʄ"), ("j-", "ɟ"), ("j\"", "ʝ"), ("j^", "ʲ"), ("jr)", "ɻ"), ("k", "k"), ("l!", "ǁ"), ("l", "l"), ("l-", "ɬ"), ("l3\")", "ɮ"), ("l\"", "ɺ"), ("l^", "ˡ"), ("lr)", "ɭ"), ("l~)", "ɫ"), ("m", "m"), ("m&", "ɯ"), ("m&\"", "ɰ"), ("m\"", "ɱ"), ("n", "n"), ("n^", "ⁿ"), ("ng)", "ŋ"), ("nj)", "ɲ"), ("nr)", "ɳ"), ("o", "o"), ("o-", "ɵ"), ("o/)", "ø"), ("oe)", "œ"), ("p!", "ʘ"), ("p", "p"), ("q", "q"), ("r!", "ǃ"), ("r", "r"), ("r&", "ɹ"), ("r\"", "ɾ"), ("r^", "˞"), ("rr)", "ɽ"), ("s", "s"), ("sr)", "ʂ"), ("t!", "ǀ"), ("t", "t"), ("tr)", "ʈ"), ("u", "u"), ("u)", "̹"), ("u-", "ʉ"), ("v", "v"), ("v&", "ʌ"), ("v)", "̬"), ("v\"", "ʋ"), ("w", "w"), ("w&", "ʍ"), ("w^", "ʷ"), ("x", "x"), ("x^", "̽"), ("xr^", "ɚ"), ("y", "y"), ("y&", "ʎ"), ("z", "z"), ("zi)", "ʑ"), ("zr)", "ʐ"), ("{", "̼"), ("|", "|"), ("||", "‖"), ("~", "̰"), ("~)", "̴"), ("~^", "̃"), ).sorted( key: (pair) => -pair.at(0).len() ) #let parse-tiebar(text, reverse: false) = { let tiebar = if reverse { regex("(.)͡(.)") } else { regex("(.)(.)\)\)") } let transform = if reverse { (match) => match.captures.at(0) + match.captures.at(1) + "))" } else { (match) => match.captures.at(0) + "͡" + match.captures.at(1) } let unique-matches = text.matches(tiebar).dedup(key: (match) => match.text) for match in unique-matches { text = text.replace(match.text, transform(match)) } return text } #let convert-branner(text, reverse: false) = { let (from, to) = if reverse { (1, 0) } else { (0, 1) } if reverse { text = parse-tiebar(text, reverse: true) } for pair in branner-unicode { text = text.replace(pair.at(from), pair.at(to)) } if not reverse { text = parse-tiebar(text, reverse: false) } return text }
https://github.com/hooyuser/typst_math_notes
https://raw.githubusercontent.com/hooyuser/typst_math_notes/master/README.md
markdown
# Typst template for math notes Example ``` #import "preamble.typ": math_notes, definition, proposition, lemma, theorem, corollary, example, proof #show: math_notes #block(inset: (left: -0.5em, right: -0.5em))[ #outline(title: text(font: "Noto Sans", size: 23pt, weight: 700, stretch: 150%)[Contents #v(1em)], depth: 3) ] #pagebreak() = Linear Algebra #definition[ Linear Space ][ A vector space over a field F is a non-empty set V together with a binary operation and a binary function. ] ```
https://github.com/caffeinatedgaze/bare-bones-cv
https://raw.githubusercontent.com/caffeinatedgaze/bare-bones-cv/main/main.typ
typst
#let configuration = yaml("configuration.yaml") #let settings = yaml("settings.yaml") #show link: set text(blue) #set page( paper: "a4", margin: ( top: 1.5cm, bottom: 1cm, ) ) #show heading: h => [ #set text( size: eval(settings.font.size.heading_large), font: settings.font.general ) #h ] #let sidebarSection = {[ #par(justify: true)[ #par[ #set text( size: eval(settings.font.size.contacts), font: settings.font.minor_highlight, ) Email: #link("mailto:" + configuration.contacts.email) \ Phone: #link("tel:" + configuration.contacts.phone) \ LinkedIn: #link(configuration.contacts.linkedin.url)[#configuration.contacts.linkedin.displayText] \ GitHub: #link(configuration.contacts.github.url)[#configuration.contacts.github.displayText] \ #configuration.contacts.address ] #line(length: 100%) ] = Summary #par[ #set text( eval(settings.font.size.education_description), font: settings.font.minor_highlight, ) An experienced *software engineer* with a confident grasp of *infrastructure* and *system design*, now seeking opportunities to excel in the realms of solution architecture. Open to roles ranging from *software engineering* to *infrastructure*. ] = Education #{ for place in configuration.education [ #par[ #set text( size: eval(settings.font.size.heading), font: settings.font.general ) #{ if "to" in place and "from" in place [ #place.from – #place.to \ ] else if "arbitrary_interval" in place [ #place.arbitrary_interval ] } #link(place.place.link)[#place.place.name] ] #par[ #set text( eval(settings.font.size.education_description), font: settings.font.minor_highlight, ) #{ let description_items = () if "degree" in place and "major" in place [ #description_items.push(place.degree + " " + place.major) ] if "track" in place [ #description_items.push(place.track + " " + "track") ] if "note" in place [ #description_items.push(place.note) ] if "location" in place [ #description_items.push(place.location) ] description_items.join("\n") } ] ] } = Skills #{ for skill in configuration.skills [ #par[ #set text( size: eval(settings.font.size.description), ) #set text( // size: eval(settings.font.size.tags), font: settings.font.minor_highlight, ) *#skill.name* #linebreak() #skill.items.join(" • ") ] ] } ]} #let mainSection = {[ // #par[ // #set align(center) // #figure( // image("images/Kodak 20 Zanvoort Lumi.jpg", width: 6em), // placement: top, // ) // ] #par[ #set text( size: eval(settings.font.size.heading_huge), font: settings.font.general, ) *#configuration.contacts.name* ] #par[ #set text( size: eval(settings.font.size.heading), font: settings.font.minor_highlight, top-edge: 0pt ) #configuration.contacts.title ] = Experience #{ for job in configuration.jobs [ #par(justify: false)[ #set text( size: eval(settings.font.size.heading), font: settings.font.general ) *#job.position* #link(job.company.link)[\@ #job.company.name] \ #job.from – #job.to ] #par( justify: false, leading: eval(settings.paragraph.leading) )[ #set text( size: eval(settings.font.size.description), font: settings.font.general ) #{ for point in job.description [ #h(0.5cm) • #point \ ] } ] #par( justify: true, leading: eval(settings.paragraph.leading), )[ #set text( size: eval(settings.font.size.tags), font: settings.font.minor_highlight ) #{ let tag_line = job.tags.join(" • ") tag_line } ] ] } = Hackathons #{ for hack in configuration.hackathons [ #par( justify: true, leading: eval(settings.paragraph.leading) )[ #par[ #set text( size: eval(settings.font.size.heading), font: settings.font.general ) - #hack.year #hack.from – #hack.to \ #link(hack.hackathon.link)[#hack.hackathon.name] – #link(hack.certificate_link)[Credential] ] #par[ #set text( size: eval(settings.font.size.description), font: settings.font.general ) #hack.description ] ] ] } ]} #{ grid( columns: (2fr, 5fr), column-gutter: 3em, sidebarSection, mainSection, ) }
https://github.com/pluttan/trps
https://raw.githubusercontent.com/pluttan/trps/main/lab2/lab2.typ
typst
#import "@docs/bmstu:1.0.0":* #import "@preview/tablex:0.0.8": tablex, rowspanx, colspanx, cellx #show: student_work.with( caf_name: "Компьютерные системы и сети", faculty_name: "Информатика и системы управления", work_type: "лабораторной работе", work_num: "2", discipline_name: "Технология разработки программных систем", theme: "Тестирование программного обеспечения (Вариант 11)", author: (group: "ИУ6-42Б", nwa: "<NAME>"), adviser: (nwa: "<NAME>"), city: "Москва", table_of_contents: true, ) = Ручное тестирование программных продуктов == Задание Программа должна формировать типизированный файл с информацией о фамилии человека, дне рождения, а также осуществлять поиск в файле информации о дне рождения (файл исходного кода v11.doc). == Методы ручного тестирования Основными методами ручного тестирования являются: - инспекции исходного текста; - сквозные просмотры; - просмотры за столом; - обзоры программ. Для тестирования методом инспекции исходного текста требуется группа специалистов, в которую входят автор программы, проектировщик,специалист по тестированию и координатор (компетентный программист, но не автор программы), поэтому ручное тестирование данным методом невозможно в рамках данной лабораторной работы. Для тестирования методом сквозным просмотров требуется группа из 3-5 человек: председатель или координатор, секретарь, фиксирующий все ошибки, специалист по тестированию, программист и независимый эксперт. Поэтотму данный метод тестирования тоже не возможен в рамках выполнения лабораторной работы. В методе оценки посредством просмотра выбирается программист, который должен выполнять обязанности администратора процесса. Администратор набирает группу от 6 до 20 участников, которые должны быть одного профиля. Каждому участнику предлагается представить для рассмотрения две программы: наилучшую и наихудшую. Отобранные программы случайным образом распределяются между участниками. Им дается по 4 программы — две наилучшие и две наихудшие, но программист не знает, какая из них плохая, а какая хорошая. Программист просматривает их и заполняет анкету, в которой предлагается оценить их относительное качество по шкале из семи баллов. Кроме того, проверяющий дает общий комментарий и рекомендации по улучшению программы. Так как в данной лабораторной требуется оценить только одну программу данный метод тоже не подходит. == Метод проверки за столом Следующим методом ручного обнаружения ошибок является используемая ранее других методов проверка за столом. Этот метод включает проверку исходного кода программы (или сквозной просмотр), выполняемую одним человеком, который читает код программы, проверяет его по списку вопросов и пропускает через программу тестовые данные. Исходя из принципов тестирования, проверку за столом должен проводить человек, который не является автором программы. Недостатками метода являются: - полностью неупорядоченный процесс проверки; - отсутствие обмена мнениями и здоровой конкуренции; - меньшая эффективность по сравнению с другими методами. Несмотря на недостатки, данный метод является единственным возможным в рамках выполнения лабораторной работы. Приведем список вопросов, на которые будем ссылаться позже, в таблице тестирования. 1. Обращения к данным. 1. Все ли переменные инициализированы? 2. Не превышены ли максимальные (или реальные) размеры массивов и строк? 3. Не перепутаны ли строки со столбцами при работе с матрицами? 4. Присутствуют ли переменные со сходными именами? 5. Используются ли файлы? Если да, то 1. при вводе из файла проверяется ли завершение файла? 2. соответствуют ли типы записываемых и читаемых значений? 6. Использованы ли нетипизированные переменные, открытые массивы, динамическая память? Если да, то 1. соответствуют ли типы переменных при наложении формата? 2. не выходят ли индексы за границы массивов? 2. Вычисления. 1. Правильно ли записаны выражения (порядок следования операторов)? 2. Корректно ли производятся вычисления неарифметических переменных? 3. Корректно ли выполнены вычисления с переменными различных типов (в том числе с использованием целочисленной арифметики)? 4. Возможны ли переполнение разрядной сетки или ситуация машинного нуля? 5. Соответствуют ли вычисления заданным требованиям точности? 6. Присутствуют ли сравнения переменных различных типов? 3. Передачи управления. 1. Будут ли корректно завершены циклы? 2. Будет ли завершена программа? 3. Существуют ли циклы, которые не будут выполняться из-за нарушения условия входа? Корректно ли продолжатся вычисления? 4. Существуют ли поисковые циклы? Корректно ли отрабатываются ситуации «элемент найден» и «элемент не найден»? 4. Интерфейс. 1. Соответствуют ли списки параметров и аргументов по порядку, типу, единицам измерения? 2. Не изменяет ли подпрограмма аргументов, которые не должны изменяться? 3. Не происходит ли нарушения области действия глобальных и локальных переменных с одинаковыми именами? Далее приведем код непосредственно тестируемой программы. #let lab2_1 = read("1.cpp") #code(lab2_1, "cpp", [Код, предоставленный для ручного тестирования], num:true, size:12.2pt) Заполним таблицу тестирования данными. #align(center)[ #tablex( columns: 4, inset: 10pt, align: horizon+center, [Номер\ вопроса],[Строки,\ подлежащие\ проверке],[Результат проверки],[Вывод], [1.1],[15-19,\ 21, 25,\ 32, 34], [Переменные, используемые в программе:\ ```c f, fb, key, fff```\ Переменные, инициализированные в программе:\ ```c f, fb, n, key, fff```], [Все используемые переменные инициализированы], [1.2],[25, 32], [Строки в программе:\ ```c fb.ff, fff```], [Используются динамические строки типа ```cpp std::string```, размеры не могут быть превышены], [1.3],[], [Работа с матрицами не производится], [], [*1.4*],[25, 32], [Переменные, инициализированные в программе:\ ```c f, fb, n, key, fff```], [_Переменные со схожими именами присутствуют:\ ```c f, fb, fff, fb.ff```_], [*1.5.1*],[37], [Проверка присутствует, выполнена с помощью сравнения количества данных, прочтенных успешно, с 20\ Проверки об успешном открытии файла отсутствуют], [_Проверка на завершение при чтении построена некорректно, так как читается всегда только один набор данных_], [*1.5.2*],[21, 26,\ 35, 37], [Файл открыт в режиме `r` и `w`\ Записываемый тип: ```cpp fam```\ Читаемый тип: ```cpp fam```], [_Режимы не соответствует условию о типизированных данных. Необходимо открывать файл в бинарных режимах `rb` и `wb`._\ Типы соответствуют], [1.6],[], [Память выделяется динамически только в библеотеках],[], [2],[], [Вычисления\ в программе\ не производятся],[], [*3.1*],[24, 37], [Условием завершения первого цикла, вероятнее всего был выбран конец ввода\ Условием завершения 2 цикла, вероятнее всего, был выбран конец файла],[_Оба условия написаны неверно: для конца ввода необходимо проверять не конец файла, а непосредственно возращаемое значение ```cpp cin```, для конца файла можно проверять считываемые значения, но учесть, что всегда считывается одно значение, а не 20_], [*3.2*],[48-49], [Программа заканчивается закрытием читаемого файла],[_Код выхода из программы не возвращен, что может привести к непредвиденным ошибкам после выполнения программы_], [3.3],[24, 37], [Условиями входа обоих циклов являются открытый на запись и чтение файл],[Входы в циклы будут производиться верно], [3.4],[37-46], [Поисковый цикл организован структурно: объявлен флаг выхода если найдено, в услоии прописан флаг, после цикла обработка если ничего так и не было найдено],[Поисковый алгоритм цикла организован верно], [*4.1*],[21, 22,\ 25, 26,\ 29, 31,\ 32, 35,\ 37, 39-40,\ 46, 48], [Список параметров и аргументов по порядку, типу, единицам измерения соответствует с ожидаемыми параметрами и аргументами библеотечными функциями. Выбор типа ```cpp unsigned char``` неуместен для месяца и даты, так как преобразование в ```cpp short``` может выполняться некорректно для некоторых версий языка],[_Необходимо изменить тип ```cpp unsigned char``` на другой, к примеру ```cpp short```_], [4.2],[6-49], [Структура изменения переменных в программе соответствует условию задачи],[Программа не изменяет аргументы, которые не должны изменяться], [4.3],[], [Глобальные переменные в коде отсутствуют],[], ) ] == Заключение При ручном тестировании получили ошибки в 6 пунктах: 1.4, 1.5.1, 1.5.2, 3.1, 3.2, 4.1. Исправим найденные ошибки и перепишем код: #let lab2_1n = read("1n.cpp") #code(lab2_1n, "cpp", [Исправленный, после ручного тестирования, код], num:true, size:8.7pt) = Белый ящик == Задание Дана схема алгоритма: #img(image("1.png", width: 80%), [Схема алгоритма]) По схеме алгоритма видим, что на вход программы поступают некоторые данные: `a`, `b`, `x`. == Покрытие операторов Критерий покрытия операторов подразумевает выполнение каждого оператора программы по крайней мере 1 раз. Это необходимое, но недостаточное условие для приемлемого тестирования. Сделаем таблицу, в которой подберем несколько разных наборов данных, чтобы покрыть все операторы: #align(center)[ #tablex( columns: 6, inset: 10pt, align: horizon+center, colspanx(3)[Входные данные], rowspanx(2)[Оператор], rowspanx(2)[Z], rowspanx(2)[Программный\ результат], [a], [b], [x], [1], [$forall$], [1], $ Z = sum_(k = 0)^infinity 1/(x^k times a^k) $, $infinity$, [$infinity$ (число k, до которого программа будет обрабатывать цикл)], [0.1], [$forall$], [1], $ Z = sum_(k = 0)^infinity x^k times a^(2 k) $, [$100/99$], [$1.010101010$], [0.1], [$forall$], [0.1], [$ Z = sum_(k = 0)^infinity x^k / a^k $], $infinity$, [$infinity$ (число k, до которого программа будет обрабатывать цикл)], [0], [0.1], [1], $ Z = sum_(k = 0)^infinity x^k times b^(2 k) $, [$100/99$], [$1.010101010$], [0], [1], [1], [$ Z = sum_(k = 0)^infinity -x^k / b^(2k) $], $-infinity$, [$-infinity$ (обратное числу k, до которого программа будет обрабатывать цикл)], ) ] Так как при таком тестировании мы сами подбираем значения нельзя с точностью утверждать, что данное тестирование может покрыть все ошибки, которые могут возникнуть, но так как в результате мы получили ответы, совпадающие с некоторой погрешностью с теоретическими, можно сказать, что данное необходимое условие выполнено. == Покрытие решений Для реализации этого критерия необходимо достаточное количество тестов, такое, что каждое решение на этих тестах принимает значение «истина» или «ложь» по крайней мере 1 раз Так как все операторы стоят после условных переходов (т. е. за 1 проход можно попасть только в один из операторов), то при покрытия решений количество тестов, сделанное для покрытия операторов не изменится (так как за один путь мы не можем покрыть 2 оператора). #align(center)[ #tablex( columns: 6, inset: 10pt, align: horizon+center, colspanx(3)[Входные данные], rowspanx(2)[Назначение\ теста], rowspanx(2)[Z], rowspanx(2)[Программный\ результат], [a], [b], [x], [1], [$forall$], [1], [Нет Нет Нет], $infinity$, [$infinity$ (число k, до которого программа будет обрабатывать цикл)], // [0.1], [$forall$], [1], [Нет Нет Да], [$100/99$], [$1.010101010$], // [0.1], [$forall$], [0.1], [Нет Да], $infinity$, [$infinity$ (число k, до которого программа будет обрабатывать цикл)], [0], [0.1], [1], [Да Нет Да], [$100/99$], [$1.010101010$], // [0], [1], [1], [Да Нет Нет], $-infinity$, [$-infinity$ (обратное числу k, до которого программа будет обрабатывать цикл)], // [0], [0], [$forall$], [Да Да], [Введенные\ данные], [Введенные\ данные], ) ] Минус у данного метод тот же самый: мы не проходим по всему диапазону возможных вариантов, а просто проверяем для нескольких вариантов работу всех условных операторов программы. == Покрытие решений/условий Этот метод требует составить тесты так, чтобы все возможные результаты каждого условия выполнились по крайней мере 1 раз, все результаты каждого решения выполнились по крайней мере 1 раз и каждой точке входа управление передается по крайней мере 1 раз. #align(center)[ #tablex( columns: 7, inset: 10pt, align: horizon+center, rowspanx(2)[№],colspanx(3)[Входные данные], rowspanx(2)[Назначение\ теста], rowspanx(2)[Z], rowspanx(2)[Программный\ результат], [a], [b], [x], [1],[1], [$forall$], [1], [Нет Нет Нет], $infinity$, [$infinity$ (число k, до которого программа будет обрабатывать цикл)], [2],[0.1], [$forall$], [1], [Нет Нет Да], [$100/99$], [$1.010101010$], [3],[0.1], [$forall$], [0.1], [Нет Да], $infinity$, [$infinity$ (число k, до которого программа будет обрабатывать цикл)], [4],[0], [0.1], [1], [Да Нет Да], [$100/99$], [$1.010101010$], [5],[0], [1], [1], [Да Нет Нет], $-infinity$, [$-infinity$ (обратное числу k, до которого программа будет обрабатывать цикл)], [6],[0], [0], [$forall$], [Да Да], [Введенные\ данные], [Введенные\ данные], ) ] Недостатки метода: - не всегда можно проверить все условия; - невозможно проверить условия, которые скрыты другими условиями; - недостаточная чувствительность к ошибкам в логических выражениях == Комбинаторное покрытие условий Данный критерий требует создания такого числа тестов, чтобы все возможные комбинации результатов условий в каждом решении и все точки входа выполнялись по крайней мере 1 раз. Каждая из 3 входных переменных может быть нулем, по модулю меньше 1 (и не ноль) и по модулю больше или равно 1. Обозначим эти состояния переменных цифрами: 0, 1 и 2. Так как у нас 3 переменные, у каждой из которых может быть 3 состояния, то по комбинаторной формуле получаем всего $3*3*3 = 27$ состояний. Предыдущая таблица была с хорошо проработанными тестами, так что покажем, что все тесты из прошлой таблицы покрывают эти 27 состояний. Получим таблицу: #align(center)[ #tablex( columns: 4, inset: 10pt, align: horizon+center, rowspanx(2)[Номер теста], colspanx(3)[Входные\ данные], [a], [b], [x], // [$eq.not 0$], [$forall$], [$> -1; < 1$], rowspanx(12)[1], $1$,$0$,$1$, $1$,$1$,$1$, $1$,$2$,$1$, $2$,$0$,$1$, $2$,$1$,$1$, $2$,$2$,$1$, $1$,$0$,$0$, $1$,$1$,$0$, $1$,$2$,$0$, $2$,$0$,$0$, $2$,$1$,$0$, $2$,$2$,$0$, // [$eq.not 0; > -1; < 1$], [$forall$], [$<= -1; >= 1$], rowspanx(3)[2], $1$,$0$,$2$, $1$,$1$,$2$, $1$,$2$,$2$, // [$eq.not 0; <= -1; >= 1$], [$forall$], [$<= -1; >= 1$], rowspanx(3)[3], $2$,$0$,$2$, $2$,$1$,$2$, $2$,$2$,$2$, // [$= 0$], [$= 0$], [$forall$], rowspanx(3)[4], $0$,$0$,$0$, $0$,$0$,$1$, $0$,$0$,$2$, // [$= 0$], [$eq.not 0; > -1; < 1$], [$forall$], rowspanx(3)[5], $0$,$1$,$0$, $0$,$1$,$1$, $0$,$1$,$2$, // [$= 0$], [$eq.not 0; <= -1; >= 1$], [$forall$], rowspanx(3)[6], $0$,$2$,$0$, $0$,$2$,$1$, $0$,$2$,$2$, ) ] Данный метод полностью отстраняется от логики и полностью полагается на математическое доказательство, поэтому его достаточно легко реализовать программно и свести вероятность того, что мы не просмотрим все возможные варианты, к нулю. == Заключение В ходе тестирования было найдено 6 тестов, способных покрыть любые ошибки алгоритма. Арифметических ошибок не было найдено. = Черный ящик Одним из способов проверки программ является стратегия тестирования, называемая стратегией «черного ящика» или тестированием с управлением по данным. В этом случае программа рассматривается как «черный ящик» и цель такого тестирования — выяснение обстоятельств, в которых поведение программы не соответствует спецификации. Для обнаружения всех ошибок в программе необходимо выполнить исчерпывающее тестирование, т. е. тестирование на всех возможных наборах данных. Для тех программ, где исполнение команды зависит от предшествующих ей событий, необходимо проверить и все возможные последовательности. Очевидно, что построение исчерпывающего входного теста для большинства случаев невозможно. Поэтому обычно выполняется разумное тестирование, при котором тестирование программы ограничивается прогонами на небольшом подмножестве всех возможных входных данных. Естественно при этом целесообразно выбрать наиболее подходящее подмножество (подмножество с наивысшей вероятностью обнаружения ошибок). Правильно выбранный тест подмножества должен обладать следующими свойствами: + уменьшать, причем более чем на единицу, число других тестов, которые должны быть разработаны для достижения заранее определенной цели «приемлемого» тестирования; + покрывать значительную часть других возможных тестов, что в некоторой степени свидетельствует о наличии или отсутствии ошибок до и после применения этого ограниченного множества значений входных данных. Стратегия «черного ящика» включает в себя следующие методы формирования тестовых наборов: - эквивалентное разбиение; - анализ граничных значений; - анализ причинно-следственных связей; - предположение об ошибке. == Задание Программа должна строить график функции по заданным в таблице значениям. Обеспечить возможность выбора вида графика: точки отдельно или точки соединены (исполняемый модуль v11.exe). Интерфейс программы представлен ниже: #img(image("2.png", width: 80%), [Поле для ввода данных]) #img(image("3.png", width: 80%), [Результат работы программы]) == Метод эквивалентного разбиения Основу метода составляют два положения: + Исходные данные программы необходимо разбить на конечное число классов эквивалентности, так чтобы можно было предположить, что каждый тест, являющийся представителем некоторого класса, эквивалентен любому другому тесту этого класса. Иными словами, если тест какого-либо класса обнаруживает ошибку, то предполагается, что все другие тесты этого класса эквивалентности тоже обнаружат эту ошибку, и наоборот; + Каждый тест должен включать по возможности максимальное количество различных входных условий, что позволяет минимизировать общее число необходимых тестов. Первое положение используется для разработки набора «интересных» условий, которые должны быть протестированы, а второе — для разработки минимального набора тестов. Разработка тестов методом эквивалентного разбиения осуществляется в два этапа: выделение классов эквивалентности и построение тестов. Для данной задачи необходимо проверить отрицательные, положительные значения по осям и построение линии относительно предыдущей точки. То есть максимум для проверки понадобится 2 точки, если программа будет работать для 2 точек, то для большего количества точек она тоже будет работать. Выделим 5 входных условий: - Ввод координаты по X точки 1 - Ввод координаты по Y точки 1 - Ввод координаты по X точки 2 - Ввод координаты по Y точки 2 - Отметка соединить точки #align(center)[ #tablex( columns: 3, inset: 10pt, align: horizon+center, [Входное условие],[Правильные классы эквивалентности],[Неправильные классы эквивалентности], [Ввод координаты по X точки 1],[Целое, вещественное],[], [Ввод координаты по Y точки 1],[],[], [Ввод координаты по X точки 2],[],[], [Ввод координаты по Y точки 2],[],[], [Отметка соединить точки],[```cpp true, false```],[--] )] Так как не на какие координаты не накладываются ограничения по заданию неправильных классов эквивалентности нет. #pagebreak() Составим тесты (тут сразу виден недочет программы: нельзя задать произвольное количество точек, поэтому во время тестирования точки, не участвующие в тестировании будут иметь значения по умолчанию): #align(center)[ #tablex( columns: 6, inset: 10pt, align: horizon+center, $x_1$, $y_1$, $x_2$, $y_2$, [Соединить\ точки], [Результат], [1], [1], [2], [2], [true],[График построен верно], [1], [1], [2], [2], [false],[График построен верно], [2], [2], [1], [1], [true],[Ошибка: точка с меньшими координатами не определяется в графике после точки с большими], [2], [0], [1], [1], [true],[Ошибка: точка с меньшей координатой не определяется в графике после точки с большей], [0], [2], [1], [1], [true],[Ошибка: точка с меньшей координатой не определяется в графике после точки с большей], [1], [1], [1], [1], [true],[Ошибка: точка с одинаковыми координатами не определяется в графике после первой точки], [0], [1], [1], [1], [true],[Ошибка: точка с одинаковой координатой не определяется в графике после первой точки], [1], [0], [1], [1], [true],[Ошибка: точка с одинаковой координатой не определяется в графике после первой точки], [-1], [1], [2], [2], [true],[График построен верно], [1], [-1], [2], [2], [true],[График построен верно], [-1], [-1], [2], [2], [true],[График построен верно], )] С помощью тестирования удалось определить 2 ошибки: при вводе точки с меньшими или равными координатами по любой из осей программа перестает работать, второй ошибкой является отсутствие возможности задать другое количество точек. Данную возможность можно было бы легко добавить, обрабатывая пустые строки отдельно. Так же в процессе тестирования выявлено, что в программе предусмотрено различное кол-во точек: это следует из ошибки о введенной только одной точки, когда программа перестает видеть вторую точку из-за первой ошибки. == Анализ граничных значений Граничные условия — это ситуации, возникающие вблизи и на границах входных классов эквивалентности. Анализ граничных значений отличается от эквивалентного разбиения следующим: - выбор любого элемента в классе эквивалентности в качестве представительного при анализе граничных условий осуществляется таким образом, чтобы проверить тестом каждую границу этого класса; - при разработке тестов рассматриваются не только входные условия (пространство входов), но и пространство результатов. Анализ граничных условий, если он применен правильно, является одним из наиболее полезных методов проектирования тестов. Однако следует помнить, что граничные условия могут быть едва уловимы и определение их связано с большими трудностями, что является недостатком этого метода. Второй недостаток связан с тем, что метод анализа граничных условий не позволяет проверять различные сочетания исходных данных. По условию граничные значения не заданы, поэтому будем проверять все возможные варианты. После проверки чисел $10^10$, $10^100$, $10^200$, $10^300$, $10^400$, $10^310$, $10^309$, $10^308$,$10^307$ было выявлено, что на отрезке от $10^307$ до $10^308$ программа ломается и все последующие числа программа просто выдает как что-то, меньшее бесконечности. Так как числа представляются в памяти в двоичном виде логично предположить, что программа ломается как раз на большой степени двойки, $10^308 tilde.eq 2^1024$. Таким образом можно предположить, что в программе используется динамическая типизация, но с ограничением на выделение памяти до 256 (128 байт = 1024 бит и отриц. числа) байт (или для каждой координаты изначально выделяется 256 байт статически). Поведение программы является неправильным только при очень больших числах, поэтому данные ограничения можно считать приемлемыми. #pagebreak() == Анализ причинно-следственных связей #align(center)[ #tablex( columns: 5, inset: 5pt, align: horizon+center, [Назначение теста],[Значения исходных данных],[Ожидаемый результат],[Реакция программы],[Вывод], [Выделение содержимого ячейки для исправления/удаления], [Тройной клик\ по ячейке],colspanx(2)[Выделение содержимого], [Программа работает верно], [Прокручивание горизонтального ползунка],[Прокручивание горизонтального ползунка],colspanx(2)[Прокрутка страницы], [Программа работает верно], [Блокировка вертикального ползунка],[Прокручивание вертикального ползунка],[Блокировка действия: пользователю доступны все строки таблицы без прокрутки],[Прокрутка таблицы вниз], [*Программа работает не верно*], [Проверка ввода после выделения],[Ввод знака и цифр с клавиатуры],[Отображение введенного числа в ячейке полностью],[Число отображается в ячейке, но не полностью. Доступна прокрутка внутри ячейки], [_Программа работает не совсем верно_], [Проверка работы checkbox'а для соединения точек],[Нажатие на checkbox],colspanx(2)[Изменение значения на\ противоположное], [Программа работает верно], [Работоспособность кнопки\ Построить],[Нажатие на кнопку],colspanx(2)[Отображение графика], [_Программа работает не совсем верно (зависит от входных данных)_] ) ] == Предположение об ошибке Так как в методе эквивалентного разбиения не нашлось никаких условий, ограничивающих точки тесты были сделаны как предположение, где программа может сломаться, после нахождения одной ошибки были составлены тесты, которые проверяли наличие подобных ошибок. Граничные условия тоже были найдены исходя из факта, что никакой компьютер не способен обработать бесконечность, следовательно подобрав правильное значение можно переполнить даже кучу, затереть стек и вызвать ошибку выполнения. Так как программа должна строить график при любых двух и более заданных точках, то если эти 2 точки не заданы, необховыводить сообзение об ошибке, иначе просто строить график. Построим логическую схему, которая будет отражать всю работоспособность программы и проверку на то, что любые 2 точки заданы. #img(image("4.png", width: 88%), [Логическая схема]) == Заключение В результате исследования методов тестирования были получены следующие результаты: - выявлены ошибки в алгоритме построения графика; - выявлены ошибки в интерфейсе (причинно-следственной связи); - выявлены ошибки в задании граничных значений; - оценена специфика каждого метода тестирования; - оценена трудоемкость тестирования для каждого метода.
https://github.com/Ttajika/class
https://raw.githubusercontent.com/Ttajika/class/main/seminar/lib/useful_functions.typ
typst
#import "@preview/lemmify:0.1.5": * #import "@preview/physica:0.9.2": * #import "translation.typ": * #let cap_body(it) = {if it != none {return it.body} else {return it} } #let inactive_versions(name_varsion) = { let name_version(title: none, label:none, body) = { } } #let noindent() = {h(-1em)} #let indent() = {h(1.2em)} //autonumbering equations #let tjk_numb_style(tag,tlabel,name) = { if tag == true { if name == none{ return it => "("+str(tlabel)+")"} else {return it => "("+str(name)+")"} } else { return "(1)" } } #let aeq(tlabel, name:none, tag:false, body) ={ locate(loc =>{ let eql = counter("tjk_auto-numbering-eq" + str(tlabel)) if eql.final(loc).at(0) == 1{ [#math.equation(numbering: tjk_numb_style(tag,tlabel,name),block: true)[#body] #label(str(tlabel))] if tag == true{counter(math.equation).update(i => i - 1)} } else { [#math.equation(numbering:none,block: true)[#body] ] } }) } #let eq_refstyle(it,lang:"en") = { return { let lbl = it.target let eq = math.equation let el = it.element let eql = counter("tjk_auto-numbering-eq"+str(lbl)) eql.update(1) if el != none and el.func() == eq { link(lbl)[ #numbering( el.numbering, ..counter(eq).at(el.location()) ) ] } else {it} } } #let plurals(single,dict) ={ if single in dict.keys() { return dict.at(single) }else {return single} } #let ref_tag(it) = { show ref: it => { return it.element.supplement } ref(it) } #let refs(..sink,dict:plurals_dic,add:" and ",comma:", ") = { let args = sink.pos() let numargs = args.len() let current_titles = () let titles_dic = (:) if numargs == 1 {link(ref(args.at(0)).target)[#ref(args.at(0))]} else { show ref: it => plurals(it.element.supplement.text,dict) ref(args.at(0)) + " " show ref: it => { let c_eq = it.element.counter numbering(it.element.numbering, ..c_eq.at(it.element.location())) } if numargs == 2{link(ref(args.at(0)).target)[#ref(args.at(0))] + ""+ add +"" + link(ref(args.at(1)).target)[#ref(args.at(1))]} else{ for i in range(numargs){ if i< numargs - 1 {link(ref(args.at(i)).target)[#ref(args.at(i))] + comma+"" } else {add+"" + link(ref(args.at(i)).target)[#ref(args.at(i))]} }} } } #let counter_body(num) = {if num != none {return num.counter} else {return num}} //定理環境の基本設定:より高度な設定はLemmifyを用いる #let my_thm_style( thm-type, name, number, body ) = { block(width:100%, breakable: true, above:0em, below:0em)[ #strong(thm-type) #if number != none { strong(number) }#if name == none {"."}#if name != none { " "+ [(#name).] + " " } #emph(body) ] indent() } #let my_defi_style( thm-type, name, number, body ) = { block(width:100%, breakable: true, above:0em, below:0em)[ #strong(thm-type) #if number != none { strong(number) }#if name == none {"."} #if name != none {[(#name).] } #body] indent() } #let my_proof_style( thm-type, name, number, body, lang ) = { block(width:100%, breakable: true)[ #if name == none {strong(trans.at(lang).at("Proof")) +"."} #if name != none { [#strong[#proofname(name,lang)]] } #body #h(1fr) #QERmark(lang) ] } #let theorem_base(thm_style, kind, supplement) ={ return{ (name:none, numbering:numbering,content) => figure( content, caption: name, kind: kind, supplement: supplement ) } } #let trans_thm(str,lang) = { if lang == "jp" { return theorem_jp.at(str) } else {return str} } #let theorem_create(tlabel, supple:none) = { if supple == none{ return{theorem_base(my_thm_style, tlabel, tlabel)} } else { return{theorem_base(my_thm_style, tlabel, supple)} } } #let theorem = theorem_create("Theorem", supple: "定理") #let prop = theorem_create("Proposition", supple: "命題") #let lemma = theorem_create("Lemma", supple: "補題") #let rem = theorem_create("Remark", supple: "注意") #let cor = theorem_create("Corollary") #let claim = theorem_create("Claim") #let fact = theorem_create("Fact") #let defi = theorem_create("Definition") #let assump = theorem_create("Assumption") #let ex = theorem_create("Example") #let proof = theorem_create("Proof", supple: "系") #let theo_list = ("Theorem","Proposition","Lemma","Remark","Corollary","Claim","Fact") #let defi_list = ("Definition","Assumption","Example") #let others_list = ("Table","Figure") #let content_remove_br(cont) = { if cont.has("body"){ let valuecon = cont.body.at("children") let val_num = valuecon.len() let value = "" for i in range(1,val_num - 1 ) { value = value + valuecon.at(i) } return value } else { return cont } } //conditional probability; different from phisyca Pr #let Pro(..sink) = { let args = sink.pos() let event = content_remove_br(args.at(0)) if args.len() <= 1 { $op("Pr")(event)$ } else { let condition = content_remove_br(args.at(1)) $op("Pr")(event mid(|) condition)$ } } #let argmax = $op("arg max", limits: #true)$ #let argmin = $op("arg min", limits: #true)$ #let cdot = $dot.c$ #let cdots = $dots.c$ //2player Normal form game #let Ngame(players,strategies,payoffs,caption:none) = { let glist = () let g_list = strategies.at(1) g_list.insert(0,"") glist.push(g_list) for i in range(strategies.at(0).len()){ let g_list = payoffs.at(i) g_list.insert(0,strategies.at(0).at(i)) glist.push(g_list) }  return { table(columns: strategies.at(1).len()+2, align: center + horizon, stroke: (x,y) => ( top: if y ==2 {1pt} else {0pt}, left: if x==2 {1pt} else {0pt} ), [], table.cell(colspan: strategies.at(1).len()+1, players.at(1)), table.cell(rowspan: (strategies.at(0).len()+1), players.at(0)), ..glist.flatten() ) } } //Date functions #let Today(style:"mdy-en") = { let y = datetime.today().year() let m = datetime.today().month() let d = datetime.today().day() if style == "ymd-en" { return str(y)+" "+tjk_month_name.en.at(str(m))+" "+str(d)} if style == "mdy-en" { return tjk_month_name.en.at(str(m))+" "+str(d)+", "+str(y)} if style == "mdy-en-abr" { return tjk_month_name.en-abr.at(str(m))+" "+str(d)+", "+str(y)} if style == "ymd-jp" { return str(y)+"年"+ str(m)+"月"+str(d)+"日"} if style == "ymd-jp-nengou" { return tjk_wareki(y)+"年"+str(m)+"月"+str(d)+"日"} if style == "ymd-jp-wareki" { return tjk_wareki(y)+"年 "+tjk_month_name.jp.at(str(m))+str(d)+"日"} } #let waritsuke(moji,body) = { } #let abstract_name = ("en": [#smallcaps[Abstract]], "jp":"概要") #let waritsuke(moji,body) ={ context[ #let size = measure[も].width #let wari_width = size * moji #let body_mojisuu = calc.round(measure[#body].width/size) #let cell_width = wari_width/body_mojisuu #let haba = (wari_width - measure[#body].width)/(body_mojisuu - 1) #let columns_cell = () #for i in range(moji) { columns_cell.push(cell_width) } #let body_array = () #let x = int(body.len()/3) #for i in range(x) { body.at(3*i) h(haba) } #h(-haba) ] }
https://github.com/mattyoung101/uqthesis_eecs_hons
https://raw.githubusercontent.com/mattyoung101/uqthesis_eecs_hons/master/pages/chapters/method.typ
typst
ISC License
= Method In this paper, we present something important, presumably. Check out @fig:abstract, would you? #figure( image("../../diagrams/abstract-unsplash.jpg", width: 60%), caption: [ An abstract pattern. Looks cool. ] ) <fig:abstract> #lorem(1700)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/metro/0.1.0/src/parsers.typ
typst
Apache License 2.0
#import "@preview/t4t:0.2.0": is #let _is-elem(elem, name) = { return type(elem) == "content" and repr(elem.func()) == name } #let res-default = (body: none, power: none, qualifier: none, per: none) // NULL unicode character as a marker #let NULL-after = [\u{FFFF} ] #let NULL-before = [ \u{FFFF}] #let tothe = (x) => math.attach(NULL-after, t: x) #let raiseto = (x) => math.attach(NULL-before, t: x) #let qualifier = (x) => math.attach(NULL-after, b: x) #let parse-math-units(input, options) = { let results = () let stack = (if is.elem(math.equation, input) and not input in options.units.values() and not input in options.prefixes.values() { input.body } else { input },) let res = res-default let prefix = none let per = 0 let func = none while stack.len() > 0 { let cur = stack.pop() func = none if cur != true { func = repr(cur.func()) if func == "attach" { if "t" in cur.fields() { res.power = cur.t } if "b" in cur.fields() { res.qualifier = cur.b } if not cur.base in (NULL-after, NULL-before) { stack.push(cur.base) } else if cur.base == NULL-after { let last = if results.last().per == none { results.last() } else { results.last().per.last() } if res.power != none { last.power = res.power res.power = none } if res.qualifier != none { last.qualifier = res.qualifier res.qualifier = none } if results.last().per == none { results.last() = last } else { results.last().per.last() = last } } } else if func == "frac" { stack += (cur.denom, true, cur.num) } else if func == "class" { if cur.class == "unary" { prefix = cur.body } else if cur.class == "binary" and cur.body == [per] { per += if options.sticky-per { 9999 // If there is a unit this long I'll be impressed } else { 1 } } } else if func in ("text", "equation", "display") { res.body += cur } else if func == "lr" { stack.push(cur.body.children.slice(1, -1).join()) } else if func == "sequence" { stack += cur.children.rev() if per > 0 { per += cur.children.filter(x => x == [ ]).len() } } } if (cur == true or func == "space") and res.body != none or stack.len() == 0 { if prefix != none { res.body = prefix + res.body prefix = none } if per > 0 { if results.len() == 0 { results.push(res-default) } results.last().per += (res,) per -= 1 } else { results.push(res) } if cur == true { per += 1 } res = res-default } } if not options.sticky-per and per > 0 { panic("A per somewhere does not have a denominator") } return results } #let parse-string-units(input, options) = { return parse-math-units( eval( input.replace(regex("_(\w+)|(?:(?:_|of)\((.+?)\))"), (m) => { let c = m.captures "_\"" + if c.first() == none { c.last() } else { c.first() } + "\"" }).replace("/", " per ").trim(), mode: "math", scope: options.units + options.prefixes + options.powers + options.qualifiers + ( per: math.class("binary", "per"), tothe: tothe, raiseto: raiseto, ) ), options ) } #let display-units(input, options, top: false) = { let result = () let stack = input.rev() let pers = () while stack.len() > 0 { let cur = stack.pop() let res = cur.at("body", default: []) if cur.power != none or cur.qualifier != none { // Need to add bracket qualifier before turning res into an attach if options.qualifier-mode == "bracket" and cur.qualifier != none { res += "(" + cur.qualifier + ")" } else if options.qualifier-mode == "phrase" and cur.qualifier != none{ res += options.qualifier-phrase + cur.qualifier } if options.power-half-as-sqrt { res = math.sqrt(res) cur.power = none } res = math.attach( res, t: cur.power, // b will be none if false b: if options.qualifier-mode == "subscript" { cur.qualifier } ) if options.qualifier-mode == "combine" and cur.qualifier != none { res += if res.t != none { "(" + cur.qualifier + ")" } else { cur.qualifier } } } if cur.per != none { if options.per-mode == "power" { result.push(res) result.push( display-units( cur.per.map(p => { let minus = [#sym.minus] let power = if p.power != none { if _is-elem(p.power, "sequence") { if p.power.children.first() == minus { p.power.children.slice(1) } else { p.power.children.insert(0, minus) }.join() } else { minus + p.power } } else { $-1$ } p.power = power return p }), options ) ) continue } else if options.per-mode == "fraction" { res = math.frac( res, display-units(cur.per, options) ) } else if options.per-mode == "symbol" { // let brackets = let denom = display-units(cur.per, options) if options.bracket-unit-denominator and cur.per.len() > 1 { denom = "(" + denom + ")" } res = res + options.per-symbol + denom } } result.push(res) } result = result.join(options.inter-unit-product) return if top { math.upright(result) } else { result } }
https://github.com/vaucher-leo/template-tb-typst
https://raw.githubusercontent.com/vaucher-leo/template-tb-typst/main/page/Introduction.typ
typst
MIT License
#import "../config.typ": * = Introduction #lorem(100)
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/evaluation/method.typ
typst
#import "/components/glossary.typ": gls == Evaluation Method To ensure the quality and functionality of the Ungrammar Language Ecosystem, we've implemented a robust evaluation plan that leverages #gls("tdd") (@sec-tdd) and #gls("bdd") (@sec-bdd) methodologies. By employing a combination of #gls("tdd") and #gls("bdd"), we can establish a robust evaluation process that ensures the quality, reliability, and user satisfaction of the Ungrammar Language Ecosystem. === TDD for Unit Testing ==== Unit Testing the Ungrammar Lezer Parser To ensure the accuracy and efficiency of the Ungrammar Lezer Parser (@subsec-impl-lezer), we've implemented a comprehensive testing strategy using #gls("tdd") (@sec-tdd) principles. By writing tests before writing production code, we can verify that the parser correctly handles various syntactic constructs and efficiently generates the expected parse trees. By employing a rigorous testing strategy and utilizing the power of #gls("tdd", mode:"full") and #gls("ci", mode:"full"), we've established a strong foundation for the Ungrammar Lezer Parser, ensuring its reliability and accuracy. - *Key Testing Approaches*: - *Unit Testing*: Create unit tests to evaluate the parser's ability to handle different grammar constructs, including valid and invalid inputs. - *Edge Case Testing*: Design tests to cover edge cases and potential error scenarios, ensuring the parser's robustness. - *Testing Framework*: We've chosen Bun Test as our testing framework due to its speed, efficiency, and compatibility with our existing project structure. Bun Test provides a powerful set of tools for writing and running tests, ensuring thorough coverage of the parser's functionality. - *Continuous Integration*: To maintain code quality and prevent regressions, we've integrated Bun Test into our #gls("ci")/#gls("cd") pipeline using GitHub Actions (@sec-githubactions). This ensures that all code changes are automatically tested, providing early feedback and catching potential issues before they are merged into the main branch. ==== Unit Testing the Ungrammar Language Service To ensure the reliability and correctness of the Ungrammar Language Service (@subsec-impl-langservice), we've implemented a comprehensive testing strategy that focuses on unit testing the core logic within the module. By isolating and testing individual components, we can identify and address potential issues early in the development process. By adopting a rigorous unit testing approach and leveraging powerful testing tools, we've established a strong foundation for the Ungrammar Language Service, ensuring its reliability, correctness, and performance. - *Unit Testing Approach*: - *Component-Level Testing*: Create unit tests for each component within the Language Service module, ensuring that they function as expected in isolation. - *Input Validation*: Test the module's ability to handle various input scenarios, including valid and invalid data. - *Error Handling*: Verify that the module handles errors and exceptions gracefully, providing informative feedback to the user. - *Testing Framework*: We've chosen Bun Test as our testing framework due to its speed, efficiency, and compatibility with our existing project structure. Bun Test provides a powerful set of tools for writing and running tests, ensuring thorough coverage of the parser's functionality. - *Continuous Integration*: To maintain code quality and prevent regressions, we've integrated Bun Test into our #gls("ci")/#gls("cd") pipeline using GitHub Actions (@sec-githubactions). This ensures that all code changes are automatically tested, providing early feedback and catching potential issues before they are merged into the main branch. === BDD for User Acceptance Testing ==== User Acceptance Testing for VS Code Extension and Online Playground To effectively evaluate the functionality and user experience of the Ungrammar VS Code Extension and Online Playground, we've adopted a #gls("uat", mode:"full") approach based on #gls("bdd", mode:"full"). By combining #gls("uat") with #gls("bdd"), we were able to effectively evaluate the functionality and usability of our Ungrammar VS Code Extension (@subsec-impl-vscode) and Ungrammar Online Demonstration Playground (@subsec-impl-playground), ensuring that they meet the needs of our users and provide a valuable contribution to the Ungrammar language ecosystem. - *BDD with Gherkin*: - *User Stories and Scenarios*: Defined clear user stories and acceptance criteria using Gherkin syntax to outline the expected behavior of the extension and playground from the end-user's perspective. - *Test Cases*: Created detailed test cases based on the Gherkin scenarios, covering various usage scenarios and potential edge cases. - *Manual Testing*: - *Real-World Simulation*: Conducted manual testing to simulate real-world user interactions and evaluate the system's performance, usability, and adherence to requirements. - *Scenario Execution*: Executed test cases based on the Gherkin scenarios, verifying that the system behaves as expected. - *Feedback Gathering*: Collected feedback from end-users to identify any areas for improvement or additional features. - *Benefits of UAT with BDD*: - *User-Centric Focus*: Ensured that the system meets the needs and expectations of end-users by focusing on their perspective. - *Early Validation*: Identified potential issues and areas for improvement before the final release. - *Improved Quality*: Enhanced the overall quality and user experience of the VS Code extension and online playground. - *Collaboration*: Fostered collaboration among stakeholders by providing a shared understanding of the system's requirements. === Key Benefits of TDD and BDD - *Early Bug Detection*: TDD and BDD help identify and address issues early in the development process, reducing the cost of fixing defects later. - *Improved Code Quality*: Writing tests before or alongside code encourages cleaner, more maintainable code. - *Enhanced Collaboration*: BDD fosters collaboration among stakeholders by providing a shared understanding of the system's requirements. - *Living Documentation*: Gherkin scenarios can serve as living documentation, providing a clear and up-to-date record of the system's behavior. === Evaluation Process - *Develop Test Cases*: Create comprehensive test cases using TDD and BDD methodologies. - *Execute Tests*: Run unit tests and user acceptance tests to validate system functionality. - *Analyze Results*: Analyze test results to identify any issues or discrepancies. - *Iterate and Improve*: Refactor code and address identified issues based on test results. === Evaluation Result #[#show figure: set block(breakable: true) #figure( raw(read("/assets/result.log"), block: true), caption: [Evaluation Result of Unit Testing], ) #figure( table( columns: 3, table.header([*Test Case*], [*VS Code*], [*Online Playground*]), [View Annotations], [Pass], [Pass], [Provide Code Completion], [Pass], [Pass], [Provide Code Actions], [Pass], [Pass], [Report Diagnostics], [Pass], [Pass], [Go to Definition], [Pass], [Pass], [Find All References], [Pass], [Pass], [Expand/Shrink Code Folding], [Pass], [Pass], [Rename Code], [Pass], [Pass], [Hover Code], [Pass], [Pass], [Format Code], [Pass], [Pass], [Highlight Semantic Syntax], [Pass], [Pass], [Highlight Related], [Pass], [Pass], [Provide Quick Navigation], [Pass], [Pass], [Update Configuration], [Pass], [Pass], ), caption: [Evaluation Result of #gls("uat", mode:"full")], ) ]
https://github.com/rem3-1415926/Typst_Thesis_Template
https://raw.githubusercontent.com/rem3-1415926/Typst_Thesis_Template/main/README.md
markdown
MIT License
# Typst_Thesis_Template Some thesis template in typst. Far from perfect or clean, but seems to work for now. See https://typst.app/docs/reference/ and https://github.com/typst/typst
https://github.com/wznmickey/JI_Lab_Report_typst_template
https://raw.githubusercontent.com/wznmickey/JI_Lab_Report_typst_template/main/README.md
markdown
# JI Physics Lab Report Template in Typst Created by wznmickey and improved by mQzLjP. ## Usage The repository contains two `.typ` files: `conf.typ` is a config file that should not be compiled, and `report.typ` is the template to generate the report. To compile `report.typ` successfully, put both in your working directory. Any issues or suggestions are welcomed. ## Reference - JI Report Template 2022. rev 4.1.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/regression/issue1.typ
typst
Other
#( let foo(x) = { return (..x, 5); } ) #foo((3,4))
https://github.com/OverflowCat/BUAA-Automatic-Control-Components-Sp2024
https://raw.githubusercontent.com/OverflowCat/BUAA-Automatic-Control-Components-Sp2024/neko/实验/5.typ
typst
#set text(lang: "zh", font: "Noto Serif CJK SC") #show "。": "." = 实验五 交流伺服电动机实验 伺服电动机在⾃动控制系统中作为执⾏元件,⼜称为执⾏电动机,将输⼊的控制电压信号变为相应的⻆位移或⻆速度。伺服电动机运⾏状态由控制信号控制,施加控制信号应当⽴即旋转,去掉控制电压应当⽴即停转,转速⾼低与控制信号成正⽐。 === 实验步骤和机械特性记录 ==== 1. 实测交流伺服电机 $U_f = 220V$, $U_c= 1 $(即 $U_c = U_N = 220V$), $C = 3 F $时的机械特性 - 左侧空气开关闭合,面板交流开关闭合。 - 调节变压器 T2 使 $U_c = U_upright(N) = 220V$。 - 调节智能负载控制器给定,电机从空载至堵转过程中,将力矩 $T$ 及电机转速记录于表 5-1 中。 - 测试完毕,及时断开所有电源开关。 #figure( caption: "机械特性", align(center)[#table( columns: (auto, auto, auto, auto, auto, auto, auto, auto, auto, auto, auto, auto, auto), table.header([序号], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]), table.hline(), [$T ( N dot.op m )$], [0.02], [0.04], [0.06], [0.08], [0.1], [0.11], [0.12], [0.13], [0.135], [0.14], [0.15], [0.155], [$n (r \/ m i n)$], [1922], [1888], [1817], [1715], [1462], [1372], [1322], [1205], [1200], [1166], [970], [0], )], ) ==== 2. 实测交流伺服电机 $U_f = 220V $, $U_c = 1 $(即 $U_c = U_N = 220V $), $C = 1.5 F $时的机械特性 - 左侧空气开关闭合,面板交流开关闭合。 - 调节单相调压器 T2 使 $U_c = U_N = 220V $。 - 调节智能负载控制器给定,电机从空载至堵转过程中,将力矩 $T $ 及电机转速记录于表 5-2 中。 - 测试完毕,及时断开所有电源开关。 #figure( align(center)[#table( columns: (auto, 8.22%, 8.22%, 8.22%, 8.22%, 8.22%, 8.22%, 8.22%, 8.22%, 8.22%), table.header([序号], [1], [2], [3], [4], [5], [6], [7], [8], [9]), table.hline(), [$T (N dot.op m)$], [0.01], [0.02], [0.03], [0.04], [0.05], [0.06], [0.07], [0.08], [0.085], [$n (r \/ m i n)$], [1663], [1629], [1597], [1518], [1471], [1300], [1054], [830], [0], )], caption: "机械特性", ) ==== 3. 实测交流伺服电机 $U_f =220V$, $U_c = 0.75$ (即 $U_c = 0.75U_N = 165V$),$C = 3 F$ 时的机械特性 - 调节单相交流调压器使 $U_c = 0.75U_N = 165V$。 - 重复上面实验,将数据记录于表 6-3 中。 - 测试完毕,及时断开所有电源开关。 #figure( caption: "机械特性", align(center)[#table( columns: (auto, 7.59%, 7.59%, 7.59%, 7.59%, 7.59%, 7.59%, 7.59%, 7.59%, 7.59%), table.header([序号], [1], [2], [3], [4], [5], [6], [7], [8], [9]), table.hline(), [$T (upright(N dot.op m))$], [0.02], [0.04], [0.06], [0.08], [0.09], [0.1], [0.11], [0.12], [0.13], [$n (upright(r \/ m i n))$], [1861], [1815], [1586], [1327], [1233], [1179], [1103], [946], [0], )], ) ==== 4. 实验方法调整堵转状态下的旋转磁场 + 断开主电源和左侧的空气开关,按照图 5-1 连接示波器,示波器两探头地线应接图中 N 线(也是变压器的 NO)。X 踪和 Y 踪幅值量程一致,并设在迭加状态。初始状态时,电容 $C $选择为 0。 + 合上交流主电源, $U_f = 220V$,再调节交流单相调压器 T2 使 $U_c = 220V$,调节智能负载控制器给定,使电机堵转。 + 逐步增大可变电容 $C $的容值,观察 $I_f $与 $I_c$(通过电流表 A1 和 A2 测量)接近过程中示波器轨迹的变化。需要确认调整时 $U_f$ 等于 $U_c$。 #figure( align(center)[#table( columns: 8, align: (auto, auto, auto, auto, auto, auto, auto, auto), table.header([$C (mu F)$], [0.47], [1], [1.5], [2], [2.2], [2.3], [2.4]), table.hline(), [$I_f (A)$], [0.04], [0.07], [0.11], [0.18], [0.20], [0.22], [0.24], [$I_c (A)$], [0.28], [0.28], [0.29], [0.30], [0.31], [0.32], [0.32], )], ) == 实验报告 + 作交流伺服电动机幅值—相位控制时的机械特性。 #figure(caption: "机械特性", image("dist/5.svg")) + 分析实验数据及实验过程中发⽣的现象。 励磁回路串联电容,电磁转矩表达式十分复杂。根据实验数据,电磁转距随转速增加,先增大再减小。$C$ 越大,转矩越大;$U_C$ 越大,转矩越小。 == 思考题 + 分析⽆“⾃转”现象的原因?怎样消除“⾃转”现象? 阻转矩大于单相运行时的最大转矩。可以通过提高转子电阻来消除自转现象。 + 幅值-相位控制的交流伺服电机,什么条件下电机⽓隙磁场为圆形磁场?其理想空载转速是多⼤? 当激磁绕组与控制绕组所产生的磁势幅值相等,且两绕组电流相位差为 90° 时,电机的气隙磁场为圆形磁场。此时,电机的理想空载转速为同步转速 $n_1$。
https://github.com/optimizerfeb/AutomaticProof
https://raw.githubusercontent.com/optimizerfeb/AutomaticProof/main/01_소개.typ
typst
#set text(font: "NanumMyeongjoOTF") #align(center, text(17pt)[ *자동 증명 프로그램 개발* \ 개념 구상 ]) #align(right, text(10pt)[ 한남대학교 수학과 20172581 김남훈 ]) = 1. 소개 기계를 이용해 어떤 명제를 자동으로 증명한다는 구상은 매우 오래 전부터 존재했으며, 컴퓨터가 실제로 등장하기 전에 이미 연구되어 왔다. 구체적으로는 1879년 수학자 *고틀롭 프레게* 가 술어 논리학을 창시했을 때부터 기계에게 명제를 증명하게 하려는 연구가 있어 왔다고 할 수 있다. 최초의 자동 증명 프로그램은 1956년 개발된 *Logic Theorist* 이며, 이후 다양한 자동 증명 프로그램이 개발되었다. = 2. 자동증명 프로그램의 구조 현재 다양한 종류의 자동 증명 프로그램들이 개발되어 있으며, 다양한 구조와 기술, 그리고 이론에 기반하여 증명을 수행한다. 이 섹션에서는 앞으로 개발할 자동 증명 프로그램의 구조를 간단히 설명할 것이다. == 2.0. 기본 개념 $G = (V, E)$ 를 그래프라고 하자. + $x_1, dots, x_n in V$ 에 대해, 모든 $i in {1, dots, n - 1}$ 에 대해 $(x_i x_(i + 1)) in E$ 이라면 $(x_1, dots, x_n)$ 을 $G$ 위의 *경로* 라고 한다. 이 때, $x_1$ 을 경로의 *시작점*, $x_n$ 을 경로의 *끝점* 이라 한다. + 모든 $x, y in V$ 에 대해 $x$ 를 시작점으로, $y$ 를 끝점으로 갖는 경로가 존재한다면 $G$ 를 *연결 그래프* 라고 한다. + $G$ 위의 경로 $X$ 의 시작점과 끝점이 같다면 $X$ 를 $G$ 위의 *회로* 라 한다. $G$ 가 회로를 갖지 않는다면 $G$ 를 *포레스트* 라고 한다. $G$ 가 포레스트이면서 연결 그래프이면 $G$ 를 *트리* 라고 한다. + 트리의 한 정점 $r$ 을 *루트(root)* 로 정의한다면 이 트리를 *루트를 갖는 트리* 라고 한다. 모든 정점은 루트가 될 수 있다. + $r$ 을 시작점으로, 한 정점 $y$ 를 끝점으로 갖는 경로는 트리의 성질에 의해 유일한데, $y$ 의 바로 이전에 오는 정점을 $x$ 라 하면 $x$ 를 $y$ 의 *부모* 라 한다. 반대로 $y$ 는 $x$ 의 *자녀* 라 한다. + 자녀를 갖지 않는 정점을 *리프* 라 한다. 루트를 제외한 모든 정점은 유일한 부모를 가지며 루트는 부모를 갖지 않는다. == 2.1. 명제를 트리로 변환하는 방법 $x + y = z w$ 라는 명제는, $x + y$ 와 $z w$ 가 같으면 참을, 다르면 거짓을 반환하는 함수로 볼 수 있다. 마찬가지로 $+$ 라는 기호는 양 쪽의 변수를 받아 두 변수의 합을 반환하는 함수로 볼 수 있다. $ "plus"(a, b) &= a + b\ "mul"(a, b) &= a b\ "equal"(a, b) &= cases( "true" & "if" & a = b \ "false" & "if" & a eq.not b ) $ 로 놓으면, 위의 등식, 다시 말해 함수는 다음과 같은 형태로 다시 작성할 수 있다. $ "equal"("plus"(x, y), "mul"(z, w)) $ 이 때, 가장 바깥쪽에 있는 함수를 트리의 루트로 놓고 각 정점이 나타내는 함수의 입력들을 정점의 자녀로 놓으면 위 함수는 다시 다음과 같이 나타낼 수 있다. #figure( image("images/Equation Tree.svg", width: 75%) )
https://github.com/yochem/apa-typst
https://raw.githubusercontent.com/yochem/apa-typst/main/main.typ
typst
#import "template.typ": apa7, showfootnotes, appendix #set text(12pt) #show: apa7.with( title: "Example of APA7 Document in Typst", authors: ( (name: "<NAME>", orcid: "test", affiliations: (1, 2)), (name: "<NAME>", affiliations: (1,)), (name: "<NAME>", affiliations: (2,)), ), affiliations: ( "School of Psychology, University of Sydney", "Center for Behavioral Neuroscience, American University" ), abstract: [ #lorem(20) ], footnotepage: false ) #lorem(40) #pagebreak() = Section (lvl 1) == Sub Section (lvl 2) #lorem(20) === Sub Section (lvl 3) #lorem(20) ==== Sub Section (lvl 4) #lorem(20) ===== Sub Section (lvl 5) #lorem(20) = Related Work #lorem(100)#footnote[test] #figure( image("./orcid-logo.svg", height: 10%), caption: "helloo" )<fig-image> _Note._ For figure notes, just use: `_Note._ Here is a note`. = Methodology #lorem(100)#footnote(lorem(20)) #figure( table( columns: (3cm, auto, auto), [Long text in tables is wrapped and indented by 0.15 inch.], [aa], [bb], ), caption: "This is an example table" )<fig-table> _Note._ These tables can also have notes. In text reference @fig-table and @fig-image. = Conclusion #lorem(100) In-text quotes #quote[are normal]. #quote[ While quotes longer than 40 words are in indented paragraphs. Like this one. It can also have multiple paragraphs, which are also indented on their first line. So nice! ] = Discussion #lorem(100) #showfootnotes #show: appendix = Test == test test = Test = Test test $ "test" $ #figure(table(), caption: "") $ "test" $
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/quotes_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(width: 250pt) // Test simple quotations in various languages. #set text(lang: "en") "The horse eats no cucumber salad" was the first sentence ever uttered on the 'telephone.' #set text(lang: "de") "Das Pferd frisst keinen Gurkensalat" war der erste jemals am 'Fernsprecher' gesagte Satz. #set text(lang: "de", region: "CH") "Das Pferd frisst keinen Gurkensalat" war der erste jemals am 'Fernsprecher' gesagte Satz. #set text(lang: "es", region: none) "El caballo no come ensalada de pepino" fue la primera frase pronunciada por 'teléfono'. #set text(lang: "es", region: "MX") "El caballo no come ensalada de pepino" fue la primera frase pronunciada por 'teléfono'. #set text(lang: "fr", region: none) "Le cheval ne mange pas de salade de concombres" est la première phrase jamais prononcée au 'téléphone'. #set text(lang: "fi") "Hevonen ei syö kurkkusalaattia" oli ensimmäinen koskaan 'puhelimessa' lausuttu lause. #set text(lang: "gr") "Το άλογο δεν τρώει αγγουροσαλάτα" ήταν η πρώτη πρόταση που ειπώθηκε στο 'τηλέφωνο'. #set text(lang: "he") "הסוס לא אוכל סלט מלפפונים" היה המשפט ההראשון שנאמר ב 'טלפון'. #set text(lang: "ro") "Calul nu mănâncă salată de castraveți" a fost prima propoziție rostită vreodată la 'telefon'. #set text(lang: "ru") "Лошадь не ест салат из огурцов" - это была первая фраза, сказанная по 'телефону'.
https://github.com/Toniolo-Marco/git-for-dummies
https://raw.githubusercontent.com/Toniolo-Marco/git-for-dummies/main/slides/advanced/revert.typ
typst
#import "@preview/touying:0.5.2": * #import themes.university: * #import "@preview/numbly:0.1.0": numbly #import "@preview/fletcher:0.5.1" as fletcher: node, edge #let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide) #import "/src/components/gh-button.typ": gh_button #import "/src/components/git-graph.typ": branch_indicator, commit_node, connect_nodes, branch #import "/src/components/utils.typ": rainbow #import "/src/components/thmbox.typ": custom-box, alert-box Still on the subject of undoes, the `git revert` command is particularly useful. Essentially what this command does is the opposite of `git diff`: that is, passed a commit as a reference, the differences made by it will be applied in reverse. Also automatically a new commit will be made. One of the advantages of `git revert` is the fact that it does not rewrite history, as well as the fact that it is _safe_: it is always possible to go back to the previous commit and resume from there, deleting the revert commit if unnecessary. As an example we take directly the one provided by Atlassian on the page dedicated to #link("https://www.atlassian.com/git/tutorials/undoing-changes/git-revert")[this command]. I quote the code below for simplicity: ```bash ➜ git init . Initialized empty Git repository in /git_revert_test/.git/ ➜ touch demo_file ➜ git add demo_file ➜ git commit -am "initial commit" [main (root-commit) 299b15f] initial commit 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 demo_file ➜ echo "initial content" >> demo_file ➜ git commit -am "add new content to demo file" [main 3602d88] add new content to demo file n 1 file changed, 1 insertion(+) ➜ echo "prepended line content" >> demo_file ➜ git commit -am "prepend content to demo file" [main 86bb32e] prepend content to demo file 1 file changed, 1 insertion(+) ``` --- This set of commands should not surprise us; #align(center)[ #scale(85%)[ #set text(10pt) #fletcher-diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, // main branch branch( name:"main", color:blue, start:(0,0), length: 3, head:2, commits: ("initial commit", "add new content", "prepend content") ), ) ] ], --- Continuing with the suggested commands we have: ```bash ➜ git revert HEAD [main b9cd081] Revert "prepend content to demo file" 1 file changed, 1 deletion(-) ``` Running the command will probably open the editor that allows us to change the commit message or leave the default one. #align(center)[ #scale(85%)[ #set text(10pt) #fletcher-diagram( node-stroke: .1em, node-fill: none, spacing: 4em, mark-scale: 50%, // main branch branch( name:"main", color:blue, start:(0,0), length: 4, head:3, commits: ("initial commit", "add new content", "prepend content", "Revert \"prepend ...\"") ), ) ] ], ```bash ➜ cat demo_file initial content ``` --- The direct consequences of the advantages listed earlier make this method the best when working in teams since there is no need for a `git push --force`.
https://github.com/zenor0/FZU-report-typst-template
https://raw.githubusercontent.com/zenor0/FZU-report-typst-template/main/fzu-report/utils/smart-pagebreak.typ
typst
MIT License
#let gen-smart-pagebreak( always-skip-even: true, skip-with-page-blank: true, ) = { if always-skip-even == false { pagebreak(weak: true) } else if skip-with-page-blank == false { pagebreak(weak: true, to: "odd") } else { page(header: none, footer: none)[~] } }
https://github.com/tingerrr/hydra
https://raw.githubusercontent.com/tingerrr/hydra/main/tests/regressions/scoped-search/test.typ
typst
MIT License
// Synopsis: // - fixes https://github.com/tingerrr/hydra/issues/5 // - if a level 2 heading cannot be found we don't go further than a level 1 heading back #import "/src/lib.typ": hydra #set heading(numbering: "1.1") #show heading.where(level: 1): it => pagebreak(weak: true) + it #set par(justify: true) #set page( paper: "a7", header: context { if calc.even(here().page()) { align(left, hydra(1)) } else { align(right, hydra(2)) } }, ) = First Chapter == First section #lorem(180) = Second Chapter === Second Subscetion #lorem(100)
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion/fp_dict_filter.typ
typst
Apache License 2.0
// contains:a,ab,ac,ad #let x = ( a: false, ab: false, ac: false, ad: true, ) #x.a /* range -1..0 */
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/closure-04.typ
typst
Other
// Redefined variable. #{ let x = 1 let f() = { let x = x + 2 x } test(f(), 3) }
https://github.com/veilkev/jvvslead
https://raw.githubusercontent.com/veilkev/jvvslead/Typst/files/6_passwords.typ
typst
#import "../sys/packages.typ": * #import "../sys/sys.typ": * #import "../sys/header.typ": * #v(150pt) = Accessing Operators #note[ There are multiple ways that you are able to view operator numbers. ] #grid(columns: (1fr, 1fr), column-gutter: 0.15in, )[ #subhead(head: true, "Manager Functions") #badge-green("From POS") #menu("3 (Checker Reports Menu)", "2 (Active Till Media - All)") #subhead(head: true, "File Maintenance Menu") #badge-green("From POS") #menu("3 (File Maintenance Menu)","..") #menu("..", "1 (Employee File Maintenance)", "HELP") #menu("...", "PAGE DOWN", "PAGE DOWN/PAGE UP") ][ #subhead(head: true, "Bookkeeping Terminal") #badge-green("From POS") #menu("2 (Reports Main Menu)", "4 (Front-End Reports Menu)") #menu("5 (POS Operator Report)", "F4") #subhead(head: true, "Reports Main Menu") #badge-green("From POS") #menu("2 (Reports Main Menu)", "5 (Detail Journal Report)") #menu("..", "Arrow Down to [Operator Number]", "HELP") ] #move(dx: 400pt, dy: -310pt, box(inset: 20pt, height: 140pt, stickybox( rotation: 0deg, width: 4cm )[ #underline("Options in bookkeeping"): \ Select (A)ll or (E)xceptions: *A* \x Group by AuthLevel (Y/N): *N* \ ] )) #v(-150pt) #set text(12pt) = Passwords #important[ Password resets of other partners requires knowing their operator numbers and having sufficient \ rights to reset that operator. ] #grid(columns: (1fr,1fr), column-gutter: 0.15in, )[ #subhead(head: true, "Password (self-reset)") #badge-green("From POS") ][ #subhead(head: true, "Password Reset (others)") #badge-green("From POS") ] #box(height: 68pt, columns(2, gutter: 11pt)[ #menu("PSID", "PASS", "MANAGER")#pin(6) #colbreak() #menu("MANAGER", "3 (Cash Control Functions)") #menu("..", "3 (Checker Reports Menu)", "6 (Delete Password)") #menu("..", "[Operator #]") ]) #pinit-point-from((6))[Enter your password, but press\ MANAGER instead of ENTER] #v(40pt) #warning[ You cannot delete an operator's password whose authority is higher than yours. \ You may only do so for those below you, or in the same level as you. \ ]
https://github.com/Jollywatt/typst-fletcher
https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/diagram-options/test.typ
typst
MIT License
#set page(width: auto, height: auto, margin: 1em) #import "/src/exports.typ" as fletcher: diagram, node, edge #diagram( node-stroke: gray.darken(50%) + 1pt, edge-stroke: green.darken(40%) + .6pt, node-fill: green.lighten(80%), node-outset: 2pt, label-sep: 0pt, node((0,1), $A$), node((1,0), $sin compose cos compose tan$, fill: none), node((2,1), $C$), edge("o-o", stroke: orange), node((3,1), $D$, shape: "rect"), edge((0,1), (1,0), $sigma$, "-}>", bend: -45deg), edge((2,1), (1,0), $f$, "<{-"), )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/let-10.typ
typst
Other
// Ref: false // Destructuring with an empty sink. #let (a, b, ..c) = (1, 2) #test(a, 1) #test(b, 2) #test(c, ())
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1E030.typ
typst
Apache License 2.0
#let data = ( ("MODIFIER LETTER CYRILLIC SMALL A", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL BE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL VE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL GHE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL DE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL IE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL ZHE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL ZE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL I", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL KA", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL EL", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL EM", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL O", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL PE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL ER", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL ES", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL TE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL U", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL EF", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL HA", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL TSE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL CHE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL SHA", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL YERU", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL E", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL YU", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL DZZE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL SCHWA", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL BYELORUSSIAN-UKRAINIAN I", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL JE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL BARRED O", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL STRAIGHT U", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL PALOCHKA", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER A", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER BE", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER VE", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER GHE", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER DE", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER IE", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER ZHE", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER ZE", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER I", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER KA", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER EL", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER O", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER PE", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER ES", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER U", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER EF", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER HA", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER TSE", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER CHE", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER SHA", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER HARD SIGN", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER YERU", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER GHE WITH UPTURN", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER BYELORUSSIAN-UKRAINIAN I", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER DZE", "Lm", 0), ("CYRILLIC SUBSCRIPT SMALL LETTER DZHE", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL ES WITH DESCENDER", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL YERU WITH BACK YER", "Lm", 0), ("MODIFIER LETTER CYRILLIC SMALL STRAIGHT U WITH STROKE", "Lm", 0), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), ("COMBINING CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I", "Mn", 230), )
https://github.com/hrbrmstr/2023-10-20-wpe-quarto-typst
https://raw.githubusercontent.com/hrbrmstr/2023-10-20-wpe-quarto-typst/main/blank-test/_extensions/blank/typst-show.typ
typst
#show: doc => article( $if(margin)$ margin: ($for(margin/pairs)$$margin.key$: $margin.value$,$endfor$), $endif$ $if(papersize)$ paper: "$papersize$", $endif$ doc )
https://github.com/EGmux/ControlTheory-2023.2
https://raw.githubusercontent.com/EGmux/ControlTheory-2023.2/main/unit2/multipleSubsystemReduction.typ
typst
#set heading(numbering: "1.") = Why do this? == Better Complexity analysis Whenever a system is analysed complexity must be the minimum required,by reducing multiple systems into a "big one" is easier to analyze, such pattern is called reduction, and that is achieved by reducing each transfer function to a single transfer function 📔\ \ _💡 is that the big system is equivalent to the smaller ones_ === The Block Diagram aprroach #figure( image("../assets/blockDiagram.png", width: 80%), caption: [A block diagram], ) <fig-blockdiagram> #cite(<cabm>) #figure( image("../assets/subsystems.png", width: 80%), caption: [A subsystem and it reduction to the equivalent transfer function], ) <fig-subsystems> #cite(<cabm>) === How to deal with parallel/series subsystems blocks #figure( image("../assets/pa.png", width: 80%), caption: [Parallel and series cases], ) <fig-pa> ==== Parallel if the current block is a parallel , do this, assuming each G(s) to be the transfer function - For each ramification add to a term and multiply by the input *i.e*: X(s) = $(R(s)G_1(s),R(s)G_2(s),R(s)G_3(s))$ -> $C(s) = [plus.minus G_1(s)plus.minus G_2(s) plus.minus G_3(s)]R(s)$ _Note that transfer function is $Y(s)/X(s)=F(s)$, thus Y(S) $=$ C(s) $=$ X(s) consequently by factoring the common terms we obtain the above expression_ ==== Series - Just sum each transfer function ==== Dealing with feedback #figure( image("../assets/plant.png", width: 80%), caption: [Dealing with feedback], ) <fig-plant> #cite(<cabm>) === Trick cases Note that any subystem the same way it can be reduced we can also do the inverse and decompose it _Sometimes the decomposition is not obvious:_ Suppose a system with *n-inputs* exists, then some of the input has a transfer function connected to it, other's don't well the topology changed! We might have something like the following equation shows #math.equation(block: true, $ sum_(i) G_i(s)R_i(s) plus.minus X_i(s) $) note that can also be rewritten as #math.equation(block: true, $ sum_(i) (G_i(s)R_i(s) plus.minus X_i(s)/G_i(s))G_i(s) $) *That is equivalent to each input without a transfer function having the $1/G_(s)$ as transfer function* #figure(image("../assets/bloc.png", width: 80%), caption: [A tricky system]) <fig-bloc> #cite(<cabm>) _ 💡 is that input shouldn't be modified only the transfer functions should be manipulated_ === Even trickier case Now consider the case where the system is a n-bifurcation of a single input, $R(s)$ for instance _So to analyze with easy is better to see each branch as a non modified branch, if you were to put the $G(s)$ in the starting point, each branch would have to be adapted to not be affected by the transfer function, thus a $1/G(s)$ T.F would be needed to preserve the final behavior_ #figure(image("../assets/tryick.png", width: 80%), caption: [Very trick case]) <fig-tryick> #cite(<cabm>) === The trickiest case Now consider a starting point with a block and bifurcations without block, ignore the bifurcation what would you expect? _ 💡 note that after passing through the block the bifurcation point is essentially $C(s)$ thus each ramification s essentially $C(s)$ appearing more than once_ #math.equation(block: true, $ C(s)/R(s) = G(s)$) #figure( image("../assets/trioek.png", width: 80%), caption: [A multibranch subystem], ) <fig-trioek> #cite(<cabm>) === Challenger 1 #figure( image("../assets/abigsystem.png", width: 80%), caption: [A really big system], ) <fig-abigsystem> #cite(<cabm>) So where to start with this beast of a system 😱? _ 💡 back to basics: parallel, series and feeback_ - Note that the region next to $C(s)$ is effectively a series reduction of $G_2(s),G_3(s)$ #math.equation(block: true, $ G_a(s) = G_2(s)+G_3(s) $) - Consider now two possibilities either a parallel or feedback, what to choose 🤔? *It's wrong to assume multiple feedback reductions exist! So we can only choose the parallel* _ For a feedback consider the block signal to be the negative of what is currently showing_ #math.equation(block: true, $ H_a(s) = [H_3(s)-H_2(s)+H_1(s)] $) - Combining with our previous reduction: #math.equation(block: true, $ D_a(s) = G(s)/(1+H_a(s)G(s)) $) - To end we sum with $G_1(s)$ #math.equation(block: true, $ F_a(s) = G_1(s)D_a (s) $) _Note: we use \* because that's the sink operator, could be a + as well, really depedent on the system behavior_ === Challenger 2 Now consider the below system #figure( image("../assets/syste2.png", width: 80%), caption: [A very complicated system], ) <fig-syste2> _We need to find a starting point, note that the middle is very hard_ - Consider the rightmost side, apply feedback strategy #math.equation(block: true, $ D_a (s) =(G_3(s))/(1+G_3(s)H_3(s)) $) - Now we have a connection from $(V_4(s),V_3(s))->D_a (s)$ but they are not in parallel _ 💡 because the process is non linear we now need to look at the middle point and try to find a reduction_ - Note that $V_3(s)$ has an "annoying" connection that make it hard to analyze, we could put in the the right and do some manipulations to mantain the equivalence *to do so note that would imply $V_4(s)=V_3(s)G_2(s)$ to compensate we multiply the new connection with the TF $1/G_2(s)$* - Now we could apply the parallel strategy to deal with $1/G_2(s),V_4(s)$ and remove another annoying wire #figure( image("../assets/checkpoint.png", width: 80%), caption: [What we currently have], ) <fig-checkpoint> #cite(<cabm>) #math.equation(block: true, $ D_b (s) = 1/G_2(s) + V_4(s) $) _ 💡 note that techinnically each section of the system is being dealt separately, whenever a section becomes a block we go to the immediatelly left block_ *_💡 😱 note that the output of each subsystem is being ignored, not the input though!_* - Now we move $G_1(s)$ inside the feedback to it's right, by doing this a direct connection between $V_1(s),V_2(s)$ will appear and we can apply the parallel strategy. *This stuff is trick notice that by moving $G_1(s)$ we have to deal with two branches at the same time, now ask this question, if you had a single branch what would you do?* - Suppose we had only $G_2(s)$ then $G_1(s)$ would be multiplying it, notice that $V_1(s)$ is the input in this case that by multipying $G_1(s)$ give us $V_2(s)$, thus we deduce that #math.equation(block: true, $ V_4(s) = V_2(s)G_2(s)$) #math.equation(block: true, $ V_4(s) = G_1(s)V_1(s)G_2(s) $) _We mantain $V_1(s)$, thun we only need to multiply by $G_1(s)$_ -For the other connection we see a case of the previous, thus we divide by $G_1(s)$ #math.equation(block: true, $ sum_(i) (G_i(s)R_i(s) plus.minus X_i(s)/G_i(s))G_i(s) $) #bibliography("./bibliography.bib")
https://github.com/pascal-huber/typst-letter-template
https://raw.githubusercontent.com/pascal-huber/typst-letter-template/master/examples/DIN-5008-B.typ
typst
MIT License
#import "@local/lttr:0.1.0": * #show : lttr-init.with( debug: true, format: "DIN-5008-B", title: "Banana Order Confirmation", opening: "Dear Peter,", closing: "Peace, I'm out", signature: "Hans", horizontal-table: ( // NOTE: we can override the default fmt to format the table entries fmt: (header, content) => [ #text(fill: green, size: 0.8em)[ #underline[#header] ] #linebreak() #content ], content: ( ("Ihr Zeichen", "Banana"), ("Ihre Nachricht vom", "12.12.2022"), ("Unser Zeichen", "BananaFactory"), ("Datum", "06.08.2023") ) ), date-place: ( date: "20.04.2023", place: "Monkey City", ), return-to: "Bananas Ltd · Fruitstreet 15 · 1234 Monkey City", receiver: ( "<NAME>", "Bahnhofsstrasse 16", "1234 Fruchtstadt", "Weitfortistan" ), sender: ( // NOTE: This overrides the DIN 5008 position.top because we want a big // banana image here position: (top: 3cm), content: [ #image("logo_big.png", width: 60%) Bananas Ltd.\ Fruitstreet 15\ 1234 Monkey City\ Gorillaland ] ), ) #show: lttr-preamble #lorem(100) #show: lttr-closing
https://github.com/touying-typ/touying
https://raw.githubusercontent.com/touying-typ/touying/main/examples/default.typ
typst
MIT License
#import "../lib.typ": * #import themes.default: * #import "@preview/numbly:0.1.0": numbly #show: default-theme.with( aspect-ratio: "16-9", config-common( slide-level: 3, zero-margin-header: false, ), config-colors( primary: blue, ), config-methods( alert: utils.alert-with-primary-color, ), config-page( header: text(gray, utils.display-current-short-heading(level: 2)), ), ) #set heading(numbering: numbly("{1}.", default: "1.1")) = Outline <touying:hidden> #components.adaptive-columns(outline(title: none, indent: 1em)) = Title == Recall <recall> *Recall* #speaker-note[Recall] #show: touying-set-config.with(config-methods(cover: utils.semi-transparent-cover)) == Animation #set math.equation(numbering: "(1)") Simple #pause $ x + y $ animation #touying-recall(<recall>) #show: appendix = Appendix Appendix
https://github.com/LugsoIn2/typst-htwg-thesis-template
https://raw.githubusercontent.com/LugsoIn2/typst-htwg-thesis-template/main/lib/appendix.typ
typst
MIT License
#let appendix(lang: "", appendix-font: "Arial", appendices: ()) = { set page( margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm), numbering: "i", number-align: center, ) counter(page).update(1) set text( font: appendix-font, size: 12pt, lang: lang, ) // { // outline( // title: { // text(size: 35pt, weight: 700, "Appendix") // v(15mm) // }, // // title: "", // indent: 2em // ) // show heading: none // heading(numbering: none)[Appendix] // pagebreak(weak: true, to: "odd") // } // label("aaa") // --- appendix--- for appendix in appendices { // label("aaa") set page(number-align: center) // Ausgabe des Anhang Titels let (marker, include_statement) = appendix counter(heading).update(0) heading(numbering: none, level: 1)[#(marker)] set heading(outlined: false) include_statement set heading(outlined: true) } // body // v(1fr) }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/007%20-%20Theros/006_Tragedy.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Tragedy", set_name: "Theros", story_date: datetime(day: 23, month: 10, year: 2013), author: "<NAME>", doc ) #figure(image("006_Tragedy/01.jpg", width: 100%), caption: [Triad of Fates | Art by Daarken], supplement: none, numbering: none) #emph[Chorus of the Triad: Hark now to the tale of bitter Penthikos, marked by the gods and bound by fate.] Theros. A land of heroes. Heroes like me. May you never share this glory. I was once among the favored of Iroas. Serving in the phalanxes of Akros, I stood by my companions on Pharagax Bridge in defense of the polis and marched with them against the marauders of Deathbellow Canyon. We slew many foes. But serving honorably as part of a group was not enough. My heart cried out for the blessing of the God of Victory, and I was determined to prove my bravery to him. One day, I and my fellow Stratians descended the Titan's Stairs to strike into the Phoberos badlands. Scarcely had we relieved the previous defenders when a mob of beasts swarmed into view: firebreathing hounds, bloodthirsty minotaurs, feral satyrs, and other creatures less easily described. The unruly creatures attacked with no strategy, and I met them in the same spirit—breaking formation and running ahead, eager to wet my blade. #figure(image("006_Tragedy/02.jpg", width: 100%), caption: [Ordeal of Heliod | Art by Lucas Graciano], supplement: none, numbering: none) Oh, it was glorious! I struck down enemies as fast as they came at me, and challenged more to face my sword. Amid the roars of dying monsters and my own battle cries, I did not at first hear the screams from behind me. I finally became aware of the sound during a pause in my slaughter. I looked back on a horrible sight. Phalanxes of grim, gold-masked soldiers were closing in on each side of the companions I had left behind. My hasty charge had left the Akroan ranks in disorder, and as they struggled to fill the gap I had left, they drowned under the advancing tide of the Returned. I hurried toward the battle, but even before I entered spear's reach I knew the fight was hopeless. I heard my shieldmates curse me as they died. All I could do was try to find another way to the polis and warn of the danger. I fought my way through the canyon and scaled the Kolophon's sheer cliffs, until finally I staggered through the gates of Akros. I fell before the Oromai, bleeding, and gasped out what had befallen my fellows in arms. They took me before the king. He heard my tale. He gave his orders. He pronounced my sentence. "As you desire not to belong, you shall be set apart forever." #figure(image("006_Tragedy/03.jpg", width: 100%), caption: [Chained to the Rocks | Art by <NAME>], supplement: none, numbering: none) I had sought the smile of Iroas, but now I was bared to the angry eye of Heliod. My stony bed grew hot as Purphoros's anvil. In my agony I hurled a prayer to the skies, hard and true as a javelin. "Let me expiate my hubris, O gods! I offer myself, to undertake any ordeal you decree." No answer came for long hours, or so it seemed. But then the rock shook beneath me, and a great voice filled the air. "So be it." #figure(image("006_Tragedy/04.jpg", width: 100%), caption: [Swamp | Art by <NAME>], supplement: none, numbering: none) I stood, free of my shackles, at the mouth of a grim and silent cave. The stink of brimstone issued forth. Although I heard no more words, I knew I must enter. The passage twisted downward like the coils of a whip. The suffocating miasma grew ever thicker. All around me echoed roars, cackles, hisses, although I could not make out shapes. My steps grew heavier, slower. My thoughts grew dim. All became darker, although I knew not whether my torch was burning out or my eyes were losing sight. I felt a chill touch my sweating skin. Something swept past, insubstantial but malevolent. I lashed out in the dark, and as my blade cleft the shape my soul was likewise rent. I heard again the screams and curses of my companions. Black tears started at my eyes. #figure(image("006_Tragedy/05.png", width: 100%), caption: [Tormented Hero | Art by <NAME>], supplement: none, numbering: none) Again and again the shadows struck at me, clawing at my flesh and chilling my blood. Only cutting them down could end the pain, although the death of each ripped my heart. With every blow, more of the foul ichor poured down my face. At length the shrieking shades left off. I could only continue on the dread road, although injuries both physical and psychic had left me crawling. Just as I thought I could go no further, I fell forward into a vast chamber. The poisonous airs cleared and sight returned, although oppressive fog hid most of the space from view. Utter silence reigned, broken only by my tortured breathing. Ahead stretched a dreadful shore, a strand of teeth and crumbled bones, black water thick as tar. The hulks of rotted ships curved overhead like skeletal ribs. In the distance glowed a dull aura, recalling the sun through a cast of rain. I stood and began to walk, slowly, toward the hopeless light. From the gloom arose a dismal heap of life's remembrances: funeral urns, torn banners, cleft helms, rusted blades. The wan illumination seemed only to increase the dreariness of the place. Beyond stretched a dank and slimy wharf that vanished into the mists, and I knew what bark was moored to it. #figure(image("006_Tragedy/06.jpg", width: 100%), caption: [Temple of Silence | Art by <NAME>ski], supplement: none, numbering: none) This, then, my end. My penance to the gods was no different from the doom that awaits all mortals, save that I had come to the Rivers' edge while yet alive. What further anguish would my soul endure when my flesh crossed over that horrid flow? If torment and death be my lot, I would show both Iroas and Erebos how a hero faces them. I took one step toward the dock, then another. "So eager to see the Underworld, when life has not yet left your limbs?" The voice, although soft, shattered the silence like a thunderbolt. I turned, startled, to see a robed figure leaning on a shivered beam. Her eyes reflected the gleam of a coin she tossed slowly as she watched me. #figure(image("006_Tragedy/07.jpg", width: 100%), caption: [Scholar of Athreos | Art by <NAME>pard], supplement: none, numbering: none) "You bring no face for the boatman. How will you cross?" My hands moved to my lips, my cheeks. They weren't there. The pitchy tears had encased my visage in a featureless surface, leaving only my eyes uncovered. Without a funerary mask, Athreos the River Guide would not know my name. Would I linger here, unmourned and unforgiven, for all eternity? "Thrice asked, and done. Do you seek oblivion?" I bent before her piercing gaze. A sob heaved in my lungs, but I gritted my teeth and swallowed it down. I would not show weakness, even now. "I seek absolution. I seek erasure. I seek peace." "What you seek I cannot give. That is for the gods alone. I can only listen, and perhaps advise." "A god sent me here. He did not say more." "And what did you pray for?" "I had offended against my polis and the gods. I asked only for the chance to set things right. Was my crime as monstrous as the punishment meted? Have I not suffered enough?" "Erebos #emph[is] suffering. Only through the pain of others can he find peace, and only thus can mortals find their fate." "Then I was a fool to take his bargain. And I defy fate." "Fate cannot be avoided. It can only be realized." "I make my own fate." I felt the matter on my face shift and sculpt itself into a grimacing death-mask as I shouted. "Come, master of the passage! This pathetic soul seeks the dark shores of the Underworld." The ancient barge silently slid forth from the fog. Its ragged guide stood expectantly, hand ready to receive my face of crystallized pain. The price paid, we drifted across to that bleak land. #figure(image("006_Tragedy/08.jpg", width: 100%), caption: [Returned Phalanx | Art by <NAME>], supplement: none, numbering: none) But I will not give the god of death his satisfaction. I will not abide in darkness among the dull shades. Even now, the final strokes fall on my new golden face. I will follow the Path of the Returned and seek my place in the ranks of the dead. #emph[Chorus of the Triad: And so what was fated has come to pass.]
https://github.com/8LWXpg/typst-treet
https://raw.githubusercontent.com/8LWXpg/typst-treet/master/test/test.typ
typst
MIT License
#import "../lib.typ": * #tree-list[ - A A - B B ] #tree-list[ - A *A* - *B* B ] #tree-list[ - a - a - a - a - a - a - a - a - a ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/030%20-%20Amonkhet/005_The%20Hand%20That%20Moves.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Hand That Moves", set_name: "Amonkhet", story_date: datetime(day: 26, month: 04, year: 2017), author: "<NAME>", doc ) #figure(image("005_The Hand That Moves/01.png", width: 100%), caption: [], supplement: none, numbering: none) #emph[Nissa discovered hints of Amonkhet's past, a history <NAME> has overwritten. Now she seeks answers from the God of Knowledge, hoping Kefnet can explain the veneer that seems to obscure the plane.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Nissa wandered through empty streets, meandering through hell. #figure(image("005_The Hand That Moves/02.jpg", width: 100%), caption: [Forest | Art by <NAME>], supplement: none, numbering: none) Most of her senses told her the city was beautiful. Giant palm leaves rustled gently under soft breezes, clear water burbled in pools and fountains, birdsong melodies chirped and trilled in harmonious counterpoint. Tantalizing smells wafted through the air. Fresh baked bread here. Lilies and jasmine there. If one looked, if one listened, they were in paradise. But when Nissa closed her eyes and extended her mana sense, the paradise crumbled. The leylines of Amonkhet, the very bones and blood of the world, were stunted. Normally endless lines of pulsing mana, but on this world they were concentrated into this decadent city. Here, behind the barrier, they were strong and stout. But that strength came with a cost. A dark virulent strain wove its way through the leylines. This was not the deadening corruption of the Eldrazi. It had a vitality the Eldrazi lacked. The pulsing darkness interlaced through and around the mana, a python choking its prey. Nissa opened her eyes and paradise reappeared. The leaves, the water, the birds. She closed her eyes again. The slippery snake squeezing its victims. The juxtaposition between the beauty and horror almost brought her to her knees. She opened her eyes and closed them again, the rapid changes both compelling and nauseating. She continued her wandering, occasionally stopping to close her eyes and glimpse horror. Her stomach and head rebelled, growing in agony, but she pressed on. She needed to find Kefnet. The God of Knowledge. She needed answers. When next she opened her eyes, the god was staring at her. The large head of an ibis gazed at her steadily, eyes unblinking, its long beak pointing straight at her, through her, to a horrible destiny no less awful for being unknown. She crumpled to the ground, her will sapped in the presence of this cruel divinity. She blinked once, twice. It was a statue. Just a statue. Kefnet, the God of Knowledge. #emph[What use is knowledge in a world like this?] #emph[Behind all veils is blight. Only blight.] She stood slowly, awkwardly#emph[, ] her stomach and head still in protest. Underneath the large stone head and the cruel fixed eyes, a pair of large limestone doors swung open. A bright blue glow emanated from the shadows behind the door. A greeting. An invitation. She stepped forward into the blue light. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) She was in a small anteroom, a cool blue light from a larger space at the other end shading the smooth stone walls and floors. The doors quietly swung shut behind her, the light outside snuffed, and Nissa was relieved to be free of the city's beguiling regard. A young man in pale robes stood behind a wooden lectern, turning pages of a book. He turned a few more pages as Nissa stood there, a thin smile on his face though he said nothing. "Excuse me . . ." she began, unsure of protocol and propriety. She was never sure of protocol and propriety, amongst people. The young man raised his head, his smile vanishing. "Do not speak, initiate! You know . . ." His voice trailed off as he took in the sight of Nissa. She felt a clumsy pawing at the outskirts of her thoughts, her association with Jace and his telepathy allowing her to recognize the attempts of a novice. His skittering probing ceased, having failed to find any purchase. "You . . . you . . . are not from here," he finished weakly. "I am here to speak with Kefnet," she said, with more confidence than perhaps was warranted. But the gods seemed to move freely around the city, their presence a given amongst their people. Why not Kefnet? The young man's eyes closed and stayed closed, his attention seemingly lost. Nissa had thought this chamber a refuge from the bright deceit of the city, but now grew certain there was no refuge to be found. Nothing made sense on this world; nothing was as it should be. #emph[Perhaps I bring the blight with me.] The thought startled. Always before she had framed the corruption she fought on Zendikar, on Innistrad, here, as enemies without. Darkness from the outside, to be vanquished. But what if the darkness was within? Perhaps that was why on every plane she visited she knew failure. She had failed to protect Zendikar. Failed to overcome Emrakul. Even her successes felt hollow. Perhaps she deserved this fate. She was bringing the emptiness with her, to soil whatever she touched. The cool blue room now felt close, stuffy. A growing panic emerged in her chest, beating and thumping to get out. The young man in front of her continued his senseless communion, his head bowed. She took a tentative step closer to the larger room at the other end of the foyer, its blue light beckoning. The young man opened his eyes. "You have been permitted to attempt the Trial of Knowledge. There are three . . ." His voice sounded strange, strained. A pack of wild dogs chasing its prey. The panic inside her burst free, overriding reason and thought. Nissa ran to the other room, and as the man sought to intercept her, she flung him against the stone walls. From the rough floor, a weakly uttered gasp, "No . . . you are not . . ." She heard no more as she plunged into the blue light. #figure(image("005_The Hand That Moves/03.jpg", width: 100%), caption: [Essence Scatter | Art by <NAME>], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The angel descended from the sky. Between two suns she flew, wings unfurled, radiant light lining her perfect form. Her shut eyes opened and snakes tumbled out. Slithering brown bodies wiggling out of empty orbs. The angel flapped her wings, coming closer, closer, all the while snakes fell to the barren ground, hissing and sliding across the parched earth. The angel opened her mouth and the skies darkened, storm clouds gathering behind her. "I can do anything I want. Anything at all. Remember that." The angel came closer . . . Nissa woke with a scream, sweat already cooling on her brow. #emph[Emrakul] . The monster had taken over her body back on Innistrad. But those words were not just Emrakul's. They were Nissa's as well. #emph[Where am I? ] She had been seeking . . . something. Someone. There had been a room. She looked at the room she was in now, a different room than before. A spare cot, a threadbare blanket. Nissa ran her hand over the ratty blanket, its coarse threads surprisingly sharp. She pulled her hand away with a yelp. In the middle of her palm was a long, thin, red line. Blood began dripping from the cut. The blanket was so sharp it had cut her. More lines appeared on her body. Tiny separations blossoming red. The pain was immense. The blanket rustled over her, cutting her, over and over . . . Nissa woke with a scream. #emph[Where am I? ] The dream had been awful. Some form of monster, with tiny teeth and claws, ripping at her . . . she shook her head. Something was wrong. She looked around her bed, but it was as if she were underwater. Nothing could come into focus. She shook her head, trying to clear her eyes, but nothing happened. A slow paralysis creeped up her spine. Her arms and legs felt glued to the bed, rooted by a merciless force. Something was wrong. She closed her eyes and she could feel the unreality surrounding her. She needed to break free. #emph[I can do anything I want. Anything at all. Remember that. ] Her words. #emph[Mine] . A burgeoning flash of green light inside her, dispelling the paralysis. She floated in mid-air, buoyed by her growing power. #emph[What can I do? ] No, that was the wrong question. #emph[What can't I do?] The power swelled, the mere vessel of her skin unable to contain it. The flesh crackled, ruptured, but she did not care. Her power sustained her. #emph[This is my destiny. ] To lose herself in the power, in the sweet rush of energy and leyline. The power was growing, burning . . . Nissa woke with a scream. There had been a light, a green light. Something awful occurred, but as Nissa tried to remember the dream danced away, escaping the touch of memory. It had been awful, of that much she was sure. #emph[This is wrong.] Nissa startled. There had been a voice. A voice in her head. It had sounded like her own voice, but somehow separate. She looked around, frantic, as the walls began bleeding shadows. The shadows flowed off the walls, approaching in a smooth glide. Nissa knew their touch would mean death, or worse. Nissa yelled for the others to come, but no sound emerged. #emph[This is wrong.] It was her voice again. Nissa shut her eyes. She could feel the unreality surrounding her. She summoned power . . . #emph[Stop. I must stop. Do not react. Think.] Nissa did not know why she should trust the voice, but she did. She took a slow breath, concentrating on the feel of her chest as she inhaled the damp air. She exhaled, letting the breath wash over her, feeling muscles loosen, expand. #emph[I am trapped.] As she said it, some of the fog in her mind receded. She had run into the blue room, the Trial of Knowledge, the acolyte had called it. Even now she could feel the illusions and phantasms lurk over her, caressing her mind with their sickly sweet call. There had been one nightmare after another, each one cascading into the next. She took another deep breath. #emph[This is magic. Powerful magic. ] She shuddered as she contemplated the eternal nightmare facing any unprepared initiate who failed this trial. But as powerful as the magic was, it was still composed of leylines. And Nissa had no small mastery of those. For most of her life, Nissa's understanding and manipulation of leylines was instinctive. But every time she relied on instinct in here, she stayed trapped in nightmare. She needed more than instinct. She needed to understand. She gazed intently at the magical structure around her, its shape and feel, the way the leylines wove together to produce such a horrible and absolute effect. She marveled at the strength and skill required to construct such a trap. It was beyond anything she had done. #emph[Yet] . #emph[There] . In the weavings of magic surrounding her, there was a tiny gap. Small, but perceptible. Nissa tugged at the mana, continuing to keep her eyes closed, relying solely on her feel of the magic. She pushed and pulled at the opening, widening it with each tug. The illusions intensified around her, calling her name, begging her to open her eyes, to see delight and horror, truth and fantasy, anything she wanted, only for the price of a twitch of an eyelid. She kept them tightly shut, and once the opening in her prison was wide enough, she stepped through. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) She floated in an airy blue sky. No, not quite a sky. A pale blue canvas, empty, waiting for meaning. More illusion, but Nissa felt a sense of control, a wakefulness, that had eluded her during the nightmares. Below Nissa saw the remnants of the nightmare trap, dark purple swirls that had elicited such terror. #figure(image("005_The Hand That Moves/04.jpg", width: 100%), caption: [Daze | Art by <NAME>], supplement: none, numbering: none) And now she could see through the illusions, to the architecture of the magic underneath. To the very underpinnings of this Trial of Knowledge, so cruelly designed. #emph[I want to see. I want to see more.] She let the illusions swirl around her, gathering force and speed. A rhythmic beat played in the chamber, a beat resonating with her own heart. She closed her eyes. She witnessed. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) A dark snake, winged and venomous, cast its shadow upon the desert. The snake was huge, bigger than an oak, bigger than a forest of oaks. Its shadow covered the whole world. The shadow spoke, its voice rumbling across the empty desert. "They would take away my power. They would take away what makes me #emph[me] . This I will not abide." The shadow of the snake wrapped its coils around the world. "For what I require, I would drain every world. I would devour every single one. But I start #emph[here] ." The shadow #emph[squeezed] . The world screamed. Nissa screamed. The scene crumbled, fleeing from the pain. She was looking up into space, into the stars. Eight stars. Eight stars in a loose circle and evenly spaced, lighting up the entire night sky. A line of darkness, somehow visible even against the night, a line that #emph[shone] darkness, wove its way through the eight stars. The line twisted and turned and vibrated, its pulsing a violent cry. When the line ceased moving, it was a figure eight on its side, a snake eating its own tail. It encompassed all eight stars, each star twinkling desperately against the curtain of dark now nestled close against them. Three of the stars winked out. Their generation of light and heat snuffed. Their lives vanished. But Nissa could still see movement where those three stars had been. Stars no more, just three dark rents in the fabric of the sky. Three dark holes, possessed of an energy and fury all their own, pulsing to a rhythm malevolent. The five remaining stars moved, their new alignment warped, all bending to the shadowy line woven through their constellation. Their new outline suggested a pair of horns. The scene shifted, swirls of illusion moving to paint the canvas anew. Awkward figures wrapped in white linen bent and dug in the harsh sands. Mummies, they called them. The anointed. Hundreds, thousands of the mummies dug into a deep pit, pulling out a blue ore. Cartloads of the ore snaked their way in a large procession toward the city. #figure(image("005_The Hand That Moves/05.jpg", width: 100%), caption: [Stone Quarry | Art by <NAME>], supplement: none, numbering: none) Farther away, three young children stopped before a barrier. The beautiful city on one side, the stark emptiness of the desert on the other. They're whispering to each other. They look around, look at each other. Uncertain. A child presses through. The two others follow. All three are swallowed by the hungry sands. A new scene. She saw a young man, his face erased, stumbling among a garden of statues. High above the man a growing cloud of dusk attacked the sun. From somewhere outside the garden there was a mighty roar. Shift. Nissa saw a world, then tens of worlds, hundreds of worlds. Thousands. She saw this world, the world of Amonkhet, and wrapped around it was a dark sinewy line. That line stretched back through all the worlds, all the thousands of worlds, and she saw an unbroken line of darkness from Amonkhet all the way back to the beginning of the line. Shift. A large golden disc, shaped and stylized like a sun, descending from the sky. The sun disc approached a large circular stone tablet covered with strange sigils, and the two discs merged, becoming a single golden disc. Cracks appeared in the golden disc, small at first, then widening, growing. The disc crumbled away into nothingness. The scenes shifted faster now, barely even an image forming before being replaced. A fizzling torch. A broken clock with a clean face. A mummified head facing backward atop a mummified body. A split tree, its sap oozing into the ground. A shattered shield, its shiny metallic pieces torn and scattered. She closed her eyes against the onslaught, but still the images came tumbling through her head, crumpling her in mid-air. A falling dragon. Giants, covered in metallic blue, stomping through streets. A massive flash of light, consuming a world. An angel descending from the sky. Nissa opened her eyes, and the angel continued to descend. It was the angel from her nightmare. The angel that reminded her of Emrakul. The angel's eyes were open, but unlike the dream, there were no snakes, just blank white orbs. She landed in front of Nissa. "Why do you dally? I showed you the ways of power. Use them." The angel's voice melodious, a cool breeze. Beautiful. And beautiful the way Amonkhet was beautiful, all horror underneath. Nissa tried to summon her power, but nothing happened. #emph[I can do anything I want. Anything at all.] Except she couldn't. She stood there rooted to the ground, as the angel continued with her beautiful voice. "Are you a pawn? Or a queen?" "Who are you?" Nissa screamed. She knew it could not be Emrakul, worlds away trapped in silver. It was just another illusion, another creation born of the magic and her own thoughts. "Just go away! Go!" Nissa bowed her head in agony, intense pain blossoming in her head. She closed her eyes, but the angel remained there in front of her clearly visible whether through eyes shut or open. "<NAME>. Are you pawn or queen?" "I . . . I don't know. I just want . . ." "No!" The angel's voice turned cold and harsh. "It is the wrong question! Pawns, queens, they're all still pieces! All still pieces, waiting to be moved." The angel put a hand to Nissa's chin. She gently tipped Nissa's head up, looking at her face. There was no love in that gaze, but the look comforted nonetheless. The pain in Nissa's head receded. "Stop being a piece, Nissa. Be the hand that moves." There was a loud rumbling behind them. The angel looked over Nissa's shoulder, and something shifted in her eyes. Without word or farewell the angel soared into the sky, and was soon just a speck in the far distance. A new voice boomed. "#strong[Who makes a mockery of my trial?] " #figure(image("005_The Hand That Moves/06.jpg", width: 100%), caption: [Winds of Rebuke | Art by <NAME>], supplement: none, numbering: none) Nissa looked up. A giant ibis stood in front of her, cloaked in blue robes with gold trim, a long bladed staff wielded in one hand. He shared the piercing, almost cruel stare of his statue in front of his temple. But this was not a statue. It was the god himself, Kefnet. He did not look pleased. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Nissa had faced Eldrazi titans and demon mages, but never had she felt so overwhelmed by sheer power as she did in the presence of the ibis god. Her thoughts, her very self, strained to remain coherent in front of Kefnet, a struggle as easy as a pile of leaves resisting a windstorm. "#strong[Who are you, mortal?] " Thoughts and memories plucked from her head without regard for her desire, leaving her mind scattered like dandelion seeds in a field. Struggle was useless. She sought to ride the windstorm, to come through on the other side. "#strong[I see. And you think to come here? For answers?] " Nissa could not read the god's tone, could not read the god's face, could not understand anything around her. All her focus was on preserving her coherence. She was losing the battle. "#strong[I have an answer for you, mortal, one of the oldest answers. Knowledge is not a gift. It is earned. Only the worthy deserve knowledge.] " Kefnet's touch on her thoughts pressed. "#strong[The unworthy deserve nothing. Dissolution is my kindness for you. Better nothing than ignorance.] " She was breaking apart. "No . . ." was the only word she could muster. She thought of the evil of <NAME>, of how he had corrupted Kefnet and the other gods, but as each thought arose it was mauled by Kefnet's touch. He did not seem to know, or care, of Bolas's blighted touch upon his essence. Even now she could see through to the essence of the god, his essence made out of the world itself. The corrupted leylines of Amonkhet were the same strands of corruption in Kefnet, a strange melding of potency and virulence, inimical to Nissa's desire for the natural beauty of a world. The leylines inside Kefnet were tiny fibers, bound together so tightly that it was easy to overlook them. The God of Knowledge was made of leylines. Leylines she could manipulate. Nissa frantically wove a spell in the seconds left to her. An infusion of magic burst from her hands, coating the leylines of Kefnet, seeping into their pockmarked surface. She guided her magic through the essence of Kefnet. She remembered her witnessing of Bolas's corruption of the gods, a dark helix in the night sky. She could not undo what he had done, but she used some of that knowledge to create a small pattern of her own making. She saw the thread she wanted. She pulled it, and added a new fiber of mana to its mix. The windstorm ceased. Kefnet stood there, unmoving, as Nissa's thoughts returned to being solely her own. She took a deep breath, shaking, aware of just how close she had come to nothingness. "#strong[You may go now, initiate. You have passed your trial.] " The ibis god barely seemed aware of her as he flew off to some other destination. Her spell had been broad, clumsy. Nissa was the merest amateur at manipulating a god. No, manipulation was far too strong of a word. She had merely altered him enough to no longer want to destroy her. And it had worked. She was still capable of breath and life and thought. #emph[Thought.] #emph[It is a gift. One that I need to use more.] And though amateur she was, there was still a pattern of her own making residing in Kefnet. Still a thread she could tug . . . to what effect, she did not yet know. But she suspected there would be a time to find out. She was tired of being a pawn, constantly reacting to nightmares and failures, never ahead. And perhaps even a queen was too small a destiny. She heard a voice, her own voice, clear as a crystal bell. "Be the hand that moves." Nissa dispelled the illusions around her. She was still standing in the same anteroom she had entered, this time empty of anyone but her. She pushed at the door back to the city, and it opened, a vista to the bright, dangerous world outside. She stepped through.
https://github.com/EpicEricEE/typst-plugins
https://raw.githubusercontent.com/EpicEricEE/typst-plugins/master/qr/README.md
markdown
# qr A package for generating QR codes (based on the Rust crate [`fast_qr`](https://github.com/erwanvivien/fast_qr)). ## Methods ### `create` method Generates a QR code from the given data. ```typ qr.create( string | array | bytes, format: string, margin: number, fill: color, width: auto | relative length,, height: auto | relative length, alt: none | string, fit: string, ) -> image ``` #### `data` parameter The data to encode into the QR code. If the data is too large to fit into a single QR code, this method will error. #### `format` parameter The image format of the QR code. - `"png"`: Raster image format. - `"svg"`: Vector image format. Default: `"svg"` #### `margin` parameter The the number of "units" between the QR code and the edge of the image. Default: `4` #### `fill` parameter The color of the QR code. Default: `black` #### `width` parameter The width of the QR code. This parameter is passed to the `image` element. Default: `auto` #### `height` parameter The height of the QR code. This parameter is passed to the `image` element. Default: `auto` #### `alt` parameter The alternative text of the QR code. This parameter is passed to the `image` element. Default: `none` #### `fit` parameter How the QR code should adjust its size to fit a given area. This parameter is passed to the `image` element. - `"cover"`: The QR code shuold completely cover the area. This is the default. - `"contain"`: The QR code should be fully contained in the area. - `"stretch"`: The QR code should be stretched so that it fills the area, even if this means that the image will be distorted. Default: `"cover"` ## Example ```typ #import "@local/qr:0.1.0" #table( columns: 2, [*Data*], [*QR Code*], [Hello world!], qr.create("Hello world!", margin: 0, width: 100%), [Hallo Welt!], qr.create("Hallo Welt!", fill: blue, width: 100%), [#(1, 2, 3, 4)], box(fill: yellow, qr.create((1, 2, 3, 4), width: 100%)), ) ``` ![Result](assets/example.svg)
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/molebeny/molebenKSrdcuJezisovmu.typ
typst
#import "/style.typ": * #import "/styleMoleben.typ": * = Moleben k Srdcu Ježišovmu #align(horizon + center)[#primText[ #text(50pt)[Moleben k \ Srdcu \ Ježišovmu] ]] #let values = ( "tropar1": (4, none, "Dnes celý svet sa raduje, – lebo na oltári v ohnivom plameni skvie sa srdce Spasi­teľa, – ktoré všetkých volá do božského prístavu, – kde sa hoja bolesti tiel i duší. – Preto aj mňa k sebe pozvi, Spasiteľ, – a nehľaď na moje previnenia."), "tropar2": (none, none, "Dnes celý svet sa raduje..."), "velebenie": ("Velebíme ťa, – Kriste, Darca života, – lebo si nás uznal za hodných stať sa účastníkmi štedrôt – tvojho najsvätejšieho Srdca", ( "Čím sa odvďačím Pánovi za všetko, čo mi preukázal?", "V neho dúfalo moje srdce a pomohol mi.", "Bože, stvor vo mne srdce čisté a v mojom vnútri obnov ducha pevného.", "Sláva: I teraz: Aleluja, aleluja, aleluja, sláva tebe, Bože." )), "prokimen": (4, "Plesaj Pánovi celá zem, – oslavujte jeho meno, hlásajte jeho chválu a slávu.", "Svoje sľuby splním pred tvárou tých, čo sa boja Pána."), "evanjelium": ("Mt", "Pán povedal svojim učeníkom: „Môj Otec mi odovzdal všetko. A nik nepozná Syna iba Otec, ani Otca nepozná nik, iba Syn a ten, komu to Syn bude chcieť zjaviť. Poďte ku mne všetci, ktorí sa namáhate a ste preťažení, a ja vám dám odpočinúť. Vezmite na seba moje jarmo a učte sa odo mňa, lebo som tichý a pokorný srdcom; a nájdete odpočinok pre svoju dušu. Moje jarmo je príjemné a moje bremeno ľahké.“"), "verse": ("Ježišu, Synu Boha živého, ktorý si odkryl bohatstvá svojho najsvätejšieho Srdca, zmiluj sa a spas teba zvelebujúcich.", ( "Ó, najsvätejšie Srdce Ježišovo, zmiluj sa nad nami.", "Srdce Ježišovo, krása najjasnejšia, zmiluj sa a spas teba zvelebujúcich.", "Srdce Ježišovo, sila nepremožiteľná, zmiluj sa a spas teba zvelebujúcich.", "Srdce Ježišovo, láska nevýslovná, zmiluj sa a spas teba zvelebujúcich.", "Srdce Ježišovo, radosť môjho srdca, zmiluj sa a spas teba zvelebujúcich.", "Srdce Ježišovo, pomoc utrápených, zmiluj sa a spas teba zvelebujúcich.", "Srdce Ježišovo, čistota panenských duší, zmiluj sa a spas teba zvelebujúcich.", "Srdce Ježišovo, očisť môj rozum od márnivých myšlienok, zmiluj sa a spas teba zvelebujúcich.", "Srdce Ježišovo, chráň moje srdce od zlých žiadostí, zmiluj sa a spas teba zvelebujúcich.", "Srdce Ježišovo, ochranca môjho života, zmiluj sa a spas teba zvelebujúcich.", "Srdce Ježišovo, nádej v mojej smrti, zmiluj sa a spas teba zvelebujúcich.", "Srdce Ježišovo, moja útecha na tvojom súde, zmiluj sa a spas teba zvelebujúcich." )), "stichiry": ( (2, "Jehda ot dreva", "Všetkých pozývaš, Ježišu: – Poďte ku mne všetci, ktorí sa namáhate a ste unavení – a ja vás posilním. – Preto, keď ospe­vu­jeme tvoju dobrotu, – vrúcne ťa prosíme: – Otvor nám bránu svojho Srdca, – v ktorom spoči­nieme a oslobodíme sa od každého nešťastia, zár­mutku a núdze – a dosiahneme nebeský pokoj."), ("Pánovi splním svoje sľuby pred všetkým jeho ľudom."), (none, none, "Raduj sa, Srdce preľúbezné, – božská a jediná brána, ktorou vstupujú spasení, – zasväcujeme sa ti a vyznávame, – že nechceme prestupovať tvoje zákony – ani slúžiť diablovi, svetu a nášmu telu. – Chceme slúžiť len tebe jedinému. – Preto ťa prosíme: – Nevylučuj nás zo svojho srdca, – ale milostivo sa zmiluj nad nami."), ("Tvoje meno chcem zvestovať svojim bratom a uprostred zhromaždenia chcem ťa velebiť."), (none, none, "Raduj sa, Srdce preľúbezné, – drahocenná perla, čo ozdobuješ prestoly chrámov Pánových. – Tebe odovzdávame celé naše bytie. – Panuj, prosíme, nad nami – a spútaj nás svojou láskou – i pretvor nás na svoj chrám."), (8, none, "Raduj sa, Srdce preľú­bezné, – plameň spaľujúci naše hriechy. – Daj, prosíme, aby naša biedna a úbohá duša, – žasla vidiac tvoje preslávne tajomstvá – a nech ti s vierou a nádejou spieva: – Obdivuhodný si, Ježišu, vo všetkých svojich dielach, – predivný v zjavení svojho Srdca.") ), "modlitba": "Pane, Ježišu Kriste, Bože náš, daj, nech sa naše srdcia stanú oltárom tvojej lásky, nech naše ústa zvestujú tvoju preveľkú milosť. Nech naše oči ustavične hľadia do rany tvojho najsvätejšieho Srdca. Nech náš rozum premýšľa o tvojich nepochopiteľných tajomstvách. Nech naša pamäť chráni milé spomienky na tvoje milosrdenstvo. Pane, Bože náš, nech všetko v nás vyznáva nevy­čer­pateľnú lásku tvojho najsvätejšieho Srdca. Lebo je požehnané meno Otca i Syna i Svätého Ducha teraz i vždycky i na veky vekov.", "ektenia": ( "Zmiluj sa, Bože, nad nami pre svoje veľké milosrdenstvo, prosíme ťa, vypočuj nás a zmiluj sa.", "Prosíme ťa aj za veľkňaza všeobecnej Cirkvi, nášho Svätého Otca povie meno, rímskeho pápeža, za najosvietenejšieho otca arcibiskupa a metropolitu povie meno, i za nášho bohumilého otca biskupa povie meno, za slúžiacich a poslu­hujúcich v tomto svätom chráme, za našich duchovných otcov a za všetkých našich bratov v Kristovi.", "Prosíme ťa, Pane, Bože náš, vypočuj stony, slzy a vzdychy trpiacich a vo svojom milosrdenstve zmiluj sa nad nami.", "Zmiluj sa aj nad svojimi služobníkmi, ktorí prichádzajú do tohto svätého chrámu. Vypočuj láskavo ich modlitby a zmiluj sa.", "Modlime sa aj za rozšírenie počtu ctiteľov tvojho najsvätejšieho Srdca. Žehnaj im a zmiluj sa.", "Prosíme ťa, Pane, aj za prítomný ľud, ktorý od teba očakáva veľké a hojné milosrdenstvo, za našich dobrodincov i za všetkých pravoverných kresťanov.", "Milosťou, štedrosťou a láskou tvojho jednorode­ného Syna, s ktorým si velebený spolu s tvojím presvätým, dobrým a životodarným Duchom teraz i vždycky i na veky vekov." ) ) #pagebreak() #nacaloPoOtcenas #tropar(..values.at("tropar1")) #sit(..values.at("tropar2")) #if values.at("velebenie") != none [#velebenie(..values.at("velebenie"))] #note[Ľud sa postaví.] #K[Vnímajme! Pokoj všetkým! Premúdrosť, vnímajme!] #prokimen(..values.at("prokimen")) #chvaly() #evanjelium(..values.at("evanjelium")) #pagebreak() #verse(..values.at("verse")) #pagebreak() #stichiry(values.at("stichiry")) #modlitba(values.at("modlitba")) #ektenia(values.at("ektenia")) #prepustenie
https://github.com/Daillusorisch/HYSeminarAssignment
https://raw.githubusercontent.com/Daillusorisch/HYSeminarAssignment/main/template/components/doc.typ
typst
#import "@preview/i-figured:0.2.4": show-figure, show-equation, reset-counters #import "../utils/style.typ": * #import "../utils/circled.typ": convert-circled #let doc( // documentclass 传入参数 info: (:), // 其他参数 fallback: false, // 字体缺失时使用 fallback,不显示豆腐块 lang: "zh", margin: (x: 90pt, y: 82pt), content ) = { set par(justify: true) set text(fallback: fallback, lang: lang) set page(margin: margin) set document( title: info.title, author: info.author, ) show heading: reset-counters show figure: show-figure show math.equation: show-equation set footnote( numbering: (..nums) => nums .pos() .map(convert-circled) .join(".") ) show footnote: set text(font: 字体.宋体) show footnote.entry: set text(font: 字体.宋体, size: 字号.五号) content }
https://github.com/Mufanc/hnuthss-template
https://raw.githubusercontent.com/Mufanc/hnuthss-template/main/pages/references.typ
typst
#import "/configs.typ": font, fontsize // Tips:你可以用这个工具将 BibTeX 格式的引用转换为 Hayagriva 格式 // - https://jonasloos.github.io/bibtex-to-hayagriva-webapp #let references = [ // 标题居中、标题字体 #show heading.where(depth: 1): set align(center) #show heading.where(depth: 1): set text(size: fontsize.L3, font: font.sans, weight: "regular") // 标题与内容间距 #show heading: h => h + v(1em) // 内容字体 #set text(size: fontsize.L5) #bibliography("/references.yml", style: "gb-7714-2015-numeric") ]
https://github.com/memset0/ZJU-Project-Report-Template
https://raw.githubusercontent.com/memset0/ZJU-Project-Report-Template/master/examples/blocks/testblocks.typ
typst
MIT License
#import "../../template.typ": * #set page(height: 85em) #show: project.with( theme: "nocover", author: "memset0", ) #let render(theme_name) = [ #state_block_theme.update(theme_name) = theme: #theme_name #note(name: [Lagrange Inversion Theorem])[ Given a power serie $F(x)$ and another power series $G(x)$ related by $F(G(x))=G(F(x))=x$, then the nth coefficient of $F(x)$ is $ [x^n] F(x) = 1 / n [x^(-1)] 1 / (G^n (x)). $ ] #v(1em) ] #render("default") #render("boxed") #render("float") #render("thickness") #render("dashed") #state_block_theme.update("rounded") = Otherwise, you will get an error block! #state_block_theme.update("xxx") #note[Hello, World!]
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/experiment/weeks/week4.typ
typst
#import "../../utils.typ": * #section("Median") #subsection("Modus") - can be used as median - attribute that is seen most often - can be scalar or non-scalar - often not clear -> multiple Modi possible - example (1,2,6,5,3,4,3,) -> Modus 3 - attributes of Modus - easy and fast to determine - can be *used on any data* - not easily changed by extreme values -> unlike average - if all values appear the same amount -> all are modi #align(center, [#image("../../Screenshots/modus.png", width: 70%)]) #subsection("Median Definition") - needs a ranking -> nominal values not possible - e.g. must be ordinal -> ranked #set text(14pt) - depends on value - uneven -> Median $M = (n-1)/2 + 1$ - even -> Median $M = ((n/2)+(n/2+1))/2$ - only offers a difference of 2 sides -> lower than median and higher - not influenced by extreme values #align( center, [#image("../../Screenshots/2023_10_12_10_35_47.png", width: 70%)], ) #align(center, [#image("../../Screenshots/median.png", width: 70%)]) #set text(11pt) #subsection("*tile") - *Quantile* -> 2 parts, split by median - *Quartile* -> 4 parts -> 25% each - *Dezile* -> 10 parts -> 10% each - *Perzentile* -> 100 parts -> 1% each Calculation Quartile: #align( center, [#image("../../Screenshots/2023_10_12_11_01_13.png", width: 70%)], ) #set text(14pt) $M_e = u + (n/Q - (H_m - 1))/(H_m - (H_m - 1)) * (o - u)$\ #set text(11pt) - Q resembles the amount of \*tile -> here 4 - o starting x - u ending x - hm - 1 starting y - hm ending y #subsection("Arithmetic Mean") Average of each attribute($x_i$) applied to each object($h_i$).\ #set text(16pt) $accent(x, -) = 1 / n sum_(i=1)^v x_i * h_i$ #set text(11pt) - most used - often criticized -> extreme values influence outcome #subsection("Harmonic Mean") The *distance* from objects before and after the median is the same.\ #set text(16pt) $accent(M_H, -) = (sum_(i=1)^v h_i)/(sum_(i=1)^v h_i/x_i)$ #set text(11pt) - $h_i$ object - $x_i$ attribute of interest - $v$ amount of elements - no 0 values allowed -> div by 0! - attribute of interest must be relative #align( center, [#image("../../Screenshots/2023_10_12_11_21_57.png", width: 70%)], ) #subsection("Geometric Mean") - not comparable with the previous means - attributes need to be relative - $x_i$ is a quotient -> result of division - usually a starting value and end value -> for example for growth per year - value must be bigger than 0 -> div by 0! - the *only* method applicable for growth over a time span #align( center, [#image("../../Screenshots/2023_10_12_11_38_57.png", width: 70%)], ) #align(center, [ The growth for this image is 12.5%\ #set text(16pt) $M_G = root(n, (product_(i=1)^n x_i))$ ]) #set text(11pt) #section("Ranges") #subsection("Range (Spannweite)") - easy to understand - no information about values in this range - easily influenced by extreme values - attribute must be interval scalable Calculation:\ #set text(16pt) $R = text(min) - text(max)$\ R = Range #set text(11pt) #subsection("Central Quartile Distance (ZQA)") - not influenced by extreme values - attribute must be interval scalable - usable when a specific range is of interest #align( center, [#image("../../Screenshots/2023_10_12_11_54_08.png", width: 60%)], ) Calculation:\ #set text(16pt) $ text("ZQA") = Q_3 - Q_1$\ #set text(11pt) #align( center, [#image("../../Screenshots/2023_10_12_11_54_39.png", width: 70%)], ) #subsection("Mean absolute Difference (Mittlere absolute Abweichung)") - attributes must be interval scalable - better than variance - extreme values can be an issue Calculation:\ #set text(16pt) $delta = 1/n sum_(i=1)^v |x_i - accent(x, -)| h_i$\ - n: count of objects - v: count of attribute values - hi: absolute quantity of objects with a specific attribute value #set text(11pt) #align( center, [#image("../../Screenshots/2023_10_12_11_58_02.png", width: 70%)], ) #subsection("Variance / standard deviation") - attributes must be interval scalable - not easy to understand immediately - can't be interpreted - extreme values are a big issue - good for describing statistic but not for closing statistic Calculation:\ #set text(16pt) $sigma^2 = 1/n sum_(i=1)^v (x_i - accent(x, -)^2 * h_i)$\ - n: count of objects - v: count of attribute values - hi: absolute quantity of objects with a specific attribute value - $sigma$: variance / standard deviation #set text(11pt) #align( center, [#image("../../Screenshots/2023_10_12_11_58_28.png", width: 70%)], ) #subsection("Variation Coefficient") *The Division of Standard Deviation and arithmetic mean multiplied by 100.* - attribute must be interval scalable - comparison between the 2 means #align( center, [#image("../../Screenshots/2023_10_12_12_19_41.png", width: 70%)], ) #section("BoxPlot") #align( center, [#image("../../Screenshots/2023_10_12_12_20_04.png", width: 100%)], )
https://github.com/0xPARC/0xparc-intro-book
https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/src/fhe3.typ
typst
#import "preamble.typ":* = Levelled FHE from LWE <fhe> == The main idea: Approximate eigenvalues Now we want to turn the public-key encryption from @lwe-crypto into a levelled FHE scheme. In other words: We want to be able to encrypt bits (0s and 1s) and operate on them with AND and NOT gates. It might help to imagine that, instead of AND and NOT, the operations we want to encrypt are addition and multiplication. If $x$ and $y$ are bits, then NOT $x$ is just $1 - x$, and $x$ AND $y$ is just $x y$. But it's easier to do algebra with $+$ and $times$. Recall the setup from @lwe-crypto: We’re going pick some large integer $q$ (in practice $q$ could be anywhere from a few thousand to $2^1000$), and do "approximate linear algebra" modulo $q$. In other words, we’ll do linear algebra, where all our calculations are done modulo $q$ – but we’ll also allow the calculations to have a small "error" $epsilon.alt$, which will typically be much, much smaller than $q$. As before, our #emph[secret key] will be a vector of length $n$: $ upright(bold(v)) = (v_1, dots, v_n) in (ZZ \/ q ZZ)^n. $ Suppose we want to encode a message $mu$ that’s just a single bit, let’s say $mu in { 0 , 1 }$. Our ciphertext will be a square $n$-by-$n$ matrix $C$ such that $ C upright(bold(v)) approx mu upright(bold(v)) . $ Now if we assume that $upright(bold(v))$ has at least one "big" entry (say $v_i$), then decryption is easy: Just compute the $i$-th entry of $C upright(bold(v))$, and determine whether it is closer to $0$ or to $v_i$. #remark[ With a bit of effort, it’s possible to make this into a public-key cryptosystem too. Just like in @lwe-crypto, the main idea is to release a table of vectors $upright(bold(x))$ such that $ upright(bold(x)) dot.op upright(bold(v)) approx 0, $ and use that as a public key. Given $mu$ and the public key, you can find a matrix $C_0$ such that $ C_0 upright(bold(v)) approx 0 $ then take $ C = C_0 + mu Id, $ where $Id$ is the identity matrix. This gives a $C$ such that $ C upright(bold(v)) approx mu upright(bold(v)). $ #problem[How do we build such a $C_0$? (One possible direction is to build it row-by-row.)] ] == Operations on encrypted data To make homomorphic encryption work, we need to explain how to operate on $mu$. We’ll describe three operations: addition, NOT, and multiplication (aka AND). Addition is simple: Just add the matrices. If $C_1 upright(bold(v)) approx mu_1 upright(bold(v))$ and $C_2 upright(bold(v)) approx mu_2 upright(bold(v))$, then $ (C_1 + C_2) upright(bold(v)) = C_1 upright(bold(v)) + C_2 upright(bold(v)) approx mu_1 upright(bold(v)) + mu_2 upright(bold(v)) = (mu_1 + mu_2) upright(bold(v)) . $ Of course, addition on bits isn’t a great operation, because if you add $1 + 1$, you get $2$, and $2$ isn’t a legitimate bit anymore. So we won’t really use this. Negation of a bit (NOT) is equally simple. If $mu in { 0 , 1 }$ is a bit, then its negation is simply $1 - mu$. And if $C$ is a ciphertext for $mu$, then $Id - C$ is a ciphertext for $1 - mu$, since $ (Id - C) upright(bold(v)) = upright(bold(v)) - C upright(bold(v)) approx (1 - mu) upright(bold(v)) . $ Multiplication is also a good operation on bits – it’s just AND. To multiply two bits, you just multiply (matrix multiplication) the ciphertexts: $ C_1 C_2 upright(bold(v)) approx C_1 (mu_2 upright(bold(v))) = mu_2 C_1 upright(bold(v)) approx mu_2 mu_1 upright(bold(v)) = mu_1 mu_2 upright(bold(v)) . $ At this point you might be concerned about this symbol $approx$ and what happens to the size of the error. That’s an important issue, and we'll resolve it with the help of a special operation called "Flatten." Anyway, once you have AND and NOT, you can build arbitrary logic gates – and this is what we mean when we say you can perform arbitrary calculations on your encrypted bits, without ever learning what those bits are. At the end of the calculation, you can send the resulting ciphertexts back to be decrypted. == The "Flatten" operation <a-constraint-on-the-secret-key-mathbfv-and-the-flatten-operation> In order to make the error estimates work out, we’re going to need to make it so that all the ciphertext matrices $C$ have "small" entries. In fact, we will be able to make it so that all entries of $C$ are either $0$ or $1$. To make this work, we will assume our secret key $upright(bold(v))$ has the special form #eqn[ $ upright(bold(v)) = ( & a_1 , 2 a_1 , 4 a_1 , dots.h , 2^k a_1, \ & a_2 , 2 a_2 , 4 a_2 , dots.h , 2^k a_2 , \ & dots.v \ & a_r , 2 a_r , 4 a_r , dots.h , 2^k a_r) , $ <fhe-v-form> ] where $k = ⌊log_2 q⌋$. To see how this helps us, try the following puzzle. Assume $q = 11$ (so all our vectors have entries modulo 11), and $r = 1$, so our secret key has the form $ upright(bold(v)) = (a_1 , 2 a_1 , 4 a_1 , 8 a_1) . $ You know $upright(bold(v))$ has this form, but you don’t know the specific value of $a_1$. Now suppose I give you the vector $ upright(bold(x)) = (9 , 0 , 0 , 0) . $ I ask you for another vector $ "Flatten"(upright(bold(x))) = upright(bold(x)) prime , $ where $upright(bold(x)) prime$ has to have the following two properties: - $upright(bold(x)) prime dot.op upright(bold(v)) = upright(bold(x)) dot.op upright(bold(v))$, and - All the entries of $upright(bold(x)) prime$ are either 0 or 1. And you have to find this vector $upright(bold(x)) prime$ without knowing $a_1$. The solution is to use binary expansion: take $upright(bold(x)) prime = (1 , 0 , 0 , 1)$. You should check for yourself to see why this works – it boils down to the fact that $(1 , 0 , 0 , 1)$ is the binary expansion of $9$. #problem[ How would you flatten a different vector, like $ upright(bold(x)) = (9 , 3 , 1 , 4) ? $ As a hint, remember we’re working with numbers modulo 11: so if you come across a number that’s bigger than 11 in your calculation, it’s safe to reduce it mod 11. ] In general, if you know that $upright(bold(v))$ has the form in @fhe-v-form and you are given some matrix $C$ with coefficients in $ZZ \/ q ZZ$, then you can compute another matrix $"Flatten"(C)$ such that: - $"Flatten"(C) upright(bold(v)) = C upright(bold(v))$, and - All the entries of $"Flatten"(C)$ are either 0 or 1. The $"Flatten"$ process is essentially the same binary-expansion process we used above to turn $upright(bold(x))$ into $upright(bold(x)) prime$, applied to each $k + 1$ entries of each row of the matrix $C$. So now, using this $"Flatten"$ operation, we can insist that all of our ciphertexts $C$ are matrices with coefficients in ${ 0 , 1 }$. For example, to multiply two messages $mu_1$ and $mu_2$, we first multiply the corresponding ciphertexts, then flatten the resulting product: $ "Flatten"(C_1 C_2) . $ Of course, revealing that the secret key $upright(bold(v))$ has this special form will degrade security. This cryptosystem is as secure as an LWE problem on vectors of length $r$, not $n$. So we need to make $n$ bigger, say $n approx r log q$, to get the same level of security. == Error analysis <error-analysis> Now let’s compute more carefully what happens to the error when we add, negate, and multiply bits. Suppose $ C_1 upright(bold(v)) = mu_1 upright(bold(v)) + upright(bold(epsilon))_1 , $ where $upright(bold(epsilon))_1$ is some vector with all its entries bounded by some $B$. (And similarly for $C_2$ and $mu_2$.) When we add two ciphertexts, the errors add: $ (C_1 + C_2) upright(bold(v)) = (mu_1 + mu_2) upright(bold(v)) + (upright(bold(epsilon))_1 + upright(bold(epsilon))_2) . $ So the error on the sum will be bounded by $2 B$. Negation is similar to addition – in fact, the error won’t change at all. Multiplication is more complicated, and this is why we insisted that all ciphertexts have entries in ${ 0 , 1 }$. We compute $ C_1 C_2 upright(bold(v)) = C_1 (mu_2 upright(bold(v)) + upright(bold(epsilon))_2) = mu_1 mu_2 upright(bold(v)) + (mu_2 upright(bold(epsilon))_1 + C_1 upright(bold(epsilon))_2) . $ Now since $mu_2$ is either $0$ or $1$, we know that $mu_2 upright(bold(epsilon))_1$ is a vector with all entries bounded by $B$. What about $C_1 upright(bold(epsilon))_2$? Here we have to think carefully about matrix multiplication: when you multiply an $n$-by-$n$ matrix by a vector, each entry of the product comes as a sum of $n$ different products. Now we’re assuming that $C_1$ is a $0$-$1$ matrix, and all entries of $upright(bold(epsilon))_2$ are bounded by $B$… so the product has all entries bounded by $n B$. Adding this to the error for $mu_2 upright(bold(epsilon))_1$, we get that the total error in the product $C_1 C_2 upright(bold(v))$ is bounded by $(n + 1) B$. In summary: We can start with ciphertexts having a very small error (if you think carefully about this protocol, you will see that the error is bounded by approximately $n log q$). Every addition operation will double the error bound; every multiplication (AND gate) will multiply it by $(n + 1)$. And you can’t allow the error to exceed $q \/ 2$ – otherwise the message cannot be decrypted. So you can perform calculations of up to approximately $log_n q$ steps. (In fact, it’s a question of #emph[circuit depth];: you can start with many more than $log_n q$ input bits, but no bit can follow a path of length greater than $log_n q$ AND gates.) This gives us a #emph[levelled] FHE protocol: it lets us evaluate arbitrary circuits on encrypted data, as long as those circuits have bounded depth. If we need to evaluate a bigger circuit, we have two options: + Increase the value of $q$. Of course, the cost of the computations increases with $q$. + Use some technique to "reset" the error and start anew, as if with a freshly encrypted ciphertext. This approach is called _bootstrapping_ and it incurs some hefty computational costs. But for large circuits, it's the only viable option. Bootstrapping is beyond the scope of this book.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/set-04.typ
typst
Other
// Test relative path resolving in layout phase. #let choice = ("monkey.svg", "rhino.png", "tiger.jpg") #set enum(numbering: n => { let path = "/" + choice.at(n - 1) move(dy: -0.15em, image(path, width: 1em, height: 1em)) }) + Monkey + Rhino + Tiger
https://github.com/domoritz/tvcg-journal-typst
https://raw.githubusercontent.com/domoritz/tvcg-journal-typst/main/template/main.typ
typst
MIT No Attribution
#import "@preview/tvcg-journal:0.0.1": tvcg #show: tvcg.with( title: [Global Illumination for Fun and Profit], abstract: [ #lorem(150) A free copy of this paper and all supplemental materials are available at https://OSF.IO/2NBSG. ], authors: ( ( name: "<NAME>", organization: [Brown University], orcid: "0000-0002-1825-0097", email: "<EMAIL>" ), ( name: "<NAME>", organization: [Grimley Widgets, Inc.], email: "<EMAIL>" ), ( name: "<NAME>", organization: [Martha Stewart Enterprises at Microsoft Research], email: "<EMAIL>" ), ), teaser: ( image: image("figs/CypressView.jpg", alt: "A view of a city with buildings peeking out of the clouds."), caption: "In the Clouds: Vancouver from Cypress Mountain. Note that the teaser may not be wider than the abstract block." ), index-terms: ("Radiosity", "Global Illumination", "Constant Time"), bibliography: bibliography("refs.bib"), ) = Introduction This template is for papers of VGTC-sponsored conferences such as IEEE VIS, IEEE VR, and ISMAR which are published as special issues of TVCG. The template does not contain the respective dates of the conference/journal issue, these will be entered by IEEE as part of the publication production process. Therefore, *please leave the copyright statement at the bottom-left of this first page untouched*. = Author Details You should specify ORCID IDs for each author (see https://orcid.org/ to register) for disambiguation and long-term contact preservation. The template shows an example without ORCID IDs for two of the authors. ORCID IDs should be provided in all cases. = Hyperlinks and Cross References Links are automatically shown for URLs but you can customize the name of the link with the `#link` function: https://typst.app/docs/reference/model/link/. = Figures Typst automatically detects the type of figure (i.e., table, image, or code) and label them accordingly. Figures are documented at https://typst.app/docs/reference/model/figure/. for figures with images, the image format is usually detected automatically. For details, head over to the image documentation: https://typst.app/docs/reference/visualize/image/. #figure( image("figs/CypressView.jpg", alt: "A view of a city with buildings peeking out of the clouds."), caption: "Caption", ) #figure( grid(columns: 2, row-gutter: 2mm, column-gutter: 1mm, image("figs/CypressView.jpg", alt: "A view of a city with buildings peeking out of the clouds."), align(horizon)[#image("figs/CypressView.jpg", alt: "A view of a city with buildings peeking out of the clouds.")]), caption: "Caption" ) == Vector figures Vector graphics like svg, eps, pdf are best for charts and other figures with text or lines. They will look much nicer and crisper and any text in them will be more selectable, searchable, and accessible. == Raster figures Of the raster graphics formats, screenshots of user interfaces and text, as well as line art, are better shown with png. jpg is better for photographs. Make sure all raster graphics are captured in high enough resolution so they look crisp and scale well. == Alternative texts Always include an alternative text that describes the image. The alt text should not be the same as the caption, but should describe the image in a way that makes sense when the image is not visible. == Figures on the first page The teaser figure should only have the width of the abstract as the template enforces it. The use of figures other than the optional teaser is not permitted on the first page. Other figures should begin on the second page. Papers submitted with figures other than the optional teaser on the first page will be refused. == Code Typst supports code blocks and inline code: https://typst.app/docs/reference/text/raw/. For example ```rust fn main() { println!("Hello World!"); } ``` = References An example of the reference formatting is provided in the *References* section at the end. == Include DOIs All references which have a DOI should have it included in the bibTeX for the style to display. The DOI can be entered with or without the https://doi.org/ prefix. = Paper overview In this paper we introduce Typst, a new typesetting system designed to streamline the scientific writing process and provide researchers with a fast, efficient, and easy-to-use alternative to existing systems. Our goal is to shake up the status quo and offer researchers a better way to approach scientific writing. Here is a reference: @netwok2020. By leveraging advanced algorithms and a user-friendly interface, Typst offers several advantages over existing typesetting systems, including faster document creation, simplified syntax, and increased ease-of-use. To demonstrate the potential of Typst, we conducted a series of experiments comparing it to other popular typesetting systems, including LaTeX. Our findings suggest that Typst offers several benefits for scientific writing, particularly for novice users who may struggle with the complexities of LaTeX. Additionally, we demonstrate that Typst offers advanced features for experienced users, allowing for greater customization and flexibility in document creation. Overall, we believe that Typst represents a significant step forward in the field of scientific writing and typesetting, providing researchers with a valuable tool to streamline their workflow and focus on what really matters: their research. In the following sections, we will introduce Typst in more detail and provide evidence for its superiority over other typesetting systems in a variety of scenarios. = Methods #lorem(90) $ a + b = gamma $ #lorem(200) = Acknowledgments The authors wish to thank A, B, and C. This work was supported in part by a grant from XYZ (\# 12345-67890).
https://github.com/sitandr/typst-examples-book
https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/typstonomicon/chapters.md
markdown
MIT License
# Create zero-level chapters ```typ // author: tinger #let chapter = figure.with( kind: "chapter", // same as heading numbering: none, // this cannot use auto to translate this automatically as headings can, auto also means something different for figures supplement: "Chapter", // empty caption required to be included in outline caption: [], ) // emulate element function by creating show rule #show figure.where(kind: "chapter"): it => { set text(22pt) counter(heading).update(0) if it.numbering != none { strong(it.counter.display(it.numbering)) } + [ ] + strong(it.body) } // no access to element in outline(indent: it => ...), so we must do indentation in here instead of outline #show outline.entry: it => { if it.element.func() == figure { // we're configuring chapter printing here, effectively recreating the default show impl with slight tweaks let res = link(it.element.location(), // we must recreate part of the show rule from above once again if it.element.numbering != none { numbering(it.element.numbering, ..it.element.counter.at(it.element.location())) } + [ ] + it.element.body ) if it.fill != none { res += [ ] + box(width: 1fr, it.fill) + [ ] } else { res += h(1fr) } res += link(it.element.location(), it.page) strong(res) } else { // we're doing indenting here h(1em * it.level) + it } } // new target selector for default outline #let chapters-and-headings = figure.where(kind: "chapter", outlined: true).or(heading.where(outlined: true)) // // start of actual doc prelude // #set heading(numbering: "1.") // can't use set, so we reassign with default args #let chapter = chapter.with(numbering: "I") // an example of a "show rule" for a chapter // can't use chapter because it's not an element after using .with() anymore #show figure.where(kind: "chapter"): set text(red) // // start of actual doc // // as you can see these are not elements like headings, which makes the setup a bit harder // because the chapters are not headings, the numbering does not include their chapter, but could using a show rule for headings #outline(target: chapters-and-headings) #chapter[Chapter] = Chap Heading == Sub Heading #chapter[Chapter again] = Chap Heading = Chap Heading == Sub Heading === Sub Sub Heading == Sub Heading #chapter[Chapter yet again] ```
https://github.com/storopoli/graphs-complexity
https://raw.githubusercontent.com/storopoli/graphs-complexity/main/slides/slides-pt.typ
typst
Creative Commons Zero v1.0 Universal
#import "@preview/slydst:0.1.0": * #import "@preview/diagraph:0.2.5": * #import "@preview/lovelace:0.3.0": * #set text(lang: "pt") #show: slides.with( title: "Teoria dos Grafos e Complexidade Computacional", subtitle: none, date: none, authors: ("<NAME>, PhD",), layout: "medium", ratio: 4 / 3, title-color: orange, ) #set text(size: 16pt) #show link: set text(blue) /* Level-one headings corresponds to new sections. Level-two headings corresponds to new slides. Blank space can be filled with vertical spaces like #v(1fr). */ == Licença #align(horizon + center)[#image("images/cc-zero.svg", width: 80%)] == Links #align(horizon + center)[ Todos os links estão em #text(blue)[azul]. Sinta-se à vontade para clicar neles. ] == Conteúdo #outline() = Por que estudar Teoria dos Grafos e Complexidade Computacional? #align(horizon + center)[#image( "images/algorithm_analysis_meme.jpg", width: 50%, )] == Teoria Computação #align(horizon)[ A *teoria da computação* é subcampo da ciência da computação e matemática que busca determinar quais problemas podem ser computados em um dado modelo de computação. A *computação* pode ser definida como o cálculo de uma função por meio de um algoritmo. ] == #link("https://en.wikipedia.org/wiki/Alan_Turing")[Turing] vs. #link("https://en.wikipedia.org/wiki/Alonzo_Church")[Church] #align(horizon + center)[ #figure( grid( columns: 2, gutter: 2mm, image("images/turing.jpg", width: 60%), image("images/church.jpg", width: 60%), ), caption: "<NAME> e <NAME>", )<turing-church> ] #pagebreak() #align(horizon)[ - Turing propôs a *máquina de Turing* como modelo de computação. - Alonzo Church propôs o *cálculo lambda* como modelo de computação. - Ambos os modelos são matematicamente *equivalentes*. ] == Algoritmo #align(horizon)[ *Algoritmo* é uma sequência finita de ações executáveis que visam obter uma solução para um determinado tipo de problema. ] == Teoria dos Grafos #align(horizon)[ Por que estudar Grafos? #v(1em) #align(center)[ _Quase_ tudo que você faz em computação pode ser modelado como um *problema de grafos*. ] ] == Complexidade Computacional #align(horizon)[ *Complexidade Computacional* é um campo da ciência da computação que estuda a quantidade de recursos necessários para resolver um problema computacional#footnote[ um problema decidível. ]. ] #pagebreak() #align(horizon)[ Usamos a notação $O$ para descrever a complexidade de um algoritmo. - $O(1)$ (complexidade *constante*): - Acessar uma _array_ - Inserir um nó em uma lista encadeada - Inserção e remoção em uma fila - $O(log n)$ (complexidade *logarítmica*): - Busca binária - Inserção e remoção em uma árvore binária de busca #pagebreak() - $O(n)$ (complexidade *linear*): - Percorrer um _array_ - Percorrer uma lista encadeada - Comparar duas _strings_ - $O(n log n)$ (complexidade *log-linear*): - Algoritmo de ordenação _Quick Sort_ - Algoritmo de ordenação _Merge Sort_ #pagebreak() - $O(n^2)$ (complexidade *quadrática*): - Percorrer uma matriz - Algoritmo de ordenação _Bubble Sort_ - Algoritmo de ordenação _Insertion Sort_ - $O(n^3)$ (complexidade *cúbica*): - Multiplicação de matrizes (abordagem ingênua) - $O(n!)$ (complexidade *fatorial*): - Solução do problema do caixeiro-viajante - Gerar todas as permutações de uma lista ] = Grafos #align(horizon + center)[#image( "images/graph_isomorphism_meme.jpg", width: 50%, )] == O que são Grafos? Grafos são estruturas matemáticas que modelam *relações entre objetos*. #align(horizon + center)[ #figure( raw-render(```dot graph G { rankdir=LR; layout=dot; a -- {b, c}; b -- {c, d}; c -- e; d -- e; e -- f; {rank=same; a;}; {rank=same; b; c;}; {rank=same; d; e;}; {rank=same; f;}; } ```), caption: "Grafo", ) <graph> ] == Formalmente Grafos são *pares ordenados* $G = (V, E)$ onde: - $V$ é um conjunto finito de *vértices* (também chamados de nós) - $E$ é um conjunto finito de *arestas* (também chamadas de arcos) representado por um par de vértices $(u, v)$ A @graph, por exemplo: #text(size: 14pt)[ $ V = \{a, b, c, d, e, f\} $ $ E = \{(a, b), (a, c), (b, c), (b, d), (c, e), (d, e), (e, f)\} $ ] == Grafos Direcionados Grafos podem ser *direcionados* ou *_não_-direcionados*. #align(horizon + center)[ #figure( raw-render(```dot digraph G { rankdir=LR; layout=dot; a -> {b, c}; b -> c; c -> e; d -> {b, e}; e -> f; {rank=same; a;}; {rank=same; b; c;}; {rank=same; d; e;}; {rank=same; f;}; } ```), caption: "Grafo Direcionado", ) <directed-graph> ] == Grafos Ponderados Grande parte dos grafos são *ponderados*, isto é, possuem valores associados às arestas. #align(horizon + center)[ #figure( raw-render(```dot graph G { rankdir=LR; layout=dot; a -- b [label=2]; a -- c [label=3]; b -- c [label=1]; b -- d [label=4]; c -- e [label=1]; d -- e [label=2]; e -- f [label=1]; {rank=same; a;}; {rank=same; b; c;}; {rank=same; d; e;}; {rank=same; f;}; } ```), caption: "Grafo Ponderado", ) <weighted-graph> ] == Exemplos de Grafos #align(horizon)[ - Redes de computadores - Redes sociais - Mapas de cidades - Estruturas moleculares ] == #link("https://en.wikipedia.org/wiki/Seven_Bridges_of_K%C3%B6nigsberg")[As 7 pontes de Königsberg] Primeira aplicação prática da teoria dos grafos, resolvida por Euler em 1736. #align(center)[ *É possível atravessar todas as pontes sem repetir nenhuma?* ] #align(horizon + center)[ #figure( image("images/konigsberg_briges.png", width: 35%), caption: "As 7 pontes de Königsberg", ) <konigsberg-brigdes> ] == #link("https://en.wikipedia.org/wiki/Seven_Bridges_of_K%C3%B6nigsberg")[As 7 pontes de Königsberg] #align(horizon + center)[ #figure( raw-render(```dot graph G { rankdir=LR; splines=curved; layout=neato; a[pos="-1,0!"]; b[pos="0,1!"]; c[pos="0,-1!"]; d[pos="1,0!"]; a -- {b, c, d}; b:w -- a; c:w -- a; b -- d; c -- d; } ```), caption: "Grafo das 7 pontes de Königsberg", ) <graph-konigsberg-brigdes> ] == Solução das 7 pontes #align(horizon)[ A solução do problema de Königsberg foi dada por Euler. O grafo precisa de *duas condições* para ser resolvido: - O grafo deve ser *totalmente conectado* - O grafo deve ter exatamente *0 ou 2 vértices de grau ímpar* ] == #link("https://en.wikipedia.org/wiki/Four_color_theorem")[O teorema das 4 cores] #align(horizon)[ *Não mais do que quatro cores são necessárias para colorir as regiões de qualquer mapa, de modo que duas regiões adjacentes não tenham a mesma cor.* ] #pagebreak() #align(horizon + center)[ #figure( image("images/four_color_graph.svg", width: 50%), caption: "Abstração de um mapa com 4 cores usando grafos", ) <four-color-map> ] #text(size: 14pt)[ O teorema foi provado em 1976 por <NAME> e <NAME>#footnote[ um dos primeiros teoremas provados auxiliado por computadores. ]. ] == Aplicações dos Grafos - Itinerários de companhias aéreas: Calcular o fluxo máximo em um grafo direcionado. - Software de roteamento (GPS): Calcular o menor caminho entre dois pontos. - Solucionar um sudoku: Resolver um problema de coloração de grafos. - Algoritmos de busca online: Determinar centralidades de vértices com base em temas. - Redes sociais: encontrar a maior comunidade de amigos. == Subgrafos Um *subgrafo* de um grafo $G$ é outro grafo formado a partir de um *subconjunto dos vértices e arestas de $G$*. O subconjunto de vértices deve incluir todos os vértices das arestas, mas pode incluir vértices adicionais. #align(horizon + center)[ #figure( image("images/subgraph.svg", width: 40%), caption: "Subgrafo", ) <subgraph> ] == Subgrafo Induzido Um *subgrafo induzido* é um subgrafo que *inclui todos os vértices e arestas* cujos extremos pertencem ao subconjunto de vértices. #align(horizon + center)[ #figure( image("images/induced_subgraph.svg", width: 50%), caption: "Subgrafo Induzido", ) <induced-subgraph> ] == Isomorfismo Um isomorfismo dos grafos $G$ e $H$ e uma bijeção#footnote[ uma função que estabelece uma correspondência biunívoca entre os elementos de dois conjuntos. ] entre os conjuntos de vértices de $G$ e $H$: $ f: V(G) -> V(H) $ #align(horizon + center)[ #figure( image("images/graph_isomorphism.png", width: 66%), caption: "Grafos Isomórficos", ) <isomorphic-graphs> ] == Representação de Grafos #align(horizon)[ Há várias formas de representar grafos, as mais comuns são: - *Matriz de adjacência* - *Lista de adjacência* ] == Matriz de Adjacência #align(horizon)[ Uma *matriz de adjacência* é uma matriz quadrada $bold(A)$ de tamanho $n times n$: $ bold(A)^(n times n) = a_(i j) $ onde $a_(i j)$ é o número de arestas entre os vértices $i$ e $j$. ] #pagebreak() #align(horizon + center)[ #figure( grid( columns: 2, gutter: 2mm, text[$ bold(A) = mat( 1, 1, 0, 0, 1, 0;1, 0, 1, 0, 1, 0;0, 1, 0, 1, 0, 0;0, 0, 1, 0, 1, 1;1, 1, 0, 1, 0, 0;0, 0, 0, 1, 0, 0; ) $], raw-render( ```dot graph G { layout=neato; rankdir=LR; 1 -- {1, 2, 5}; 2 -- {3, 5}; 3 -- {4}; 4 -- {5, 6}; } ```, width: 80%, ), ), caption: "Matriz de adjacência e Grafo", ) <adjacency-matrix> ] #pagebreak() #align(horizon)[ Propriedades de uma matriz de adjacência#footnote[ $n$ é o número de vértices do grafo. ]: - Simétrica para grafos não-direcionados - Não-simétrica para grafos direcionados - Custo de espaço $O(n^2)$ - Custo de construção $O(n^2)$ - Custo de busca de arestas $O(1)$ ] == Lista de Adjacência #align(horizon)[ Uma *lista de adjacência* é uma lista de listas, onde cada lista $L_i$ contém os vértices adjacentes ao vértice $i$. ] #pagebreak() #align(horizon + center)[ #figure( grid( columns: 2, gutter: 2mm, table( columns: 2, table.header([*Vértice*], [*Vizinhos*]), [1], [1, 2, 5], [2], [1, 3, 5], [3], [2, 4], [4], [3, 5, 6], [5], [1, 2, 4], [6], [4], ), raw-render( ```dot graph G { layout=neato; rankdir=LR; 1 -- {1, 2, 5}; 2 -- {3, 5}; 3 -- {4}; 4 -- {5, 6}; } ```, width: 80%, ), ), caption: "Lista de adjacência e Grafo", ) <adjacency-list> ] #pagebreak() #align(horizon)[ Propriedades de uma lista de adjacência#footnote[ $n$ é o número de vértices do grafo e $m$ é o número de arestas. ]: - Custo de espaço $O(n + m)$#footnote[para grafos não-direcionados.]<adjacency-list-cost> - Custo de construção $O(m)$#footnote(<adjacency-list-cost>) - Custo de busca de arestas $O(n)$ ] == Parte Prática (C ou pseudocódigo) #align(horizon)[ - Representar um grafo direcionado e não-direcionado - Parsear um grafo de uma matriz de adjacência - Parsear um grafo de uma lista de adjacência ] == Caminhos e Ciclos #align(horizon)[ #text(size: 14pt)[ *Caminho* é uma sequência de vértices tal que de cada um dos vértices existe uma aresta para o vértice seguinte. Um caminho é chamado *simples* se nenhum dos vértices no caminho se repete. O *comprimento* do caminho é o número de arestas que o caminho usa, contando-se arestas múltiplas vezes. O *custo* de um caminho num grafo balanceado é a soma dos custos das arestas atravessadas. Dois caminhos são *independentes* se não tiverem nenhum vértice em comum, exceto o primeiro e o último. ] ] #pagebreak() #align(horizon + center)[ #figure( raw-render(```dot graph G { rankdir=LR; layout=dot; a -- b[color=red]; a -- c; b -- c[color=red]; a -- d; c -- e[color=red]; d -- e; e -- f[color=red]; {rank=same; a;}; {rank=same; b; c;}; {rank=same; d; e;}; {rank=same; f;}; } ```), caption: "Caminho de Comprimento 4", ) <path> ] #pagebreak() #align(horizon)[ Um *ciclo* é um caminho em que o *primeiro e o último vértice coincidem*, mas nenhum outro vértice é *repetido*. ] #pagebreak() #align(horizon + center)[ #figure( raw-render(```dot graph G { rankdir=LR; layout=dot; a -- b; a -- c[color=red]; b -- c; a -- d[color=red]; c -- e[color=red]; d -- e[color=red]; e -- f; {rank=same; a;}; {rank=same; b; c;}; {rank=same; d; e;}; {rank=same; f;}; } ```), caption: "Ciclo de Comprimento 4", ) <cycle> ] == Caminho Euleriano #align(horizon)[ *Caminho Euleriano* é o caminho que usa cada aresta exatamente uma vez. Se tal caminho existir, o grafo é chamado traversável. Um *ciclo Euleriano* é um ciclo que usa cada aresta exatamente uma vez. ] == Caminho Hamiltoniano #align(horizon)[ *Caminho Hamiltoniano* é o caminho que visita cada vértice exatamente uma vez. Um *ciclo Hamiltoniano*#footnote[ curiosidade: um dos primeiros esquemas de zero-knowledge proofs foi baseado em achar um ciclo Hamiltoniano em um grafo gigante. Para mais detalhes, veja a #link( "https://en.wikipedia.org/wiki/Zero-knowledge_proof#Hamiltonian_cycle_for_a_large_graph", )[Wikipedia] e o #link( "https://web.archive.org/web/20230103032937/http://euler.nmt.edu/~brian/students/pope.pdf", )[paper original]. ] é um ciclo que visita cada vértice uma só vez. ] == #link("https://en.wikipedia.org/wiki/Travelling_salesman_problem")[Problema do caixeiro-viajante] O *problema do caixeiro-viajante* (PCV) é um problema que tenta determinar a menor rota para percorrer uma série de cidades (visitando uma única vez cada uma delas), retornando à cidade de origem. #align(horizon + center)[ #figure( raw-render( ```dot graph G { layout=neato; 1[pos="0,0!"] 2[pos="2,1!"] 3[pos="4,0.5!"] 4[pos="1,-1!"] 5[pos="3,-1!"] 1 -- 2[label=2]; 1 -- 4[label=3]; 1 -- 5[label=6]; 2 -- 3[label=4]; 2 -- 4[label=3]; 3 -- 4[label=7]; 3 -- 5[label=3]; 4 -- 5[label=3]; } ```, width: 50%, ), caption: "Problema do Cacheiro-Viajante", ) <travelling-salesman-problem> ] #pagebreak() #align(horizon)[ Formulando em termos de grafos, o PCV é um problema de encontrar um ciclo Hamiltoniano tal que o custo do ciclo seja o menor possível. $ C = min_("ciclo") sum_(i=1)^n c_(i, i+1) $ ] == Parte Prática (C ou pseudocódigo) #align(horizon)[ - Encontrar um caminho Euleriano em C - Encontrar um ciclo Hamiltoniano em C ] = Árvores #align(horizon + center)[#image("images/trees_meme.jpg", width: 50%)] == O que são Árvores? Árvores são grafos *acíclicos* e *conectados*. #align(horizon + center)[ #figure( raw-render( ```dot digraph G { a -> {b, c}; b -> d; c -> {e, f}; } ```, width: 50%, ), caption: "Árvore", ) <tree> ] #pagebreak() #align(horizon)[ - *Raiz*: o vértice sem arestas entrantes. Todas as árvores têm (apenas) um vértice raiz. - *Folha*: vértice sem arestas saindo. - *Nível*: distância da raiz. - *Altura*: nível máximo. - *Pai*: vértice(s) com menor nível (mais próximo da raiz). - *Filho*: vértice(s) maior nível (mais distante da raiz). - *Ancestral*: vértice(s) com menor nível. - *Descendente*: vértice(s) com maior nível. ] == Subárvores Subárvores são árvores que são subconjuntos de uma árvore. #align(horizon + center)[ #figure( raw-render( ```dot digraph G { a b c[color=red,fontcolor=red] e[color=red,fontcolor=red]; f[color=red,fontcolor=red]; a -> {b, c}; b -> d; c -> {e, f}[color=red]; } ```, width: 45%, ), caption: "Subárvore", ) <subtree> ] == Tipos de Árvores #align(horizon + center)[ #figure( raw-render(```dot digraph G { a -> b b -> c; } ```), caption: "Árvore Caminho", ) <tree-path> ] #pagebreak() #align(horizon + center)[ #figure( raw-render( ```dot graph G { layout=circo; a -- {b, c, d, e , f, g}; } ```, width: 66%, ), caption: "Árvore Estrela", ) <tree-path> ] #pagebreak() #align(horizon + center)[ #figure( raw-render( ```dot // taken from https://stackoverflow.com/a/23430742 digraph G { nodesep=0.2; ranksep=0.5; {node[style=invis,label=""]; cx_d;} {node[style=invis, label="", width=.1]; ocx_f; ocx_b;} {rank=same; b; f; cx_d} {rank=same; a; c; ocx_b} {rank=same; e; g; ocx_f} d -> b; d -> f; b -> a; b -> c; f -> e; f -> g; { edge[style=invis]; // Distantiate nodes d -> cx_d; b -> cx_d -> f; // Force ordering between children f -> ocx_f; e -> ocx_f -> g; b -> ocx_b; a -> ocx_b -> c; } } ```, width: 50%, ), caption: "Árvore Binária", ) <tree-binary> ] == Árvores Balanceadas Uma árvore é *balanceada* se a diferença de altura entre as subárvores esquerda e direita é no máximo 1. #align(horizon + center)[ #figure( raw-render( ```dot digraph G { a -> {b, c}; b -> d; c -> {e, f}; } ```, width: 45%, ), caption: "Árvore Balanceada", ) <balanced-tree> ] #pagebreak() #align(horizon + center)[ #figure( raw-render( ```dot digraph G { a -> {b, c}; c -> {d, e}; d -> f; } ```, width: 40%, ), caption: "Árvore Desbalanceada", ) <unbalanced-tree> ] == Parte Prática (C ou pseudocódigo) #align(horizon)[ - Detectar se um grafo é uma árvore (ou seja, se é acíclico e conectado) - Detectar qual é o vértice raiz de uma árvore ] = Interlúdio: Funções Polinomiais e Exponenciais #align(horizon + center)[#image("images/polynomials_meme.jpg", width: 50%)] == Funções Polinomiais #align(horizon)[ Uma função é polinomial se ela pode ser expressa na forma $ O(a_n dot n^k + a_(n-1) dot n^(k-1) + ... + a_1 dot n + a_0) $ onde: - $n$ é o tamanho da entrada - $k$ é uma constante - $a_n, a_{n-1}, ..., a_1, a_0$ são coeficientes constantes ] == Exemplos #align(horizon)[ - $n$ - $n^2 + 3n + 2$ - $4n^4 + n^3 + 2n^2 + 7$ - $n^(100) + 500n^(50) + 3000$ ] == Notação $O$ #text(size: 15pt)[ #align(horizon)[ A notação $O$ é usada para descrever a complexidade de um algoritmo. Por exemplo, na função $n^3 + n^2 + 5n + 100$, a maior constante $k = 3$ assimptoticamente#footnote[ a medida que algo tende ao infinito, ou seja $lim -> oo$. ] dominará o tempo de computação, então a complexidade é $O(n^3)$. Também em notação $O$, desconhecemos os coeficientes constantes. Por exemplo, $O(3n^2)$ é simplificado para $O(n^2)$ e $50 O(1)$ é simplificado para $O(1)$. ] ] == Tipos de Complexidade Polinomial #align(horizon)[ - Constante: $O(1)$ - Logarítmica: $O(log n)$ - Linear: $O(n)$ - Log-linear#footnote[também chamada de linearítimica.]: $O(n log n)$ - Quadrática: $O(n^2)$ - Cúbica: $O(n^3)$ - Polinomial: $O(n^k)$ ] == Funções Exponenciais #align(horizon)[ Uma função é exponencial se ela pode ser reduzida usando notação $O$ para $ O(n^m) $ onde $m$ *_não_* é uma constante positiva. Por exemplo, $O(2^n)$ é uma complexidade exponencial#footnote[ note que $n$ não é constante. ]. ] == Tipos de Complexidade Exponencial #align(horizon)[ - Exponencial: $2^n$ - Fatorial: $n!$ - Superexponencial: $n^n$ - Duplamente exponencial: $2^(2^n)$ ] = Complexidade Computacional #align(horizon + center)[#image("images/big_o_meme.jpg", width: 45%)] == Definição #align(horizon)[ Complexidadiade computacional de um algoritmo é o *número de operações computacionais (tais como operaçõe aritméticas, comparações, e acessos a memória) requerido para sua execução*. #v(1em) Este número claramente depende do tamanho e da natureza dos inputs. ] == Complexidade Limitada #align(horizon)[ Se a complexidade de um algoritmo é limitada por uma função $f(n)$, onde $f$ é uma função polinomial de $n$ (tamanho do input), então o algoritmo é dito ter complexidade *polinomial*. #v(1em) Algoritmos com complexidade polinomial pertencem a classe $cal(P)$ ] == Classe $cal(P)$ #align(horizon)[ Um *problema de decisão* é um problema que tem como resposta *sim* ou *não*. Tal problema pertence a classe $cal(P)$ se existe um algoritmo que solucione qualquer instância do problema em *complexidade polinomial*. ] == Classe $cal(N P)$ #align(horizon)[ Um problema de decisão pertence a classe $cal(N P)$ se existe um *algoritmo em tempo polinomial que _verifique_ a solução de um problema*. #v(1em) É trivial estabelecer que $cal(P) subset.eq cal(N P)$. ] == Exemplos de Problemas $cal(P)$ e $cal(N P)$ #align(horizon)[ - Classe $cal(P)$: - Algoritmos de ordenação - Algortimos de busca - Classe $cal(N P)$: - Problema da fatoração de inteiros em primos - Problema do caixeiro-viajante ] == $cal(P)$ vs $cal(N P)$ #text(size: 9.8pt)[ #table( columns: 3, align: left + horizon, table.header([], [*$cal(P)$*], [*$cal(N P)$*]), [*Solvabilidade*], [Solucionável eficientemente em tempo polinomial.], [Verificação eficiente, mas a solução pode não ser encontrada eficientemente.], [*Complexidade de Tempo*], [Algoritmos de tempo polinomial são conhecidos.], [Algoritmos de verificação eficiente são conhecidos, mas algoritmos eficientes para a solução não são garantidos.], [*Natureza das Soluções*], [As soluções podem ser encontradas eficientemente.], [As soluções, uma vez propostas, podem ser verificadas eficientemente.], [*Relação Conhecida*], [$cal(P)$ é um subconjunto de $cal(N P)$.], [Não se sabe se $cal(N P)$ é um subconjunto próprio de $cal(P)$ ou se são iguais.], ) ] == $cal(P)$ vs $cal(N P)$ #align(horizon + center)[#image("images/p_vs_np.png")] == $cal(N P)$-completos #align(horizon)[ Um problema $cal(N P)$-completo é um problema $cal(N P)$ que é *tão difícil quanto qualquer outro problema em $cal(N P)$*. Se um problema $cal(N P)$-completo puder ser resolvido em tempo polinomial, então todos os problemas em $cal(N P)$-completo também podem. ] == Satistifabilidade Booleana (SAT) #align(horizon)[ O problema de satisfatibilidade booleana (SAT) busca determinar se uma *fórmula proposicional pode ser tornada verdadeira* por meio de uma atribuição adequada ("solução") de valores de verdade para suas variáveis. $ (a and b and c) or (d and e and f) or (g and h and i) or (j and k and l) $ onde $a, b, c, d, e, f, g, h, i, j, k, l$ são variáveis booleanas, e $and$ (`AND`) e $or$ (`OR`) são operadores booleanos. #pagebreak() #v(1em) Embora seja fácil verificar se uma determinada atribuição torna a fórmula verdadeira, não se conhece um método essencialmente mais rápido para encontrar uma atribuição satisfatória além de testar todas as atribuições sucessivamente. #v(1em) #link("https://en.wikipedia.org/wiki/Cook%E2%80%93Levin_theorem")[Cook e Levin provaram] que todo problema de fácil verificação pode ser resolvido tão rapidamente quanto o SAT, que, por isso, é NP-completo. ] == $cal(N P)$-difíceis #align(horizon)[ Um problema $cal(N P)$-difícil é um problema para o qual *não se conhece um algoritmo eficiente para resolvê-lo*. No entanto, se um algoritmo eficiente para um problema $cal(N P)$-difícil for encontrado, então todos os problemas em $cal(N P)$ podem ser resolvidos eficientemente. ] == $cal(P)$ vs $cal(N P)$-completo e $cal(N P)$-difícil #align(horizon + center)[#image("images/P_np_np-complete_np-hard.svg")] == $cal(P)$ vs $cal(N P)$-completo e $cal(N P)$-difícil #align(horizon)[ - $cal(N P)$-completo: - Problema do Caixeiro Viajante na forma de decisão: "Existe um caminho de custo menor ou igual a X?" - $cal(N P)$-difícil: - Problema do Caixeiro Viajante na forma de otimização: "Qual é o caminho de custo mínimo?" ] == Parte Prática (C) #text(size: 14pt)[ #align(horizon)[ #link("https://en.wikipedia.org/wiki/Knapsack_problem")[*Problema da Mochila (_Knapsack Problem_)*] Você é um aventureiro e encontrou uma caverna cheia de tesouros. No entanto, sua mochila tem uma capacidade limitada e você precisa decidir quais itens levar para maximizar o valor total, sem exceder a capacidade da mochila. Você tem uma lista de `n` itens, onde cada item `i` tem: - *Valor*: $v[i]$ (em ouro) - *Peso*: $w[i]$ (em quilogramas) A capacidade da sua mochila é $W$ (em quilogramas). #pagebreak() - Escrever um algoritmo que determine o subconjunto de itens que maximiza o valor total na mochila sem exceder o peso total $W$. - Escrever um algoritmo que dado um certo input de itens e capacidade, determine se é possível colocar todos os itens na mochila. ] ] = Identificando a Complexidade de Algoritmos #align(horizon + center)[#image( "images/recursion_joker_debugging_meme.jpg", width: 80%, )] == Introdução #align(horizon)[ A análise de complexidade é fundamental para avaliar a *eficiência de algoritmos*. Ela nos ajuda a prever o comportamento de um algoritmo à medida que a entrada aumenta, o que é crucial para a *otimização* e escolha do *algoritmo certo* para uma aplicação específica. ] == Notação Big-O #align(horizon)[ A notação Big-O ($O$) é usada para descrever o *pior caso do tempo de execução de um algoritmo* em função do *tamanho de entrada $n$*. ] == Passos para Determinar a Complexidade #align(horizon)[ 1. *Identifique as operações dominantes*: Concentre-se nas operações que são executadas repetidamente, como _loops_, recursões e chamadas de funções. #pagebreak() 2. *Estime o número de vezes que essas operações são executadas*: Analise a profundidade e o número de iterações dos _loops_ e recursões. #pagebreak() 3. *Ignore constantes e termos não dominantes*: Na notação Big-O, ignoramos constantes multiplicativas e termos de ordem inferior. #pagebreak() 4. *Escolha a notação Big-O apropriada*: Use o resultado das etapas anteriores para identificar a complexidade Big-O correta. ] #pagebreak() #align(horizon + center)[#image( "images/recursion_world_burn_meme.jpeg", width: 80%, )] == Estruturas de Controle - *Estruturas Sequenciais*: complexidade constante $O(1)$ - *Estruturas Condicionais*: complexidade constante $O(1)$ - *_Loops_*: complexidade linear $O(n)$ - *_Loop_ Aninhado*: complexidade quadrática $O(n^2)$ - *Recursão*: - *Linear*: complexidade linear $O(n)$ - *Divisória*: complexidade logarítmica $O(log n)$ - *Binária*: complexidade $O(n log n)$ - *Exponencial*: complexidade exponencial $O(2^n)$ == Estruturas Sequenciais #align(horizon)[ Estruturas de controle que não envolvem _loops_ ou recursão têm complexidade constante $O(1)$. ```c int x = 5; int y = 10; int z = x + y; // O(1) ``` ] == Estruturas Condicionais #align(horizon)[ Condicionais simples, como `if`-`else`, não afetam a complexidade, mas a execução de blocos internos deve ser considerada. ```c if (x > y) { z = x - y; // O(1) } else { z = y - x; // O(1) } // Complexidade total: O(1) ``` ] == _Loops_ #align(horizon)[ A complexidade de um _loop_ depende do número de iterações: - *_Loop_ Simples*: ```c for (int i = 0; i < n; i++) { // operação de O(1) } // Complexidade total: O(n) ``` #pagebreak() - *_Loop_ Aninhado*: ```c for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // operação de O(1) } } // complexidade total: O(n^2) ``` #pagebreak() - *_Loop_ com incremento multiplicativo*: ```c for (int i = 1; i < n; i *= 2) { // operação de O(1) } // Complexidade total: O(log n) ``` ] == Recursão #align(horizon + center)[#image( "images/recursion_joker_stackoverflow_meme.jpeg", width: 80%, )] #pagebreak() #align(horizon)[ A complexidade de algoritmos recursivos depende do número de chamadas recursivas e do tamanho da entrada em cada chamada. - *Recursão Linear*: ```c void recursao_linear(int n) { if (n == 0) return; // operação de O(1) recursao_linear(n-1); } // Complexidade total: O(n) ``` #pagebreak() - *Recursão Divisória*: ```c void recursao_divisoria(int n) { if (n == 0) return; // operação de O(1) recursao_divisoria(n/2); } // Complexidade total: O(log n) ``` #pagebreak() - *Recursão Binária (como _Merge Sort_)*: ```c void merge_sort(int arr[], int n) { if (n < 2) return; int mid = n / 2; merge_sort(arr, mid); merge_sort(arr + mid, n - mid); merge(arr, mid, n - mid); // O(n) } // Complexidade total: O(n log n) ``` #pagebreak() - *Recursão Exponencial*: ```c int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n-1) + fibonacci(n-2); } // Complexidade total: O(2^n) ``` ] == Exemplo Prático - Busca Linear #align(horizon)[ ```c int busca_linear(int arr[], int n, int x) { for (int i = 0; i < n; i++) { if (arr[i] == x) return i; } return -1; } // Complexidade total: O(n) ``` ] == Exemplo Prático - Busca Binária #align(horizon)[ ```c int busca_binaria(int arr[], int n, int x) { int inicio = 0, fim = n - 1; while (inicio <= fim) { int meio = (inicio + fim) / 2; if (arr[meio] == x) return meio; if (arr[meio] < x) inicio = meio + 1; else fim = meio - 1; } return -1; } // Complexidade total: O(log n) ``` ] == Exemplo Prático - _Bubble Sort_ #text(size: 14pt)[ #align(horizon)[ ```c void bubble_sort(int arr[], int n) { for (int i = 0; i < n-1; i++) { for (int j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { // troca de elementos int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } // Complexidade total: O(n^2) ``` ] ] == Parte Prática (C ou pseudocódigo) #pagebreak() #align(horizon)[ - Implementar e determinar a complexidade de um algoritmo que conta o número de ocorrências de um elemento em uma matriz. - Descobrir uma maneira de reduzir a complexidade do cálculo de Fibonacci. ] = Interlúdio: Analisando a Complexidade de Algoritmos com Código C #align(horizon + center)[#image("images/programming_meme.jpg", width: 50%)] #pagebreak() #align(horizon)[ #text(size: 12pt)[ Revertendo um _array_: // Complexidade total: O(n) ```c void reverse_array(int arr[], int n) { int start = 0, end = n - 1; while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } ``` #pagebreak() Checando se uma _string_ é um #link("https://en.wikipedia.org/wiki/Palindrome")[palíndromo]: // Complexidade total: O(n) ```c bool is_palindrome(char str[]) { int start = 0; // strings in C are null-terminated int end = strlen(str) - 1; while (start < end) { if (str[start] != str[end]) { return false; } start++; end--; } return true; } ``` #pagebreak() Achando o maior elemento em um _array_ que o maior elemento vem antes do menor: // Complexidade total: O(n) #text(size: 11pt)[ ```c int max_difference(int arr[], int n) { int min_element = arr[0]; int max_diff = arr[1] - arr[0]; for (int i = 1; i < n; i++) { if (arr[i] - min_element > max_diff) { max_diff = arr[i] - min_element; } if (arr[i] < min_element) { min_element = arr[i]; } } return max_diff; } ``` ] #pagebreak() Ordenando um _array_ usando o algoritmo #link("https://en.wikipedia.org/wiki/Insertion_sort")[_insertion sort_]: // Complexidade total: O(n^2) ```c void insertion_sort(int arr[], int n) { for (int i = 1; i < n; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } ``` #pagebreak() Encontrar os elementos duplicados em um _array_: // Complexidade total: O(n^2) ```c void find_duplicates(int arr[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { printf("Duplicate found: %d\n", arr[i]); } } } } ``` #pagebreak() Computando a potência de um número: // Complexidade total: O(log n) ```c int power(int x, int n) { if (n == 0) { return 1; } int half = power(x, n / 2); if (n % 2 == 0) { return half * half; } else { return x * half * half; } } ``` #pagebreak() Encontrar o #link("https://en.wikipedia.org/wiki/Greatest_common_divisor")[_greatest common divisor_] (minimo múltiplo comum) de dois números: // Complexidade total: O(log(min(a, b))) ```c int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } ``` #pagebreak() #link("https://en.wikipedia.org/wiki/Primality_test")[Teste de primalidade] (método ingênuo) // Complexidade total: O(sqrt(n)) ```c bool is_prime(int n) { if (n <= 1) { return false; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } ``` #pagebreak() Achando o elemento majoritário (um elemento que aparece mais de $n/2$ vezes) usando o algoritmo de votação de #link( "https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm", )[Boyer-Moore's]. // Complexidade total: O(n) #text(size: 6pt)[ ```c int find_majority_element(int arr[], int n) { int count = 0, candidate = -1; // Find potential candidate for (int i = 0; i < n; i++) { if (count == 0) { candidate = arr[i]; count = 1; } else if (arr[i] == candidate) { count++; } else { count--; } } // Verify if the candidate is the majority element count = 0; for (int i = 0; i < n; i++) { if (arr[i] == candidate) { count++; } } if (count > n / 2) { return candidate; } else { return -1; // No majority element } } ``` ] #pagebreak() Gerando o #link("https://en.wikipedia.org/wiki/Pascal%27s_triangle")[Triângulo de Pascal] // Complexidade total: O(n^2) #text(size: 11pt)[ ```c void generate_pascals_triangle(int n) { int arr[n][n]; for (int line = 0; line < n; line++) { for (int i = 0; i <= line; i++) { if (i == 0 || i == line) { arr[line][i] = 1; } else { arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i]; } printf("%d ", arr[line][i]); } printf("\n"); } } ``` ] #pagebreak() Algoritmo de #link("https://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane's_algorithm")[Kadane] para encontrar a soma do _subarray_ máximo: // Complexidade total: O(n) #text(size: 11pt)[ ```c int max_subarray_sum(int arr[], int n) { int max_ending_here = 0; int max_so_far = INT_MIN; for (int i = 0; i < n; i++) { max_ending_here = max_ending_here + arr[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; } if (max_ending_here < 0) { max_ending_here = 0; } } return max_so_far; } ``` ] #pagebreak() Encontrar a maior subsequência comum #link( "https://en.wikipedia.org/wiki/Longest_common_subsequence", )[(_longest common subsequence_ -- LCS)]: // Complexidade total: O(n * m) #text(size: 10pt)[ ```c int lcs(char *X, char *Y, int m, int n) { int dp[m + 1][n + 1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { dp[i][j] = 0; } else if (X[i - 1] == Y[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[m][n]; } ``` ] #pagebreak() Fundir duas _arrays_ ordeanadas: // Complexidade total: O(N log N) #text(size: 8pt)[ ```c void merge_sorted_arrays(int A[], int B[], int m, int n, int C[]) { int i = 0, j = 0, k = 0; int N = m + n; // N representa o tamanho combinado de A e B while (i < m && j < n) { if (A[i] <= B[j]) { C[k++] = A[i++]; } else { C[k++] = B[j++]; } } // Copia os elementos restantes de A, se houver while (i < m) { C[k++] = A[i++]; } // Copia os elementos restantes de B, se houver while (j < n) { C[k++] = B[j++]; } } ``` ] #pagebreak() Esse algoritmo é uma #link( "https://en.wikipedia.org/wiki/Fast_inverse_square_root", )[maneira rápida de calcular a raiz quadrada inversa], $1 / sqrt(x)$, que ficou famoso por seu uso no jogo Quake III Arena por #link("https://en.wikipedia.org/wiki/John_Carmack")[<NAME>]. O método usa uma aproximação inteligente e uma única iteração do of #link("https://en.wikipedia.org/wiki/Newton%27s_method")[método de Newton] para calcular a raiz quadrada inversa de um número. // Complexidade total: O(1) #text(size: 8pt)[ ```c float Q_rsqrt(float number) { long i; float x2, y; const float threehalfs = 1.5F; x2 = number * 0.5F; y = number; i = *(long*)&y; // Evil bit-level hacking i = 0x5f3759df - (i >> 1); // What the fuck? y = *(float*)&i; y = y * (threehalfs - (x2 * y * y)); // 1st iteration of Newton's method // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed return y; } ``` ] ] ] = Algoritmos de Busca #align(horizon + center)[#image( "images/search_algorithms_meme.png", width: 100%, )] == O que é um Algoritmo de Busca? #align(horizon)[ Um *algoritmo de busca* é uma sequência de instruções que permite encontrar um determinado elemento dentro de uma estrutura de dados. É fundamental em ciência da computação, pois otimiza o acesso e a manipulação de dados. ] == Por que Estudar Algoritmos de Busca? #align(horizon)[ - *Eficiência*: Algoritmos de busca eficientes economizam tempo e recursos. - *Fundamentos*: São a base para algoritmos mais complexos e estruturas de dados. - *Aplicações Práticas*: Usados em bancos de dados, sistemas operacionais, inteligência artificial, entre outros. ] == Tipos de Algoritmos de Busca #align(horizon)[ - *Busca Linear* (_Linear Search_) - *Busca Binária* (_Binary Search_) - *Busca em Grafos*: - *Busca em Largura* (_Breadth-First Search - BFS_) - *Busca em Profundidade* (_Depth-First Search - DFS_) ] == Busca Linear === Conceito #align(horizon)[ A *busca linear* é o algoritmo mais simples de busca. Ela percorre cada elemento da estrutura de dados até encontrar o elemento desejado ou até o final da estrutura. ] #pagebreak() === Características da Busca Linear #align(horizon)[ - *Simples de Implementar* - *_Não_ Requer Estrutura Ordenada* - *Complexidade de Tempo*: $O(n)$, onde $n$ é o número de elementos. ] #pagebreak() === Pseudoalgoritmo #align(horizon)[ #figure( kind: "algorithm", supplement: [Algoritmo], caption: [Busca Linear], text(size: 12pt)[ #pseudocode-list( title: smallcaps[dado uma lista $A$ de $n$ elementos com valores $A_0, dots A_(n-1)$, e valor-alvo $T$:], )[ + *for* $i$ *in* $A$: + *if* $A_i = T$: + *return* $i$ + *return* _null_ ] ], ) <linear-search> ] #pagebreak() === Exemplo em C #align(horizon)[ #text(size: 14pt)[ ```c int busca_linear(int arr[], int n, int x) { for (int i = 0; i < n; i++) { if (arr[i] == x) // Elemento encontrado na posição i return i; } return -1; // Elemento não encontrado } ``` ] ] #pagebreak() === Análise da Complexidade #align(horizon)[ - *Melhor Caso*: O elemento está na primeira posição; $O(1)$. - *Pior Caso*: O elemento está na última posição ou não está presente; $O(n)$. - *Caso Médio*: Em média, percorre metade dos elementos; $1/2 O(n) = O(n)$. ] == Busca Binária #align(horizon)[ A *busca binária* é um algoritmo eficiente para encontrar um elemento em uma lista ordenada, reduzindo o espaço de busca pela metade a cada iteração. ] #pagebreak() === Características da Busca Binária #align(horizon)[ - *Requer Estrutura Ordenada* - *Complexidade de Tempo*: $O(log n)$ - *Mais Eficiente que a Busca Linear em Grandes Conjuntos de Dados* ] #pagebreak() === Pseudoalgoritmo #align(horizon)[ #figure( kind: "algorithm", supplement: [Algoritmo], caption: [Busca Binária], text(size: 9pt)[ #pseudocode-list( title: smallcaps[dado uma lista _ordenada_ $A$ de $n$ elementos com valores $A_0, dots A_(n-1)$, e valor-alvo $T$:], )[ + $L := 0$; $R := n-1$. + *while* $L <= R$: + $m := floor((L+R) / 2)$ + *if* $A_m < T$: + $L := m+1$ + *else if* $A_m > T$: + $R := m-1$ + *else*: + *return* $m$ + *return* _null_ ] ], ) <binary-search> ] #pagebreak() === Exemplo em C #align(horizon)[ #text(size: 12pt)[ ```c int busca_binaria(int arr[], int n, int x) { int inicio = 0, fim = n - 1; while (inicio <= fim) { int meio = inicio + (fim - inicio) / 2; if (arr[meio] == x) // Elemento encontrado return meio; if (arr[meio] < x) inicio = meio + 1; else fim = meio - 1; } // Elemento não encontrado return -1; } ``` ] ] #pagebreak() === Análise da Complexidade #align(horizon)[ - A cada iteração, o algoritmo reduz o espaço de busca pela metade. - *Complexidade de Tempo*: $O(log n)$ - *Eficiência*: Muito mais rápido que a busca linear em grandes conjuntos de dados. ] #pagebreak() === E se tivermos $k > 1$ pivôs? #align(horizon)[ #text(size: 14pt)[ Em cada passo: - Divide a _array_ em $k+1$ partições - O espaço de busca é reduzido para $n / (k+1)$ - As comparações aumentam de $1$ para $k$ Total de comparações: - Total de iterações: $log_(k+1) n$ - Total de comparações: $k dot.c log_(k+1) n$ Complexidade: - $O (k dot.c (log n) / (log(k+1))) = O(log n)$ ] ] == Busca em Grafos #pagebreak() === Tipos de Busca em Grafos #align(horizon)[ - *Busca em Largura* (_Breadth-First Search - BFS_) - *Busca em Profundidade* (_Depth-First Search - DFS_) ] #pagebreak() === Aplicações #align(horizon)[ - *Encontrar Caminhos*: Entre dois vértices em um grafo. - *Verificar Conectividade*: Se todos os vértices são alcançáveis. - *Detecção de Ciclos*: Em grafos direcionados e não direcionados. ] == Busca em Largura (BFS) #align(horizon)[ Busca em Largura (_Breadth-First Search_) é um algoritmo de busca em grafos que explora todos os vértices ] #pagebreak() === Conceito #align(horizon)[ A *busca em largura* explora um grafo visitando todos os vértices na mesma camada de distância da origem antes de passar para a próxima camada. ] #pagebreak() === Características da BFS #align(horizon)[ - *Usa Fila (_Queue_)* - *Garante o Caminho Mais Curto em Grafos Não Ponderados* - *Complexidade de Tempo*: $O(V + E)$, onde $V$ é o número de vértices e $E$ é o número de arestas. ] #pagebreak() === Pseudoalgoritmo #align(horizon)[ #figure( kind: "algorithm", supplement: [Algoritmo], caption: [Busca em Largura], text(size: 8pt)[ #pseudocode-list( title: smallcaps[dado um grafo $G$, um vértice raiz _root_, e valor-alvo $T$:], )[ + $Q := "queue"$ + _root_.explored $:= "true"$ + $Q$.enqueue(_root_) + *while* $!Q$.empty(): + $v := Q$.dequeue() + *if* $v = T$ + *return* $v$ + *for* todas as arestas de $v$ para $w$ *in* $G$.adjacentEdges(v): + *if* $!w$.explored: + $w$.explored $:= "true"$ + $w$.parent $:= v$ + $Q$.enqueue($w$) + *return* _null_ ] ], ) <breadth-first-search> ] #pagebreak() === Exemplo em C #align(horizon)[ #text(size: 7pt)[ ```c int bfs(int grafo[][MAX], int inicio, int n) { if (inicio->value == T) return inicio->id; int visitado[MAX] = {0}; int fila[MAX], frente = 0, traseira = 0; visitado[inicio] = 1; fila[traseira++] = inicio; while (frente < traseira) { int atual = fila[frente++]; for (int i = 0; i < n; i++) { if (atual->value == T) return atual->id; if (grafo[atual][i] && !visitado[i]) { visitado[i] = 1; fila[traseira++] = i; } } } return -1; } ``` ] ] #pagebreak() === Ilustração da BFS #align(horizon + center)[ #figure( raw-render( ```dot digraph BFS { rankdir=TB; node [shape=circle, style=filled, color=lightgrey]; // Definição dos nós e suas labels A [label="1"]; B [label="2"]; C [label="3"]; D [label="4"]; E [label="5"]; F [label="6"]; G [label="7"]; H [label="8"]; // Definição das arestas A -> {B; C}; B -> {D; E}; C -> {F; G}; E -> H; } ```, width: 35%, ), caption: "Ilustração da BFS em um digrafo com os vértices numerados pela ordem de visitação", ) ] == Busca em Profundidade (DFS) #align(horizon)[ Busca em Profundidade (_Depth-First Search_) é um algoritmo de busca em grafos que explora todos os vértices ] #pagebreak() === Conceito #align(horizon)[ A *busca em profundidade* explora o grafo o mais profundo possível antes de retroceder. ] #pagebreak() === Características da DFS #align(horizon)[ - *Usa Pilha (_Stack_)* (pode ser implementada recursivamente) - *Não Garante o Caminho Mais Curto* - *Complexidade de Tempo*: $O(V + E)$ ] #pagebreak() === Pseudoalgoritmo #align(horizon)[ #figure( kind: "algorithm", supplement: [Algoritmo], caption: [Busca em Profundidade], text(size: 12pt)[ #pseudocode-list( title: smallcaps[dado um grafo $G$, um vértice $v$, e valor-alvo $T$:], )[ + $v$.discovered $:= "true"$ + *if* $v = T$ + *return* $v$ + *for* todas as arestas de $v$ para $w$ *in* $G$.adjacentEdges(v): + *if* $!w$.discovered: + DFS($G$, $w$) + *return* _null_ ] ], ) <depth-first-search> ] #pagebreak() === Exemplo em C (Recursivo) #align(horizon)[ #text(size: 13pt)[ ```c int dfs(int grafo[][MAX], int atual, int visitado[], int n) { if (atual->value == T) return atual->id; visitado[atual] = 1; for (int i = 0; i < n; i++) { if (grafo[atual][i] && !visitado[i]) { dfs(grafo, i, visitado, n); } } return -1; } ``` ] ] #pagebreak() === Ilustração da DFS #align(horizon + center)[ #figure( raw-render( ```dot digraph DFS { rankdir=TB; node [shape=circle, style=filled, color=lightgrey]; // Definição dos nós e suas labels A [label="1"]; B [label="2"]; C [label="6"]; D [label="3"]; E [label="4"]; F [label="7"]; G [label="8"]; H [label="5"]; // Definição das arestas A -> {B; C}; B -> {D; E}; C -> {F; G}; E -> H; } ```, width: 35%, ), caption: "Ilustração da DFS em um digrafo com os vértices numerados pela ordem de visitação", ) ] == Comparação entre BFS e DFS #align(horizon)[ #text(size: 12pt)[ #table( columns: 2, align: left + horizon, table.header([*Característica*], [*BFS*], [*DFS*]), [*Estrutura de Dados*], [Fila (_Queue_)], [Pilha (_Stack_)], [*Uso de Memória*], [Maior (guarda todos os vizinhos)], [Menor (apenas caminho atual)], [*Caminho Mais Curto*], [Sim (em grafos não ponderados)], [Não necessariamente], [*Completo*], [Sim], [Sim], [*Aplicações*], [Caminho mais curto, nível dos nós], [Detecção de ciclos, ordenação topológica], ) ] ] = Algoritmos de Ordenação #align(horizon + center)[ #image( "images/sorting_algorithms_meme.jpg", width: 60%, ) ] == Introdução #align(horizon)[ *Algoritmos de ordenação* são algoritmos que colocam elementos de uma lista em uma certa ordem. As ordens mais frequentemente usadas são ordem numérica e ordem lexicográfica. A ordenação é importante porque: - Organiza os dados para torná-los mais utilizáveis. - Otimiza a eficiência de outros algoritmos que requerem dados ordenados. - Facilita a busca e a representação de dados. ] == Tipos de Algoritmos de Ordenação #align(horizon)[ #text(size: 14pt)[ Os algoritmos de ordenação podem ser classificados com base em vários fatores: - *Baseados em comparação vs. Não-comparação*: Se os elementos são comparados para determinar sua ordem. - *Estável vs. Instável*: Se elementos equivalentes mantêm sua ordem relativa original. - *Complexidade de Tempo*: Como o tempo de execução aumenta com o número de elementos. - *Complexidade de Espaço*: A quantidade de memória necessária além dos dados de entrada. ] ] == Estável vs. Instável #align(horizon + center)[ #image( "images/sort_stable_vs_unstable.png", width: 100%, ) ] == Algoritmos de Ordenação Comuns #align(horizon)[ - *_Bubble Sort_* - *_Selection Sort_* - *_Insertion Sort_* - *_Merge Sort_* - *_Quick Sort_* - *_Heap Sort_* - *_Counting Sort_* - *_Radix Sort_* - *_Bucket Sort_* ] == _Bubble Sort_ #align(horizon)[ *_Bubble Sort_* é um algoritmo simples baseado em comparação onde cada par de elementos adjacentes é comparado, e os elementos são trocados se estiverem na ordem errada. Este processo é repetido até que nenhuma troca seja necessária. É chamado de "bolha" porque elementos menores "sobem" para o topo da lista. ] #pagebreak() === Passos do Algoritmo #align(horizon)[ 1. Compare cada par de itens adjacentes. 2. Troque-os se estiverem na ordem errada. 3. Repita os passos 1 e 2 para todos os elementos. 4. Continue o processo até que uma passagem complete sem trocas. ] #pagebreak() === Pseudocódigo #align(horizon)[ #figure( kind: "algorithm", supplement: [Algoritmo], caption: [_Bubble Sort_], text(size: 12pt)[ #pseudocode-list( title: smallcaps[Dado um _array_ $A$ de $n$ elementos:], )[ + *para* $i$ de $0$ até $n - 1$: + *para* $j$ de $0$ até $n - i - 1$: + *se* $A[j] > A[j + 1]$: + troque $A[j]$ e $A[j + 1]$ ] ], ) <bubble-sort> ] #pagebreak() === Exemplo em C #align(horizon)[ #text(size: 13pt)[ ```c void bubble_sort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { // Os últimos i elementos já estão // na posição correta for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Troca arr[j] e arr[j + 1] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } ``` ] ] #pagebreak() === Análise de Complexidade #align(horizon)[ - *Complexidade de Tempo*: - Melhor Caso: $O(n)$ (quando o _array_ já está ordenado) - Caso Médio: $O(n^2)$ - Pior Caso: $O(n^2)$ - *Complexidade de Espaço*: $O(1)$ (ordenamento _in-place_) - *Estabilidade*: Estável (elementos iguais mantêm sua ordem relativa) ] == _Selection Sort_ #align(horizon)[ *_Selection Sort_* divide a lista de entrada em duas partes: uma sublista de elementos ordenados construída da esquerda para a direita, e uma sublista dos elementos restantes não ordenados. Repetidamente seleciona o menor (ou maior) elemento da sublista não ordenada, trocando-o com o elemento não ordenado mais à esquerda. O processo continua movendo os limites da sublista um elemento à direita. ] #pagebreak() === Passos do Algoritmo #align(horizon)[ 1. Defina o primeiro elemento não ordenado como o mínimo. 2. Compare este mínimo com o próximo elemento. 3. Se o próximo elemento for menor, defina-o como o novo mínimo. 4. Continue até o final do _array_. 5. Troque o mínimo com a primeira posição não ordenada. 6. Mova o limite um elemento à direita. 7. Repita até que o _array_ esteja ordenado. ] === Pseudocódigo #align(horizon)[ #figure( kind: "algorithm", supplement: [Algoritmo], caption: [_Selection Sort_], text(size: 12pt)[ #pseudocode-list( title: smallcaps[Dado um _array_ $A$ de $n$ elementos:], )[ + *para* $i$ de $0$ até $n - 1$: + $"minIdx" := i$ + *para* $j$ de $i + 1$ até $n$: + *se* $A[j] < A["minIdx"]$: + minIdx := $j$ + troque $A[i]$ e $A["minIdx"]$ ] ], ) <selection-sort> ] #pagebreak() === Exemplo em C #align(horizon)[ #text(size: 13pt)[ ```c void selection_sort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { int min_idx = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[min_idx]) min_idx = j; } // Troca o menor elemento encontrado com // o primeiro elemento int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } } ``` ] ] #pagebreak() === Análise de Complexidade #align(horizon)[ - *Complexidade de Tempo*: - Melhor Caso: $O(n^2)$ - Caso Médio: $O(n^2)$ - Pior Caso: $O(n^2)$ - *Complexidade de Espaço*: $O(1)$ - *Estabilidade*: Instável (elementos iguais podem não manter sua ordem relativa) ] == _Insertion Sort_ #align(horizon)[ *_Insertion Sort_* constrói o _array_ ordenado final um elemento de cada vez. Assume que o primeiro elemento já está ordenado, então insere cada elemento subsequente na posição correta em relação à porção ordenada. É semelhante à forma como as pessoas organizam cartas em um jogo de baralho. ] #pagebreak() === Passos do Algoritmo #align(horizon)[ 1. Comece pelo segundo elemento (índice $1$). 2. Compare o elemento atual com os elementos na porção ordenada. 3. Desloque todos os elementos maiores na porção ordenada uma posição à direita. 4. Insira o elemento atual em sua posição correta. 5. Repita até que o _array_ esteja ordenado. ] #pagebreak() === Pseudocódigo #align(horizon)[ #figure( kind: "algorithm", supplement: [Algoritmo], caption: [_Insertion Sort_], text(size: 12pt)[ #pseudocode-list( title: smallcaps[Dado um _array_ $A$ de $n$ elementos:], )[ + *para* $i$ de $1$ até $n - 1$: + $"key" := A[i]$ + $j := i - 1$ + *enquanto* $j >= 0$ *e* $A[j] > "key"$: + $A[j + 1] := A[j]$ + $j := j - 1$ + $A[j + 1] := "key"$ ] ], ) <insertion-sort> ] #pagebreak() === Exemplo em C #align(horizon)[ #text(size: 11pt)[ ```c void insertion_sort(int arr[], int n) { for (int i = 1; i < n; i++) { int key = arr[i]; int j = i - 1; // Move elementos de arr[0..i-1], // que são maiores que key, // para uma posição à frente // de sua posição atual while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } ``` ] ] === Análise de Complexidade #align(horizon)[ - *Complexidade de Tempo*: - Melhor Caso: $O(n)$ (quando o _array_ já está ordenado) - Caso Médio: $O(n^2)$ - Pior Caso: $O(n^2)$ - *Complexidade de Espaço*: $O(1)$ - *Estabilidade*: Estável ] == _Merge Sort_ #align(horizon)[ *_Merge Sort_* é um algoritmo de divisão e conquista que divide o _array_ ao meio, ordena cada metade e, em seguida, mescla-as de volta. É eficiente e tem um tempo de execução garantido de $O(n log n)$. ] #pagebreak() === Passos do Algoritmo #align(horizon)[ 1. Se o _array_ tiver comprimento $0$ ou $1$, já está ordenado. 2. Divida o _array_ em duas metades. 3. Ordene recursivamente cada metade. 4. Mescle as duas metades ordenadas em um _array_ ordenado. ] #pagebreak() === Pseudocódigo #align(horizon)[ #figure( kind: "algorithm", supplement: [Algoritmo], caption: [_Merge Sort_], text(size: 12pt)[ #pseudocode-list( title: smallcaps[Função merge_sort(_array_ A, left, right):], )[ + *se* $"left" < "right"$: + $"mid" := ("left" + "right") / 2$ + $"merge_sort"(A, "left", "mid")$ + $"merge_sort"(A, "mid" + 1, "right")$ + $"merge"(A, "left", "mid", "right")$ ] ], ) <merge-sort> ] #pagebreak() === Função `merge` #align(horizon)[ A função `merge` combina duas _subarrays_ ordenadas em um _array_ ordenado. - _Subarray_ esquerda: $A["left".."mid"]$ - _Subarray_ direita: $A["mid"+1.."right"]$ ] #pagebreak() === Exemplo em C #align(horizon)[ #text(size: 6pt)[ ```c void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; // Cria arrays temporários int L[n1], R[n2]; // Copia os dados para os arrays temporários L[] e R[] for (int i = 0; i < n1; i++) L[i] = arr[l + i]; for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; // Mescla os arrays temporários de volta em arr[l..r] int i = 0, j = 0, k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k++] = L[i++]; } else { arr[k++] = R[j++]; } } // Copia os elementos restantes de L[], se houver while (i < n1) arr[k++] = L[i++]; // Copia os elementos restantes de R[], se houver while (j < n2) arr[k++] = R[j++]; } ``` ] ] #pagebreak() #align(horizon)[ #text(size: 12pt)[ ```c void merge_sort(int arr[], int l, int r) { if (l < r) { int m = l + (r - l) / 2; merge_sort(arr, l, m); merge_sort(arr, m + 1, r); merge(arr, l, m, r); } } ``` ] ] #pagebreak() === Análise de Complexidade #align(horizon)[ - *Complexidade de Tempo*: - Melhor Caso: $O(n log n)$ - Caso Médio: $O(n log n)$ - Pior Caso: $O(n log n)$ - *Complexidade de Espaço*: $O(n)$ (devido aos _arrays_ auxiliares) - *Estabilidade*: Estável ] == _Quick Sort_ #align(horizon)[ *_Quick Sort_* é um algoritmo de divisão e conquista que seleciona um elemento *pivô* e particiona o _array_ em torno do pivô, de modo que elementos menores que o pivô fiquem à esquerda, e elementos maiores fiquem à direita. Em seguida, ordena recursivamente os _subarrays_ em ambos os lados do pivô. ] #pagebreak() === Passos do Algoritmo #align(horizon)[ 1. Escolha um elemento pivô. 2. Particione o _array_ em dois _subarrays_: - Elementos menores que o pivô. - Elementos maiores que o pivô. 3. Aplique recursivamente os passos acima aos _subarrays_. ] #pagebreak() === Pseudocódigo #align(horizon)[ #figure( kind: "algorithm", supplement: [Algoritmo], caption: [_Quick Sort_], text(size: 12pt)[ #pseudocode-list( title: smallcaps[Função quick_sort(_array_ A, low, high):], )[ + *se* $"low" < "high"$: + $pi := "partition"(A, "low", "high")$ + $"quick_sort"(A, "low", pi - 1)$ + $"quick_sort"(A, pi + 1, "high")$ ] ], ) <quick-sort> ] #pagebreak() === Função `partition` #align(horizon)[ A função `partition` rearranja o _array_ de modo que: - Todos os elementos menores que o pivô venham antes dele. - Todos os elementos maiores que o pivô venham após ele. - O pivô está em sua posição final ordenada. Ela retorna o índice do pivô. ] #pagebreak() === Exemplo em C #align(horizon)[ #text(size: 9pt)[ ```c int partition(int arr[], int low, int high) { int pivot = arr[high]; // pivô int i = low; // Índice do menor elemento for (int j = low; j <= high - 1; j++) { // Se o elemento atual é menor ou igual ao pivô if (arr[j] <= pivot) { i++; // incrementa o índice do menor elemento int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // Troca arr[i] e arr[high] (ou pivô) int temp = arr[i]; arr[i] = arr[high]; arr[high] = temp; return i; } ``` ] ] #pagebreak() #align(horizon)[ #text(size: 14pt)[ ```c void quick_sort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); // Separa a ordenação dos elementos antes // e depois da partição quick_sort(arr, low, pi - 1); quick_sort(arr, pi + 1, high); } } ``` ] ] #pagebreak() === Análise de Complexidade #align(horizon)[ - *Complexidade de Tempo*: - Melhor Caso: $O(n log n)$ - Caso Médio: $O(n log n)$ - Pior Caso: $O(n^2)$ (quando o menor ou maior elemento é sempre escolhido como pivô) - *Complexidade de Espaço*: $O(log n)$ (devido às chamadas recursivas) - *Estabilidade*: Instável ] == _Heap Sort_ #align(horizon)[ *_Heap Sort_* envolve construir um `max heap` a partir dos dados de entrada, e então repetidamente extrair o elemento máximo do _heap_ e reconstruir o _heap_. Utiliza as propriedades de uma estrutura de dados _heap_ para ordenar elementos. ] #pagebreak() === Passos do Algoritmo #align(horizon)[ 1. Construa um `max heap` a partir dos dados de entrada. 2. Troque a raiz (valor máximo) do _heap_ com o último elemento. 3. Reduza o tamanho do _heap_ em um. 4. `heapify` o elemento raiz para obter novamente o maior elemento na raiz. 5. Repita os passos 2 a 4 até que o tamanho do _heap_ seja maior que 1. ] #pagebreak() === Pseudocódigo #align(horizon)[ #figure( kind: "algorithm", supplement: [Algoritmo], caption: [_Heap Sort_], text(size: 12pt)[ #pseudocode-list( title: smallcaps[Função heap_sort(_array_ A, n):], )[ + *para* $i$ de $n / 2 - 1$ até $0$: + heapify(A, n, i) + *para* $i$ de $n - 1$ até $0$: + troque $A[0]$ e $A[i]$ + heapify(A, i, 0) ] ], ) <heap-sort> ] #pagebreak() === Função `heapify` #align(horizon)[ A função `heapify` garante que a subárvore enraizada no índice $i$ satisfaça a propriedade de _max heap_. - Se os filhos do nó $i$ forem _max heaps_ mas o nó $i$ pode ser menor que seus filhos. - Troque o nó $i$ com seu maior filho. - Recursivamente aplique `heapify` na subárvore afetada. ] #pagebreak() === Exemplo em C #align(horizon)[ #text(size: 9pt)[ ```c void heapify(int arr[], int n, int i) { int largest = i; // Inicializa largest como raiz int l = 2 * i + 1; // esquerda = 2*i + 1 int r = 2 * i + 2; // direita = 2*i + 2 // Se o filho esquerdo é maior que a raiz if (l < n && arr[l] > arr[largest]) largest = l; // Se o filho direito é maior que largest até agora if (r < n && arr[r] > arr[largest]) largest = r; // Se largest não é a raiz if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursivamente heapify a subárvore afetada heapify(arr, n, largest); } } ``` ] ] #pagebreak() #align(horizon)[ #text(size: 12pt)[ ```c void heap_sort(int arr[], int n) { // Constrói o heap (rearranja o array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // Um a um extrai um elemento do heap for (int i = n - 1; i >= 0; i--) { // Move a raiz atual para o fim int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // chama max heapify no heap reduzido heapify(arr, i, 0); } } ``` ] ] #pagebreak() === Análise de Complexidade #align(horizon)[ - *Complexidade de Tempo*: - Melhor Caso: $O(n log n)$ - Caso Médio: $O(n log n)$ - Pior Caso: $O(n log n)$ - *Complexidade de Espaço*: $O(1)$ - *Estabilidade*: Instável ] == _Counting Sort_ #align(horizon)[ *_Counting Sort_* é um algoritmo de ordenação de inteiros que opera contando o número de objetos que possuem valores de chave distintos (tipo um _hashing_). Não é uma ordenação por comparação e tem um tempo de execução de $O(n + k)$ onde $k$ é o intervalo dos dados de entrada. É eficiente quando o intervalo dos dados de entrada não é significativamente maior que o número de objetos a serem ordenados. ] #pagebreak() === Passos do Algoritmo #align(horizon)[ 1. Encontre o elemento máximo no _array_. 2. Inicialize um _array_ de contagem de tamanho ($max + 1$) com zeros. 3. Armazene a contagem de cada elemento em seu índice respectivo. 4. Modifique o _array_ de contagem adicionando as contagens anteriores. 5. Construa o _array_ de saída colocando os elementos em suas posições corretas. ] #pagebreak() === Pseudocódigo #align(horizon)[ #figure( kind: "algorithm", supplement: [Algoritmo], caption: [_Counting Sort_], text(size: 10pt)[ #pseudocode-list( title: smallcaps[Dado um _array_ $A$ de $n$ elementos:], )[ + $max := "find_max"(A)$ + inicialize o _array_ de contagem $C[0..max]$ + *para* cada elemento em $A$: + $C["element"] := C["element"] + 1$ + *para* $i$ de $1$ até $max$: + $C[i] := C[i] + C[i - 1]$ + *para* $i$ de $n - 1$ até $0$: + $"output"[C[A[i]] - 1] := A[i]$ + $C[A[i]] := C[A[i]] - 1$ + copie o _array_ de saída para $A$ ] ], ) <counting-sort> ] #pagebreak() === Exemplo em C #align(horizon)[ #text(size: 5.8pt)[ ```c void counting_sort(int arr[], int n) { int output[n]; int max = arr[0]; // Encontra o maior elemento no array for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } int count[max + 1]; // Inicializa o array de contagem com zeros for (int i = 0; i <= max; ++i) count[i] = 0; // Armazena a contagem de cada elemento for (int i = 0; i < n; i++) count[arr[i]]++; // Armazena a contagem cumulativa for (int i = 1; i <= max; i++) count[i] += count[i - 1]; // Encontra o índice de cada elemento do array original no array de contagem e // coloca os elementos no array de saída for (int i = n - 1; i >= 0; i--) { output[count[arr[i]] - 1] = arr[i]; count[arr[i]]--; } // Copia os elementos ordenados para o array original for (int i = 0; i < n; i++) arr[i] = output[i]; } ``` ] ] #pagebreak() === Análise de Complexidade #align(horizon)[ - *Complexidade de Tempo*: $O(n + k)$ onde $k$ é o intervalo dos dados de entrada. - *Complexidade de Espaço*: $O(n + k)$ - *Estabilidade*: Estável - *Limitação*: Funciona apenas com inteiros e quando $k$ não é significativamente maior que $n$. ] == _Radix Sort_ #align(horizon)[ *_Radix Sort_* é um algoritmo de ordenação não por comparação que ordena dados com chaves inteiras agrupando chaves por dígitos individuais que compartilham a mesma posição significativa e valor. Ele usa _Counting Sort_ como uma sub-rotina para ordenar elementos. ] #pagebreak() === Passos do Algoritmo #align(horizon)[ 1. Encontre o número máximo para saber o número de dígitos. 2. Faça `counting_sort` para cada dígito, começando do dígito menos significativo para o mais significativo. ] #pagebreak() === Pseudocódigo #align(horizon)[ #figure( kind: "algorithm", supplement: [Algoritmo], caption: [Radix Sort], text(size: 12pt)[ #pseudocode-list( title: smallcaps[Função radix_sort(_array_ A, n):], )[ + $max := "find_max"(A)$ + *para* $"exp" := 1$; $"max" / "exp" > 0$; $"exp" *= 10$: + $"counting_sort_by_digit"(A, n, "exp")$ ] ], ) <radix-sort> ] #pagebreak() === Função `counting_sort_by_digit` #align(horizon)[ A função `counting_sort_by_digit` ordena o _array_ de acordo com o dígito representado por `exp` (expoente). - Para $"exp" = 1$, ordena de acordo com o dígito menos significativo. - Para $"exp" = 10$, ordena de acordo com o segundo dígito menos significativo. ] #pagebreak() === Exemplo em C #align(horizon)[ #text(size: 9pt)[ ```c void counting_sort_by_digit(int arr[], int n, int exp) { int output[n]; int count[10] = {0}; // Armazena a contagem de ocorrências em count[] for (int i = 0; i < n; i++) count[(arr[i] / exp) % 10]++; // Altera count[i] para que count[i] contenha a posição real // deste dígito no array de saída for (int i = 1; i < 10; i++) count[i] += count[i - 1]; // Constrói o array de saída for (int i = n - 1; i >= 0; i--) { output[count[(arr[i] / exp) % 10] - 1] = arr[i]; count[(arr[i] / exp) % 10]--; } // Copia o array de saída para arr[], de modo que arr[] agora // contenha números ordenados de acordo com o dígito atual for (int i = 0; i < n; i++) arr[i] = output[i]; } ``` ] ] #pagebreak() #align(horizon)[ #text(size: 14pt)[ ```c void radix_sort(int arr[], int n) { // Encontra o número máximo para saber o número de dígitos int max = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; // Faz counting sort para cada dígito for (int exp = 1; max / exp > 0; exp *= 10) counting_sort_by_digit(arr, n, exp); } ``` ] ] #pagebreak() === Análise de Complexidade #align(horizon)[ - *Complexidade de Tempo*: $O(d dot.c (n + b))$ - $d$: Número de dígitos - $b$: Base do sistema numérico (10 para decimal) - *Complexidade de Espaço*: $O(n + b)$ - *Estabilidade*: Estável - *Limitação*: Funciona melhor quando $d$ não é significativamente grande. ] == Comparação - Algos de Ordenação #align(horizon)[ #text(size: 9pt)[ #table( columns: 7, align: left + horizon, table.header( [*Algoritmo*], [*Melhor Caso*], [*Caso Médio*], [*Pior Caso*], [*Espaço*], [*Estável*], [*Método*], ), [*_Bubble Sort_*], [$O(n)$], [$O(n^2)$], [$O(n^2)$], [$O(1)$], [Sim], [Troca], [*_Selection Sort_*], [$O(n^2)$], [$O(n^2)$], [$O(n^2)$], [$O(1)$], [Não], [Seleção], [*_Insertion Sort_*], [$O(n)$], [$O(n^2)$], [$O(n^2)$], [$O(1)$], [Sim], [Inserção], [*_Merge Sort_*], [$O(n log n)$], [$O(n log n)$], [$O(n log n)$], [$O(n)$], [Sim], [Intercalação], [*_Quick Sort_*], [$O(n log n)$], [$O(n log n)$], [$O(n^2)$], [$O(log n)$], [Não], [Partição], [*_Heap Sort_*], [$O(n log n)$], [$O(n log n)$], [$O(n log n)$], [$O(1)$], [Não], [Seleção], [*_Counting Sort_*], [$O(n + k)$], [$O(n + k)$], [$O(n + k)$], [$O(n + k)$], [Sim], [Contagem], [*_Radix Sort_*], [$O(n k)$], [$O(n k)$], [$O(n k)$], [$O(n + k)$], [Sim], [Dígito], ) ] ] == Seção Prática (C ou pseudocódigo) #align(horizon)[ - *Tarefa*: Implemente um algoritmo de ordenação de sua escolha e analise sua complexidade de tempo e espaço. - *Tarefa*: Modifique o algoritmo _Quick Sort_ para usar um pivô aleatório para melhorar o desempenho em arrays já ordenados. - *Tarefa*: Implemente uma versão estável da _Selection Sort_. ] = Recursão #align(horizon + center)[ #image( "images/recursion_meme.jpg", width: 50%, ) ] == O que é Recursão? #align(horizon)[ *Recursão* é uma técnica de programação onde uma função chama a si mesma para resolver um problema menor do mesmo tipo _até_ atingir um caso base. É uma forma de *dividir um problema complexo em subproblemas mais simples e manejáveis*. ] == Como Funciona? #align(horizon)[ 1. *Caso Base*: Define quando a função recursiva deve parar de chamar a si mesma. É a condição de parada. 2. *Chamada Recursiva*: A função chama a si mesma com uma entrada modificada que a aproxima do caso base. 3. *Resolução*: As chamadas recursivas retornam valores que são combinados para resolver o problema original. ] == Exemplo Clássico: Fatorial #align(horizon)[ - *Definição Matemática*: $ n! = cases( 1 "se" n = 0, n times (n - 1)! "se" n > 0 ) $ - *Implementação Recursiva em C*: ```c int fatorial(int n) { if (n == 0) return 1; else return n * fatorial(n - 1); } ``` ] == Visualização da Recursão do Fatorial #align(horizon + center)[ #figure( raw-render( ```dot digraph Fatorial { n4 [label="f(4)"]; n3 [label="f(3)"]; n2_1 [label="f(2)"]; n2_2 [label="f(2)"]; n1_1 [label="f(1)"]; n1_2 [label="f(1)"]; n1_3 [label="f(1)"]; n0_1 [label="f(0)"]; n0_2 [label="f(0)"]; n4 -> {n3, n2_1}; n3 -> {n2_2, n1_3}; n2_1 -> {n1_1, n0_1}; n2_2 -> {n1_2, n0_2}; } ```, width: 70%, ), caption: "Árvore de Recursão para fatorial(4)", ) ] == Quando Usar Recursão? #align(horizon)[ - *Problemas que podem ser divididos em subproblemas semelhantes*: Como árvores, grafos e estruturas hierárquicas. - *Algoritmos que requerem _backtracking_*: Como busca em profundidade (DFS), algoritmos de permutação e combinação. - *Facilitar a implementação*: Alguns algoritmos são mais fáceis de implementar de forma recursiva do que iterativa. ] == Vantagens e Desvantagens #align(horizon)[ *Vantagens*: - Código mais limpo e legível para certos problemas. - Naturalmente adequada para estruturas de dados recursivas (árvores, grafos). - Facilita a solução de problemas complexos ao dividi-los em partes menores. #pagebreak() *Desvantagens*: - Consome mais memória devido à pilha de chamadas. - Pode ser menos eficiente em termos de tempo em comparação com soluções iterativas. - Risco de estouro de pilha#footnote[_stack overflow_] se a recursão for muito profunda. ] == Recursão vs Iteração #align(horizon)[ #text(size: 15pt)[ - *Recursão*: - Usa chamadas de função para repetir o código. - Pode ser menos eficiente devido ao overhead de chamadas de função. - Mais intuitiva para problemas que são naturalmente recursivos. - *Iteração*: - Usa estruturas de repetição como loops (`for`, `while`). - Geralmente mais eficiente em termos de uso de memória e tempo. - Pode ser menos intuitiva para certos problemas. ] #pagebreak() *Exemplo*: Cálculo do fatorial de `n`. - *Recursivo*: ```c int fatorial(int n) { if (n == 0) return 1; else return n * fatorial(n - 1); } ``` #pagebreak() - *Iterativo*: ```c int fatorial(int n) { int resultado = 1; for (int i = 2; i <= n; i++) { resultado *= i; } return resultado; } ``` ] == Cautela com Recursão Excessiva #align(horizon)[ - *Estouros de Pilha*: Cada chamada recursiva adiciona um quadro à pilha de chamadas. Recursão muito profunda pode levar a estouros. - *Redundância de Cálculos*: Em algumas recursões, como no cálculo ingênuo de Fibonacci, muitos cálculos são repetidos. - *Otimização*: Técnicas como *_memoization_* ou transformar a recursão em iteração podem melhorar a eficiência. ] == _Memoization_ #align(horizon)[ Armazena os resultados de subproblemas já resolvidos para evitar cálculos repetidos. *Exemplo com Fibonacci*: #text(size: 11pt)[ ```c int fibonacci(int n, int memo[]) { if (memo[n] != -1) return memo[n]; if (n == 0) memo[n] = 0; else if (n == 1) memo[n] = 1; else memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo); return memo[n]; } ``` ] ] == Recursão de Cauda #align(horizon)[ - *Definição*: Uma recursão onde a chamada recursiva é a última operação da função. - *Benefícios*: Alguns compiladores podem otimizar recursões de cauda para evitar o crescimento da pilha (eliminação de recursão de cauda). - *Exemplo*: #text(size: 11pt)[ ```c int fatorial_tail(int n, int acumulador) { if (n == 0) return acumulador; else return fatorial_tail(n - 1, n * acumulador); } ``` ] ] == Parte Prática (C ou pseudocódigo) #align(horizon)[ - *Problema*: Implemente uma função recursiva que determina se uma palavra é um palíndromo. - *Dica*: Compare o primeiro e o último caractere da _string_ e chame a função recursivamente para a _substring_ interna. ] = Divisão e Conquista #align(horizon + center)[ #image( "images/divide_and_conquer_meme.png", width: 50%, ) ] == O que é Divisão e Conquista? #align(horizon)[ *Divisão e Conquista* é um paradigma de projeto de algoritmos que consiste em dividir um problema em subproblemas menores, resolver esses subproblemas de forma recursiva e então combinar as soluções para obter a solução final. ] == Como Funciona? #align(horizon)[ 1. *Dividir*: O problema é dividido em subproblemas menores que são instâncias do mesmo tipo do problema original. 2. *Conquistar*: Os subproblemas são resolvidos recursivamente. Se forem suficientemente pequenos, são resolvidos diretamente. 3. *Combinar*: As soluções dos subproblemas são combinadas para resolver o problema original. ] == Exemplos Clássicos #align(horizon)[ - *_Merge Sort_*: Um algoritmo de ordenação que divide o _array_ ao meio, ordena cada metade e então combina as duas metades ordenadas. - *_Quick Sort_*: Um algoritmo que seleciona um pivô, divide o _array_ em _subarrays_ menores e maiores que o pivô, e então ordena recursivamente os _subarrays_. - *Busca Binária*: Um método de busca que divide o espaço de busca pela metade a cada iteração. ] == Teorema mestre #align(horizon)[ Na análise de algoritmos, o #link("https://en.wikipedia.org/wiki/Master_theorem_(analysis_of_algorithms)")[*teorema mestre*] para recorrências de divisão e conquista fornece uma análise assintótica (usando a notação Big-O) para *relações de recorrência* que ocorrem na análise de muitos algoritmos de divisão e conquista. #pagebreak() Considere um problema que pode ser resolvido usando um algoritmo recursivo como o algoritmo a seguir: #figure( kind: "algorithm", supplement: [Algoritmo], caption: [Exemplo de Recursão], text(size: 12pt)[ #pseudocode-list( title: smallcaps[Procedimento $p$(entrada $x$ de tamanho$n$)], )[ + *if* $n < "alguma constante" k$: + resolver $x$ diretamente, sem recursão + *else*: + criar a subproblemas de $x$, cada um com tamanho $n/b$ + chamar o procedimento $p$ recursivamente em cada subproblema + combinar os resultados dos subproblemas ] ], ) <master-theorem> #pagebreak() - A árvore de chamadas tem um nó para cada chamada recursiva. - Os nós-folha são os casos base da recursão: subproblemas de tamanho menor que $k$ que não se resolve recursivamente. - Cada nó realiza uma quanidade de trabalho que corresponde ao tamanho do subproblema $m$ dada por $p(m)$. - A quantidade total de trabalho realizado pelo algoritmo completo é a soma do trabalho realizado por todos os nós na árvore. #pagebreak() #align(horizon + center)[ #image( "images/master_theorem_intuition.png", width: 100%, ) ] ] == Análise de Complexidade #align(horizon)[ A complexidade de algoritmos de divisão e conquista pode ser expressa pela *recorrência de Mestre*: $ T(n) = a T(n / b) + f(n) $ #pagebreak() Onde: - $T(n)$: Tempo de execução do algoritmo em uma entrada $n$. - $a$: Número de subproblemas. - $b$: Fator pelo qual o tamanho do problema é dividido. - $f(n)$: Custo de dividir e combinar os subproblemas. #pagebreak() A solução dessa recorrência depende da relação entre $f(n)$ e $n^(log_b a)$. - *Caso 1*: Se $f(n) = O(n^(log_b a - epsilon))$ para algum $epsilon > 0$, então $T(n) = O(n^(log_b a))$. - *Caso 2*: Se $f(n) = O(n^(log_b a) log^k n)$ para algum $k >= 0$, então $T(n) = O(n^(log_b a) log^(k+1) n)$. - *Caso 3*: Se $f(n) = O(n^(log_b a + epsilon))$ para algum $epsilon > 0$ e se $a f(n/b) <= c f(n)$ para algum $c < 1$, então $T(n) = O(f(n))$. ] == Exemplo: _Merge Sort_ #align(horizon)[ #text(size: 14pt)[ - *_Merge Sort_* divide o problema em 2 subproblemas de tamanho $n/2$: $ T(n) = 2 T(n / 2) + O(n) $ - Aqui, $a = 2$, $b = 2$, $f(n) = O(n)$. - Calculamos $n^(log_b a) = n^(log_2 2) = n^1$. - Como $f(n) = O(n^(log_b a))$, estamos no *Caso 2* do Teorema Mestre. - Portanto, $T(n) = O(n log n)$. ] ] == Exemplo: _Quick Sort_ (Pior Caso) #align(horizon)[ - No pior caso, o *_Quick Sort_* divide o problema em um subproblema de tamanho $n-1$ e outro de tamanho 0: $ T(n) = T(n - 1) + O(n) $ - Essa recorrência resolve para $T(n) = O(n^2)$. - No melhor caso (partições equilibradas), a complexidade é $O(n log n)$. ] == Aplicações de Divisão e Conquista #align(horizon)[ - *Multiplicação de Inteiros Grandes* (#link("https://en.wikipedia.org/wiki/Karatsuba_algorithm")[Algoritmo de Karatsuba]) - *Transformada Rápida de Fourier*: (#link("https://en.wikipedia.org/wiki/Fast_Fourier_transform")[FFT]) - *Multiplicação de Matrizes* (#link("https://en.wikipedia.org/wiki/Strassen_algorithm")[Algoritmo de Strassen]) - *Problemas de Geometria Computacional*: (#link("https://en.wikipedia.org/wiki/Convex_hull")[Fecho Convexo], etc.) ] == Vantagens e Desvantagens #align(horizon)[ #text(size: 14pt)[ *Vantagens*: - Pode reduzir a complexidade de problemas complexos. - Utiliza a recursividade, facilitando a implementação de algoritmos complexos. *Desvantagens*: - Pode ter sobrecarga de tempo e espaço devido às chamadas recursivas. - Nem todos os problemas são naturalmente divisíveis em subproblemas menores. ] ] == Parte Prática (C ou pseudocódigo) #align(horizon)[ - *Problema*: Implemente um algoritmo que eleva um número $x$ a uma potência $n$ utilizando o paradigma de divisão e conquista, otimizando para $O(log n)$. - *Dica*: Utilize a propriedade que $x^n = (x^(n/2))^2$ para $n$ par. ]
https://github.com/kazewong/lecture-notes
https://raw.githubusercontent.com/kazewong/lecture-notes/main/Engineering/SoftwareEngineeringForDataScience/lab/python.typ
typst
#set page( paper: "us-letter", header: align(center, text(17pt)[ *Introduction to Python* ]), numbering: "1", ) #import "./style.typ": style_template #show: doc => style_template(doc,) = Foreword `Python` is probably the most popular programming language by many measure these days, due to its simple learning experience and large ecosystem. In fact, I bet most of the people who are reading this note already know `python`. `python` has a long history and a huge community which you can probably do everything you want in `python`. However, being simple to learn also means it is easy to write bad code. Getting your calculation is one thing, building a nice package which people can use happily is another. There are many tricks and know-hows in `python` that you may not be aware of. And this is what we are going to focus in this lab. #outline(title: [Outline \ ], depth: 2, indent: 1em) #pagebreak() = Key Concepts == Python is an interpreted language Why do people say `python` is slow? The reaons is it is, and that is because `python` is an interpreted language, meaning it does not have a compiler that turns your human-readable code into machine code that can be executed. Instead, `python` has an interpreter that reads your code line by line and execute it. The interpreter pays an overhead everytime it is trying to execute a line because it needs to figure out what you are trying to do. In exchange, you get a very interactive experience when you are writing code, and you can see the result of your code without going through compilation. == Everything is an object In `python`, everything is an object. This means everything has some attributes and methods to themselves. This is a very powerful feature in `python`, which makes it very flexible and easy to use. For example, you can define a list `a = [0, 1]`, and you can access the first element of the list by `a[0]`. You can also call the `append` method on the list to append an element to the list by `a.append(2)`. This is an example for some built-in object, but you can also define your own object with attributes and methods. == Indentation is important One thing that people who started learning programming in other languages may find this a bit annoying is the indentation in `python`. In `python`, the indentation is not just for readability, it is actually part of the syntax. Instead of using curly braces like `C` or `Java`, `python` uses indentation to define the scope of the code. For example, if you write a for-loop in `python` like the following: ```python for i in range(10): print(i) ``` The `print(i)` line is indented by 4 spaces, which means it is inside the for-loop. If you do not indent the line, the interpreter will throw an error. #pagebreak() = Basic Syntax In this section, we are going to go through some basic syntax of python. We are only cover the minimum you need to know to write a simple insertion sort algorithm, especially most of you are already familiar with the `python` syntax. == Variables To define a variable in python, you simply assign a value to a variable name. For example, to define a variable `a` with value `1`, you can do: `a = 1`. There are a couple of basic data types in `python`, like numbers, string, boolean. Three slightly more complicated datatypes are list, tuple, and dictionary. List is a list of objects, which can be defined using the syntax `a = [0,1]`. A Tuple is an immutable list of objects, which can be defined using `a = (0,1)`. It is handy whenever you do not want things to change. A dictionary is basically a list but instead of accessing it by the index of the element, there are a list of key-value pairs, which you can access the values through their respective key. You can define a dictionary with the syntax `a = {"x": 1, "y": 2}` The dictionary in `python` is basically a hash table. They all can be accessed using `variable[index/key]` One thing to remember is everything is an object in Python, meaning they (almost) all have some attributes and methods to themselves. If you have a background in `C` or some similiarly low level language, you may find be able to define something like `a = [0, "this", true]` blasphemous. There is certainly performance and stability implication to this feature, but I believe this flexibility is what makes `python` easy to get into. == Control flow `python` has most of the basic contorl flow that you will find in another language, such as `if-else`, `for`, and `while` loops. `if-else` and `while` loops are similar to other languages. Here are an example for each of them: ```python # if-else a = 1 if a == 1: print("a is 1") else: print("a is not 1") # while loop a = 0 while a < 10: print(a) a += 1 ``` If you come from a `C` background, you may find the `for` loop in `python` a bit strange. In `python`, the `for` loop is actually a `for-each` loop, which means it iterates over the elements in a list or a dictionary, instead of reling on counter. Here is an example of a `for` loop in `python`: ```python a = [0, 1, 2, 3, 4] for i in a: print(i) ``` == Functions In order to define a function in python, you use the `def` keyword. For example, to define a function `add` which takes two arguments `a` and `b` and return the sum of `a` and `b`, you can do: ```python def add(a, b): return a + b ``` Now there is one tricky thing about `python`, which is the passed-by-object-reference. Some of you may have already ran into this in an unfortunate way, but for those who are not aware, here is a very sneaky failure mode one may spend hours trying figure out what's going on. Say I have defined a list `x = [0, 1]`, and I have a function that wants to modify the element in the list and return the modified list, what would you do? You may think you can do something like this: ```python def modify_list(x): x[0] = 1 return x x = [0, 1] y = modify_list(x) ``` Now run try running this in a `python` interpreter, what do you get? Indeed, `y` will have the correct value. However, if you check `x`, you will find `x` is also modified. This is because when dealing with mutable objects such as lists or dictionaries, python passes a reference to the object instead of copying its value. This means when the interpreter is executing the line `x[0] = 1`, it is actually modifying the original object being passed it, causing this problem. To avoid this, you can either make a copy of the object before modifying it, or you can return a new object instead of modifying the original object. For example, you can do: ```python def modify_list(x): x = x.copy() x[0] = 1 return x ``` Copying the object may have some implication on memory usage and performance, so you may want to be careful when doing this. = Exercise: Writing an insertion sort algorithm Now given the information above, let's try to write an insertion sort algorithm. The insertion sort algorithm is pretty simple. Imagine you are holding a hand of unsorted poker cards, and you want to sort the hand by the cards' rank. Let say we start from left and we are going to scan to the right. When ever we are about to sort a card, we compare the current card to the card on the left, if it has a lower rank than the card on its left, we swap their order (say I am trying to sort the second card which is a 2, and the first card is a 5, I will swap them). We keep doing this until we reach the end of the hand. At the end, the hand should be sorted. == Step 1: Clone the repository Fork #link("https://github.com/KazeClasses/python_guide")[this github template repository], then clone it to your local machine. You should see the file named "test_sort.py" in the root directory. == Step 2: Implement the sorting algorithm Open it with your favorite text editor, then change the body of the inerstion_sort function to an insertion sort algorithm. == Step 3: Test the algorithm Run the test_sort.py script with the following command: ```bash python test_sort.py ``` If the test passes, you should see the following output: ``` Tests passed! ``` This means your sorting algorithm is correct. #pagebreak() = Packaging code Now the code is running, let's try to put it in a package so people has an easier time to use it. You can find more reference in the #link("https://packaging.python.org/tutorials/packaging-projects/")[official python packaging guide]. *PSA*: We are making the code base unnecessarily complicated for the sake of learning. The core code we have here is extremely small so there is absolutely no reason to go through all this hassle in practice, but this should be a good exercise to understand how to package a python project. == Step 1: Setting up virtual environment Before we start playing with the code and package it, we do not want these potentially unstable code to be in our global python environment, which may cause some unexpected headache. So let's create a virtual environment for this project. You can do this by running the following command outside the project or in a directory where you want to store the virtual environment: ```bash python -m venv insertion_sort ``` You should see a new directory named `insertion_sort` in the current directory. This is the virtual environment we just created, and it has some executable in it. To activate the virtual environment, you can run the following command: ```bash source insertion_sort/bin/activate ``` You should see your terminal prompt has changed to something like `(insertion_sort) $`. This means you are now in the virtual environment. You can deactivate the virtual environment by running `deactivate`. == Step 2: Modules and imports A `python` package usually contains many modules, which can be imported like `from package.module import function`. The goal here is structure our code such that it can be imported as a package. Now the code is just living the root directory, which is not ideal when you start adding more and more files to the project. Instead, let's follow some standard structure and put our files in the right place. In the root directory of your project, create a directory named `src`, within it create a directory named `insertion_sort`. Create a file named `sort.py` in the `insertion_sort` directory. Move the `insertion_sort` function from `test_sort.py` to `sort.py`. There is one more step to make this work. In order to turn the `insertion_sort` directory into a module, you need to create a file named `__init__.py` in the `insertion_sort` directory. This file can be empty, but it is necessary to make the directory a module when it is packaged. Now your project structure should look like this: ``` root ├── src │ └── insertion_sort │ └── __init__.py │ └── sort.py └── test_sort.py ``` == Step 3: pyproject.toml The next thing to add to the package is a description of project such that the standard build tool can package that information. I used to use `setup.cfg` to set up my project because that was the convention a couple years back. Now the standard way to set up a project is through `pyproject.toml`, which can still use `setuptools` as its backend. There are a lot of options to choose from for `pyproject.toml`, which we are not going to cover all of them. We are going to cover the minimum you need to know to build a binary. For a more complete tutorial and all the different options, you can find more information in the #link("https://packaging.python.org/en/latest/guides/writing-pyproject-toml/")[write your `pyproject.toml` guide]. At the root directory of your project, create a file named `pyproject.toml`. Add the following content to the file: ```toml [build-system] requires = ["setuptools>=61.0"] build-backend = "setuptools.build_meta" [project] name = "insertion_sort" version = "0.0.1" authors = [ { name="<NAME>", email="<EMAIL>" }, ] description = "A small example package" readme = "README.md" requires-python = ">=3.8" classifiers = [ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ] [project.scripts] insertion_sort_cli = "insertion_sort.sort:run_sort" ``` There are three parts in this file. The first part is the `build-system` section, which tells the build system what to use to build the project. The second part is the `project` section, which contains the metadata of the project, such as the name, version, authors, description, and so on. The third part is the `project.scripts` section, which tells the build system to create a binary named `insertion_sort_cli` that runs the `run_sort` function in the `insertion_sort.sort` module. Change the content in the `project` section if you want to. We included the `script` section since I want to show you how to build a bbinary that also provide a command line tool. This is optional but it can be quite convinient for the user. That script is equivalent to running `from insertion_sort.sort import run_sort; run_sort()` in a python shell. == Step 4: Build and install It is time to build and install our package! To build binary that you can distribute, first install `build` with `pip install build`, then you can run the following command: ```bash python -m build ``` If everything goes well, you should see a new directory named `dist` in the root directory of your project. It should contain a `.tar.gz` file and a `.whl` file. These are the binary files that you can distribute to others, and usually it is uploaded to `pypi` with `twine` so people can install it with `pip`. To install the package locally using the binary we just build, you can run the following command: ```bash pip install dist/insertion_sort-0.0.1-py3-none-any.whl ``` Now you should be able to import the package in your python script. On top of that, you should also be able to run the `insertion_sort_cli` binary in your terminal. Try running it and see whether it works. #pagebreak() = Building documentation The structure of the code starting to look nice, however, nothing bring more trust to your code more than a nice documentation page. Once you have some serious documentation going, people will more likely to trust your code and use it. There are many different tools to build documentation in `python`. The more traditionally taught one is sphinx, but I personally find it unnecessarily complicated and looking dull, so I prefer to use `mkdocs` and style it with `material` instead. `Mkdocs` let you write your documenation pages in the `Markdown` format, which is pretty easy to write. == Step 1: Install mkdocs and build basic documentation The first thing to do is to install `mkdocs`. With your environment activated, you can run the following command: ```bash pip install mkdocs ``` Then in the root directory of your project, create a file named `mkdocs.yml`. Add the following content to the file: ```yaml site_name: Insertion Sort nav: - Home: index.md ``` Now, create a fold named `docs` in the root directory of your project. In the `docs` directory, create a file named `index.md`. Add some random content to the file. Then in the root directory of your project, run the following command: ```bash mkdocs serve ``` This will start a local server that serves the documentation. You can then click the link shown in the terminal and you should see your documentation page up and running. For more reference related to `mkdocs`, the official page is #link("https://www.mkdocs.org/")[here]. == Step 2: Style it with Material with mkdocs Plain `mkdocs` actually look quite depressing too. Let's add some style to make it looks nice. I use Material for MkDocs to style my documentation page. You can install it by running the following command: ```bash pip install mkdocs-material ``` Then in the `mkdocs.yml` file, change the content to the following: ```yaml site_name: Insertion Sort theme: name: material nav: - Home: index.md ``` Now if you go back to your doc page, you should see it suddenly looks much nicer already. There are many choices you can make to customize the look of the documentation page, you can find more information in the #link("https://squidfunk.github.io/mkdocs-material/")[official documentation page]. == Step 3: API documentation Now this could be a bit more indepth since it needs to install your package, read the doc strings in your code and automatically generate the documentation page for API. I am not going into the detail of how to configure this, but you look for the voodoo magic I cooked up in one of my public repo #link("https://github.com/kazewong/flowMC/tree/main")[flowMC]. Here, I will show you the bare minimum of getting an API documentation page up and running. The package you will need here is `mkdocstrings` and its python handler. You can install it by running the following command: ```bash pip install mkdocstrings mkdocstrings-python ``` In `docs` directory, create a file named `api.md`. Add the following content to the file: ```markdown # API Documentation ::: insertion_sort.sort ``` Then in the `mkdocs.yml` file, change the content to the following: ```yaml site_name: Insertion Sort theme: name: material nav: - Home: index.md - API: api.md plugins: - mkdocstrings: ``` Now if you look at the page, you should see the API documentation there. #pagebreak() = Writing tests If you do not like writing documentation, there is a high likelihood that you do not like writing unit tests for your code. Unit tests are great way to catch any errors in your code, and when more contributors start to work on the same code, it is also a great way to catch any unexpected failure. The thing is, writing tests sound like some extra chores you have to do on top of the already dreadful development, so no body likes to do it. Here is how I trick myself into writing tests: we often write a bunch of scrappy scripts in development to se whether the code we created are function in the way we expected. I always create these scripts in either `test/integration` or `test/unit`, and only move them out if I want to make them an example. In this way, when I am done with my development, the tests are automatically there. The most popular package used for testing `python` code is `pytetst`, and it is quite easy to use. You can find more information in #link("https://docs.pytest.org/en/stable/")[here]. == Step 1: Install pytest With your environment activated, you can run the following command to install `pytest`: ```bash pip install pytest ``` Now for all the test we want to write, we have to write it with the prefix `test_`, so `pytest` know it is a test. This includes the test function name and the test file name. == Step 2: Move the test code to a test directory I have this default test script `test_sort.py` in the root directory, let's create a `test` directory in the root directory and move the `test_sort.py` to the `test` directory. The next thing you will have to do is to take off the extra function definition in the test file, including the `__main__` block, and import the package we wrote. Once that is done, you can run the following command in the root directory of your project: ```bash pytest ``` This should run all the test in the `test` directory. If everything goes well, you should a long green line saying how many tests passed. == Rules of thumb People have different opinions on writing tests. I usually keep two sets of tests in my test directory, `integration` and `unit` test. `integration` tests are aiming to test the entire code base in the way we anticipate the user to use it, while `unit` tests are testing the individual function in the code base. I usually write `unit` tests for all the functions I wrote, and I only write `integration` tests when I am done with the development and I want to make sure the code is working as expected. When you write tests, you want to make sure they are as brutal as possible. The more brutal the test is, the more likely it is going to catch any unexpected failure. There is no point in writing a test that is going to pass no matter what. Use `assert <condition>` to make sure the test is going to fail if the condition is not met. #pagebreak() = Best practices/Development tips == Virtual environment In general it is good to have a virtual environment for each project you are working on. This is because different projects may have different dependencies, and you do not want to have a conflict between the dependencies of different projects. This is especially important when you are working on a project that has a lot of dependencies, or you are working on a project that has a lot of dependencies that are not compatible with each other. However, this means you may potentially create a lot of files and unwanted stress for the file system, so make sure you clean up the virtual environment when you are done with the project. == IPython One tool I use for quick experiment quite a lot is just plain old IPython. These days people prefer to use Jupyter notebook whenever they experiment, but if I am on a cluster environment or I just need to test a couple of easy thing, I prefer ipython over Jupyter notebook simply because in this way I can (am required to) navigate with my keyboard, which is much faster for me than mouse. == Debugging There are many ways to debug a python code. You can use the `print` statement method of course, and fundamentally there is nothing wrong about that. There is two more methods I use quite often, first is with `IPython`, you can use the `pdb` module to debug your code. Say you are running some code and hit an error, instead of running the code again and wait for the print statement, you can actually do `%debug` in `IPython` to enter a `pdb` session immediately to investigate the stack. This method also works in Jupyter notebook, but it gets pretty clumsy pretty quickly if you don't have the set up. Another method you can use is the debugger integration in your IDE. I use `VSCode`, which allows you to set breakpoints and run the code in debug mode. This is especially useful when you are working on a large code base and you want to investigate the code step by step, but sometimes the debugger can get caught in some environment issue related to VSCode, making it slightly less reliable. == Typing Typing is probably one thing that is overlooked and never taught in `python`, and yet it is quite essential in making your code more readable and maintainable, espcially when it comes to machine learning code. Typing refers to syntax like the following ```python def add(a: int, b: int) -> int: return a + b ``` Instead of just `def add(a, b):`, you can add type hint to the function signature to make it clear what type of argument the function is expecting and what type of value it is returning. In an IDE, there are usually plugins associated with `python` that can scan through your local code base and relay typing information, which can be very useful during development. For example, if you have a custom class defined within your project with cetain methods and attrbiutes, if the typing information is available, you can see what methods are available and their function signature when hovering your cursor over the instance, and the IDE can automcomplete your code. == Linting and formatting Linting and formatting are essential to ensure the quality of your code. Linting is the process of checking your code for potential errors, while formatting is the process of making your code look consistent. The linter I use is #link("https://github.com/astral-sh/ruff")[ruff]. The formatter is #link("https://github.com/psf/black")[black]. You can also install plugin in your IDE to show linting errors and format your code automatically. == Pre-commit Pre-commit is very useful tool enforce linting and formatting for your code. It runs linter and formatting automatically before you are allow to commit. It is espcially useful when you are managing a project with multiple contributors, such that we can ensure code on the repository is well format and clean from common mistakes. You can find more information in the #link("https://pre-commit.com/")[official page]. = Noteworthy libraries == Jax I like to start with `jax` probably because I am a heavy `jax` user. Don't get me wrong, I use `PyTorch` too, but I use `jax` more because of its performance but also the workflow I have in `jax` is very close to the workflow I had before machine learning library became a thing. Basically, if you are familiar with `numpy` and `scipy`, you should find `jax` is basically `numpy` on steroids. We are going to do a deeper diver later in the course. == Flask Flask is a minimalistic web framework for `python`, which is very easy to get start, making it a great choice for beginners and a starting point for small-scale projects. A quick start can be done in 5 lines of code ```python from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): return "<p>Hello, World!</p>" ``` If you save the file under the name `hello.py`, then you can start a development server by running ```bash flask --app hello run```. Once your server is up and running, you can visit the url in your browser and you should see the message `Hello, World!`. We are going to build some simple web app later in the course, so we will come back to this. You can find more information in the #link("https://flask.palletsprojects.com/en/3.0.x/")[official page]. == HoloViews The most common introductory plotting library in python is probably `matplotlib`, which is pretty straight forward to get start with. However, sometimes it may seem to be hard to interact with plot and iterate over your projects quickly. To do this, I discovered `HoloViews` not too long ago, which I find it to be great for data exploration. You can find some of `HoloViews` killer features #link("https://holoviews.org/getting_started/Introduction.html#effortlessly-exploring-data")[here]. == Too common/Too obscure `numpy`, `scipy`, `pandas`, `matplotlib`, `seaborn`, `scikit-learn`, `pytorch`,
https://github.com/haxibami/haxipst
https://raw.githubusercontent.com/haxibami/haxipst/main/README.md
markdown
# haxipst My typst templates & utilities (WIP). Includes: - `resume` - resume / document template - `set-metadata` - utility to set metadata for PDF files - `better-indent` - utility to indent first paragraph (See: [typst/typst #311](https://github.com/typst/typst/issues/311)) - `better-heading` - utilty to get loose heading - `macro/*` - various macros (`#noindent`, `#latex`...) ## Install This package is not published to official repo, since it is my personal one. But you can use it as local package (See [Official Guide](https://github.com/typst/packages#local-packages) for more information). ```sh cd {data-dir} # Depends on your environment mkdir -p ./typst/packages/local/haxipst && cd ./typst/packages/local/haxipst git clone https://github.com/haxibami/haxipst.git 0.1.1 ``` ## Usage See `test/sample.typ` for example usage. ```typ #import "@local/haxipst:0.1.1": * #show: resume.with( pdf-author: "著者", pdf-keywords: ( "キーワード1", "キーワード2", ), title: [#text(size: 1.5em)[*タイトル*]], author: [著者], header: [ヘッダー #h(1fr) #datetime.today().display()], ) ```
https://github.com/rinmyo/ruby-typ
https://raw.githubusercontent.com/rinmyo/ruby-typ/main/manual.typ
typst
MIT License
// Set the document's basic properties. #set document(author: ("rinmyo"), title: "ruby-typ") #set page(numbering: "1", number-align: center) #set text(font: "Linux Libertine", lang: "en") #show link: underline // Title row. #align(center)[ #block(text(weight: 700, 1.75em, "ruby-typ")) ] // Author information. #pad( top: 0.5em, bottom: 0.5em, x: 2em, align(center)[rinmyo] ) // Main body. #set par(justify: true) // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #import "ruby.typ": get_ruby #let ruby = get_ruby() = Introduction A library to implement ruby just like this: #align(center)[ #ruby(alignment:"between", "レールガン")[超電磁砲]、#ruby("ページ")[頁]、#ruby("きょう")[今日]もいい#ruby("てん|き")[天|気] ] = Usage To use ruby-typ, you should import the `get_ruby` from `ruby.typ` at first. ```typ #import "ruby.typ": get_ruby ``` `get_ruby` is a higher-order function which be used to configure ruby-typ. and it will return a function for ruby. and its function signature is ```typc get_ruby( size: .5em, // the font size of ruby text dy: 0pt, // to add a shifting space on y axis pos: top, // the position of ruby text, can be (top, bottom) alignment: "center", // can be ("center", "start", "between", "around") delimiter: "|" // the delimiter used in mono-ruby ) ``` to get a ruby function with default setting ```typ #let ruby = get_ruby() ``` and the `ruby()` function will receive two arguments, the first one for ruby text and the second one for ruby body. for example, if you'd like to use a `start` alignment. ```typ #let ruby = get_ruby(alignment: "start") #ruby("しずく", "雫") ``` which the result will be #let ruby = get_ruby(alignment: "start") #align(center, ruby("しずく")[雫]) #let ruby = get_ruby() == ruby for content Besides the `string`, it's also allowed to pass a content except sequence as `ruby()`'s ruby body just like how other element functions do. ```typ #ruby("したた")[滴]る ``` will produce #align(center)[#ruby("したた")[滴]る] Moreover, almost all kinds of content excluding sequence can be passed, which is convenient for some styled text. ```typ #ruby("エックス|せん")[#underline[_*X|ray*_]] ``` will output #align(center)[#ruby("エックス|せん")[_*X|ray*_]] == mono/group ruby ruby-typ supports mono-ruby and group-ruby automatically, which depends on whether the inputs are separated by a delimiter. ```typ #ruby("とうきょうこうぎょうだいがく")[東京工業大学] #ruby("とう|きょう|こう|ぎょう|だい|がく")[東|京|工|業|大|学] ``` will generate respectively #align(center)[ #ruby("とうきょうこうぎょうだいがく")[東京工業大学] #ruby("とう|きょう|こう|ぎょう|だい|がく")[東|京|工|業|大|学] ] As you see, ruby-typ is able to adjust the spaces of the body texts automatically in mono-ruby mode. = Thanks this project is based on #link("https://github.com/SaitoAtsush")[<NAME>]'s great idea and the #link("https://zenn.dev/saito_atsushi/articles/ff9490458570e1")[original source codes] posted on their blog = Changelog - [20230425a] Release the initial version. - [20230426a] a newer implement - [20230426b] add `pos` option to specify the position of ruby texts
https://github.com/VadimYarovoy/Networks2
https://raw.githubusercontent.com/VadimYarovoy/Networks2/main/lab2/report/typ/questions.typ
typst
#import "@preview/colorful-boxes:1.2.0": * = Ответы на вопросы == Вопрос 1 #colorbox( title: "TODO", color: "blue", radius: 2pt, width: auto )[ Архитектура современной почтовый системы: Протоколы: SMTP, POP3, IMAP – зачем нужны MTA, MDA, MUA – что это Примеры используемого софта ] \ Протоколы: - SMTP (Simple Mail Transfer Protocol): Используется для отправки электронных писем. Отправитель передает письмо на почтовый сервер, который затем доставляет его получателю. - POP3 (Post Office Protocol version 3): Используется для загрузки электронных писем с сервера на клиентское устройство (обычно почтовый клиент). Письма обычно удаляются с сервера после загрузки. - IMAP (Internet Message Access Protocol): Также используется для доступа к электронным письмам на сервере, но письма остаются на сервере и синхронизируются между клиентским устройством и сервером. Архитектурные компоненты: - MTA (Mail Transfer Agent): Программное обеспечение, ответственное за передачу электронных писем между почтовыми серверами. - MDA (Mail Delivery Agent): Программное обеспечение, отвечающее за доставку электронных писем на конечное устройство получателя или их хранение на сервере. - MUA (Mail User Agent): Клиентское приложение, используемое конечным пользователем для чтения, отправки и управления электронными письмами Примеры софта: - MTA: Postfix, Exim, Sendmail. - MDA: Dovecot, Cyrus. - MUA: Microsoft Outlook, Mozilla Thunderbird, Apple Mail. == Вопрос 2 #colorbox( title: "TODO", color: "blue", radius: 2pt, width: auto )[ Типичный сценарий работы по протоколу SMTP ] + Отправитель устанавливает соединение с почтовым сервером получателя. + Отправляет команду HELO или EHLO для установки соединения. + Передает получателя командой MAIL FROM. + Указывает адрес получателя командой RCPT TO. + Отправляет само письмо с командой DATA. + Завершает передачу командой QUIT. == Вопрос 3 == Вопрос 2 #colorbox( title: "TODO", color: "blue", radius: 2pt, width: auto )[ Коды ответов серверов SMTP/IMAP/POP3 ] \ *SMTP* (Simple Mail Transfer Protocol): + 2xx (успешно): - 211 – Система приняла команду. Информационный ответ. - 214 – Справочная информация по системе. - 220 – Сервер готов к работе. - 221 – Закрывается соединение. - 250 – Успешное выполнение команды. + 3xx (переадресация): - 354 – Ожидается ввод данных. + 4xx (временная недоступность): - 421 – Сервер временно недоступен. - 450 – Ошибка при передаче команды. Повторите. + 5xx (постоянная недоступность): - 501 – Синтаксическая ошибка в команде. - 550 – Невозможно выполнить команду. - 552 – Превышен лимит по размеру сообщения. *IMAP* (Internet Message Access Protocol): + Основные: - OK: Команда выполнена успешно. - NO: Ошибка в выполнении команды. - BAD: Синтаксическая ошибка или неверный запрос. + Дополнительные: - PREAUTH: Сообщение перед успешной аутентификацией. - BYE: Закрывается соединение. *POP3* (Post Office Protocol version 3): + Основные: - +OK: Команда выполнена успешно. - -ERR: Ошибка в выполнении команды. + Дополнительные: - CAPA: Сервер поддерживает список возможностей. - TOP: Запрос заголовка и первых N строк сообщения. - USER/PASS: Аутентификация пользователя. - QUIT: Закрытие соединения. == Вопрос 4 #colorbox( title: "TODO", color: "blue", radius: 2pt, width: auto )[ В чем разница между протоколами *IMAP* и *POP3* ] \ *IMAP* (Internet Message Access Protocol): - Хранение: Сообщения хранятся на сервере. - Синхронизация: Состояние почтового ящика синхронизируется между сервером и клиентским устройством. - Оффлайн режим: Работа с письмами возможна в оффлайн-режиме. - Управление письмами: Можно создавать папки и управлять письмами на сервере. *POP3* (Post Office Protocol version 3): - Хранение: Сообщения загружаются на клиентское устройство и могут быть удалены с сервера. - Синхронизация: Нет синхронизации состояния между сервером и клиентским устройством. - Оффлайн режим: Требует подключения к серверу для просмотра писем. #pagebreak()
https://github.com/SundaeSwap-finance/sundae-audits-public
https://raw.githubusercontent.com/SundaeSwap-finance/sundae-audits-public/main/template/audit.typ
typst
// severity colors #let severity_colors = ( Critical: rgb("#6E0B05"), Major: rgb("#EC4460"), Minor: rgb("#F7797D"), Info: rgb("#CCDAD1"), Witness: rgb("#9EE493"), ) #let severity_text_colors = ( Critical: rgb("#FFFFFF"), Major: rgb("#FFFFFF"), Minor: rgb("#FFFFFF"), Info: rgb("#000000"), Witness: rgb("#000000"), ) // status colors #let status_colors = ( Resolved: rgb("#00CE60"), Mitigated: rgb("#FC9F5B"), Acknowledged: rgb("#890620"), Identified: rgb("#77479F"), ) #let status_text_colors = ( Resolved: rgb("#000000"), Mitigated: rgb("#000000"), Acknowledged: rgb("#FFFFFF"), Identified: rgb("#FFFFFF"), ) // other colors #let table_header = rgb("#E5E5E5") // table cells #let cell = rect.with( inset: 10pt, fill: rgb("#F2F2F2"), width: 100%, height: 50pt, radius: 2pt ) #let tx_link(url, content) = { link(url, underline(text(fill: rgb("#007bff"), content))) } // The project function defines how your document looks. // It takes your content and some metadata and formats it. // Go ahead and customize it to your liking! #let report( client: "", title: "", authors: (), date: none, repo: "", body, ) = { // Set the document's basic properties. set document(author: authors.map(a => a.name), title: client + " - " + title) set text(font: "Linux Libertine", lang: "en") set heading(numbering: "1.a.i -") set underline(offset: 0.3em) show link: underline // Title page. // The page can contain a logo if you pass one with `logo: "logo.png"`. set page( background: [ #image("img/bg.jpg", width: 100%, height: 100%) ] ) text(1.1em, date, fill: white) v(1.2em, weak: true) text(2em, weight: 500, client, fill: white) v(0em) text(3em, weight: 700, title, fill: white) v(9.6fr) v(4.8fr) // Author information. if authors.len() > 0 { set text(1.3em, fill: white) pad( top: 0.7em, right: 20%, grid( columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..authors.map(author => align(start, strong(author.display))), ), ) } v(2.4fr) pagebreak() set page(numbering: "1", number-align: center, fill: none, background: []) // Table of contents. outline(depth: 2, indent: true, ) pagebreak() // Main body. set par(justify: true, leading: 1.5em) body [ = Appendix #v(1em) == Disclaimer #v(1em) This Smart Contract Security Audit Report ("Report") is provided on an "as is" basis, for informational purposes only, and should not be construed as investment advice or any other kind of advice on legal, financial, or other matters. The entities and individuals involved in preparing this Report ("Auditors") do not guarantee the accuracy, completeness, or usefulness of the information provided herein and shall not be held liable for any contents, errors, omissions, or inaccuracies in this Report or for any actions taken in reliance thereon. The Auditors make no claims, promises, or guarantees about the absolute security of the smart contracts audited and the underlying code. The findings, interpretations, and conclusions presented in this Report are based on the best efforts of the Auditors and reflect their professional judgment at the time of the audit. The blockchain and cryptocurrency landscape is rapidly evolving, and new vulnerabilities may emerge that were not identified or considered at the time of the audit. As such, this Report should not be considered as a comprehensive guarantee of the audited smart contracts' security. The Auditors disclaim, to the fullest extent permitted by law, any and all warranties, whether express or implied, including without limitation, warranties of merchantability, fitness for a particular purpose, and non-infringement. The Auditors shall not be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this Report, even if advised of the possibility of such damage. This Report is not exhaustive and is subject to change without notice. The Auditors reserve the right to update, modify, or revise this Report based on new information, subsequent developments, or further analysis. The Auditors encourage all interested parties to conduct their own independent research and due diligence when evaluating the security of smart contracts. By using or relying on this Report, you agree to indemnify and hold harmless the Auditors from any claim, demand, action, damage, loss, cost, or expense, including attorney fees, arising out of or relating to your use of or reliance on this Report. If you have any questions or require further clarification regarding this Report, please contact the <EMAIL>. #pagebreak() == Issue Guide === Severity #v(1em) #grid( columns: (20%, 80%), gutter: 1pt, cell(fill: table_header, height: auto)[ #set align(horizon + center) *Severity* ], cell(fill: table_header, height: auto)[ #set align(horizon + center) *Description* ], cell(fill: severity_colors.Critical, height: 7em)[ #set align(horizon + center) #set text(fill: severity_text_colors.Critical) Critical ], cell(height: 7em)[ #set align(horizon) Critical issues highlight exploits, bugs, loss of funds, or other vulnerabilities that prevent the dApp from working as intended. These issues have no workaround. ], cell(fill: severity_colors.Major, height: 6.5em)[ #set align(horizon + center) #set text(fill: severity_text_colors.Major) Major ], cell(height: 6.5em)[ #set align(horizon) Major issues highlight exploits, bugs, or other vulnerabilities that cause unexpected transaction failures or may be used to trick general users of the dApp. dApps with Major issues may still be functional. ], cell(fill: severity_colors.Minor, height: 6em)[ #set align(horizon + center) #set text(fill: severity_text_colors.Minor) Minor ], cell(height: 6em)[ #set align(horizon) Minor issues highlight edge cases where a user can purposefully use the dApp in a non-incentivized way and often lead to a disadvantage for the user. ], cell(fill: severity_colors.Info, height: 10.4em)[ #set align(horizon + center) #set text(fill: severity_text_colors.Info) Info ], cell(height: 10.4em)[ #set align(horizon) Info are not issues. These are just pieces of information that are beneficial to the dApp creator, or should be kept in mind for the off-chain code or end user. These are not necessarily acted on or have a resolution, they are logged for the completeness of the audit. ], cell(fill: severity_colors.Witness, height: 9.4em)[ #set align(horizon + center) #set text(fill: severity_text_colors.Witness) Witness ], cell(height: 9.4em)[ #set align(horizon) Witness findings are affirmative findings, which covers bizarre corner cases we considered and found to be safe. Not all such cases are covered, but when something is considered interesting, or might be a common question, we try to include it. ], ) #v(1em) === Status #v(1em) #grid( columns: (20%, 80%), gutter: 1pt, cell(fill: table_header, height: auto)[ #set align(horizon + center) *Status* ], cell(fill: table_header, height: auto)[ #set align(horizon + center) *Description* ], cell(fill: status_colors.Resolved)[ #set align(horizon + center) #set text(fill: status_text_colors.Resolved) Resolved ], cell()[ #set align(horizon) Issues that have been *fixed* by the *project* team. ], cell(fill: status_colors.Mitigated)[ #set align(horizon + center) #set text(fill: status_text_colors.Resolved) Mitigated ], cell()[ #set align(horizon) Issues that have a *partial mitigation*, and are now vulnerable in only *extreme* corner cases. ], cell(fill: status_colors.Acknowledged)[ #set align(horizon + center) #set text(fill: status_text_colors.Acknowledged) Acknowledged ], cell()[ #set align(horizon) Issues that have been *acknowledged* or *partially fixed* by the *project* team. Projects can decide to not *fix* issues for whatever reason. ], cell(fill: status_colors.Identified)[ #set align(horizon + center) #set text(fill: status_text_colors.Identified) Identified ], cell()[ #set align(horizon) Issues that have been *identified* by the *audit* team. These are waiting for a response from the *project* team. ], ) #pagebreak() == Revisions #v(1em) This report was created using a git based workflow. All changes are tracked in a github repo and the report is produced using #tx_link("https://typst.app")[typst]. The report source is available #tx_link(repo)[here]. All versions with downloadable PDFs can be found on the #tx_link(repo + "/releases")[releases page]. #v(1em) == About Us #v(1em) Sundae Labs stands at the forefront of innovation within the Cardano ecosystem, distinguished by its pioneering development of the first Automated Market Maker (AMM) Decentralized Exchange (DEX) on Cardano. As a trusted leader in blockchain technology, we offer a comprehensive suite of products and services designed to enhance the Cardano network's functionality and security. Our offerings include Sundae Rewards, Sundae Governance, Sundae Exchange, and Sundae Taste Test—an automated price discovery platform—all available on a Software as a Service (SaaS) basis. These solutions empower other high-profile projects within the ecosystem by providing them with turnkey rewards and governance capabilities, thereby fostering a more robust and scalable blockchain infrastructure. Beyond our product offerings, Sundae Labs is deeply committed to the advancement of the Cardano community and its underlying technology. We contribute significantly to research and development efforts aimed at improving Cardano's security and scalability. Our engagement with Input Output Global (IOG) initiatives, such as Voltaire, and participation in core technological discussions underscore our dedication to the Cardano ecosystem's growth. Additionally, our expertise extends to software development consulting services, including product design and development, and conducting security audits. Sundae Labs is not just a contributor but a vital partner in Cardano's journey towards achieving its full potential. #v(1em) === Links #v(1em) ] } #let software_versions(items: ()) = { grid( columns: (1.5fr, 1.6fr, 2fr), gutter: 1pt, cell(fill: rgb("#E5E5E5"), height: 2.4em)[*Software*], cell(fill: rgb("#E5E5E5"), height: 2.4em)[*Version*], cell(fill: rgb("#E5E5E5"), height: 2.4em)[*Commit*], ..items.map( row => ( cell(height: 2.4em)[*#row.name*], cell(height: 2.4em)[ #align(horizon, text(0.7em, raw(row.version)))], cell(height: 2.4em)[ #align(horizon, text(0.7em, raw(row.commit))) ], ) ).flatten() ) } #let files_audited(items: ()) = { grid( columns: (1fr, 1.3fr), gutter: 1pt, cell(fill: rgb("#E5E5E5"), height: 2.4em)[*Filename*], cell(fill: rgb("#E5E5E5"), height: 2.4em)[*Hash (SHA256)*], ..items.map( row => ( cell(height: 3.4em)[ #align(horizon, text(0.8em, row.file)) ], cell(height: 3.4em)[ #align(horizon, text(0.7em, raw(row.hash))) ], ) ).flatten() ) } #let parameters( parameters, column_sizes: (1fr, 1fr) ) = { grid( columns: column_sizes, gutter: 1pt, cell(fill: rgb("#E5E5E5"), height: 2.4em)[*Parameter*], cell(fill: rgb("#E5E5E5"), height: 2.4em)[*Value*], ..parameters.map( row => ( cell(height: 2.4em)[#text(0.8em, raw(row.name))], cell(height: 2.4em)[#text(0.7em, raw(row.value))], ) ).flatten() ) } #let artifacts( artifacts, column_sizes: (1fr, 1fr, 3fr) ) = { grid( columns: column_sizes, gutter: 1pt, cell(fill: rgb("#E5E5E5"), height: 2.4em)[*Validator*], cell(fill: rgb("#E5E5E5"), height: 2.4em)[*Method*], cell(fill: rgb("#E5E5E5"), height: 2.4em)[*Hash (Blake2b-224)*], ..artifacts.map( row => ( cell(height: 2.4em)[#text(0.8em, row.validator)], cell(height: 2.4em)[#text(0.8em, row.method)], cell(height: 2.4em)[#text(0.7em, raw(row.hash))], ) ).flatten() ) } #let tx_out_height_estimate(input) = { let address = if "address" in input { 1 } else { 0 } let value = if "value" in input { input.value.len() } else { 0 } let datum = if "datum" in input { input.datum.len() } else { 0 } return (address + value + datum) * 8pt } #let datum_field(indent, k, val) = [ #if val == "" [ #h(indent)\+ #raw(k) ] else [ #h(indent)\+ #raw(k): #if type(val) == content { val } #if type(val) == str and val != "" {repr(val)} #if type(val) == int {repr(val)} #if type(val) == array [ #stack(dir: ttb, spacing: 0.4em, for item in val [ #datum_field(indent + 1.2em, "", item) \ ] ) ] #if type(val) == dictionary [ #v(-0.7em) #stack(dir: ttb, spacing: 0em, for (k, v) in val.pairs() [ #datum_field(indent + 1.2em, k, v) \ ] ) ] ] ] #let tx_out(input, position, inputHeight, styles) = { let address = if "address" in input [ *Address: #h(0.5em) #input.address* ] else [] let value = if "value" in input [ *Value:* #if ("ada" in input.value) [ *#input.value.ada* ADA ] \ #v(-1.0em) #stack(dir: ttb, spacing: 0.4em, ..input.value.pairs().map(((k, v)) => [ #if k != "ada" { [#h(2.3em) \+ *#v* #raw(k)] } ]) ) ] else [] let datum = if "datum" in input [ *Datum:* \ #v(-0.8em) #stack(dir: ttb, spacing: 0.4em, ..input.datum.pairs().map(((k,val)) => datum_field(1.2em, k, val)) ) ] else [] let addressHeight = measure(address, styles).height + if "address" in input { 6pt } else { 0pt } let valueHeight = measure(value, styles).height + if "value" in input { 6pt } else { 0pt } let datumHeight = measure(datum, styles).height + if "datum" in input { 6pt } else { 0pt } let thisHeight = 32pt + addressHeight + valueHeight + datumHeight return ( content: place(dx: position.x, dy: position.y, [ *#input.name* #line(start: (-4em, -1em), end: (10em, -1em)) #place(dx: 10em, dy: -1.5em)[#circle(radius: 0.5em, fill: white, stroke: black)] #if "address" in input { place(dx: 0em, dy: -3pt)[#address] } #place(dx: 0em, dy: addressHeight)[#value] #if "datum" in input { place(dx: 0em, dy: addressHeight + valueHeight)[#datum] } ]), height: thisHeight, ) } #let collapse_values(existing, v, one) = { if type(v) == int { existing.qty += one * v } else { let parts = v.matches(regex("([ ]*([+-]?)[ ]*([0-9]*)[ ]*([a-zA-Z]*)[ ]*)")) for part in parts { let sign = part.captures.at(1) let qty = int(if part.captures.at(2) == "" { 1 } else { part.captures.at(2) }) let var = part.captures.at(3) let existing_var = existing.variables.at(var, default: 0) if var == "" { existing.qty += one * qty } else { if sign == "-" { existing.variables.insert(var, existing_var - one * qty) } else { existing.variables.insert(var, existing_var + one * qty) } } } } existing } #let transaction(name, inputs: (), outputs: (), signatures: (), certificates: (), validRange: none, notes: none) = style(styles => { let inputHeightEstimate = inputs.fold(0pt, (sum, input) => sum + tx_out_height_estimate(input)) let inputHeight = 0em let mint = (:) let inputs = [ #let start = (x: -18em, y: 1em) #for input in inputs { // Track how much is on the inputs if not input.at("reference", default: false) { if "value" in input { for (k, v) in input.value { let existing = mint.at(k, default: (qty: 0, variables: (:))) let updated = collapse_values(existing, v, -1) mint.insert(k, updated) } } } let tx_out = tx_out(input, start, inputHeight, styles) tx_out.content // Now connect this output to the transaction place(dx: start.x + 10.5em, dy: start.y + 0.84em)[ #path( stroke: if input.at("reference", default: false) { aqua } else { black }, ((0em, 0em), (0em, 0em), (8em, 0em)), ((7.44em, (inputHeightEstimate / 1.25) - (inputHeight / 1.25)), (-4em, 0em)) ) ] place(dx: start.x + 10.26em, dy: start.y + 0.59em)[#circle(radius: 0.25em, fill: black)] if input.at("redeemer", default: none) != none { place(dx: start.x + 12.26em, dy: start.y - 0.2em)[#input.at("redeemer")] } start = (x: start.x, y: start.y + tx_out.height) inputHeight += tx_out.height } ] let outputHeightEstimate = outputs.fold(0pt, (sum, output) => sum + tx_out_height_estimate(output)) let outputHeight = 0em let outputs = [ #let start = (x: 4em, y: 1em) #for output in outputs { // Anything that leaves on the outputs isn't minted/burned! if "value" in output { for (k, v) in output.value { let existing = mint.at(k, default: (qty: 0, variables: (:))) let updated = collapse_values(existing, v, 1) mint.insert(k, updated) } } let tx_out = tx_out(output, start, outputHeight, styles) tx_out.content start = (x: start.x, y: start.y + tx_out.height) outputHeight += tx_out.height } ] // Collapse down the `mint` array let display_mint = (:) for (k, v) in mint { let has_variables = v.variables.len() > 0 and v.variables.values().any(v => v != 0) if v.qty == 0 and not has_variables { continue } let display = [] if v.qty != 0 { display = if v.qty > 0 { [\+] } + [#v.qty] } let vs = v.variables.pairs().sorted(key: ((k,v)) => -v) if vs.len() > 0 { for (k, v) in vs { if v == 0 { continue } else if v > 0 { display += [ \+ ] } else if v < 0 { display += [ \- ] } if v > 1 or v < -1 { display += [#calc.abs(v)] } display += [*#k*] } } display += [ *#raw(k)*] display_mint.insert(k, display) } let mints = if display_mint.len() > 0 [ *Mint:* \ #for (k, v) in display_mint [ #v \ ] ] else [#v(-1em)] let sigs = if signatures.len() > 0 [ *Signatures:* \ #for signature in signatures [ - #signature ] ] else [#v(-1em)] let certs = if certificates.len() > 0 [ *Certificates:* #for certificate in certificates [ - #certificate ] ] else [#v(-1em)] let valid_range = if validRange != none [ *Valid Range:* \ #if "lower" in validRange [#validRange.lower $<=$ ] `slot` #if "upper" in validRange [$<=$ #validRange.upper] ] else [#v(-1em)] let boxHeight = 100pt + if certificates.len() > 0 { 32pt * certificates.len() } else { 0pt } + if signatures.len() > 0 { 32pt * signatures.len() } else { 0pt } let transaction = [ #set align(center) #rect( radius: 4pt, height: calc.max(boxHeight, inputHeight + 16pt, outputHeight + 16pt), [ #pad(top: 1em, name) #v(1em) #set align(left) #stack(dir: ttb, spacing: 1em, mints, sigs, certs, valid_range, ) ] ) ] let diagram = stack(dir: ltr, inputs, transaction, outputs ) let size = measure(diagram, styles) block(width: 100%, height: size.height)[ #set align(center) #diagram #if notes != none [ *Note*: #notes ] ] }) // Utilities #let anchor(title) = label("anchor_" + title) #let defn(title, ..definition) = block( inset: 8pt, radius: 4pt, { [ - #underline[#strong[#title]] #anchor(title) #list(tight: false, spacing: 1em, ..definition.pos().map(d => d)) ] } ) #let ref(title, display: "") = link(anchor(title))[ #underline[#strong[ #if display == "" { title } else { display } ]] ] #let titles = ("ID", "Title", "Severity", "Status") #let finding_titles = ("Category", "Commit", "Severity", "Status") #let findings(prefix: "XX", items: ()) = { let severity_num = ( Critical: "0", Major: "1", Minor: "2", Info: "3", Witness: "4", ) let counters = ( Critical: 0, Major: 0, Minor: 0, Info: 0, Witness: 0, ) findings = () for finding in items { let resolution = finding.at("resolution", default: (:)) let status = if resolution == (:) { "Identified" } else if finding.resolution.at("commit", default: "") != "" { "Resolved" } else if finding.resolution.at("comment", default: "") != "" { "Acknowledged" } if finding.severity == "Witness" { status = "Resolved" } let idx = "00" + str(counters.at(finding.severity)) let id = prefix + "-" + severity_num.at(finding.severity) + idx.slice(-2) finding.insert("status", status) finding.insert("id", id) counters.insert(finding.severity, counters.at(finding.severity) + 1) findings.push(finding) } findings = findings.sorted(key: row => severity_num.at(row.severity)) grid( columns: (1fr, 46%, 1fr, 1.2fr), gutter: 1pt, ..titles.map(t => cell(fill: table_header, height: auto)[ #set align(horizon + center) *#t* ]), ..findings .map( row => { ( cell()[ #set align(horizon + center) #ref(row.id) ], cell()[ #set align(horizon) #row.title ], cell( fill: severity_colors.at(row.severity) )[ #set align(horizon + center) #set text(fill: severity_text_colors.at(row.severity)) #row.severity ], cell( fill: status_colors.at(row.status) )[ #set align(horizon + center) #set text(fill: status_text_colors.at(row.status)) #row.status ] ) } ) .flatten() ) pagebreak() set heading(numbering: none) for finding in findings { [ == #finding.id - #finding.title #anchor(finding.id) #v(1em) #grid( columns: (1fr, 40%, 0.8fr, 0.8fr), gutter: 1pt, ..finding_titles.map(t => cell(fill: rgb("#E5E5E5"), height: auto)[ #set align(horizon + center) *#t* ]), cell(height: 2.5em)[ #set align(horizon + center) #finding.at("category", default: "None") ], cell(height: 2.5em)[ #set align(horizon + center) #set text(0.7em) #finding.at("resolution", default: (commit: " ")).at("commit", default: " ") ], cell( height: 2.5em, fill: severity_colors.at(finding.severity) )[ #set align(horizon + center) #set text(fill: severity_text_colors.at(finding.severity)) #finding.severity ], cell( height: 2.5em, fill: status_colors.at(finding.status) )[ #set align(horizon + center) #set text(0.9em, fill: status_text_colors.at(finding.status)) #finding.status ] ) #v(1em) === Description #v(1em) #finding.description #if finding.at("recommendation", default: none) != none [ #v(1em) === Recommendation #v(1em) #finding.recommendation ] #if finding.at("resolution", default: none) != none [ #v(1em) === Resolution #v(1em) #let status = finding.at("status", default: none) #if status == "Resolved" { "This issue was resolved as of commit " + raw(finding.resolution.commit) if finding.resolution.at("comment", default: "") != "" { ", with the comment: " + finding.resolution.comment + "." } else { "." } } else if status == "Acknowledged" { "This issue was acknowledge by the project team with the comment: " + finding.resolution.comment + "." } else { "This issue is still open and has not been resolved." } ] ] pagebreak() } }
https://github.com/JvandeLocht/assignment-template-typst-hfh
https://raw.githubusercontent.com/JvandeLocht/assignment-template-typst-hfh/main/layout/acronyms.typ
typst
MIT License
#import "@preview/acrostiche:0.3.2": * #let init-acronyms = init-acronyms(( "WTP": ("Wonderful Typst Package","Wonderful Typst Packages"), ))
https://github.com/coco33920/template_tdd
https://raw.githubusercontent.com/coco33920/template_tdd/main/README.md
markdown
Other
# Typst template Welcome to the typst template of french associations. Feel free to clone it and change the logo and you have your own template for your association :) Feel free to change the name of the University and other people who would happen to give you money. Cheers, <NAME>
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/_general/casoslov.typ
typst
#import "/style.typ": * #let bg = { rect(width: 95%, height: 95%, inset: 10pt, radius: 5pt, stroke: (paint: primary, thickness: 2pt), rect(width: 100%, height: 100%, outset: 0pt, radius: 5pt, stroke: (paint: primary, thickness: 2pt)) ) } #let project(body) = { set page( paper:"a5", numbering: "1", number-align: top+right, margin: (x: 35pt, y: 40pt), background: bg, footer: locate(loc => { let h1 = query( selector(heading.where(level:1)).before(loc), loc, ) if h1.len() != 0 { let body1 = h1.last().body text(8pt, body1) } }), header-ascent: 75%, footer-descent: 75% ) // HEADINGS show heading.where(level: 1): it => [ #align(horizon + center)[#primText[ #text(hyphenate:false, 45pt)[#it] ]] ] show heading.where(level: 2): it => [ #header(it) ] show heading.where(level: 3): it => [ #subheader(it) ] show heading.where(level: 4): it => [ #subsubheader(it) ] show heading.where(level: 5): it => [ #subsubheader(it) ] // Main body. set par(justify: true) body } #show: project #include("casoslov/vecierne.typ") #include("casoslov/utierne.typ") #include("casoslov/casy.typ")
https://github.com/Its-Alex/resume
https://raw.githubusercontent.com/Its-Alex/resume/master/lib/profile.typ
typst
MIT License
#import "components/link_with_icon.typ": linkWithIcon #let profile(profile) = [ #block(breakable: false)[ #set text(size: 10pt) #text(size: 18pt, weight: 800, fill: rgb("404040"))[#profile.name] #text(size: 10pt, weight: 300,)[#profile.position] #text(size: 10pt)[ #profile.birthday \ #profile.address #grid( columns: (100%), gutter: 0pt, row-gutter: 1em, ..profile.links.map((data_link) => [ #linkWithIcon( data_link.icon, data_link.url, data_link.name ) ]) ) ] ] ]
https://github.com/kotfind/hse-se-2-notes
https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/prob/lectures/2024-09-06.typ
typst
#import "/utils/math.typ": * = Введение $ "Итог" = 0.1 dot "ИДЗ" + 0.15 dot "Сем" + 0.25 dot "КР" + 50 dot "Экз" $ Нужно набрать $4$ --- не $3.5$ По ИДЗ бывают защиты На семинарах могут быть самостоятельные Кибзун, Горяинова, Наумов "ТВ и МС. Базовый курс с примерами к задачам" 2013 или 2014 КР на тему "случайные события и случайные величины (одномерные)" примерно после 7-ми занятий, в начале 20-ого модуля Экз на тему "многомерные случайные величины" = Основные понятия #def[ #defitem[Теория Вероятностей] --- раздел математики, изучающий математические модели массовых случайных явлений ] При большом кол-ве событий величина $m / n -> P$ стабилизируется $omega_1, ..., omega_n$ --- элементарные случайные события #def[ #defitem[Пространство Элементарных Событий ($Omega$)] --- совокупность элементарных случайных событий ] #def[ #defitem[Случайное событие] --- $"любое" A subset Omega$ ] #def[ #defitem[Достоверное событие] --- событие, которое происходит в опыте всегда. Совпадает с $Omega$ ] #def[ #defitem[Невозможное событие] --- событие, которое не происходит в опыте никогда. Является $emptyset$ ] Операции над множествами/ событиями: - Произведение событий $A dot B$ --- событие из $A sect B$ - Сумма событий $A + B$ --- событие из $A union B$ - Разность событий $A without B$ - Противоположное событие $overline(A) = Omega without A$ Свойства операций над множествами: - $A + A = A$ - $A dot A = A$ - $A dot Omega = A$ - $A + Omega = Omega$ - $A + B = B + A$ - $A dot B = B dot A$ - $A + (B + C) = (A + B) + C$ - $A dot (B dot C) = (A dot B) dot C$ - $overline(overline(A)) = A$ - $overline(A + B) = overline(A) dot overline(B)$ #def[ #defitem[$sigma$-алгебра событий] класс подмножеств в $cal(A)$ на пространстве элементарных событий $Omega$, если: + $Omega in cal(A)$ + $A in cal(A) => overline(A) in cal(A)$ + $forall A_1, ..., A_n, ... in cal(A) => sum_(i = 1)^infinity A_i in cal(A) and "П"_(i = 1)^infinity A_i in cal(A)$ ] = Классическое определение вероятности Пусть $Omega$ содержит *конечное* число *равновозможных* *взаимоисключающих* исходов, тогда: #def[ #defitem[Вероятность события $A$ (классическое определение)] $ P(A) = abs(A) / abs(Omega), $ где |A| -- мощность события, количество событий, входящих в $A$ ] Свойства: - $P(A) in [0; 1]$ - $P(Omega) = 1$ - Если $A dot B = emptyset$, то $P(A + B) = P(A) + P(B)$
https://github.com/veilkev/jvvslead
https://raw.githubusercontent.com/veilkev/jvvslead/Typst/files/3_reprints_suspends.typ
typst
#import "../sys/packages.typ": * #import "../sys/sys.typ": * #import "../sys/header.typ": * #show "Note": "Tip" #v(120pt) == Common Scenarios Remote Evacuation #h(10pt) 1) Partner asks lead to reprint a receipt while the lead is on the register. \ #h(10pt) 2) Soft boot needs to be performed, but an override is required to access main menu. \ #h(10pt) 3) Lead is locked in on a SCO lane #note[ Remote evacuations allow you to boot your operator from any register regardless if \ an active order is present ] == Key Differences #grid(columns: (1fr, 1fr), column-gutter: -3.8in, align(left)[ #subhead(head: true, "Reprint Finalized Orders") #badge-green("From POS") ], align(right)[ #subhead(head: true, "Recall Unfinalized Orders") #badge-green("From POS") #h(7em) ] ) #box(height: 68pt, columns(2, gutter: 11pt)[ #menu("MANAGER", "4 (reprint)", "ENTER") #menu("MANAGER", "4 (reprint)", "Order Number", "ENTER") #pin(4) #colbreak() #menu("SUSP RECALL", "Order Number", "ENTER" ) #colbreak() ]) #v(45pt, weak: false) #pinit-point-from(4, start-dx: 100pt, end-dx: 150pt)[ Alternative Method:\ Specify the order to reprint ] == Suspended Orders #box(height: 68pt, columns(2, gutter: 11pt)[ #subhead(head: true, "Open Orders") #badge-green("From POS") #menu("MANAGER", "2 (Print Open Order Report)") #colbreak() #subhead(head: true, "Open Orders") #badge-green("From Main Menu") #menu("2 (Reports Main Menu)", "9 (Reports Menu Cont)") #menu("...", "8 (Open Order Report)") ]) #box(height: 190pt, columns(2, gutter: 15pt)[ #slantedColorbox( title: "Receipt", color: "black", radius: 0pt, width: auto, )[ Open Orders Report\ -------------------------------------------------------------------------\ Order \# #h(15pt) Amount #h(8pt) Op\#/Ln\# #h(8pt) \<Last use>\ 841770 #h(30pt) 0.00 #h(20pt) 205 00 #h(18pt)06-08 3:49\ 841770 #h(30pt) 0.00 #h(20pt) 205 00 #h(18pt)06-08 3:49 ] #stickybox( rotation: 0deg, width: 9cm )[ Key differences: \ #h(2pt) 1. All active and suspended orders are shown #v(26pt) ] #colbreak() #slantedColorbox( title: "Receipt", color: "black", radius: 0pt, width: auto, )[ Open Orders Report \ -------------------------------------------------------------------------------------\ Order #h(15pt) Amount #h(8pt) Ln\#/Op\# #h(8pt) Time #h(15pt) Age #h(8pt) Mgr\# 841770 #h(19pt) 0.00 #h(23pt) 205 00 #h(15pt)13:48 #h(13pt)03:49 #h(6pt) 116\ #v(14pt) ] #stickybox( rotation: 0deg, width: 9cm )[ Key differences: \ #h(2pt) 1. Only suspended orders are shown\ #h(2pt) 2. The amount the order has been suspended for\ #h(2pt) 3. The approving manager who suspended the order ] ])
https://github.com/chilingg/kaiji
https://raw.githubusercontent.com/chilingg/kaiji/main/part1/chapter1.typ
typst
Other
#import "../template/main.typ": main_body, font_size_list, parenthese_numbers, sans_font_cfg, thin_line, font_cfg #import "@preview/tablex:0.0.6": gridx, tablex, rowspanx, colspanx, hlinex, vlinex, cellx #show: body => main_body(body) #counter(page).update(1) #text(size: 30pt, tracking: 0em)[ 汉字设计理论 #v(12pt) ] = 序言 <wide_title> == 字形与字体·字体的骨架 #columns(2)[ // ■字体はその字がその字として認知されるために必要な点画(点や線)の配置構成をさす。それが具体的な肉付けを持てば書体と言われる。したがって〔字体〕という慨念は逆に書体から抽出されたものである,とも言える。中国の漢字の長い歴史を通して字体と書体とは分離されずに変化してきた。活字書体となり,表情の多機性よりも規格化がより必要となったとき,明朝体・ゴシック体・教科書体などを同じ字体から統一的に導びかれるようにしたいという念願が起こり,その時字体の慨念が抽出された。それはつい26年前のことであった(昭和24年当用漢字字体表の告示)。 ■字形是指一个字被识别为该字所必需的笔画(点和线)的结构骨架。如果它的笔画有一个具体的造型,就可以说它是一种字体。因此,也可以说〔字形〕的概念是从字体中提炼出来的。在汉字漫长的历史中,字形和字体没有分离开来,且一直在变化。当活字印刷出现后,比起字形多样化的表达,标准化变得更为重要,人们希望能够从同一种字形中统一派生出明朝体、黑体、教科书体等,字形的概念就是在那个时候被提取出来的。这仅仅是26年前的事情(昭和24年现行汉字字体表的告示)。 // 字体はその字として認知されれば良い範囲であるから,それ以上の構成の巧拙美醜は間わない。そこで完成度の高い書体を作ろうとするとき,まず調和ある骨組の設計から出発することになる。つまり字体と書体の問に〔骨組みの設計〕というプロセスが必要となる。骨組は書体から独立しては考えられない。どういう書体として肉付けされるかによって骨組のあり方は当然違ってくる。 字形的好坏只在于它作为一个字的辨识度,因此没有必要在意结构的美丑。要想创作出高度完美的字体,首先要设计出和谐的骨架。换句话说,对于字形和字体的问题,〔设计骨架〕的过程是必不可少的。不能脱离字体来考虑骨架,骨架的形态亦会因字体笔画不同而不同。 // 字体 // 骨組構成 // 書体 // 一組の活字としての調和 // 姿形の均整 // 一定の肉づけ #align(center)[ #block(width: 85%)[ #grid( columns: (auto, 1fr, auto, 1fr, auto), rect([字形]),[ #set align(horizon) #sym.arrow ],rect([骨架结构]),[ #set align(horizon) #sym.arrow ],rect([字体]), [],align(center)[ #box()[ #set text(size: font_size_list.at(3)) #set align(start) #set par(leading: 0.4em) 作字 形\ 为的 态\ 一协 调\ 组调 整\ 活\ ] ],[],[ #set text(size: font_size_list.at(3)) #set par(leading: 0.4em) #set align(center) 添\ 加\ 笔\ 画\ 细\ 节 ],[], ) ] ] // 書体は線幅を持つが,骨組はその線幅の中央の位置に考えたら良いのか。われわれが骨組をイメージするときは,それが肉付けされた姿までイメージしている。骨組とは線幅を意識しながらだいたいの位置を設定するラフスケッチと言えるであろうか。しかしそれを正確に測定しようとすれぱ,線幅の中央とか上端下端,内のり外のりを決めなければならない。 字体的笔画都有其线度,我们能否在这个宽度的中间位置想象骨架呢?当我们想象骨架的时候,也是在想象它的丰满形态。骨架是线宽大致位置的粗略勾勒。如果我们想要精确测量它,就必须确定线宽的中心、上下端、内外侧。 // ■ここで〔書体〕と言う概念を改めて考えれば,一定の様式を持って肉付けされた1組の漢字の姿ということになるであろう。その一定の様式とは,歴史的には使った材料・用具によって決められ,またその時代の民族・文化状況によって変遷してきた。調和ある姿といっても,毛筆書道の段階ではきわめて自由度が大きく,そこにその時々の作者の心情を表現できる。文字の前後のつづきなりによって,また隣の行との調和においてその字を適当に変形することができる。しかし活字書体においては ■此处若我们重新思考〔字体〕这个概念的话,那么它应该是具有相同外观样式的一系列汉字。从历史上看,这种样式风格是根据当时所用的材料、工具而决定的,也随着当时的民族与文化环境而变迁。虽说是和谐的姿态,但在毛笔书法阶段有着极大的自由度,可以依据作者当时的心境自由表现。字与字之间可以依据前后承接的关系进行适当的变换,并与相邻的笔画进行协调。但是在活字字体中 // - 1)どんな字と組み合わされても調和すること。 // - 2)サイズが小さいので,限界状況のサイズで楽に読めなければならない。 // - 3)一書体の表情は厳格に統制され,常に一定である。 + 与任何字搭配都必须协调。 + 由于尺寸较小,必须在极限范围内保持易于阅读。 + 字体的表达受到严格控制,并始终保持恒定。 // 以上の点で活字書体独自の設計法が必要である。それは一面機械の部分品的な面を持ち,印刷方式や材料によって著しく制約を受けるものである。だがその一方〔文字言語〕つまり〔視覚化されたことば〕であるから,ことばのリズムやアクセントを生き生きと表現できる媒体であることが要求される。 以上几点要求表明对活字字体设计需采用一种独特的设计方法。一方面,由于它是机械零件的一部分,受到印刷方式和材料的严格限制。另一方面,它又是一种〔文字语言〕,或者说是〔视觉表达〕,它必须是一种能够生动表达文字节奏和语调的媒介。 // 文字の第一機能は〔読むもの〕として文章の内容をじかに読者に伝える役割を持っ。本文用書体はこれを第一義とする。 文字的第一功能是把文章的内容直接传达给读者。正文用字体以此为第一要义。 // しかしその他に文字は文章の内容を表現する表情——少なくともそれと反撥しあわないムードを感じさせることも要求される。本文用書体では読書中は文字の存在すら感じさせず,直接内容に触れさせることが大切であるが,読む前,これから読もうとするときには,その書体の持っている表情がその文章の内容にふさわしく,それを暗示しているらしく見せるところに,読もうとする意欲を刺激されるわけである。この表情効果は文字のサイズが大きくなるほど,つまり大見出しになるほど強く要求される。 除此之外,还要求文字表现文章内容的感情——至少要给人一种与之不相冲突的氛围。就正文字体而言,重要的是读者在阅读时可以直接接触到内容,而不用被字形干扰。然而,在读者准备阅读之时,字体的表现与文章的内容相称,似乎是在暗示着正文内容,这会刺激读者的阅读欲望。文字尺寸越大——也就是大标题,这种对于表达感情的要求就越高。 // == 一字一字の個性と一書体の統一性 == 字形的个性与字体中的共性 // ■活字書体設計の基本は何か。個々別々な漢字を,一組の統一ある書体として実感上のサイズ・ウエイト・ライン等を揃える努力であると言ってもよい。 ■活字字体设计的基本是什么?可以说,它是一种将各个不同的汉字,作为一套统一的字体,在感觉上统一尺寸、字重、基线等的行为。 // 1 字体 // 2 構造 // 3 輪郭の形 // 4 実感上の大きさ 4‘ 測定できる大きさ // 5 実感上の黒み 5‘ 測定できる線幅 // 6 実感上の字並び 6‘ 測定できるライン幅 #gridx( columns: 3, gutter: -2pt, rowspanx(2)[ #set align(horizon) - 1 字形 \{ ], [2 构造], [], (), [3 轮廓形状], [], colspanx(2)[- 4 感觉上的大小], (), [4' 测量的大小], colspanx(2)[- 5 感觉上的灰度], (), [5' 测量的线宽], colspanx(2)[- 6 感觉上的字对齐], (), [6' 测量的基线位置], ) // 一つーつの漢字で上記1は全部異なる。しかし2の構遭,3の輪郭の形はいくつかに分類できる。われわれがその字と識別するためには,まず2,3の違いを感じとるのかもしれない。さらに4の大きさ,5の黒みなどもそれに劣らぬ役割りを持つものであろう。識別のためには,それらは違いが大きいほど良いことになるが,しかし印刷された文章を目で追っていくときには,ラインが整備されていること,黒みのムラが激し過ぎないことが要求される。個々の字の〔違い〕を保ちながら,それを〔揃える〕ときに何をどこまで揃えるかが設計のポイントとなる。 每个汉字的上述1都不同。但是2构造,3轮廓的形状可以分为相同的几类。要识别不同的字,可以先从它们的2、3之间看出差异。另外,4大小,5灰度也具有一定的作用。从识别的角度来说,它们的差异越大越好,但是在浏览印刷出来的文章时,会要求基线统一,黑色大体均匀。在保持各个字间〔差异〕的同时,〔统一〕什么以及统一到什么程度是设计的重点。 // 本書で扱う設計理論では,〔漢字の基本的なイメージ修得〕については触れず,それらを一組の活字書体にどのようにまとめてゆくかという技術に焦点を合わせて話を進めることにする。 在本书所讲述的设计理论中,不涉及〔汉字的基本印象掌握〕,而是将焦点放在如何将它们归纳成一组活字字体这一技术上。 ] #pagebreak() #columns(2)[ #show enum: it => [ #set text(tracking: 0.05em); #it ] == 设计的目标 // ■漢字の個々の字はどういう形であるべきか。今ここで新しい設計をしようとするとき,当然土台となる形がある。 // 既成のものとして, // + 既成の活字の中から,それらを集大成したもの,または特に模範とする優秀作。 // - ●明治以来製作された活字はすべて一種の実験作品とみなす。個々の作品の個性は分解しがたいものであるが,数量的な部分などは抽出し,整理することができる。 // + 活字以前の〔書〕の名品のイメージ。 // - ●すでに明朝体はある完成度に達しているが,それをますます機械化の方向に進めるだけが良いとも限らない。活字になる以前の楷書(たとえば唐時代の名家の作品)について,〔漢字文化圏独自の構成〕を研究することは充分に意義がある。 // + 欧米活字の中で,デザインのルールなど参考となるもの。 // - ●日増しに横組が多くなろうとする現在,横組効果への順応はやはりラテン文字の伝統からいろいろなルールを学ぶことが多い。 // + ゲシュタルトとしての図形のバランス。 // - ●これは世界共通のもの。中横線による上下分割比のもっとも良いバランスは,〔HE〕も〔日王〕も同一であろう。 ■汉字的各个字形应该是怎样的呢?当我们尝试做一个新的设计时,自然要有一种形态作为基础 #set enum(numbering: n => [#parenthese_numbers.at(n - 1)]) 现有的 + 从现有活字中选取其集大成者,或是被当作模范的优秀作品。 - ●明治以来制作的活字都被视为一种实验作品。每个作品因其个性难以分解,但可以提炼和整理其中部分数值。 + 活字印刷以前的〔书法〕名作的形象。 - ●明朝体已经达到了一定的完成度,一味地将其向机械化方向推进并不一定是个好主意。对于成为活字之前的楷书(如唐代名家的作品),研究〔汉字文化圈独自的构成〕是有重大意义的。 + 参考欧美活字中的设计规则。 - ●由于横向书写日益普遍,适应横向效果仍然需要学习拉丁文书写传统中的各种规则。 + 完形崩溃时图像的平衡。 - ●这是全世界通用的。对于〔HE〕和〔日王〕来说,水平中线上下分割的比例的最佳平衡点是相同的。 // 創作にむかっての目標 // + 印刷された文章による市場調查,可読性テスト。 // + そのデザイナーによる新しい可能性の発見,または個人的好みで将来人々の支持を受けるであろうもの。 // - ●活字が実際に組まれて使用されたとき,それを受け入れる人々(編集者・印刷会社・デザイナー等を通じて,最終的には読者)の反応を知る必要がある。印刷条件及び好みは常に流動的に変化している。既成の書体だけでなく,もっかデザイン中の書体についての実験も重要である。 // 一般読者は幼時から接している文字によっで慣らされていて,慣れた字形をよいものとして受けいれるであろうが,そこにはまた非常な個人差がある。個々の字について細かく問いつめれば,何も意見が言えない人が多いのであるが,その人達に対して印刷された文章を示し,どの書体を好むか,内容にふさわしいと思うか等の質間をすれば,かなり集中した解答が得られる。それとは別に一定時間内で読める字数等を調査することによって,その成績と書体デザインや組み形式との関係も得られる。結局活字は多くの人に使われ読まれるために設計するのであるから,それらの人々の要求を知らなければならない。それは〔大数の法則〕に従う。それゆえ統計的な値として,ある程度はつかむことができよう。現在までの既成書体を分析するだけでなく,新しい試みについては実験によってデータを得ることができる。 // + 現在まではどうであったか——既成の書体ではどうなっているか(分析),そこにどういうルールがあるか。 // + 今後どうあるべきか——新しい目標を求めて,それはどうあるべきかを考える。過去にとらわれず,その本質を究明する。新しい目標とは,新しいメカニズム・人々の新しい好み・デザイナーの主張したい未開拓の書体等々である。 创作的目标 + 利用印刷的文章进行市场调研、可读性测试。 + 设计者发现新的可能性,或纯粹个人喜好,将来可能会受到公众的青睐。 - #[●活字在其实际编排使用前,有必要了解它的受众(通过编辑、印刷公司、设计师等,最终是读者)的反应。印刷条件和喜好是不断变化的。不只是对现有字体,对目前设计中的字体进行实验也很重要。\ 一般读者对于从小接触的文字形成了习惯,习惯了的字形会被认为是好的,这其中又存在着非常大的个人差异。 如果向他们细问每个字,很多人都无法表达出任何意见,但如果把印刷的文章展示给他们看,询问他们喜欢哪种字体、是否适合内容等问题,会得到相当有针对性的答案。 此外,通过调查在一定时间内可阅读的字数等,还可以得到其与字体设计、排版形式之间的关系。毕竟活字是为了大多数人使用和阅读而设计的,因此有必要了解这些人的需求。调查结果遵循〔大数定律〕,因此它作为统计值,在某种程度上是可以获得的。不仅可以对现有字体进行分析,对于新的尝试也可以通过实验获得数据。] + 迄今为止的情况是如何——现有字体的情况如何(分析),它们有哪些规则? + 今后应该怎样——寻求新的目标,考虑未来如何发展。不囿于过去,究其本质。新目标包括新的机制、人们的新喜好、设计师主张的未开发的新字体等。 // == 発想の2つの出発点 == 构思的两个出发点 // ■一つの書体がデザインされる動機,制作へのプロセスはどういうものであろうか? ■一个字体的设计动机和制作过程是怎样的呢? // 編集者·印刷業者・タイポグラファーは印刷された文章のイメージから発想するだろう(右図A)。それに対し,現在の書体デザイナーは,拡大された原字のイメージから発想するであろう。ここで問題なのはAとBの関係がどれくらいつかまえられているかということである。これは容易なことではない。AとBとはイメージとしてまったく別物と言ってもよいくらいのものである。 编辑、印刷业者、排版师会根据印刷出来的文章的形象进行构思(右图A)。与此相对,当前的字体设计师则是从放大的原字形象来获得灵感。问题在于如何把握A和B的关系。这绝非易事,A和B的形象可以说是完全不同的东西。 // 戦前の活字職人はこの点どうであったか?時には数代にわたる経験の上で,自分が原寸の種字を彫っているとき,それが組まれ,印刷された結果を予想できたのであろうか?しかし,この場合と言えども,次の一例はそれがどのくらい不完全であったかを示すものであろう。築地活版製作所の後期の文字が見本帳主義におちいり,結局は秀英舎(大日本印刷)に負けたのもそのためであった。後者は社内でただちに組版され,書物という具体的な姿において販売され,世人の批評にこたえたのであった。 战前的活字工匠在这一点上是如何的呢?有时要根据几代人的经验,他们才能雕刻原始尺寸的种字。此时,他们能预见到其编排、印刷出来的效果吗?这种方式存在很大缺陷,築地活版制作所后期的文字陷入样板主义,最终输给秀英舍(大日本印刷)就是因为这个原因。后者在社内即时排版,并以书的具体形式销售,以回应世人的批评。 // 今われわれが新しい書体をデザインしようとするときに,それが本文用書体ならば,まず最初に留意しなければならないことは,実にこの問題である。すなわち上記Aから発想し,それがBに分析され,BはたえずAの姿として検討を重ねられ,仕上げられなければならない。 现在我们在设计新的字体时,若它是正文用字体的话,首先要注意的就是这个问题。也就是说,必须从上述A开始构思,然后由B来分析,且过程中B必须不断地作为A的形象来反复研究,直至最终完成。 #v(1em) // ■〔BからA,AからBへのイメージ変換〕——(1)AとBの関係をつけること。すなわちそのイメージ変換には,数量的なワクが有力な助けとなる。なぜなら単に視覚的なイメージから言えば,AとBとはほとんど縁もゆかりもない別の実体(ォブジェ)だからである。見ただけでは両者の連関はほとんどつけがたい。印刷された文章についての批判,あるいは可読性テストの結果を分析する——きわめて経験に豊んだ専門家の知見と同時に,一般の人々についての調査を対比して,その関係をつかむことも大切であろう。とにかくそれらの結果は何らかの意味での数量に抽象化されて比較される(字のサイズ・ウエイトなどが,字間・行間アキ・1行字詰・行数・余白などの条件のもとに比較される)。 ■〔从B到A,从A到B的形象转换〕—— + 建立A和B的关系。即对其形象进行转换,对于这种转换,数值分析是一种有力的手段。因为单从视觉上的形象来看,A和B是几乎没有任何联系的两种实体(object)。仅仅通过视觉观察,很难看出两者的关联。重要的是,通过分析经验丰富的专家对印刷文章的批评或是对可读性的测试结果,加上普通公众调查的结果来把握两者之间的关系。总之,把它们抽象化为某种意义上的数值,从而进行比较(在字间、行间距、字数、行数、余白等同条件下,对比字的尺寸、字重等)。 // + 数量になりにくい部分——線質・姿形——それらのかもし出す表情等は最後に残る質的なもので,これは分類をして比較する他はあるまい。 + 难以量化的部分——线条的质量、形状及其产生的感情等,是最后残留的东西了,它们只能进行分类和比较。 #v(1em) // ■日本文を構成している2要素(漢字とひらがな)は,その構造上かなり違ったものであり,しかも両者のサイズやウエイトの関係がAの上で重大な要素となる。文章中の漢字%によって,この条件は変動するであろうが,もっとも良い比率は何であるか,という問に対してまず大まかに答えられるのは,やはり数量的なワクについてであろう。 ■构成日文的两要素(汉字和平假名),在结构上有相当大的不同,而且两者的尺寸和字重关系是影响A的重大要素。根据文章中汉字占比的不同,这一关系可能是变动的,那么最好的比例是什么?对于这个问题,能大致回答的还是数值分析。 ] #pagebreak() #columns(2)[ // 611 一5 数値とイメージの関係について == 数值与形象间的关系 // ■(1)数値はそのままイメージではない。イメージを盛り込むワクのようなものであるとみなして,〔数値のワク〕という言葉を使った。 ■ #parenthese_numbers.at(0)数值不能直接体现形象。使用了〔数值形象〕这一词是因为它被视为描述一种形象的数值轮廓。 // (2)一組の漢字・ひらがななりの,字の大きさやウエイトを一つの数値であらわすことができたら便利である。その方法にはかなりの困難がともなうが,しかし適切な定義・测定法を決めれば,かなり良い結果が得られる。別な人と同じ問題を語り合うとき,そのように客観化された数値によらなければ,何をよりどころにして比較できるであろうか。 #parenthese_numbers.at(1)将汉字、平假名的大小或字重用一个数值来表示,这样的做法存在一定的困难,因为必需要给出适当的定义和测量方法。如果能成功,这将是意义非凡的。毕竟,在与别人讨论一个问题时,如果不是通过这种客观的数值,那有什么可比较的呢? // (3)数値やグラフを読む力が必要だ。文字は〔記号図形の群〕である。そのイメージと数値との対応は自分で测定し,自分で計量することによって,自分の中に対応の鍵を育てる以外に方法はない。 #parenthese_numbers.at(2)文字是〔符号图形组〕。必需要有阅读数值和坐标的能力。这种形象与数值的对应,只能通过自己测量和分析,掌握其中关键。 // (4)まったく自由な手書きの文字が活字書体に変化・発展してきた過程は,いわば数量的なシステムをイメージの内部にとり入れるプロセスであった。整理された比例関係,どの字にも共通した量,普遍的に成立するルール——これこそ,いかにも活字らしく,きちんとならんで揃っている美しさの秘密であろう。 #parenthese_numbers.at(3)从完全自由的手写文字发展演变为活字字体的过程,就是将形象融入量化型系统的过程。有条理的比例关系,任何字都共通的量,普遍成立的规则——这就是活字整齐排列美的秘密所在。 // (5)機械の設計工学においては,諸量が数値として取り扱われる。活字書体も印刷メカニズムの一部分品であるからには,機械のメカニズムに直結する工学的な面が数値として規定されるのは当然であろう。 #parenthese_numbers.at(4)在机械设计工程学中,将诸量化作数值来处理。活字字体也是印刷机制的一部分,所以将其视为与机械机制直接相关的工程,并为它规定各种数值也是理所当然的。 // (6)活字は機械の部分品である。その時代の精神の表現手段であり,シンボルでもある。人々は言葉によって物を考え,精神の世界を構築するのであるが,活字文化の発達は,現代では言葉は音声言語であるよりも,文字言語として人々の中にくい入ってくる。すなわち人々は活字のイメージによって,精神を構築しているのだといってもよい。 #parenthese_numbers.at(5)活字是机器的零件。是一个时代精神的表现与象征。人们通过语言思考事物,构筑精神世界,但活字文化的发展,使得文字语言代替声音语言,成为现代的主要语言。也就是说,现代人们是通过活字的形象来建构精神世界的。 // 機械の部分品の一面と,精神の道具としての一面がどこで結びつくのであろうか? 作为机械零件的一面和作为精神工具的另一面该如何结合呢? #colbreak() // 611 一6 設計項目の概要 == 设计项目的概要 // ■結局は一つのまとまった書体を作ることである。便宜上細目に分けて研究するが,その全体が互いに密接な関係でまとめられ一つのイメージに統合されなければならない。そこで,設計項目は多次元にからみあった網目のようになる。決して,1次元的に(1列に)並べることはできない。同じ問題が網の結び目ごとに表われる。しかし記述の複重もさけねばならぬ,というわけで,少なくとも次のような2次元図式で,設計項目のあらましを,あらかじめ頭の中に位置づけておこう。 ■为了方便起见,我们细分项目来研究,项目之间必须密切关联,并能恰当的融合。最终目的是要形成一个完整的字体。为此,设计项目要像一个多维交织的网。绝对不能单维(1列)排列。同样的问题会表现在每个网络结点上。必须避免重复描述,因此至少要用如下的二维图,预先在脑海中定位设计项目的大致情况。 // 設計項目の中には,ウエイトとかラインとか欧米系タイポグラフィの術語も多い。従来の日本語の術語では適確に表現できないので,文字デザイナーやタイポグラファーはそのまま使っている。しかし各々の正確な定義等は,改めて考える必要のあるものも多く,各章ごとに,その解明に努めたつもりである。 在设计项目中存在很多欧美系排版术语,如字重、基线等,这是由于以往的日语术语无法准确表达,所以文字设计师和排版师需要对此沿用。不过,许多术语的准确定义需要重新考虑,我在每一章中都尽量加以说明。 // 文字のデザインについての,これらの基本要素は,われわれが文字を見て直感的に感じるものである。一般人が文字を読むときも,自覚はしていないが,ぼんやりとそれを感じている。設計デザイナーはそれを数百倍も強く精緻に感受しなければならない。研究を進めるにつれ,《個々の感覚の客観的な表現,数量的記述のむずかしさ》をつくづく思い知らされる反面,《それら感覚の織りなすシステムのみごとさ,多次元の網目状の諸関係の確実さ》が見えてくるので,不完全な数量化にあえぎながらも,その関係に法則性をつかもうと努力を続けるのである。それは,われわれに内在するものであり,文字デザインはそれが反映された記号形態である。 这些文字设计的基本要素就是我们看到文字时的直观感受。普通人阅读文字时,虽然没有自觉,但还是能隐约感受到。而设计者必须对其有着强烈的感知,并精益求精。随着研究的深入,我们会意识到“客观表达和量化描述个体感觉的困难”,但同时也能看到“由感知组成的系统的美妙,多维网状关系的确定性”。尽管我们在不完全量化的过程中挣扎,但我们仍在继续尝试把握这些关系的规律。它是我们内在的东西,文字设计是它所反映的符号形态。 // n次元の網目と言ったが,その大まかな見取図を2次元にして下図に示した。また目次2は,そうした立場から設計項目が索引できるように試みたものである。 之前提到的n维网状关系,其大致的平面图是二维的,如下图所示。目录2(设计项目索引)依此对设计项目进行索引。 ] #columns(2)[ // 編集者 印刷業者 タイポグラファー // 最終結果 印刷物となつた 文章のイメージ // 拡大された原字のイメージ // 書体デザイナー #block(width: 90%)[ #set align(center + horizon) #grid( columns: 3, [],[],rect(width: 10em, height: 8em)[ (2)\ 字体设计师 ], [],[],rect(fill: black, width: font_size_list.at(2), height: 3em), circle(radius: 5em)[ #text(size: font_size_list.at(1))[*A* <sans_font>]\ 最终结果\ 印刷品\ 文章的形象 ], [#rect(width: 3em, stroke: none)[⇄]], circle(radius: 5em)[ #text(size: font_size_list.at(1))[*B* <sans_font>]\ 放大后的\ 原字形象 ], rect(fill: black, width: font_size_list.at(2), height: 3em),[],[], rect(width: 10em, height: 8em)[ (1)\ 编辑\ 印刷业者\ 排版师 ],[],[] ) ] // 613 // 活字サイズと // 文字サイズ // (字づら) // 616 // 骨組構成 // 格子構造 // 曲線構造 // 617 // 線幅と // ウエイト // 614 // エレメント // (最小単位) // ●基準ワクと最長線 // ●各エレメントの形と線幅バランス // 615 // 一字の構成 // ·一書体のまとまり // ●線間隔と線長のリズム // ●空白部分(フトコロ)内陣と外陣·漢字のボディ // ●各字の固有性と一書体としての画一性(そろい) // ●骨組の密度と字づら面積と線幅の相互調整 // ●一字の中でのウエイト調整 // ひらがな // カタカナ // との関係 // 文章として綴ること // ●文字スペースと字間スペース // ●組方向への〔続きなり〕,重心の位置 // ●ライン効果 // 縦組……中央垂直ライン // 横組……上下水平ライン #show <number>: it => text(size: 11pt)[#it] #set text(tracking: 0em) #set list( marker: [●], indent: 0em, body-indent: 0.2em ) #tablex( columns: (auto, auto, auto, auto, auto), stroke: thin_line, inset: 0.6em, auto-lines: false, map-cells: cell => { cell.content = if cell.x > 1 and cell.y > 0 { [ #set text(size: font_size_list.at(3), tracking: 0.1em) #cell.content ] } else { [ #cell.content<sans_font> ] } return cell }, vlinex(), vlinex(), vlinex(), (), vlinex(start: 1, end: 5), vlinex(), hlinex(), [],[],[ 613<number>\ 活字尺寸\ 文字尺寸\ #text(font_size_list.at(3))[(字面)] ],[ 616<number>\ 骨架结构\ #math.cases([格子构造],[曲线构造]) ], [ 617<number>\ 线宽与\ 字重 ], hlinex(), rowspanx(5)[ #set align(center + horizon) 汉\ 字 ],[ 614<number>\ 部件\ #text(font_size_list.at(3))[(最小单位)] ],colspanx(2)[- 基准框与最长线],(),[- 各部件的形状与线宽平衡], hlinex(), (),rowspanx(4)[ #align(center)[ ↑\ #align(start)[ 615<number>\ 字的结构\ 字体的一致性 ] ↓ ] ],colspanx(2)[- 线间隔与线长的规律],(),rowspanx(3)[- 一个字的字重调整], (),(),colspanx(2)[ - 空白部分(字怀)内阵与外阵·汉字的字躯 ],(),(), (),(),colspanx(2)[- 各字的特征与字体的统一性(成套)],(),(), (),(),colspanx(3)[- 骨架密度、字面面积和线宽的相互调整],(),(), hlinex(), rowspanx(5)[ #set align(center + horizon) #set par(leading: 0.4em) 平 片\ 假 假\ 名 名\ ︸\ 相\ 互\ 关\ 系\ ],rowspanx(4)[ #set align(horizon) 组成文章 ],colspanx(3)[- 文字余白与字间余白],(),(), (),(),colspanx(3)[- 组合方向的〔连续样式〕,重心的位置],(),(), (),(),rowspanx(2)[ #set align(horizon) - 基线效果 ],colspanx(2)[纵排……中央垂直基线],(), (),(),(),colspanx(2)[横排……上下水平基线],(), (),[],[],[],[], hlinex(), ) ]
https://github.com/lvignoli/typst-action
https://raw.githubusercontent.com/lvignoli/typst-action/main/tests/math.typ
typst
MIT License
#set page( width: auto, height: auto, background: rect(width: 100%, height: 100%, fill: rgb("ffe5b4")) ) #set text(28pt) $ e^(i pi) + 1 = 0 $
https://github.com/drupol/ipc2023
https://raw.githubusercontent.com/drupol/ipc2023/main/src/ipc2023/operating-system.typ
typst
#import "imports/preamble.typ": * #focus-slide[ #set align(center + horizon) #set text(size: 1.5em, fill: white, font: "Virgil 3 YOFF") Nix is just#uncover("2-4")[.]#uncover("3-4")[.]#uncover("4-4")[.] #uncover("5-")[a configuration management system] #pdfpc.speaker-note(```md Nix could also be used as a system orchestrator, it is the one that build the system and deploy it, locally or remotely. Just like tools like Ansible, Puppet, Chef would do, but with a totally different approach and fixing the technical limitations of those tools along the way. As I said already earlier, NixOS is the Linux distribution built around the Nix tool. Let's summarize the key features... ```) ] #slide(title: "The operating system", new-section: "NixOS")[ #let cell = box.with() #grid( columns: (2fr, 3fr), cell(height: 100%)[ #uncover("1,4-", mode: "transparent")[- Linux distribution] #uncover("2,4-", mode: "transparent")[- Rolling or point release] #uncover("3,4-", mode: "transparent")[- Binary packages] #uncover("4,4-", mode: "transparent")[- Unique repository] ], cell(height: 100%, width: 100%)[ #set text(size: 15pt) #only("1")[ #set text(size: .5em) #figure( image("../../resources/images/Tux.svg", height: 90%, fit: "contain"), caption:[ #link("https://commons.wikimedia.org/wiki/File:Tux.svg")[Tux] ] ) ] #only("4")[ #set text(size: .5em) #figure( image("../../resources/screenshots/Screenshot_20231026_062532.png", height: 90%, fit: "contain"), caption:[ #link("https://github.com/drupol/nixos-x260")[https://github.com/drupol/nixos-x260] ] ) ] ] ) #pdfpc.speaker-note(```md - NixOS is a Linux distribution just like any other existing Linux distribution. - The release model is flexible since you can either choose to use it as a rolling release or as a point release, you can even switch from one to another without breaking your system. Since Nix is doing atomic upgrades, breaking your system would be a very hard task to achieve. - Binary packages are available for most of the packages, so you don't have to compile everything from source. But you can also choose to not use any binary package... and you have basically... a Gentoo but on steroids! - Nix and NixOS sources are in the same repository, it's very easy to contribute to both projects, as I showed you before. ```) ]
https://github.com/storopoli/Bayesian-Statistics
https://raw.githubusercontent.com/storopoli/Bayesian-Statistics/main/slides/06-logistic_regression.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "@preview/polylux:0.3.1": * #import themes.clean: * #import "utils.typ": * #import "@preview/cetz:0.1.2": canvas, plot #new-section-slide("Logistic Regression") #slide(title: "Recommended References")[ - #cite(<gelman2013bayesian>, form: "prose") - Chapter 16: Generalized linear models - #cite(<mcelreath2020statistical>, form: "prose") - Chapter 10: Big Entropy and the Generalized Linear Model - Chapter 11, Section 11.1: Binomial regression - #cite(<gelman2020regression>, form: "prose"): - Chapter 13: Logistic regression - Chapter 14: Working with logistic regression - Chapter 15, Section 15.3: Logistic-binomial model - Chapter 15, Section 15.4: Probit regression ] #focus-slide(background: julia-purple)[ #align(center)[#image("images/memes/logistic_regression.jpg")] ] #slide(title: [Welcome to the Magical World of the Linear Generalized Models])[ Leaving the realm of the linear models, we start to adventure to the generalized linear models -- GLM. #v(2em) The first one is *logistic regression* (also called Bernoulli regression or binomial regression). ] #slide(title: [Binary Data #footnote[ also known as dichotomous, dummy, indicator variable, etc. ] ])[ #v(5em) We use logistic regression when our dependent variable is *binary*. It only takes two distinct values, usually coded as $0$ and $1$. ] #slide(title: [What is Logistic Regression])[ Logistic regression behaves exactly as a linear model: it makes a prediction by simply computing a weighted sum of the independent variables $bold(X)$ using the estimated coefficients $bold(β)$, along with a constant term $α$. #v(2em) However, instead of outputting a continuous value $bold(y)$, it returns the *logistic function* of this value: $ "logistic"(x) = 1 / (1 + e^(-x)) $ ] #slide(title: [Logistic Function])[ #align(center)[ #canvas( length: 0.9cm, { plot.plot( size: (16, 9), x-label: $x$, y-label: $"logistic"(x)$, x-tick-step: 5, y-tick-step: 0.25, y-min: -0.01, y-max: 1.01, { plot.add( domain: (-10, 10), samples: 200, // label: $"logistic"(x)$, // FIXME: depends on unreleased cetz 2.0.0 x => logistic(x), ) }, ) }, ) ] ] #slide(title: [Probit Function])[ We can also opt to choose to use the *probit function* (usually represented by the Greek letter $Φ$) which is the CDF of a normal distribution: #v(2em) $ Φ(x)= 1 / (sqrt(2π)) ∫_(-oo)^(x)e^((-t^2) / 2) dif t $ ] #slide(title: [Probit Function])[ #align(center)[ #canvas( length: 0.9cm, { plot.plot( size: (16, 9), x-label: $x$, y-label: $Φ(x)$, x-tick-step: 5, y-tick-step: 0.25, y-min: -0.01, y-max: 1.01, { plot.add( domain: (-10, 10), samples: 200, // label: $"probit"(x)$, // FIXME: depends on unreleased cetz 2.0.0 x => normcdf(x, 0, 1), ) }, ) }, ) ] ] #slide(title: [Logistic Function versus Probit Function])[ #align(center)[ #canvas( length: 0.9cm, { plot.plot( size: (16, 9), x-label: $x$, y-label: $Φ(x)$, x-tick-step: 5, y-tick-step: 0.25, y-min: -0.01, y-max: 1.01, { plot.add( domain: (-10, 10), samples: 200, // label: $"logistic"(x)$, // FIXME: depends on unreleased cetz 2.0.0 x => logistic(x), ) plot.add( domain: (-10, 10), samples: 200, // label: $"probit"(x)$, // FIXME: depends on unreleased cetz 2.0.0 x => normcdf(x, 0, 1), ) }, ) }, ) ] ] #slide(title: [Comparison with Linear Regression])[ Linear regression follows the following mathematical expression: $ "linear" = α + β_1 x_1 + β_2 x_2 + dots + β_k x_k $ - $α$ -- intercept. - $bold(β) = β_1, β_2, dots, β_k$ -- independent variables' $x_1, x_2, dots, x_k$ coefficients. - $k$ -- number of independent variables. If you implement a small mathematical transformation, you'll have *logistic regression*: - $hat(p) = "logistic"("linear") = 1 / (1 + e^(-op("linear")))$ -- probability of an observation taking value $1$. - $hat(y) = cases(0 &"if" hat(p) < 0.5, 1 &"if" hat(p) >= 0.5)$ -- $bold(y)$'s predicted binary value. ] #slide(title: [Logistic Regression Specification])[ We can model logistic regression using two approaches: #v(3em) - *Bernoulli likelihood* -- *binary* dependent variable $bold(y)$ which results from a Bernoulli trial with some probability $p$. - *binomial likelihood* -- *discrete and positive* dependent variable $bold(y)$ which results from $k$ successes in $n$ independent Bernoulli trials. ] #slide(title: [Bernoulli Likelihood])[ #text(size: 16pt)[ $ bold(y) &tilde "Bernoulli"(p) \ p &= "logistic/probit"(α + bold(X) bold(β)) \ α &tilde "Normal"(μ_α, σ_α) \ bold(β) &tilde "Normal"(μ_bold(β), σ_bold(β)) $ where: - $bold(y)$ - dependent binary variable. - $p$ - probability of $bold(y)$ taking value of $1$ -- success in an independent Bernoulli trial. - $"logistic/probit"$ -- logistic or probit function. - $α$ -- intercept (also called constant). - $bold(β)$ -- coefficient vector. - $bold(X)$ -- data matrix. ] ] #slide(title: [Binomial Likelihood])[ #text(size: 16pt)[ $ bold(y) &tilde "Binomial"(n, p) \ p &= "logistic/probit"(α + bold(X) bold(β)) \ α &tilde "Normal"(μ_α, σ_α) \ bold(β) &tilde "Normal"(μ_bold(β), σ_bold(β)) $ where: - $bold(y)$ - dependent binary variable. - $n$ - number of independent Bernoulli trials. - $p$ - probability of $bold(y)$ taking value of $1$ -- success in an independent Bernoulli trial. - $"logistic/probit"$ -- logistic or probit function. - $α$ -- intercept (also called constant). - $bold(β)$ -- coefficient vector. - $bold(X)$ -- data matrix. ] ] #slide(title: [Posterior Computation])[ Our aim to is to *find the posterior distribution of the model's parameters of interest* ($α$ and $bold(β)$) by computing the full posterior distribution of: #v(3em) $ P(bold(θ) | bold(y)) = P(α, bold(β) | bold(y)) $ ] #slide(title: [How to Interpret Coefficients])[ If we revisit logistic transformation mathematical expression, we see that, in order to interpret coefficients $bold(β)$, we need to perform a transformation. #v(3em) Specifically, we need to undo the logistic transformation. We are looking for its inverse function. ] #slide(title: [Probability versus Odds])[ #text(size: 17pt)[ But before that, we need to discern between *probability and odds* #footnote[mathematically speaking.]. - *Probability*: a real number between $0$ and $1$ that represents the certainty that an event will occur, either by long-term frequencies (frequentist approach) or degrees of belief (Bayesian approach). - *Odds*: a positive real number ($RR^+$) that also measures the certainty of an event happening. However this measure is not expressed as a probability (between $0$ and $1$), but as the *ratio between the number of results that generate our desired event and the number of results that _do not_ generate our desired event*: $ "odds" = p / (1 - p) $ where $p$ is the probability. ] ] #slide(title: [Probability versus Odds])[ $ "odds" = p / (1 - p) $ where $p$ is the probability. #v(2em) - Odds with a value of $1$ is a neutral odds, similar to a fair coin: $p = 1 / 2$ - Odds below $1$ decrease the probability of seeing a certain event. - Odds over $1$ increase the probability of seeing a certain event. ] #slide(title: [Logodds])[ If you revisit the logistic function, you'll se that the intercept $α$ and coefficients $bold(β)$ are literally the *log of the odds* (logodds): $ p &= "logistic"(α + bold(X) bold(β)) \ p &= "logistic"(α) + "logistic"(bold(X) bold(β)) \ p &= 1 / (1 + e^(-bold(β))) \ bold(β) &= log("odds") $ ] #slide(title: [Logodds])[ Hence, the coefficients of a logistic regression are expressed in logodds, in which $0$ is the neutral element, and any number above or below it increases or decreases, respectively, the changes of obtaining a "success" in $bold(y)$. To have a more intuitive interpretation (similar to the betting houses), we need to *convert the logodds into chances* by undoing the $log$ function. We need to perform an *exponentiation* of $α$ and $bold(β)$ values: $ "odds"(α) & = e^α \ "odds"(bold(β)) & = e^(bold(β)) $ ]
https://github.com/florianhartung/studienarbeit
https://raw.githubusercontent.com/florianhartung/studienarbeit/main/preparation/main.typ
typst
#set page(paper: "a4", margin: 2cm) #set text(size: 12pt, font: "Arial"); #set par( justify: true, hanging-indent: 0em, leading: 0.8em, ); #align(center)[ #text(size: 1.5em)[ Exploring WebAssembly for versatile plugin systems through the example of a text editor ] _<NAME>_ ] = Problem definition WebAssembly is a bytecode format, initially released in 2017 as a compilation target for web-based applications. However, the utilisation of WebAssembly has since expanded beyond the web. It offers advantages such as cross-language interoperability and sandboxed execution, which enable emerging use cases in vastly different areas such as cloud computing, safety-critial systems and blockchains. Another promising application for WebAssembly is plugin systems, for which only limited research and a few projects exists. Plugin systems are software components that allow plugins to extend or modify the functionality of some host application. Most common plugin systems using languages such as JavaScript, Lua or Python have some issues regarding performance or safety while their plugins might be non-portable and locked to their respective programming language. This work aims to explore how WebAssembly can be leveraged to create fast and safe plugin systems for portable and interoperable plugins. As a test case a plugin system will be developed for a text editor. Text editors are suitable as their broad spectrum of users usually demand a high degree of customization. A WebAssembly plugin system provides this customization by enabling features to be implemented by third-party developers, while still guaranteeing a safe, sandboxed plugin execution. = Objectives - Analyze requirements for plugin systems from real world projects - Analyze the pros and cons of WebAssembly (and its related technologies) in comparison to traditional architectures of plugin systems - Performance, Safety, Portability of the plugin system - Language-interoperability for plugin development - Gain insight into designing and implementing a WebAssembly plugin system for a text editor as a proof of concept = Approach/ Table of contents (WIP) - Introduction - Fundamentals - WebAssembly - Plugin systems - Rust - Plugin system requirements - Related work (research and projects) - WebAssembly for plugin systems - Overview - Choosing a plugin API (native/wat/wasi) - Safety - Performance - Summary - Implementing a plugin system for a text editor - Requirements - Design - Implementation - Example plugin development (preferable in different languages to demonstrate interoperability) - Verification and validation - Discussion - Conclusion // - allows for portable software as it runs platform-independent and can run a lot of different languages, safe by default // - plugin systems traditionally use specific languages and interfaces for their plugins // - WASM might be a suitable language for versatile plugin systems, however there is a gap in are few plugin systems that use WASM // Plugin systems are software components that can be used by host software to execute plugin components. // These modular plugin components may add new or modify existing features of the host software. // That makes a plugin systems architecture a popular approach for text editors, IDEs, games and audio processing software. // However most plugin systems require their plugins to be implemented in a specific programming language where they are provided a language-specific interface to the host software. // WebAssembly is a new platform-independent bytecode format, that allows its bytecode to be executed in a sandbox while still providing high performance. // It acts as a compilation target for some languages (C, C++, Rust, ...) and allows code of other languages (Python, Javascript, ...) to be embedded along with a their runtime engine. // Thus WebAssembly allows for extreme interoperability for plugin developers of any language and also allows for compiled plugins to be portable to all architectures, that can provide a WebAssembly runtime. // It is still unclear to what extent one can make use of WebAssembly plugin systems in practise and also what downsides might arise. // Text editors, in particular, benefit from such systems because they offer a high degree of customization to meet the diverse needs of users. // Common text editors and IDEs require their plugins to be written in a particular language such as Java, Javascript, Lua, a custom scripting languages, etc. // In contrast to these traditional plugin systems stands WebAssembly - a bytecode format that many languages (C, C++, Rust, ...) can be compiled to and in which other can be embedded (Javascript, Python, ...). // promises interoperability, portability and a sandboxed code execution environment, while still providing high performance. // Even though plugin systems that use WebAssembly have been developed, it is still unsure whether a WebAssembly plugin system is suited for a text editor. // Helix is a new terminal-based text editor with vim-like controls, but it currently lacks support for a plugin system. // Its official issue tracker has long-requested features like a filetree (since 2021) or an integration for generative AI (since 2022), which could greatly profit off of a plugin system. // A plugin systems would allow the development of unofficial self-contained plugins, that can be used without them having to go through a time-consuming CI/CD pipeline, review and merge processes. // In summary, it is unsure, if and how text editors can make use of WebAssembly plugin systems. // Some existing features might even be outsourced into their own build-in plugins for a reduction in code complexity and better encapsulation. // *Context* // - What are plugin systems? // - Why are plugin system architectures better? // - Text editors and their need for plugin systems // *Actual problem* // - What is Helix as a project? // - Helix does not provide a plugin system and it has a lot of new requested features (some of which are for very special usecases, and thus they should not necessarily be included in the core software due to additional dependencies, complexity (and performance overhead)). // - Software-Systems provide plugin systems // - Plugin systems enable development of new features by independent third-party developers // - A plugin system architecture has lots of advantages over including a set of features from the start: // - Such modular software has lots of advantages, as it is impossible to // - Text editors need really high configurability, which a plugin system can provide. // - Big text editors and IDEs provide plugin system: VSCode, IntelliJ-based IDEs, (Neo-)Vim // - Helix is a new terminal-based editor inspired by VIM motions. // - As of now Helix does not provide a plugin // Some software systems offer plugin systems, through which users can extend the orginal software with new features. // Especially text editors and IDEs make use of such plugin systems, where they benefit from extreme configurability and versatility. // Common plugins (also called extensions) might provide custom syntax highlighting, colored highlighting for matching braces, new keybinds or a GUI for dependency management in NodeJS and Rust projects. // Helix is a new terminal-based text editor with vim-like controls, but it currently lacks support for a plugin system. // Its official issue tracker has long-requested features like a filetree (since 2021) or an integration for generative AI (since 2022), which could greatly profit off of a plugin system. // A plugin systems would allow the development of unofficial self-contained plugins, that can be used without them having to go through a time-consuming CI/CD pipeline, review and merge processes. // In summary, it is unsure, if and how text editors can make use of WebAssembly plugin systems. // The objective is to explore WebAssembly as a language for versatile plugin systems. // This will be done by analysing existing plugin systems, then designing and implementing a new WebAssembly plugin system. // Then the pros and cons of using WebAssembly and the // design a new WebAssembly plugin system based on an analysis of plugin systems of some common text editors and IDEs. // explore what pros and cons there are to WebAssembly plugin systems for text editors. // As a proof To prove the results // This includes one text editor in particular: Helix. // Helix is a new terminal-based text editor with vim-like controls, but it currently lacks support for a plugin system. // Its official issue tracker has long-requested features like a filetree (since 2021) or an integration for generative AI (since 2022), which could greatly profit off of a plugin system. // A plugin systems would allow the development of unofficial self-contained plugins, that can be used without them having to go through a time-consuming CI/CD pipeline, review and merge processes. // This work will present and analyze plugin systems of common text editors and IDEs. // Also and existing WebAssembly plugin systems. // Then a generic and versatile plugin system will be developed as a proof of concept to showcase how plugin systems benefit from using WebAssembly. // With this knowledge a generic plugin system will be designed and developed. // This plugin system will use the very promising WebAssembly bytecode format for plugins // Then a new plugin system // This work will extend the Helix editor with a new WebAssembly plugin system, that allows for plugins to be written in almost any language. // Plugins will be able to add or modify basic functionality of the Helix editor, such as adding new commands, inserting text or rendering new UI components. // More complex features will not be implemented in this work, as this is is as a proof of concept and lays a foundation for future development rather than providing a fully functional product. // - Careful integration into Helix while still being flexible for future upstream Helix changes // - Decoupling of plugin system into separate modular library // - Especially the plugin system design requires analysis of current technologies and research. // However, the plugin system will not be implemented directly inside the Helix editor project, and instead it will be implemented as a separate modular plugin system, that has the possibility of being used in other projects in the future. // / Analysis of existing technologies and (WebAssembly) plugin systems, design and implementation of a generic and versatile WebAssembly plugin system: aflk // / Analysis of Helix's architecture and a careful integration of the plugin system into the project, while keeping complexity to a minimum: adsf // + The goal is to create a plugin system that runs plugins in the WebAssembly bytecode format. // This plugin system shall provide a simple, yet versatile interface for a host to execute plugins. // These plugins may have been written in any language that compiles to WebAssembly, which is why designing a generic plugin interface will be especially important. // Even though some technology decisions are already made (Rust and WebAssembly), a lot of analysis will be required to design a robust and extensible plugin system: // - Which WASM runtime to choose: Wasmtime, Wasmer, ... // - How to design the plugin interfaces: native WASM vs. WAT, events/commands, ... // - What to learn from existing (WebAssembly) plugin systems: zellij, extism, VSCode, IntelliJ, ... // + In this section the previously developed plugin system will be integrated into the Helix text editor as a proof of concept with the potential to become a fully functioning system eventually. // To make the integrated plugin system future-proof and extensible for newer upstream Helix features, a careful plugin system integration is necessary. // This requires a careful analysis of the current Helix architecture to decide how to integrate the plugin system. // To achieve this robustness and allow for newer Helix features to be integrated easily, the Helix project architecture must be carefully analysed and the plugin system integrated as modular as possible without introducing too much complexity. // - WebAssembly as the plugin language // - performance (in comparison to traditional plugin languages), interoperability (any language can be compiled to or embedded into WebAssembly) and portability (WASM plugins are platform-independent) // - Rust as the plugin system language // - Helix is written in Rust. Thus introducing another language barrier includes unnecessary complexity. // - The plugin system shall be safe to use for the host system. Rust's safety guarantees will help achieve this. // - This work will design and implement a generic plugin system, that can then later be embedded into the Helix text editor project. // - A fundamental design decicision // - In the plugin system design process other plugin systems // will design analyze other plugin systems and // = Approach // Instead of directly implementing the plugin system in the Helix project, this work will be split into two main sections: // / Design and implementation of a generic plugin system: // To make the generic plugin system as versatile as possible, existing plugin systems and technologies such as the WebAssembly runtime and the plugin interface will have to be analyzed. // Then a generic plugin system can be designed and implemented as a standalone project. // / Integration of the plugin system into the Helix project: // In this section the previously developed plugin system will be integrated into the Helix editor. // The integration requires careful analysis of Helix's architecture to make sure that the result is future-proof and extensible for newer upstream Helix features. // They essentially provide the framework for a working editor while also benefitting from to allow for extreme configurability and // Bestimmte Software-Systeme bieten Plugin-Systeme an, sodass modular neue Funktionen hinzugefügt werden können. // Vorallem bei Text-Editoren spielen Plugin-Systeme eine große Rolle, denn sie erlauben es den Nutzern eigene Syntaxregeln, , ... // Plugin-Systeme von konventionellen Texteditoren wie VSCode, IntelliJ oder Neovim verwenden jeweils eine eigene Programmiersprache zur Erstellung // #pagebreak // == Kontext // - Herkömmliche Plugin-Systeme für Text-Editoren verwenden oft spezifische Sprachen wie Lua (neovim), Java (IntelliJ) oder JS/TS (VScode) // - Sicherheit? // == Problem // - Sprache und Ecosystem müssen z.T. neu erlernt werden // - Schnittstelle ist stark abhängig von den Features der Programmiersprache des Plugin-Systems (Exception, async mit Promises, ...) // // Idee: Language and editor-agnostic plugins? VSCode plugins in intellij? probably impossible though // = Zielsetzung // = Vorgehen // == Zeitplan // Bereits erfolgt: // - Tests mit Helix // - Tests mit WebAssembly Component Model in Rust und anderen Sprachen für WASM-Programme // Noch zu tun: // - Ratatui Layouting anschauen // - Helix Codebase testing: Left panel for future file explorer, new hello world command, manche commands anpassen // - WASM-Engine in Helix integrieren // - Plugin: activate() and deactivate() // - Plugin: Logging // - Plugin: Calling Helix commands // - Metadata for plugins // - Plugin: Definition of new commands // - Plugin: Insert text/ prompt input text // - Centralized Plugin Loader mit Plugin Store in ~/.config/Helix/plugins/ // = Notizen // - Hier schon zentrale Literatur nennen // - Selber Plugin Development ausprobieren // - Anmelde-Formular // - Plugin-Host stellt Features bereit: Tree-Component, Command-System, File-Access and (Configuration-)Storage // - Es sollen als Proof of Concept Plugins in den meistverwendeten Sprachen implementiert werden (Rust, Java, Javascript, Python).
https://github.com/MilanR312/ugent_typst_template
https://raw.githubusercontent.com/MilanR312/ugent_typst_template/main/chapters/c1/text.typ
typst
MIT License
#import "../../template/prelude.typ": * = The color blue #introduction[We start by talking about how amazing the color blue is and end with why it is nice compared to other colors] #todo[ talk about why it is amazing] == The amazing color #figure( image("images/blue.png"), caption: [A blue square] ) == Compared to other colors #figure( table( columns: 2, align: center, table.header([Color], [Reason]), [Blue], [Looks good], [Red], note(caption: [it is too red tbh])[it is too red] ), caption: [Colors] )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/block-spacing-00.typ
typst
Other
#set block(spacing: 10pt) Hello There #block(spacing: 20pt)[Further down]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/par_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test changing leading and spacing. #set block(spacing: 1em) #set par(leading: 2pt) But, soft! what light through yonder window breaks? It is the east, and Juliet is the sun.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/regression/issue12.typ
typst
Other
he'*llo World* l’*exactitude* a*b_c_e
https://github.com/SantaHirai/TypstTemplate
https://raw.githubusercontent.com/SantaHirai/TypstTemplate/main/template.typ
typst
#set text(font: "MS Mincho") #set figure(supplement:[図]) #set heading(supplement: []) #set image(width:80%) #set heading(numbering: "1.") #set raw(block: true,lang: "Java") #show heading: it=>[ #set text(12pt,weight:900 ,font: "MS Gothic") #strong(it) ] #set par(justify: false,leading: 0.75em) #set par(first-line-indent: 1em) #show heading: it => { it par(text(size: 0pt, "")) } #show raw: it=>[ #box( stroke:1pt+black, width:100%, pad( 4pt, it ) ) ] #show link: it=>[ #text(it,fill:blue) ] #set document(title: [title], author: "name", date: none) // #show: rest => columns(2, rest) // #colbreak() // #set document(title: "Title", author: "Name", date: none) // #align(center,text("Title",20pt,font:"MS Gothic")) // #align(right,text("Name",font:"MS Gothic")) // = 実験の課題・目的 <purpose> // = 実験の原理 // == Socketの原理 @Socket // #pagebreak() // #figure( // table( // columns: (auto,auto,auto), // inset: 10pt, // align: horizon, // [], [], [], // "","","", // "","","" // ), // supplement:[表], // caption: [キャプション], // ) // #figure( // image("sample.png",width: 80%), // caption: [キャプション] // ) <Sample> // @Sample に画像の例を示す。 // ```lang // code // ``` // + ナンバリング // - ドット // $integral_(- oo)^(oo) a_b dif x // &= a_b\ // &= a_c$ // = 参考資料 // #bibliography("参考文献_例.yml",title:none,style: "sist02")
https://github.com/eliapasquali/typst-thesis-template
https://raw.githubusercontent.com/eliapasquali/typst-thesis-template/main/preface/summary.typ
typst
Other
#import "../config/constants.typ": abstract #set page(numbering: "i") #counter(page).update(1) #v(10em) #text(24pt, weight: "semibold", abstract) #v(2em) #set par(first-line-indent: 0pt) Il presente documento descrive il lavoro svolto durante il periodo di stage, della durata di circa trecento ore, dal laureando <NAME> presso l'azienda Azienda S.p.A. Gli obbiettivi da raggiungere erano molteplici. In primo luogo era richiesto lo sviluppo di ... In secondo luogo era richiesta l'implementazione di un ... Tale framework permette di registrare gli eventi di un controllore programmabile, quali segnali applicati Terzo ed ultimo obbiettivo era l'integrazione ... #v(1fr)
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/6-conclusion/mod.typ
typst
MIT License
#import "../../lib/mod.typ": * #pagebreak() = Conclusion <conclusion> // Hypothesis 1 // Reimplementing the original GBP Planner in a modern, flexible multi-agent simulator // framework using a modern programming language will enhance the software’s scien- // tific communication and extendibility. This redevelopment will not only ensure fidelity // in reproducing established results but also improve user engagement and development // through advanced tooling, thereby significantly upgrading the usability and function- // ality for multi-agent system simulations. // Accompanying research questions: // RQ-1.1 Which architecture and framework is suitable for such a task, and can it reproduce the original results? Specify which tasks it suitable for. Decoupling? Modelling? Visualization? // RQ-1.2 What kind of tooling will be most beneficial for the software? // RQ-1.3 How can tooling help with future reproducibility and engagement with the software? // RQ-1.4 How can tooling help with understanding and extending the software? // Produced an interactive simulation tool, that can work as a tool to more easierly explore the future algorithms and variations on using GBP as a method for distributed path planning. // A valuable tool that can be used by others, e.g. companies to quickly assess if the gbpplanner algorithm is a suitable method for doing multi-agent distributed path planning given their requirements, such as density of robots, and environment structure. // On hypothesis 1 The original GBP Planner has been reimplemented in a modern, flexible multi-agent simulator framework using a modern programming language. The chosen #acr("ECS") architecture in the Bevy Engine has proven itself to be a suitable framework both for reproducing the original `gbpplanner` and for extending it with a large amount of tooling. The result is a fully-fledged interactive simulation tool called #acr("MAGICS"). The tool is designed to enhance the scientific communication and extendibility by introducing a highly configurable #acr("UI"), with a lot of options for visualization; providing many different perspective on the underlying theoretical concepts. The hope is that #acr("MAGICS") can provide a simple playground for the further development of multi-agent systems based off of #acr("GBP") at its core. Furthermore, extensive though has been put into the configuration formats; the main configuration `config.toml` providing the initial tool state, while the `environment.yaml` provides a simplified way to design a plethora of environments, either by using the character matrix or placing obstacles manually; both in a highly declarative manner. Lastly, the `formation.yaml` once again provides a declarative interface, but this time for expressing the otherwise highly dynamic and sporadic nature of multi-agent formations. This is accomplished through a series of spawning rules that when put together can represent highly complex scenarios of interweaving robots. Not only do these three configuration formats provide a single source of truth, not dependant on the program state, but they also collectively make up the notion of a scenario, which is easily reproduced and shared between users of #acr("MAGICS"). // Hypothesis 2 // The original work can be enhanced through specific modifications without interfering // with the original work’s functionality. Specifically, we introduce and rigorously test // various GBP iteration schedules, and strategically enhance the system by advancing // towards a more distributed approach. These targeted improvements are expected to op- // timize flexibility and move towards a closer-to-reality system. // Accompanying research questions: // RQ-2.1 Which possible ways can the GBP iteration scheduling be improved? // RQ-2.2 How can such iteration schedules be tested, to ensure that they are an improvement? // RQ-2.3 Which possible avenues exist to advance towards a more distributed approach? // RQ-2.4 Are these targeted improvements able to enhance the original work without transforming it? // On hypothesis 2 // #k[hypothesis 2] // ------------------------------------------------------------------------------- Two additional experiments have been performed to test different parameters of the GBP algorithm not explored in the original work. Firstly, the effect of the number of internal and external iterations on the algorithm's convergence and performance was examined. A key finding is that having more internal iterations than external iterations is beneficial, especially when internal iterations are low. Generally, no more than 10 iterations of each are sufficient across various scenarios to achieve good results. Additionally, the information within each robot's factor graph can be overwhelmed in highly connected cases if insufficient internal message passes are executed. These insights are promising for deploying GBP on a broad range of robots with limited computational power. Secondly, the order in which new information is passed between robots from interrobot factors does not significantly impact performance. Similar results were obtained for all five schedules considered, supporting the strong benefits of using GBP as an inference algorithm for multi-agent path planning. However, strong conclusive statements require real-world tests or more advanced simulations of networking conditions. The reimplemented version uses singular owned stable graphs for each robot's factor graph instead of a bidirectional shared pointer data structure. Despite this fundamental transformation, the system still achieves similar results to the original across several metrics. This promising finding motivates further exploration of the method's merits in real-world scenarios with the algorithm running distributed across multiple hosts. // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Two additional experiments have been performed to test different parameters of the GBP algorithm not explored in the original work. // // Firstly the effect the number of internal and external iterations has on the convergange of the algorithm and performance. A key finding here is that more internal iterations than external iterations is beneficial. when internal iterations is low. Generally that no more than 10 iterations of each is sufficient across a broader range of scenarios to achieve good results. In addition, the information contained within each robots factorgraph, can be overwhelmed to detrimental effect in highly connected cases, if not enough intermal messages passes are executed. A result that is promising for the potential to deploy on a broad range of robots with not a lot of compute power. // // Secondly the order in which new information is passed from interrobot factors between robots does not appear to be significant. With roughly the same results for all five schedules considered. Supporting the strong benefits of using GBP as an inference algorithm for multi agent path planning. Although it is hard to state conclusively without real world test or a more advanced/sophisticated simulation of networking conditions. // // Using singular owned stable graphs as the underlying in-memory representation of each robots factorgraph has been used as an alternative to bidirectional shared pointer data structure in the reimplemented version. Even with this fundamental transformation of the system it is still found to faithfully achieve similar results to the original, as shown across several different metrics. This is a promising finding that motivates further work on exploring the merits of the method in real-world scenarios with the the algorithm running distributed across multiple hosts. // ------------------------------------------------------------------------------- // The alternatively p // - Simulating factorgraphs in a more distributed manner that maps more realisticly to the a real-scenario. // Achieves similar results on several metrics // - use different graph structure and still reproduce/get similar results // #line(length: 100%, stroke: 1em + red) // Hypothesis 3 // Extending the original GBP Planner software with a global planning layer will extend // the actors’ capability to move in complex environments, without degradation to the re- // produced local cooperative collision avoidance, while maintaining a competitive level // of performance. Furthermore, to this end, a new type of factor can be added to the GBP // factor graphs to aid in path-following. // Accompanying research questions: // RQ-3.1 Will global planning improve the actors' capability to move autonomously in complex environments? // RQ-3.2 Will global planning degrade the existing local cooperative collision avoidance? // RQ-3.3 What impact will the global planning layer have on performance? // RQ-3.4 Is it possible to introduce a new type of factor that can aid in path-following? // RQ-3.5 What impact will this factor have on the existing behaviour of the actors, importantly; will it degrade their ability to collaborate and avoid collisions - both with each other and the environment? // RQ-3.6 What will the impact of this factor be on the actors' capability to move in complex environments? // On hypothesis 3 The agents have received the ability to perform individual pathfinding by using an #acr("RRT*") algorithm. This path-finding element has been embedded into the concept of a _robot mission_, which keeps track of the mission state and when to call the asynchronous global path-finder. The global planning element in itself does not degrade the local cooperative collision avoidance. This is due to the fact that the waypoint tracking approach is simply an automated way of placing the waypoints that were placed manually before. The downside of the implemented solution is the random nature of the #acr("RRT*") algorithm, which causes an inoptimal amount of crossing paths. Oppositely, when manually placing waypoints, the waypoints can be placed in a risk-averse way; decreasing the amount of crosses. This problem is excaserbated by the introduction of the tracking factor, which pulls the actors towards the planned paths. And when these paths have no concern for the paths of other actors, the tracking factor makes it very difficult for the interrobot factors to push hard enough to avoid collisions. If the path tracking approach with the tracking factors is desired, this is the main problem to solve. Even with an attempt to balance the tracking and interrobot factors to the point where the tracking factor has little impact of the path deviation error, the amount of collisions is still worse than that of the waypoint tracking approach without tracking factors altogether. One thing that becomes easier for the actors is the avoidance of static obstacles in the environment. As the global path-finder already takes care of only planning paths that are collision free, the actors can simply follow the planned paths without having to worry about the environment in any major way. Due to this, it can be concluded that the waypoint tracking approach is highly superior, as it lets the actors avoid each other much more effectively while still being able to use their obstacle factors to avoid static obstacles even when deviating from their otherwise collision-free paths.
https://github.com/Hyiker/report-typst
https://raw.githubusercontent.com/Hyiker/report-typst/master/main_en.typ
typst
Creative Commons Attribution 4.0 International
#import "report.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: "Sample Project Report", subtitle: "A sample project on this & that", abstract: lorem(50), subject: "WTF is this?", authors: ( (name: "<NAME>", department: "BIG & GOOD State Key Lab", rollno: "114514"), ), department: "College of Computer Science and Technology", institute: "WTF University", language: "en" ) // We generated the example code below so you can see how // your document will look. Go ahead and replace it with // your own content! = Introduction #lorem(60) == In this paper #lorem(320) == Contributions #lorem(40) == Some Other Things #lorem(40) == Some Other Things #lorem(40) = Related Work #lorem(50) == Level 2 Heading #lorem(100) === Level 3 Heading #lorem(100) ==== Level 4 Heading #lorem(100) ===== Level 5 Heading #lorem(100) #box( stroke: 1pt, inset: 10pt, lorem(10) )
https://github.com/WinstonMDP/knowledge
https://raw.githubusercontent.com/WinstonMDP/knowledge/master/progressions.typ
typst
#import "cfg.typ": cfg #show: cfg = Прогрессии == Арифметическая $a_n = a_1 + (n - 1)d$ Сумма: $n(a_1 + a_n)/2$
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/147.%20growth.html.typ
typst
growth.html Startup = Growth Want to start a startup? Get funded by Y Combinator. September 2012A startup is a company designed to grow fast. Being newly founded does not in itself make a company a startup. Nor is it necessary for a startup to work on technology, or take venture funding, or have some sort of "exit." The only essential thing is growth. Everything else we associate with startups follows from growth.If you want to start one it's important to understand that. Startups are so hard that you can't be pointed off to the side and hope to succeed. You have to know that growth is what you're after. The good news is, if you get growth, everything else tends to fall into place. Which means you can use growth like a compass to make almost every decision you face. RedwoodsLet's start with a distinction that should be obvious but is often overlooked: not every newly founded company is a startup. Millions of companies are started every year in the US. Only a tiny fraction are startups. Most are service businesses — restaurants, barbershops, plumbers, and so on. These are not startups, except in a few unusual cases. A barbershop isn't designed to grow fast. Whereas a search engine, for example, is.When I say startups are designed to grow fast, I mean it in two senses. Partly I mean designed in the sense of intended, because most startups fail. But I also mean startups are different by nature, in the same way a redwood seedling has a different destiny from a bean sprout.That difference is why there's a distinct word, "startup," for companies designed to grow fast. If all companies were essentially similar, but some through luck or the efforts of their founders ended up growing very fast, we wouldn't need a separate word. We could just talk about super-successful companies and less successful ones. But in fact startups do have a different sort of DNA from other businesses. Google is not just a barbershop whose founders were unusually lucky and hard-working. Google was different from the beginning.To grow rapidly, you need to make something you can sell to a big market. That's the difference between Google and a barbershop. A barbershop doesn't scale.For a company to grow really big, it must (a) make something lots of people want, and (b) reach and serve all those people. Barbershops are doing fine in the (a) department. Almost everyone needs their hair cut. The problem for a barbershop, as for any retail establishment, is (b). A barbershop serves customers in person, and few will travel far for a haircut. And even if they did, the barbershop couldn't accomodate them. [1]Writing software is a great way to solve (b), but you can still end up constrained in (a). If you write software to teach Tibetan to Hungarian speakers, you'll be able to reach most of the people who want it, but there won't be many of them. If you make software to teach English to Chinese speakers, however, you're in startup territory.Most businesses are tightly constrained in (a) or (b). The distinctive feature of successful startups is that they're not. IdeasIt might seem that it would always be better to start a startup than an ordinary business. If you're going to start a company, why not start the type with the most potential? The catch is that this is a (fairly) efficient market. If you write software to teach Tibetan to Hungarians, you won't have much competition. If you write software to teach English to Chinese speakers, you'll face ferocious competition, precisely because that's such a larger prize. [2]The constraints that limit ordinary companies also protect them. That's the tradeoff. If you start a barbershop, you only have to compete with other local barbers. If you start a search engine you have to compete with the whole world.The most important thing that the constraints on a normal business protect it from is not competition, however, but the difficulty of coming up with new ideas. If you open a bar in a particular neighborhood, as well as limiting your potential and protecting you from competitors, that geographic constraint also helps define your company. Bar + neighborhood is a sufficient idea for a small business. Similarly for companies constrained in (a). Your niche both protects and defines you.Whereas if you want to start a startup, you're probably going to have to think of something fairly novel. A startup has to make something it can deliver to a large market, and ideas of that type are so valuable that all the obvious ones are already taken.That space of ideas has been so thoroughly picked over that a startup generally has to work on something everyone else has overlooked. I was going to write that one has to make a conscious effort to find ideas everyone else has overlooked. But that's not how most startups get started. Usually successful startups happen because the founders are sufficiently different from other people that ideas few others can see seem obvious to them. Perhaps later they step back and notice they've found an idea in everyone else's blind spot, and from that point make a deliberate effort to stay there. [3] But at the moment when successful startups get started, much of the innovation is unconscious.What's different about successful founders is that they can see different problems. It's a particularly good combination both to be good at technology and to face problems that can be solved by it, because technology changes so rapidly that formerly bad ideas often become good without anyone noticing. <NAME>'s problem was that he wanted his own computer. That was an unusual problem to have in 1975. But technological change was about to make it a much more common one. Because he not only wanted a computer but knew how to build them, Wozniak was able to make himself one. And the problem he solved for himself became one that Apple solved for millions of people in the coming years. But by the time it was obvious to ordinary people that this was a big market, Apple was already established.Google has similar origins. Larry Page and Ser<NAME> wanted to search the web. But unlike most people they had the technical expertise both to notice that existing search engines were not as good as they could be, and to know how to improve them. Over the next few years their problem became everyone's problem, as the web grew to a size where you didn't have to be a picky search expert to notice the old algorithms weren't good enough. But as happened with Apple, by the time everyone else realized how important search was, Google was entrenched.That's one connection between startup ideas and technology. Rapid change in one area uncovers big, soluble problems in other areas. Sometimes the changes are advances, and what they change is solubility. That was the kind of change that yielded Apple; advances in chip technology finally let <NAME> design a computer he could afford. But in Google's case the most important change was the growth of the web. What changed there was not solubility but bigness.The other connection between startups and technology is that startups create new ways of doing things, and new ways of doing things are, in the broader sense of the word, new technology. When a startup both begins with an idea exposed by technological change and makes a product consisting of technology in the narrower sense (what used to be called "high technology"), it's easy to conflate the two. But the two connections are distinct and in principle one could start a startup that was neither driven by technological change, nor whose product consisted of technology except in the broader sense. [4]RateHow fast does a company have to grow to be considered a startup? There's no precise answer to that. "Startup" is a pole, not a threshold. Starting one is at first no more than a declaration of one's ambitions. You're committing not just to starting a company, but to starting a fast growing one, and you're thus committing to search for one of the rare ideas of that type. But at first you have no more than commitment. Starting a startup is like being an actor in that respect. "Actor" too is a pole rather than a threshold. At the beginning of his career, an actor is a waiter who goes to auditions. Getting work makes him a successful actor, but he doesn't only become an actor when he's successful.So the real question is not what growth rate makes a company a startup, but what growth rate successful startups tend to have. For founders that's more than a theoretical question, because it's equivalent to asking if they're on the right path.The growth of a successful startup usually has three phases: There's an initial period of slow or no growth while the startup tries to figure out what it's doing. As the startup figures out how to make something lots of people want and how to reach those people, there's a period of rapid growth. Eventually a successful startup will grow into a big company. Growth will slow, partly due to internal limits and partly because the company is starting to bump up against the limits of the markets it serves. [5] Together these three phases produce an S-curve. The phase whose growth defines the startup is the second one, the ascent. Its length and slope determine how big the company will be.The slope is the company's growth rate. If there's one number every founder should always know, it's the company's growth rate. That's the measure of a startup. If you don't know that number, you don't even know if you're doing well or badly.When I first meet founders and ask what their growth rate is, sometimes they tell me "we get about a hundred new customers a month." That's not a rate. What matters is not the absolute number of new customers, but the ratio of new customers to existing ones. If you're really getting a constant number of new customers every month, you're in trouble, because that means your growth rate is decreasing.During Y Combinator we measure growth rate per week, partly because there is so little time before Demo Day, and partly because startups early on need frequent feedback from their users to tweak what they're doing. [6]A good growth rate during YC is 5-7% a week. If you can hit 10% a week you're doing exceptionally well. If you can only manage 1%, it's a sign you haven't yet figured out what you're doing.The best thing to measure the growth rate of is revenue. The next best, for startups that aren't charging initially, is active users. That's a reasonable proxy for revenue growth because whenever the startup does start trying to make money, their revenues will probably be a constant multiple of active users. [7] CompassWe usually advise startups to pick a growth rate they think they can hit, and then just try to hit it every week. The key word here is "just." If they decide to grow at 7% a week and they hit that number, they're successful for that week. There's nothing more they need to do. But if they don't hit it, they've failed in the only thing that mattered, and should be correspondingly alarmed.Programmers will recognize what we're doing here. We're turning starting a startup into an optimization problem. And anyone who has tried optimizing code knows how wonderfully effective that sort of narrow focus can be. Optimizing code means taking an existing program and changing it to use less of something, usually time or memory. You don't have to think about what the program should do, just make it faster. For most programmers this is very satisfying work. The narrow focus makes it a sort of puzzle, and you're generally surprised how fast you can solve it.Focusing on hitting a growth rate reduces the otherwise bewilderingly multifarious problem of starting a startup to a single problem. You can use that target growth rate to make all your decisions for you; anything that gets you the growth you need is ipso facto right. Should you spend two days at a conference? Should you hire another programmer? Should you focus more on marketing? Should you spend time courting some big customer? Should you add x feature? Whatever gets you your target growth rate. [8]Judging yourself by weekly growth doesn't mean you can look no more than a week ahead. Once you experience the pain of missing your target one week (it was the only thing that mattered, and you failed at it), you become interested in anything that could spare you such pain in the future. So you'll be willing for example to hire another programmer, who won't contribute to this week's growth but perhaps in a month will have implemented some new feature that will get you more users. But only if (a) the distraction of hiring someone won't make you miss your numbers in the short term, and (b) you're sufficiently worried about whether you can keep hitting your numbers without hiring someone new.It's not that you don't think about the future, just that you think about it no more than necessary.In theory this sort of hill-climbing could get a startup into trouble. They could end up on a local maximum. But in practice that never happens. Having to hit a growth number every week forces founders to act, and acting versus not acting is the high bit of succeeding. Nine times out of ten, sitting around strategizing is just a form of procrastination. Whereas founders' intuitions about which hill to climb are usually better than they realize. Plus the maxima in the space of startup ideas are not spiky and isolated. Most fairly good ideas are adjacent to even better ones.The fascinating thing about optimizing for growth is that it can actually discover startup ideas. You can use the need for growth as a form of evolutionary pressure. If you start out with some initial plan and modify it as necessary to keep hitting, say, 10% weekly growth, you may end up with a quite different company than you meant to start. But anything that grows consistently at 10% a week is almost certainly a better idea than you started with.There's a parallel here to small businesses. Just as the constraint of being located in a particular neighborhood helps define a bar, the constraint of growing at a certain rate can help define a startup.You'll generally do best to follow that constraint wherever it leads rather than being influenced by some initial vision, just as a scientist is better off following the truth wherever it leads rather than being influenced by what he wishes were the case. When Richard Feynman said that the imagination of nature was greater than the imagination of man, he meant that if you just keep following the truth you'll discover cooler things than you could ever have made up. For startups, growth is a constraint much like truth. Every successful startup is at least partly a product of the imagination of growth. [9] ValueIt's hard to find something that grows consistently at several percent a week, but if you do you may have found something surprisingly valuable. If we project forward we see why. weeklyyearly 1%1.7x 2%2.8x 5%12.6x 7%33.7x 10%142.0x A company that grows at 1% a week will grow 1.7x a year, whereas a company that grows at 5% a week will grow 12.6x. A company making $1000 a month (a typical number early in YC) and growing at 1% a week will 4 years later be making $7900 a month, which is less than a good programmer makes in salary in Silicon Valley. A startup that grows at 5% a week will in 4 years be making $25 million a month. [10]Our ancestors must rarely have encountered cases of exponential growth, because our intuitions are no guide here. What happens to fast growing startups tends to surprise even the founders.Small variations in growth rate produce qualitatively different outcomes. That's why there's a separate word for startups, and why startups do things that ordinary companies don't, like raising money and getting acquired. And, strangely enough, it's also why they fail so frequently.Considering how valuable a successful startup can become, anyone familiar with the concept of expected value would be surprised if the failure rate weren't high. If a successful startup could make a founder $100 million, then even if the chance of succeeding were only 1%, the expected value of starting one would be $1 million. And the probability of a group of sufficiently smart and determined founders succeeding on that scale might be significantly over 1%. For the right people — e.g. the young <NAME> — the probability might be 20% or even 50%. So it's not surprising that so many want to take a shot at it. In an efficient market, the number of failed startups should be proportionate to the size of the successes. And since the latter is huge the former should be too. [11]What this means is that at any given time, the great majority of startups will be working on something that's never going to go anywhere, and yet glorifying their doomed efforts with the grandiose title of "startup."This doesn't bother me. It's the same with other high-beta vocations, like being an actor or a novelist. I've long since gotten used to it. But it seems to bother a lot of people, particularly those who've started ordinary businesses. Many are annoyed that these so-called startups get all the attention, when hardly any of them will amount to anything.If they stepped back and looked at the whole picture they might be less indignant. The mistake they're making is that by basing their opinions on anecdotal evidence they're implicitly judging by the median rather than the average. If you judge by the median startup, the whole concept of a startup seems like a fraud. You have to invent a bubble to explain why founders want to start them or investors want to fund them. But it's a mistake to use the median in a domain with so much variation. If you look at the average outcome rather than the median, you can understand why investors like them, and why, if they aren't median people, it's a rational choice for founders to start them. DealsWhy do investors like startups so much? Why are they so hot to invest in photo-sharing apps, rather than solid money-making businesses? Not only for the obvious reason.The test of any investment is the ratio of return to risk. Startups pass that test because although they're appallingly risky, the returns when they do succeed are so high. But that's not the only reason investors like startups. An ordinary slower-growing business might have just as good a ratio of return to risk, if both were lower. So why are VCs interested only in high-growth companies? The reason is that they get paid by getting their capital back, ideally after the startup IPOs, or failing that when it's acquired.The other way to get returns from an investment is in the form of dividends. Why isn't there a parallel VC industry that invests in ordinary companies in return for a percentage of their profits? Because it's too easy for people who control a private company to funnel its revenues to themselves (e.g. by buying overpriced components from a supplier they control) while making it look like the company is making little profit. Anyone who invested in private companies in return for dividends would have to pay close attention to their books.The reason VCs like to invest in startups is not simply the returns, but also because such investments are so easy to oversee. The founders can't enrich themselves without also enriching the investors. [12]Why do founders want to take the VCs' money? Growth, again. The constraint between good ideas and growth operates in both directions. It's not merely that you need a scalable idea to grow. If you have such an idea and don't grow fast enough, competitors will. Growing too slowly is particularly dangerous in a business with network effects, which the best startups usually have to some degree.Almost every company needs some amount of funding to get started. But startups often raise money even when they are or could be profitable. It might seem foolish to sell stock in a profitable company for less than you think it will later be worth, but it's no more foolish than buying insurance. Fundamentally that's how the most successful startups view fundraising. They could grow the company on its own revenues, but the extra money and help supplied by VCs will let them grow even faster. Raising money lets you choose your growth rate.Money to grow faster is always at the command of the most successful startups, because the VCs need them more than they need the VCs. A profitable startup could if it wanted just grow on its own revenues. Growing slower might be slightly dangerous, but chances are it wouldn't kill them. Whereas VCs need to invest in startups, and in particular the most successful startups, or they'll be out of business. Which means that any sufficiently promising startup will be offered money on terms they'd be crazy to refuse. And yet because of the scale of the successes in the startup business, VCs can still make money from such investments. You'd have to be crazy to believe your company was going to become as valuable as a high growth rate can make it, but some do.Pretty much every successful startup will get acquisition offers too. Why? What is it about startups that makes other companies want to buy them? [13]Fundamentally the same thing that makes everyone else want the stock of successful startups: a rapidly growing company is valuable. It's a good thing eBay bought Paypal, for example, because Paypal is now responsible for 43% of their sales and probably more of their growth.But acquirers have an additional reason to want startups. A rapidly growing company is not merely valuable, but dangerous. If it keeps expanding, it might expand into the acquirer's own territory. Most product acquisitions have some component of fear. Even if an acquirer isn't threatened by the startup itself, they might be alarmed at the thought of what a competitor could do with it. And because startups are in this sense doubly valuable to acquirers, acquirers will often pay more than an ordinary investor would. [14] UnderstandThe combination of founders, investors, and acquirers forms a natural ecosystem. It works so well that those who don't understand it are driven to invent conspiracy theories to explain how neatly things sometimes turn out. Just as our ancestors did to explain the apparently too neat workings of the natural world. But there is no secret cabal making it all work.If you start from the mistaken assumption that Instagram was worthless, you have to invent a secret boss to force <NAME> to buy it. To anyone who knows <NAME>, that is the reductio ad absurdum of the initial assumption. The reason he bought Instagram was that it was valuable and dangerous, and what made it so was growth.If you want to understand startups, understand growth. Growth drives everything in this world. Growth is why startups usually work on technology — because ideas for fast growing companies are so rare that the best way to find new ones is to discover those recently made viable by change, and technology is the best source of rapid change. Growth is why it's a rational choice economically for so many founders to try starting a startup: growth makes the successful companies so valuable that the expected value is high even though the risk is too. Growth is why VCs want to invest in startups: not just because the returns are high but also because generating returns from capital gains is easier to manage than generating returns from dividends. Growth explains why the most successful startups take VC money even if they don't need to: it lets them choose their growth rate. And growth explains why successful startups almost invariably get acquisition offers. To acquirers a fast-growing company is not merely valuable but dangerous too.It's not just that if you want to succeed in some domain, you have to understand the forces driving it. Understanding growth is what starting a startup consists of. What you're really doing (and to the dismay of some observers, all you're really doing) when you start a startup is committing to solve a harder type of problem than ordinary businesses do. You're committing to search for one of the rare ideas that generates rapid growth. Because these ideas are so valuable, finding one is hard. The startup is the embodiment of your discoveries so far. Starting a startup is thus very much like deciding to be a research scientist: you're not committing to solve any specific problem; you don't know for sure which problems are soluble; but you're committing to try to discover something no one knew before. A startup founder is in effect an economic research scientist. Most don't discover anything that remarkable, but some discover relativity. Notes[1] Strictly speaking it's not lots of customers you need but a big market, meaning a high product of number of customers times how much they'll pay. But it's dangerous to have too few customers even if they pay a lot, or the power that individual customers have over you could turn you into a de facto consulting firm. So whatever market you're in, you'll usually do best to err on the side of making the broadest type of product for it.[2] One year at Startup School <NAME> encouraged programmers who wanted to start businesses to use a restaurant as a model. What he meant, I believe, is that it's fine to start software companies constrained in (a) in the same way a restaurant is constrained in (b). I agree. Most people should not try to start startups.[3] That sort of stepping back is one of the things we focus on at Y Combinator. It's common for founders to have discovered something intuitively without understanding all its implications. That's probably true of the biggest discoveries in any field.[4] I got it wrong in "How to Make Wealth" when I said that a startup was a small company that takes on a hard technical problem. That is the most common recipe but not the only one.[5] In principle companies aren't limited by the size of the markets they serve, because they could just expand into new markets. But there seem to be limits on the ability of big companies to do that. Which means the slowdown that comes from bumping up against the limits of one's markets is ultimately just another way in which internal limits are expressed.It may be that some of these limits could be overcome by changing the shape of the organization — specifically by sharding it.[6] This is, obviously, only for startups that have already launched or can launch during YC. A startup building a new database will probably not do that. On the other hand, launching something small and then using growth rate as evolutionary pressure is such a valuable technique that any company that could start this way probably should.[7] If the startup is taking the Facebook/Twitter route and building something they hope will be very popular but from which they don't yet have a definite plan to make money, the growth rate has to be higher, even though it's a proxy for revenue growth, because such companies need huge numbers of users to succeed at all.Beware too of the edge case where something spreads rapidly but the churn is high as well, so that you have good net growth till you run through all the potential users, at which point it suddenly stops.[8] Within YC when we say it's ipso facto right to do whatever gets you growth, it's implicit that this excludes trickery like buying users for more than their lifetime value, counting users as active when they're really not, bleeding out invites at a regularly increasing rate to manufacture a perfect growth curve, etc. Even if you were able to fool investors with such tricks, you'd ultimately be hurting yourself, because you're throwing off your own compass.[9] Which is why it's such a dangerous mistake to believe that successful startups are simply the embodiment of some brilliant initial idea. What you're looking for initially is not so much a great idea as an idea that could evolve into a great one. The danger is that promising ideas are not merely blurry versions of great ones. They're often different in kind, because the early adopters you evolve the idea upon have different needs from the rest of the market. For example, the idea that evolves into Facebook isn't merely a subset of Facebook; the idea that evolves into Facebook is a site for Harvard undergrads.[10] What if a company grew at 1.7x a year for a really long time? Could it not grow just as big as any successful startup? In principle yes, of course. If our hypothetical company making $1000 a month grew at 1% a week for 19 years, it would grow as big as a company growing at 5% a week for 4 years. But while such trajectories may be common in, say, real estate development, you don't see them much in the technology business. In technology, companies that grow slowly tend not to grow as big.[11] Any expected value calculation varies from person to person depending on their utility function for money. I.e. the first million is worth more to most people than subsequent millions. How much more depends on the person. For founders who are younger or more ambitious the utility function is flatter. Which is probably part of the reason the founders of the most successful startups of all tend to be on the young side.[12] More precisely, this is the case in the biggest winners, which is where all the returns come from. A startup founder could pull the same trick of enriching himself at the company's expense by selling them overpriced components. But it wouldn't be worth it for the founders of Google to do that. Only founders of failing startups would even be tempted, but those are writeoffs from the VCs' point of view anyway.[13] Acquisitions fall into two categories: those where the acquirer wants the business, and those where the acquirer just wants the employees. The latter type is sometimes called an HR acquisition. Though nominally acquisitions and sometimes on a scale that has a significant effect on the expected value calculation for potential founders, HR acquisitions are viewed by acquirers as more akin to hiring bonuses.[14] I once explained this to some founders who had recently arrived from Russia. They found it novel that if you threatened a company they'd pay a premium for you. "In Russia they just kill you," they said, and they were only partly joking. Economically, the fact that established companies can't simply eliminate new competitors may be one of the most valuable aspects of the rule of law. And so to the extent we see incumbents suppressing competitors via regulations or patent suits, we should worry, not because it's a departure from the rule of law per se but from what the rule of law is aiming at. Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this.Arabic TranslationEstonian TranslationPortuguese TranslationItalian Translation
https://github.com/SillyFreak/typst-preprocess
https://raw.githubusercontent.com/SillyFreak/typst-preprocess/main/tests/failure-outside-root/main.typ
typst
#import "@preview/prequery:0.1.0" #prequery.image( "https://upload.wikimedia.org/wikipedia/commons/a/af/Cc-public_domain_mark.svg", "assets/public_domain.svg")
https://github.com/WeetHet/typst.zed
https://raw.githubusercontent.com/WeetHet/typst.zed/main/README.md
markdown
Apache License 2.0
# Typst - Tree Sitter: [tree-sitter-typst](https://github.com/uben0/tree-sitter-typst/) - Language Server: [tinymist](https://github.com/Myriad-Dreamin/tinymist/)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-0B80.typ
typst
Apache License 2.0
#let data = ( (), (), ("TAMIL SIGN ANUSVARA", "Mn", 0), ("TAMIL SIGN VISARGA", "Lo", 0), (), ("TAMIL LETTER A", "Lo", 0), ("TAMIL LETTER AA", "Lo", 0), ("TAMIL LETTER I", "Lo", 0), ("TAMIL LETTER II", "Lo", 0), ("TAMIL LETTER U", "Lo", 0), ("TAMIL LETTER UU", "Lo", 0), (), (), (), ("TAMIL LETTER E", "Lo", 0), ("TAMIL LETTER EE", "Lo", 0), ("TAMIL LETTER AI", "Lo", 0), (), ("TAMIL LETTER O", "Lo", 0), ("TAMIL LETTER OO", "Lo", 0), ("TAMIL LETTER AU", "Lo", 0), ("TAMIL LETTER KA", "Lo", 0), (), (), (), ("TAMIL LETTER NGA", "Lo", 0), ("TAMIL LETTER CA", "Lo", 0), (), ("TAMIL LETTER JA", "Lo", 0), (), ("TAMIL LETTER NYA", "Lo", 0), ("TAMIL LETTER TTA", "Lo", 0), (), (), (), ("TAMIL LETTER NNA", "Lo", 0), ("TAMIL LETTER TA", "Lo", 0), (), (), (), ("TAMIL LETTER NA", "Lo", 0), ("TAMIL LETTER NNNA", "Lo", 0), ("TAMIL LETTER PA", "Lo", 0), (), (), (), ("TAMIL LETTER MA", "Lo", 0), ("TAMIL LETTER YA", "Lo", 0), ("TAMIL LETTER RA", "Lo", 0), ("TAMIL LETTER RRA", "Lo", 0), ("TAMIL LETTER LA", "Lo", 0), ("TAMIL LETTER LLA", "Lo", 0), ("TAMIL LETTER LLLA", "Lo", 0), ("TAMIL LETTER VA", "Lo", 0), ("TAMIL LETTER SHA", "Lo", 0), ("TAMIL LETTER SSA", "Lo", 0), ("TAMIL LETTER SA", "Lo", 0), ("TAMIL LETTER HA", "Lo", 0), (), (), (), (), ("TAMIL VOWEL SIGN AA", "Mc", 0), ("TAMIL VOWEL SIGN I", "Mc", 0), ("TAMIL VOWEL SIGN II", "Mn", 0), ("TAMIL VOWEL SIGN U", "Mc", 0), ("TAMIL VOWEL SIGN UU", "Mc", 0), (), (), (), ("TAMIL VOWEL SIGN E", "Mc", 0), ("TAMIL VOWEL SIGN EE", "Mc", 0), ("TAMIL VOWEL SIGN AI", "Mc", 0), (), ("TAMIL VOWEL SIGN O", "Mc", 0), ("TAMIL VOWEL SIGN OO", "Mc", 0), ("TAMIL VOWEL SIGN AU", "Mc", 0), ("TAMIL SIGN VIRAMA", "Mn", 9), (), (), ("TAMIL OM", "Lo", 0), (), (), (), (), (), (), ("TAMIL AU LENGTH MARK", "Mc", 0), (), (), (), (), (), (), (), (), (), (), (), (), (), (), ("TAMIL DIGIT ZERO", "Nd", 0), ("TAMIL DIGIT ONE", "Nd", 0), ("TAMIL DIGIT TWO", "Nd", 0), ("TAMIL DIGIT THREE", "Nd", 0), ("TAMIL DIGIT FOUR", "Nd", 0), ("TAMIL DIGIT FIVE", "Nd", 0), ("TAMIL DIGIT SIX", "Nd", 0), ("TAMIL DIGIT SEVEN", "Nd", 0), ("TAMIL DIGIT EIGHT", "Nd", 0), ("TAMIL DIGIT NINE", "Nd", 0), ("TAMIL NUMBER TEN", "No", 0), ("TAMIL NUMBER ONE HUNDRED", "No", 0), ("TAMIL NUMBER ONE THOUSAND", "No", 0), ("TAMIL DAY SIGN", "So", 0), ("TAMIL MONTH SIGN", "So", 0), ("TAMIL YEAR SIGN", "So", 0), ("TAMIL DEBIT SIGN", "So", 0), ("TAMIL CREDIT SIGN", "So", 0), ("TAMIL AS ABOVE SIGN", "So", 0), ("TAMIL RUPEE SIGN", "Sc", 0), ("TAMIL NUMBER SIGN", "So", 0), )
https://github.com/jaoleal/Sob_Proposal_Floresta
https://raw.githubusercontent.com/jaoleal/Sob_Proposal_Floresta/main/Sob_proposal.typ
typst
#show link: underline #set page(numbering: "1") = Floresta: Move Async-std to Tokio <proposal> == Concepts Preview <concepts-preview> The proposal is about changing the async runtime from `async-std` to `tokio` in the Floresta project, but more how they work on Floresta. The change is proposed by the lead developer and maintainer of the project, #link("https://github.com/Davidson-Souza")[Davidson Souza]. The main goal is to improve performance and enhance features that `async-std` at the moment does not provide. Here some information about the concepts that will be used in this proposal: === Floresta A opensource lightweight Bitcoin full node implementation written in Rust. === Rust Rust is a programming language focused on memory safety and performance. Its `Async` features was developed to be in the standard library but the `Runtime` was outsourced to the community. === Rust Crates Crates are how the Rust modules and libraries are called. Every piece of code that has its own Cargo.toml can be called a crate. === Async and Runtime Async is a programming paradigm that allows the execution of tasks concurrently. In Rust, to use Async, a `Runtime` is needed to manage the tasks. === Tokio and Async-std `Tokio` and `Async-std` are two of the most used `Runtimes` in Rust. They provide the necessary tools to manage async tasks. But `Async-std` is not as performant as `Tokio` and can be considered a bit of deprecated. If remains any doubt about the concepts, check the #link(<source-of-information>)[Source of Information] section. == First Phase of Proposal <first-phase-of-proposal> As proposed by #link("https://github.com/Davidson-Souza")[<NAME>za], lead developer and maintainer of #link("https://github.com/Davidson-Souza/Floresta")[`Floresta`], the project is eager to offer #link("https://tokio.rs")[`tokio`] as the primary async runtime. Currently, the `Floresta` uses #link("https://async.rs/")[`async-std`]. Potential advantages are performance improvements and enhanced features from `tokio` that `async-std` cannot provide. The "crates" that will be affected by this proposal: === `florestad` <florestad> located at `/florestad`. The Floresta node itself uses `async` operations to resolve shutdown calls, communicate with the Electrum server and I/O functions. - Notable used `async-std` features: - `sync::{Rwlock, Block_on}` === `floresta-electrum` <floresta-electrum> located at `/crates/floresta-electrum`. An Electrum server adapted to floresta node exposing a proper API to communicate with Electrum wallets. Async features are used to provide Tcp connections, message based channels between tasks and I/O functions. - Notable used `async-std` features: - `channel::{unbounded, Receiver, Sender}` - `io::{BufReader}` - `net::{TcpListener, TcpStream, ToSocketAddrs}` - `sync::{Rwlock}` - `task::{spawn}` === `floresta-wire` <floresta-wire> Located at `/crates/floresta-wire`. Api to find and discover new blocks, it has have p2p protocol and utreexod's JSON-rpc implemented. Async feature is heavily present on p2p communication. - Notable used Async-std features: - sync::{RwLock} - Channel::{bounded, receiver, sender, sendError} - net::{TcpStream} Regarding the use of asynchronous, the future trait is used in the mentioned crates to manage an asynchronous approach to some tasks, even not being inherited directly from the Async-std Its outsourcing to Tokio can be evaluated since the discovery of a different approach to use Tokio that can reward more performance and trust in its execution. == The Challenge <the-Challenge> To fit Tokio in Floresta some parameters have to be evaluated before the change execution. + The performance can't be worse than the alternative that is currently being used. (Async-std) + The code complexity is not supposed to increase. Even if the Tokio implementation needs rewriting, that is probably what will be, the rewriting needs to follow a similar way to deal with tasks that the actual code already has. + The tests that are related to the affected crates by the runtime change need to stay intact and untouched, showing that all functionalities are all working fine and as expected. == Steps Planning <steps-planning> The next steps covers the main purpose of the proposal, extras and possibilities that will come with the dependency change will be described and explored at #link(<second-phase-of-proposal>)["Second Phase of Proposal"]. + #strong("Floresta-Wire"), #strong("Floresta-Electrum") and #strong("Florestad") Rust test battery for internal functions and Python test battery for mocking external cases and performance cover, focused on async functionalities. Deeper understanding of the project. #strong[\(1 - 2 weeks).] + #strong("Floresta-Wire") async functionalities dependencies from Async-std to Tokio. #strong[\( 1 - 2 weeks).] + #strong("Floresta-Electrum") async functionalities dependencies from Async-std to Tokio. #strong[\(8 - 12 days).] + #strong("Florestad") async functionalities dependencies from Async-std to Tokio. #strong[\(8 - 12 days).] The estimated work time may vary depending on problems encountered during the execution of the proposal even if, in this document, defined for organized work, properly documented, Error handling and covering possible errors. Considering that the start of the work in the Floresta's project would begin at 15 May 2024 and is safely expected by the midlle/end of july 2024. == Second Phase of Proposal <second-phase-of-proposal> After the sucessfull integration of Tokio, the good pratices in code versioning (see #link(<code-versioning-planning>)[code versioning planning]) can introduce us to an opportunity to integrate a good feature to Floresta portability, #link(<agnostic-runtime>)[Agnostic Runtime]. === Agnostic runtime <agnostic-runtime> Agnostic, outside the context of the religious meaning, can infer something that is "unattached" of another thing. In this project context we can "unattach" the Async runtime that rust outsorced to the community in a trade for just a little workaround and some "redesign" in how the async functions works for floresta. This is a rust representation of how things could work (not final work): ```rust use std::{future::Future, process::Output}; use anyhow::Result; use std::marker::Send; use async_std::task::{self as std_task}; use tokio::task::{spawn as tokio_spawn}; trait Asyncfunctions { async fn task<F, T>(&self,t: F) -> T where F: Future<Output = T> + Send + 'static, T: Send + 'static; } struct StdAsync; struct TokioRuntime; impl Asyncfunctions for TokioRuntime{ async fn task<F, T>(&self,t: F) -> T where F: Future<Output = T> + Send + 'static, T: Send + 'static{ tokio_spawn(t).await.unwrap() } } impl Asyncfunctions for StdAsync{ async fn task<F, T>(&self,t: F) -> T where F: Future<Output = T> + Send + 'static, T: Send + 'static{ std_task::spawn(t).await } } async fn agnostic_function<F: Asyncfunctions> (runtime: F) -> Result<()> { let task = runtime.task( async { let mut i = 0; for j in 0..1_000_000_000 { i += 1; } println!("one billion is reached. i:{}", i ); }); task.await; Ok(()) } #[tokio::main] async fn main() { println!("print one billion using Async-std funtions:"); let _ = agnostic_function(StdAsync); println!("print one billion using tokio functions:"); let _ = agnostic_function(TokioRuntime).await; } ``` See that in `agnostic_function()` we can use #link("https://en.wikipedia.org/wiki/Dependency_injection")[Dependency injection], a technique that allow the use of dependencies as parameters and calling functionalities from that parameters, to make functions that need async use just the library that we want to inherit the async funcions, in this case, `Async-std` and `Tokio` are used. both functions work as expected using eachother runtime just printing: ```shell print one billion using Async-std funtions: one billion is reached. i:1000000000 print one billion using tokio functions: one billion is reached. i:1000000000 ``` In the example, using Tokio runtime. Is good to note the Rust feature that is being use in the design of code, including a "`wrapper`" function to async functionalities as `traits` and them making structs for the Async libraries that can be called. Note the use of aliases when inheriting async functions from their respective libraries in this way, the compiler knows exactly what to call when building the binary. ```rust use async_std::task::{self as std_task}; use tokio::task::{spawn as tokio_spawn}; ``` Even if the code in question calls both libraries, in a oficial implementation is better to be precise and include this use of aliases The runtime needs to be declared in the code, this can be achieved with cargo features and Rust macros to change the desired runtime in the compile time. Example: ``` cargo build --features "async-std-runtime" ``` or ``` cargo build --features "tokio-runtime" ``` and using types in Rust ```rust #[cfg(feature = "async-std-runtime")] type Runtime = StdAsync; #[cfg(feature = "tokio-runtime")] type Runtime = TokioRuntime; ``` The idea about "Runtime Agnostic" was mentioned by #link("https://github.com/Davidson-Souza")[Davidson Souza] at the #link("https://www.summerofbitcoin.org/project-ideas-details/floresta/r/recCx3APdQ11FICfZ")[Summer of Bitcoin] #set quote(block: true) #quote(attribution: [Davidson at Floresta's Project Ideas])[ "A stretch goal would be making it runtime agnostic, rather than tied to tokio alone." ] The code design can be better discussed, but in first idea, the code could rely in modulating only the used async functions by the #strong("libFloresta") and #strong("florestad") make better use and reuse of the code. #figure( image("Floresta-agnostic-Modules(Light).svg", width: 75%), caption: [ Before and After the "Agnostic Runtime" implementation in Floresta. ], ) Using modularization to a point that the async functions used by Floresta are all together in a single module can expand and simplify the possibilities of features, one of them being the runtime change without taking down the whole Node and can simplify the code in the other modules by just calling the async functions from the module. With this technique of "Agnostic Runtime" the Floresta node can fit or can easily be modified to fit in any device if the "Main runtime" can be a problem. For more low-end devices and environments with scarce computing resources, the use of `smol-rs` can be a good fit and will need less work to implement it in the project than if the project was using only one runtime. Depending on Mentor's will or ideas, the Agnostic Runtime code design and technique can be changed before the implementation. Time expectation of implementation: #strong[\( 3 + weeks).] == Code versioning planning <code-versioning-planning> Code Versioning can help to decrease the implementation time and prevent errors since a good definition of the work objetives at the beginning of the work. #figure( grid( columns: 2, figure( image("Versioning_without_agnostic.svg", width: 54%), caption: [ Versioning representation without Agnostic runtime.], ), figure( image("Versioning_with_agnostic.svg", width: 60%), caption: [ Versioning representation with Agnostic runtime. ], ) ), ) As represented in the images above, the agnostic modularization can start beeing implemented since the beginning of the work in the project. == A Promising Feature for Bitcoin and Rust Community <a-promising-feature-for-bitcoin-and-rust-community> After the success of the proposal work, we'll stand with a more portable and flexible bitcoin project that has the great potential to be the `"Must Use"` bitcoin node for low-end devices, even because the Rust programming language is promising in this environments, and for it enthusiast that love to fingering with the code. The Floresta project attack in the bitcoin most requested feature: The `Adoption`, when evolving the project to be a fit for any device. The Rust community, in general, can make a good use of a future `Floresta-Async`, a possible runtime agnostic rust crate made for Floresta project since the highly mentioned technique is quite reproducible for other projects. To follow the lightweight ideal of Floresta the implementation of `smol-rs`, a lightweight async Rust runtime with permissive license, will bring the project closer to be perfect and a icing on the cake to work with after the conclusion of the proposal. == The Writer The writer of this proposal is #link("https://github.com/jaoleal")[João Leal], a Brazilian Science Computer student at his first semester that tries to run out of obvious but never from the simple. The writer became a Rust adopter to learn things using modern and efficient tools. The programming modernity can't be explained without talking about the Bitcoin solution to the global society money problem, and maybe ower best piece of code for ourselves as humans, the poor, the rich, the minority and the majority, they are all the same for Bitcoin and Bitcoin is the same for them. If anyhting on this proposal sounds good for you, and you want more of it, you can talk with the writer: - Full name: <NAME> - E-mail: <EMAIL> - Github: #link("https://github.com/jaoleal")[João Leal's Github]. - Discord: jleall - Nacionality: 🇧🇷 Brazilian - Timezone: São Paulo - SP (GMT-3) == Source of Information: <source-of-information> #link("https://doc.rust-lang.org/book/")[The Rust Programming Language] #link("https://en.wikipedia.org/wiki/Runtime_system")[Runtime at Wikipedia] #link("https://async.rs/")[Async-std] #link("https://tokio.rs/Async")[Tokio] #link("https://en.wikipedia.org/wiki/Dependency_injection")[Dependency injection] #link("https://github.com/smol-rs/smol")[smol-rs at Github] #link("https://www.youtube.com/watch?v=w1vKAUor-4o")[Runtime agsnostic async crates by Zeeshan Ali]. #link("https://www.summerofbitcoin.org/project-ideas-details/floresta/r/recCx3APdQ11FICfZ")[Summer of Bitcoin website proposal] #link("https://github.com/Davidson-Souza/Floresta/issues/144")[\#144 \[SoB\]: Move Async-std to Tokio]
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/layout/measure.typ
typst
--- measure --- // Test `measure`. #let f(lo, hi) = context { let h = measure[Hello].height assert(h > lo) assert(h < hi) } #text(10pt, f(6pt, 8pt)) #text(20pt, f(13pt, 14pt)) --- measure-given-area --- // Test `measure` given an area. #let text = lorem(100) #context { let d1 = measure(text) assert(d1.width > 2000pt) assert(d1.height < 10pt) let d2 = measure(width: 400pt, height: auto, text) assert(d2.width < 400pt) assert(d2.height > 50pt) } --- measure-counter-width --- // Measure a counter. Tests that the introspector-assisted location assignment // is able to take `here()` from the context into account to find the closest // matching element instead of any single one. Crucially, we need to reuse // the same `context c.display()` to get the same span, hence `it`. #let f(it) = context [ Is #measure(it).width wide: #it \ ] #let c = counter("c") #let it = context c.display() #c.update(10000) #f(it) #c.update(100) #f(it) #c.update(1) #f(it) --- measure-citation-in-flow --- // Try measuring a citation that appears inline with other stuff. The // introspection-assisted location assignment will ensure that the citation // in the measurement is matched up with the real one. #context { let it = [@netwok] let size = measure(it) place(line(length: size.width)) v(1mm) it + [ is cited] } #show bibliography: none #bibliography("/assets/bib/works.bib") --- measure-citation-in-flow-different-span --- // When the citation has a different span, it stops working. #context { // Error: 22-29 cannot format citation in isolation // Hint: 22-29 check whether this citation is measured without being inserted into the document let size = measure[@netwok] place(line(length: size.width)) v(1mm) [@netwok is cited] } #show bibliography: none #bibliography("/assets/bib/works.bib") --- measure-citation-deeply-nested --- // Nested the citation deeply to test that introspector-assisted measurement // is able to deal with memoization boundaries. #context { let it = box(pad(x: 5pt, grid(stack[@netwok]))) [#measure(it).width] it } #show bibliography: none #bibliography("/assets/bib/works.bib") --- measure-counter-multiple-times --- // When the thing we measure appears multiple times, we measure as if it was // the first one. #context { let c = counter("c") let u(n) = c.update(n) let it = context c.get().first() * h(1pt) let size = measure(it) table(columns: 5, u(17), it, u(1), it, u(5)) [#size.width] // 17pt }
https://github.com/thornoar/lambda-calculus-course
https://raw.githubusercontent.com/thornoar/lambda-calculus-course/master/main-lectures/final-test-2.typ
typst
#import "@local/common:0.0.0": * #import "@local/theorem:0.0.0": * #show: theorem #import "./template.lib.typ": * #show: formatting #set heading(numbering: none) #set text(size: 13pt) #set page(background: image("pictures/troubles-faded.jpg", width: 100%, height: 100%, fit: "stretch")) #head([ Итоговая работа, II вариант ]) == На 3: + Дайте определение _комбинатора неподвижной точки._ Приведите примеры. Докажите, что выражение $#Y _M == @f.. (@x%y.. f(x x y))(@x%y.. f(x x y))M$ является комбинатором неподвижной точки для любого $M in #L$. + Дайте определение _чисел Барендрегта_ и _чисел Чёрча._ Постройте л-выражения $H$ и $H^(-1)$, которые переводят одни в другие: $H nums(n) = c_n$, #h(5pt) $H^(-1) c_n = num(n)$. + Дайте определение л-представимости числовой функции. Определите функцию _суперпозиции_ для числовых функций $chi, psi_1, psi_2, ..., psi_k$. + Покажите, что функция $#Am == @x%y%z.. x(y z)$ задаёт умножение на числах Чёрча: $#Am c_n c_m = c_(n m)$. == На 4: + Докажите, что класс л-представимых функций замкнут относительно минимизации. + Определите понятие _адекватной числовой системы._ Докажите, что числовая система $d = (d_0, #S^+_d)$ адекватна в том и только том случае, когда она имеет оператор предшествующего элемента $#P^-_d$: #h(5pt) $#P^-_d #h(2pt) d_(n+1) = d_n, hs forall n in NN_0$. + Докажите _обобщённую теорему о неподвижной точке:_ $forall F_1, F_2, ..., F_n in #L: hs exists X_1, X_2, ..., X_n in #L:$ $ X_1 &= F_1 X_1 X_2 ... X_n,\ X_2 &= F_2 X_1 X_2 ... X_n,\ dots.v\ X_n &= F_n X_1 X_2 ... X_n.\ $ == На 5: + Докажите теорему Скотта-Карри о неразрешимости. + Покажите, что следующие две последовательности являются адекватными числовыми системами:\ [a]#hs $d = (#Y, @x.. [x, P])$, где $P in #L$ произвольно;\ [b]#hs $e = (#K, @x.. [x, #Y])$.\ (подсказка: для $d$ используйте $#Zero _d == [#K (#K #K), #I]$) + Покажите, что функция $"id" : NN_0 -> NN_0, hs "id"(n) = n$ является рекурсивной. Покажите, что всякий многочлен $ &P : NN_0 -> NN_0,\ P(n) &= a_0 + a_1 n + a_2 n^2 + ... + a_k n^k, $ с коэффициентами $a_0, a_1, ..., a_k in NN_0$, --- рекурсивная функция.
https://github.com/Amalbeld/d-veloppement_informatique
https://raw.githubusercontent.com/Amalbeld/d-veloppement_informatique/main/Lab-3.typ
typst
#import "Class.typ": * #show: ieee.with( title: [#text(smallcaps("Lab #3: Web Application with Genie"))], /* abstract: [ #lorem(12). ], */ authors: ( ( name: "<NAME>", department: [ELNI], organization: [ISET Bizerte --- Tunisia], profile: "amalbeld", ), ) // index-terms: (""), // bibliography-file: "Biblio.bib", ) = Exercise In this lab, we will create a basic web application using *Genie framework* in Julia. The application will allow us to control the behaviour of a sine wave, given some adjustble parameters. You are required to carry out this lab using the REPL as in @fig:repl. #figure( image("Images/0_6q1ZoAIh51k7HlRh.png", width: 90%, fit: "contain"), caption: "Julia" ) <fig:repl> #exo[Sine Wave Control][We provide the Julia and HTML codes to build and run a web app that allows us to control. * the amplitude* and *frequency* of a sine wave. *Plotly* is used to plot the corresponding graph. *Samples* : We also added a slider to change the number of samples used to draw the figure. The latter setting permits to grasp the influence of sampling frequency on the look of our chart.] #let code=read("../Codes/web-app/app.jl") #raw(code, lang: "julia") #let code=read("../Codes/web-app/app.jl.html") #raw(code, lang: "html") ```zsh julia --project ``` ```julia cd("location of the folder/infodev/web-app") julia> using GenieFramework julia> Genie.loadapp() # Load app julia> up() # Start the server ``` #figure( image("Images/Capture.PNG", width: 100%, fit: "contain"), caption: "Genie -> Sine Wave" ) <fig:wave> We can now open the browser and navigate to the link #highlight[#link("localhost:8000")[http://127.0.0.1:8000/]]. #exo[Phase][ Phase ranging between $-pi$ and $pi$, changes by a step of $pi/100$ ] ```zsh julia ``` ```julia using GenieFramework @genietools @app begin ------- @in pha::Float32 = 1 ------ @onchange N, amp, freq , pha begin x = range(0, 1, length=N) y = amp*sin.(2*π*freq*x .+pha ) ``` ```zsh HTML ``` ```html <div class="st-col col-12 col-sm st-module"> <p><b>phase</b></p> <q-slider v-model="pha" :min="-3.14" :max="3.14" :step=".0314" :label="true"> </q-slider> </div> ``` #figure( image("Images/Capture1.PNG", width: 100%, fit: "contain"), caption: "Genie -> Sine Wave with phase" ) <fig:wave1> #exo[offset][Offset varies from $-0.5$ to $1$, by a step of $0.1$.] ```zsh julia ``` ```julia using GenieFramework @genietools @app begin ------- @in ofs::Float32 = 1 ------ @onchange N, amp, freq , pha , ofs begin x = range(0, 1, length=N) y = amp*sin.(2*π*freq*x .+pha ) .+ofs ``` ```zsh HTML ``` ```html <div class="st-col col-12 col-sm st-module"> <p><b>offset</b></p> <q-slider v-model="ofs" :min="-0.5" :max="1" :step="0.1" :label="true"> </q-slider> </div> ``` #figure( image("Images/Capture2.PNG", width: 100%, fit: "contain"), caption: "Genie -> Sine Wave with phase and offset" ) <fig:wave2>
https://github.com/floriandejonckheere/utu-thesis
https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/chapters/07-proposed-solution/01-introduction.typ
typst
#import "@preview/acrostiche:0.3.1": * #import "/helpers.typ": * = Proposed solution <proposedsolution> In this chapter, we propose *Modular Optimization to Service-oriented Architecture Identification Kit (MOSAIK)*, our solution for automated identification of microservice candidates in a monolith application. The approach is based on the analysis of a dependency graph, that aggregates information from the static and evolutionary analysis of the source code. We focus on answering the following research question: #link(<research_question_3>)[*Research Question 3*]: How can static analysis of source code identify module boundaries in a modular monolith architecture that maximize internal cohesion and minimize external coupling? The motivation behind the research question is discussed in @introduction. == Problem statement The goal of MOSAIK is to automate microservice candidate identification in a monolith application, by statically analyzing the codebase of the application. The resulting decomposition can be used as a starting point for the migration to microservices or modular monolith architecture. The problem can be formulated as a graph partitioning problem, where the vertices correspond to the software components in the monolith application, and the edges represent the dependencies between them. The input of the algorithm is a representation $M$ of the monolith application, which exposes a set of functionalities $M_F$ through a set of classes $M_C$, and history of modifications $M_H$. The triplet is described by @monolith_triplet_formulas. $ M_i = { M_F_i, M_C_i, M_H_i } $ <monolith_triplet_formulas> The set of functionalities $M_F$, the set of classes $M_C$, and the set of historical modifications $M_H$ are described by @monolith_formulas. $ M_F_i = { f_1, f_2, ..., f_j } #linebreak() M_C_i = { c_1, c_2, ..., c_k } #linebreak() M_H_i = { h_1, h_2, ..., h_l } $ <monolith_formulas> Where $j$, $k$, and $l$ are the number of functionalities, classes, and historical modifications in the monolith application, respectively. The output of the algorithm is a set of microservices $S$, according to @decomposition_formula, where $m$ is the number of microservices in the proposed decomposition. $ S_i = { s_1, s_2, ..., s_m } $ <decomposition_formula> As each class belongs to at most microservice, the proposed decomposition $S$ can be written as a surjective function $f$ of $M_C_i$ onto $S_i$ as in @microservice_formula, where $f(c_i) = s_j$ if class $c_i$ belongs to microservice $s_j$. $ f: M_C_i -> S_i $ <microservice_formula> A microservice that contains only one class is called a _singleton microservice_. Singleton microservices typically contain classes that are not used by any other class in the monolith application. As an optimization of the microservice decomposition, these classes can be omitted from the final decomposition, as they do not have any functional contribution.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/import-22.typ
typst
Other
// A star in the list. // Error: 26-27 unexpected star #import "module.typ": a, *, b
https://github.com/SillyFreak/typst-stack-pointer
https://raw.githubusercontent.com/SillyFreak/typst-stack-pointer/main/src/lib.typ
typst
MIT License
#import "@preview/polylux:0.3.1": only #import "effects.typ": * /// Sequence item with type `"step"`: a single step at which execution state can be inspected. /// A step can have any fields associated with it that can be used to visualize the execution state. /// /// - ..args (dictionary): exclusively named arguments to be added to the step /// -> array #let step(..args) = { assert(args.pos().len() == 0, message: "only named arguments allowed") let args = args.named() assert("type" not in args, message: "type can't be used as a field in a step") ((type: "step", ..args),) } /// A template for creating functions like @@l(). This function takes effects as positional /// parameters and step fields as named parameters. To Define a custom `l()`-like function, use /// something like this: /// ```typ /// #let my-l(foo, ..args) = bare-l(foo: foo, ..args) /// ``` /// Now `my-l()` lets you specify the `foo` field for your executions as a positional parameter. /// /// - ..args (arguments): the effects to apply before the next step, and the fields for the next step /// -> array #let bare-l(..args) = { let effects = args.pos() let args = args.named() for effect in effects { effect } step(..args) } /// -> array /// High-level step creating function. Emits any number of effects, followed by a single step. This /// function takes a line number as a positional parameter, then effects as additional positional /// parameters, and step fields as named parameters. /// /// - line (integer): the line number to add to the step as a field /// - ..args (arguments): the effects to apply before the next step, and the extra fields for the next step /// -> array #let l(line, ..args) = bare-l(line: line, ..args) /// Sequence item-like value with type `"return-value"` for @@func(): a simulated function may /// generate this as its last "item" to signify its return value. A function that doesn't use this /// can simply be called by another like this: /// ```typc /// my-func(a, b) /// ``` /// which will result in its sequence items being put into the sequence where it is called. A /// function that calls `retval()` is called like this: /// ```typc /// let (result, ..rest) = my-func(a, b); rest /// ``` /// here, the result given to `retval()` is destructured into its own variable, and the real items /// are emitted so that they appear in the sequence of steps. /// /// `retval()` being called multiple times or not as the last item is an error. /// /// - result (any): the return value of the function /// -> array #let retval(result) = ((type: "return-value", result: result),) /// A helper for writing functions that produce execution sequences. This function automatically /// inserts @@call() and @@ret() effects. The implementation used by this function is given as a /// closure that receives a function similar to @@l(), but which adapts the line number according to /// the `first-line` parameter. /// /// Usually, the first thing in a function using this will be a step to show the function call, /// optionally preceded by @@push() effects for the parameters. The last thing may be a @@retval() /// pseudo sequence item. If it is, then the returned array will have the return value as the /// _first_ element. /// /// The return effect is not part of a step generated by this function; usually the caller will add /// a step to display the new state at the location (line number) to which execution returned. /// /// - name (string): the name of the function; used for the call effect /// - first-line (int): the line at which the simulated function starts /// - callback (function): simulates the function, receives an `l()`-like function /// -> array #let func(name, first-line, callback) = { import "effects.typ": call, ret // evaluate the function let _l(line, ..args) = { if line != none and first-line != none { line = first-line + line } l(line, ..args) } let steps = callback(_l) // if there was an exit(), extract it and the value from it let result = if steps.last().type == "return-value" { (steps.remove(steps.len() - 1).result,) } // if there is exit() anywhere else, that's an error assert( steps.all(step => step.type != "return-value"), message: "only one exit() at the end of a function execution is allowed: " + repr(steps) ) // prepend the result, if any result // assemble the final steps call(name) steps ret() } /// Simulates the given execution sequence and returns an array of states for each step in the /// sequence. Each element of the array is a dictionary with two fields: /// - `step`: the fields of the step (not including the type); this will often include a line number /// - `state`: the execution state according to the executed effects. Currently, the state only /// contains a `stack` field, which is in turn an array of stack frames with `name` and `vars` /// fields. /// /// In total, the returned value looks like this: /// ```typc /// ( /// ( /// step: (line: 1, ..), // any step fields /// state: ( // currently, executuion state is only the stack /// stack: ( /// (name: "main", vars: ( // function main is the topmost stack frame /// foo: 1, // local variable foo in main has value 1 /// .. // more local variables /// )), /// .. // more stack frames /// ) /// ) /// ), /// .. // execution states for other steps /// ) /// /// ``` /// This value can then be used to visualize the individual steps. /// /// - sequence (array): an execution sequence /// -> dictionary #let execute(sequence) = { let state = (stack: ()) let steps = () for (type: t, ..rest) in sequence { // step if t == "step" { steps.push(( step: rest, state: state, )) // effects } else if t == "call" { let (name,) = rest state.stack.push((name: name, vars: (:))) } else if t == "push" { let (name, value) = rest state.stack.last().vars.insert(name, value) } else if t == "assign" { let (name, value) = rest state.stack.last().vars.at(name) = value } else if t == "return" { let _ = state.stack.pop() // unknown } else { panic(t) } } steps }
https://github.com/HackingGate/typst-out
https://raw.githubusercontent.com/HackingGate/typst-out/main/README.md
markdown
MIT License
# Typst Out GitHub Action This GitHub action builds Typst files in your repository using a custom Typst ref, producing configurable output files and uploading them as artifacts. [![Test Typst Out Action](https://github.com/HackingGate/typst-out/actions/workflows/test_typst_out_action.yml/badge.svg)](https://github.com/HackingGate/typst-out/actions/workflows/test_typst_out_action.yml) ## Features - Configurable Typst ref for building your Typst files. - Option to set the number of days to retain the compiled outputs as artifacts. - Customizable naming convention for the artifacts. - Configurable output file extensions. - Ability to use a custom template file. - Optional use of built-in Typst fonts or specify your own font path. ## Usage To leverage the Typst Out action in your GitHub repository, create a new workflow file (e.g., `.github/workflows/typst_out.yml`) and add the content shown below: ```yaml on: push: paths: - '**.typ' jobs: build_typst: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v3 - name: Build Typst files uses: HackingGate/typst-out@v1 with: typst_ref: main retention_days: 7 artifacts_name: typst_output output_extensions: pdf template_file: template.typ ``` To use the latest release of Typst, you can utilize the `pozetroninc/github-action-get-latest-release` action to fetch the latest release from `typst/typst`. ```yaml steps: - name: Checkout repository uses: actions/checkout@v3 - name: Get latest release of Typst id: get-latest-release uses: pozetroninc/github-action-get-latest-release@master with: repository: typst/typst - name: Build Typst files uses: HackingGate/typst-out@main with: typst_ref: ${{ steps.get-latest-release.outputs.release }} ``` ## Inputs | Name | Description | Required | Default | | ------------------- | ------------------------------------------------------------ | -------- | -------------- | | `typst_ref` | The ref of Typst for building | No | `main` | | `retention_days` | Number of days to keep the PDFs as artifacts | No | `7` | | `artifacts_name` | Name for the uploaded artifacts | No | `typst_output` | | `output_extensions` | Output file extensions | No | `pdf` | | `template_file` | Template file to utilize | No | `template.typ` | | `use_typst_fonts` | Decide whether to use built-in Typst fonts | No | `true` | | `fonts_path` | Specify the path for custom fonts (if not using Typst fonts) | No | `''` | ## Caching This GitHub action employs caching to speedily store and recover build artifacts and dependencies. This optimizes the action's execution time by preventing the need to rebuild the Typst binary and reacquire Rust dependencies on every run. There are three main caching phases in this action: 1.**Cache Typst build**: This phase caches the constructed Typst binary using the `actions/cache@v3` action. The cache key is determined by the Typst commit SHA from the given `typst_ref`. If a cache hit is detected (i.e., a stored Typst binary is found for the commit SHA), the subsequent Rust setup and Typst building steps are skipped, directly proceeding to Typst file compilation. 2.**Cache Typst fonts**: This caches fonts from `typst/assets/fonts` with the `actions/cache@v3` action. The cache key is again derived from the Typst commit SHA. If there's a cache hit, the font acquisition step is omitted. 3.**Cache Rust**: When a cache miss occurs for the Typst build, Rust dependencies are cached using the `Swatinem/rust-cache@v2` action. This substantially diminishes setup time for Rust and the Typst binary compilation in subsequent runs.