repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/tingerrr/chiral-thesis-fhe | https://raw.githubusercontent.com/tingerrr/chiral-thesis-fhe/main/src/utils/token.typ | typst | #let is-boundary(value) = {
value.len() == 0 or value.starts-with(" ")
}
#let eat(value, token) = {
if value.starts-with(token) {
let rest = value.trim(at: start, repeat: false, token)
let part = value.len() - rest.len()
(value.slice(0, part), value.slice(part))
} else {
(none, value)
}
}
#let eat-any(value, tokens) = {
for curr in tokens {
let (token, rest) = eat(value, curr)
if token != none {
return (token, rest)
}
}
(none, value)
}
|
|
https://github.com/lyzynec/hys-or-kys | https://raw.githubusercontent.com/lyzynec/hys-or-kys/main/05/main.typ | typst | #import "../lib.typ": *
#knowledge[
#question(name: [Explain the key components of hybrid equations (also
flow--event equations, also flow--jump equations).])[]
]
#skills[
#question(name: [Find a model of a simple dynamical system in the form of
hybrid equations, that is, determine the four components of hybrid
equations.])[]
#question(name: [Implement a model in the form of hybrid equations using the
free #link("https://github.com/pwintz/HyEQ_Toolbox")[HyEQ Toolbox for Matlab (beta)].])[]
] |
|
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/project_documentation/content/personal_report_jann.typ | typst | #import "../../acronyms.typ": ac
= <NAME>
Even before studying at #ac("OST"), I was interested in functional
programming. I worked on some small personal projects in F\# and looked at
foundational topics such as the lambda-calculus.
Unfortunately, I've never had the chance to use functional programming to
realize a large project. Thus, I very much looked forward to working on this
topic, and retrospectively, the project met these expectations. I am happy that
I have chosen a functional direction for the student research project and value
the experience I gained.
Thinking about how functional concepts can be translated into visualizations was
interesting, although I enjoyed the implementation work for the proof of concept
more. After the first few proposals, I was eager to start programming,
but spending more time to think about the fundamentals was valuable and led to a
better result. I liked creating the first iterations of the inference engine in
the application the most since it was both challenging to implement and intriguing
from a theoretical point of view.
The project management worked out well, which is surprising because, in the
middle of the project, I expected time to run tight for the proof of concept.
Luckily, this didn't turn out to be accurate, and we delivered an application that
even exceeded my initial expectations.
As expected, we were able to work well together as a team. Since we are
both part-time students, a lot of asynchronous communication was required, which
can be challenging, but it worked out for us. I am glad we can repeat this
setup for the bachelor's thesis.
Overall, I enjoyed working on the project and am happy with the results. |
|
https://github.com/atlanswer/typst-template-ieee | https://raw.githubusercontent.com/atlanswer/typst-template-ieee/main/example.typ | typst | MIT License | #set page(paper: "us-letter", header: align(right)[
A fluid dynamic model for glacier flow
], numbering: "1")
#set par(justify: true)
#set text(font: "Linux Libertine", size: 11pt)
#let skel(len) = {
assert(type(len) == int)
set highlight(fill: silver, radius: 0.2em)
highlight(" " * 5 * len)
}
a
#skel(12).
#highlight(" ", fill: silver, radius: 0.2em)
= Introduction
In this report, we will explore the various factors that influence _fluid dynamics_ in
glaciers and how they contribute to the formation and behaviour of these natural
structures. See @smiley_face.
This is a reference@harry. This is a literal \@.
+ The climate
- Temperature
- Precipitation
+ The topography
+ The geology
The equation $Q = rho A v + C$
defines the glacial flow rate.
The flow rate of a glacier is defined by the following equation:
$ Q = rho A v + C $
The flow rate of a glacier is given by the following equation:
$ Q = rho A v + "time offset" $
Total displaced soil by glacial flow:
$ 7.32 beta +
sum_(i=0)^nabla Q_i / 2 $
Total displaced soil by glacial flow:
$ 7.32 beta +
sum_(i=0)^nabla
(Q_i (a_i - epsilon)) / 2 $
$ v := vec(x_1, x_2, x_3) $
$ a arrow.squiggly b $
#par(
justify: true,
)[
= Background
In the case of glaciers, fluid dynamics principles can be used to understand how
the movement and behaviour of the ice is influenced by factors such as
temperature, pressure, and the presence of other fluids (such as water).
]
#align(center + top)[
#figure(image("smiley_face.jpg", width: 3.5in), caption: [Smile])
<smiley_face>
]
#lorem(600)
#bibliography("references.yaml", title: [References])
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/delimited_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test fence confusion.
$ |x + |y| + z/a| \
lr(|x + |y| + z/a|) $
|
https://github.com/elouan660/Portes_Ouvertes | https://raw.githubusercontent.com/elouan660/Portes_Ouvertes/main/po.typ | typst | #import "doc-template.typ": *
#Exercice("Portes Ouvertes 2023-2024", "Liste portes ouvertes 2023-2024 © 2023 by <NAME> is licensed under CC BY 4.0. To view a copy of this license, visithttp://creativecommons.org/licenses/by/4.0/", "30/10/2023")[
#show link: set text(blue)
== Préambule:
#text(size: 10pt)[
_Ce document liste les dates de portes ouvertes des établissements post-bac qui m'intéressent moi Elouan Deschamps, ils incluent donc une part potententielle plus ou moins grande d'informatique et/ou de mathématiques dans leurs formations et sont publics. Sauf indication contraire, chaque tableau correspond à un voeu parcoursup et chaque ligne à un ou plusieurs sous-voeux (les établissement peuvent proposer pluesieurs cursus)_.] \ \
== Lexique:
#text(size: 10pt)[
*CPGE:* Classe préparatoire aux grandes écoles, plus communément applelée prépa, c'est un cursus en deux qui se passe dans un lycée et qui vise à préparer aux concours aux grandes écoles, principale voie d'accès à celles-ci \
*Prépa intégrée:* Cursus interne à une école d'ingénieur visant à préparer l'entrée en cycle ingénieur au sein de cette même école, à ne pas confondre avec la CPGE \
*Diplôme d'ingénieur:* Master spécial se passant dans une école d'ingénieur, il suppose de passer une partie de sa scolarité (6 mois à 2 ans) à l'étranger
]
= #link("https://www.geipi-polytech.org/les-ecoles-du-concours-geipi-polytech")[Concours geipi polytech]
Le concours geipi polytech est un concours commun à *beaucoup* d'écoles d'ingenieurs publiques post-bac et nottament les école polytech, connues pour être faciles d'accès et pour leur prépa intégrée commune qui permet aisément de passer d'une école à l'autre. Il permet nottament d'intégrer des écoles sans avoir pris la spé math en terminale et de faire valoir les spés qu'on a rattrapé de notre coté sans les avoir choisies en terminale ou en première.
#align(center)[
#table(
columns: (auto, auto, auto),
inset: 10pt,
align: horizon,
[*École*], [*Dates*], [*Lieux*],
[Télécom Saint étienne], [2 décembre \ 24 janvier], [Saint étienne],
[ENISE], [9 décembre \ 24 janvier \ 10 février], [Saint Étienne],
[ENIB], [26 janvier \ 17 février], [Brest],
[ISTY], [27 janvier], [Vélizy \ Mantes],
[IMT Nord Europe], [3 février], [Lille],
[Polytech Angers], [3 février], [Angers],
[Polytech Annecy-Chambéry], [3 février], [Annecy \ Chambéry],
[Polytech Lille], [3 février], [Lille],
[Polytech Dijon], [7 février], [Dijon],
[ENSIBS], [10 février], [Lorient \ Vannes],
[ESIR], [10 février], [Rennes],
[ESISAR], [10 février], [Valence],
[Polytech Lyon], [10 février], [Lyon],
[Polytech Marseille], [10 février], [Marseille],
[Polytech Nantes], [10 février \ 17 février], [Nantes],
[Polytech Nice Sophia], [10 février], [Nice],
[Sup Galilée], [11 février], [Paris],
[Polytech Paris-Saclay], [11 février], [Paris],
[ENSGSI], [17 février], [Nancy],
[Polytech Nancy], [17 février], [Nancy],
[Polytech Grenoble], [25 février], [Grenoble],
[Polytech Montpellier], [2 mars], [Montpellier],
[Polytech Clermont], [4 mars], [Clermont],
[Polytech Tours], [4 mars], [Tours],
[Polytech Sorbonne],[?], [Paris]
)
= #link("https://www.groupe-insa.fr/preparer/comment-candidater/journees-portes-ouvertes-et-salons-en-2023-2024")[Groupe INSA et partenaires]
#align(left)[
La procédure INSA n'inclue pas de de concours, elle se base uniquement sur le dossier. Les INSA sont réputées difficiles, les places en branche en troisième année sont limitées ce qui créé de la concurrence entre les étudiants. Contrairement aux écoles Polytech, les passages d'une INSA à une autre ne se font pas facilements. Les INSA proposent de nombreux doubles-diplômes dans toute sorte de domaine (droit, économie, paysage, architecture...)]
#table(
columns: (auto, auto, auto),
inset: 10pt,
align: horizon,
[*École*], [*Dates*], [*Lieux*],
[INSA Rouen], [2 décembre \ 3 février], [Rouen],
[ISIS Castres], [27 janvier], [Castres],
[INSA Lyon], [3 février], [Lyon],
[INSA Centre val de loire], [3 février], [Blois \ Bourges],
[INSA Strasbourg], [3 février], [Strasbourg],
[INSA Toulouse], [3 février], [Toulouse],
[ENSIL-ENSCI], [3 février], [Limoges],
[Sup’EnR UPVD Perpignan], [3 février], [Toulouse \ Perpignan],
[INSA Hauts de France], [10 février], [Valenciennes],
[INSA Rennes], [10 février], [Rennes],
[ENSISA Mulhouse], [10 février], [Mulhouse],
)
= Groupe UT
#align(left)[
La procédure UT n'inclue elle aussi pas de concours.
Les UT sont les seules écoles en France à être à la fois écoles d'ingénieurs et universités, elles s'inspirent des unversités américaines. Les élèves ne sont pas en concurrence et le parcours est à la carte au moins pour les deux premières années. Dans le cas de l'UTC qui est une école généraliste, on peut construire nous même notre parcours sur les cinq années et se retrouver avec un diplôme possédant une mention unique.]
#table(
columns: (auto, auto, auto),
inset: 10pt,
align: horizon,
[*École*], [*Dates*], [*Lieux*],
[UTC], [#link("https://www.utc.fr/agenda-actualites/journee-portes-ouvertes-2024-presentiel/")[13 janvier (présentiel)] \ #link("https://www.utc.fr/agenda-actualites/journee-portes-ouvertes-2024-distanciel/")[24 février (distanciel)]], [Compiègne],
[UTBM], [#link("https://www.utbm.fr/%C3%A9v%C3%A8nement/journee-portes-ouvertes-de-lutbm-n1/?instance_id=468")[9 décembre (distanciel)] \ #link("https://www.utbm.fr/%C3%A9v%C3%A8nement/journee-portes-ouvertes-de-lutbm-n1-2/?instance_id=467")[20 janvier (présentiel)]], [Sevenans],
[UTT], [#link("https://www.utt.fr/formations/rencontrez-nous/journees-portes-ouvertes")[24 février]], [Troyes],
)
= Centrale Lille Institut
#align(left)[
La prestigieuse école Centrale lille possède des sous-écoles pour les parcours plus spécifiques. Ces écoles sont très différentes les unes des autres et comptent comme des voeux différents sur parcoursup]
#table(
columns: (auto, auto, auto),
inset: 10pt,
align: horizon,
[*École*], [*Dates*], [*Lieux*],
[IG2I], [?], [Lens],
[ITEEM], [?], [Villeneuve]
)
= Prépa des INP
#align(left)[
La prépa des INP est une prépa intégrée commune à toutes les école du groupe INP, elle est peu connue mais permet à son terme d'intégrer des écoles très prestigieuses comme l'ENSIMAG sans avoir à passer de concours. Les étudiants y restent cependant en concurrence, le nombre de place par école étant limité. Comme toutes les prépas intégrées elle ne laisse que peu de possibiltés de réorientation.
]
#table(
columns: (auto, auto),
inset: 10pt,
align: horizon,
[*Campus*], [*Dates*],
[Cambrai], [27 janvier],
[Bordeaux], [3 février],
[Nancy], [10 février],
[Grenoble], [10 février],
[Valence], [10 février],
[Saint Denis (Réunion)], [24 février]
)
= #link("https://prepas-mp2i.fr/")[CPGE MP2I]
_Uniquement celles autour de Nantes._ \
#align(left)[
La prépa MP2I est une prépa mélant math physique et informatique. C'est la prépa la plus orientée Math avec la MPSI. Elle n'est pas moins difficile ni moins généraliste que les autres prépas, bien au contraire puisqu'elle se base sur trois matières au lieu de deux. Comme toutes les CPGE elle vise les concours des grandes école (Dont les écoles d'ingénieurs) pour aller vers un bac +5 et propose à chaque semestre un passage en licence en cas d'abandon. C'est donc une voie qui garantit à tous des débouchés]
#table(
columns: (auto, auto, auto),
inset: 10pt,
align: horizon,
[*Lycée*], [*Dates*], [*Lieux*],
[Descartes], [#link("https://www.lyc-descartes.fr/")[27 janvier]], [Tours],
[Lesage], [?], [Vannes],
[Clemenceau], [?], [Nantes],
)
= Universités
_Uniquement celles autour de Nantes._ \
#align(left)[
*#underline("La licence (bac +3):")* est une formation accessible de droit sous condition d'obtention du bac. L'accompagnement y est moindre et il n'est pas rare d'y échouer si on manque d'organisation. La licence est généralement monodisciplinaire et suppose d'enchainer sur un master (bac +5); Il existe des licences spéciales (CUPGE) visant à préparer leurs étudiants aux concours des écoles d'ingénieurs. Il est également possible de s'incrire dans deux licence différentes en même temps si vous êtes un peu mazo. \
*#underline("Le BUT (bac +3):")*, est similaire à la licence mais l'accompagnement y est plus grand et il n'est accessible de droit que pour les bacheliers technologiques, on dit souvent que les IUT ressemblent à des lycées; Le BUT pouvant se suffire à lui-même, les étudiants en BUT ne sont pas prioritaires pour entrer en master
*#underline("Le CMI (bac +5):")* est un cursus s'étalant sur 5 ans comprenant une licence et un master avec quelques cours et accompagnements suplémentaires. C'est un quasi-diplôme d'ingénieur, les seules différences avec celui-ci étant le type d'établissement dans lequel il est passé et sa reconnaissance plus difficile en dehors de l'Union Européenne.
]
#table(
columns: (auto, auto),
inset: 10pt,
align: horizon,
[*Université*], [*Dates*],
[Nantes Université], [?],
[Université de Rennes], [?],
[Université Bretagne Sud], [?]
)
]
]
|
|
https://github.com/francescoo22/masters-thesis | https://raw.githubusercontent.com/francescoo22/masters-thesis/main/config/thesis-config.typ | typst | #import "../config/constants.typ": chapter
#import "@preview/codly:1.0.0": *
#import "@preview/ctheorems:1.1.2": *
#let vpr-name = stack(
dir: ltr,
image("../images/viper-logo.png", width: .9em), " Viper",
)
#let kt-name = stack(
dir: ltr,
image("../images/Kotlin.svg", width: .9em), " Kotlin",
)
#let cpp-name = stack(
dir: ltr,
image("../images/cpp-logo.svg", width: .8em), " C++",
)
#let vpr-show() = r => {
// Types:
show regex("\b(Ref)\b"): set text(rgb("#4b69c6"))
show regex("\b(Bool)\b"): set text(rgb("#4b69c6"))
show regex("\b(Int)\b"): set text(rgb("#4b69c6"))
// Keywords:
show regex("\b(inhale)\b"): set text(rgb("#d73a49"))
show regex("\b(exhale)\b"): set text(rgb("#d73a49"))
show regex("\b(method)\b"): set text(rgb("#d73a49"))
show regex("\b(function)\b"): set text(rgb("#d73a49"))
show regex("\b(predicate)\b"): set text(rgb("#d73a49"))
show regex("\b(field)\b"): set text(rgb("#d73a49"))
show regex("\b(fold)\b"): set text(rgb("#d73a49"))
show regex("\b(unfold)\b"): set text(rgb("#d73a49"))
show regex("\b(unfolding)\b"): set text(rgb("#d73a49"))
show regex("\b(in)\b"): set text(rgb("#d73a49"))
show regex("\b(requires)\b"): set text(rgb("#d73a49"))
show regex("\b(ensures)\b"): set text(rgb("#d73a49"))
show regex("\b(returns)\b"): set text(rgb("#d73a49"))
show regex("\b(var)\b"): set text(rgb("#d73a49"))
show regex("\b(if)\b"): set text(rgb("#d73a49"))
show regex("\b(else)\b"): set text(rgb("#d73a49"))
show regex("\b(acc)\b"): set text(rgb("#d73a49"))
show regex("\b(while)\b"): set text(rgb("#d73a49"))
show regex("\b(forall)\b"): set text(rgb("#d73a49"))
show regex("\b(axiom)\b"): set text(rgb("#d73a49"))
show regex("\b(invariant)\b"): set text(rgb("#d73a49"))
show regex("\b(assert)\b"): set text(rgb("#d73a49"))
show regex("\b(wildcard)\b"): set text(rgb("#d73a49"))
show regex("\b(null)\b"): set text(rgb("#d73a49"))
show regex("\b(true)\b"): set text(rgb("#d73a49"))
show regex("\b(false)\b"): set text(rgb("#d73a49"))
show regex("\b(domain)\b"): set text(rgb("#d73a49"))
show regex("\b(write)\b"): set text(rgb("#d73a49"))
show "&&": set text(rgb("#d73a49"))
show "||": set text(rgb("#d73a49"))
show "=": set text(rgb("#d73a49"))
show "<": set text(rgb("#d73a49"))
show ">": set text(rgb("#d73a49"))
show ":": set text(rgb("#d73a49"))
show "!": set text(rgb("#d73a49"))
show "*": set text(rgb("#d73a49"))
show regex("//.*"): set text(rgb("#8a8a8a"))
r
}
#let grammar-show() = r => {
show regex("//.*"): set text(rgb("#9a9a5b"))
show regex("⊣.*"): set text(rgb("#8a8a8a"))
r
}
#let config(
myAuthor: "<NAME>",
myTitle: "Titolo",
myLang: "en",
myNumbering: "1.",
body
) = {
// Set the document's basic properties.
set document(author: myAuthor, title: myTitle)
show: codly-init
show: thmrules
show math.equation: set text(weight: 400)
show table.cell.where(y: 0): strong
// LaTeX look (secondo la doc di Typst)
// set page(margin: 1.75in, numbering: myNumbering, number-align: center)
set page(margin: 1.55in, numbering: "1", number-align: center)
// set par(leading: 0.55em, first-line-indent: 1.8em, justify: true)
set par(leading: 0.55em, justify: true)
set text(font: "New Computer Modern", size: 10pt, lang: myLang)
set heading(numbering: myNumbering)
// show raw.where(block: false): set text(font: "New Computer Modern Mono", size: 10pt, lang: myLang)
show raw.where(block: true): it => {
// #let kt-logo = image("images/Kotlin.svg", width: 200%)
codly(
enabled: true,
languages: (
kt: (name: kt-name, color: purple),
vpr: (name: vpr-name, color: orange),
cpp: (name: cpp-name, color: blue)
)
)
it
codly-disable()
}
show raw.where(lang: "vpr"): vpr-show()
show raw.where(lang: none): grammar-show()
show par: set block(spacing: 0.55em)
show heading: set block(above: 1.4em, below: 1em)
show heading.where(level: 2): set heading(supplement: [Section])
show heading.where(level: 3): set heading(supplement: [Subsection])
show heading.where(level: 1): it => {
stack(
spacing: 2em,
if it.numbering != none {
text(size: 1.5em)[#heading.supplement #counter(heading).display()]
// text(size: 1em)[Chapter #counter(heading).display()]
},
text(size:1.75em, it.body),
// text(size:1.5em,it.body),
[]
)
}
body
}
|
|
https://github.com/mriganksagar/cv | https://raw.githubusercontent.com/mriganksagar/cv/main/modules/skills.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Skills")
#cvSkill(
type: [Programming Languages],
info: [Scala #hBar() Java #hBar() JavaScript #hBar() TypeScript #hBar() C++ #hBar() C #hBar() Python]
)
#cvSkill(
type: [Frontend],
info: [React.js #hBar() Next.js #hBar() React Native #hBar() Redux #hBar() HTML/CSS #hBar() Tailwind]
)
#cvSkill(
type: [Backend],
info: [Play #hBar() Spring #hBar() Nest.js #hBar() PostgresQL #hBar() REST APIs #hBar() GraphQL]
)
#cvSkill(
type:[Scala Tech-stack],
info: [Play #hBar() Cats #hBar() Cats-Effects #hBar() Akka #hBar() Akka/pekko streams #hBar() Slick #hBar() Doobie, Quill]
)
#cvSkill(
type: [Tools & Platforms],
info: [Git #hBar() Docker #hBar() Kubernetes #hBar() Linux]
)
#cvSkill(
type: [Concepts],
info: [Data Structures & Algorithms #hBar() Functional Programming #hBar() Object-Oriented Design.]
)
#cvSkill(
type: [Languages],
info: [English #hBar() Hindi]
)
|
https://github.com/MrToWy/Bachelorarbeit | https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Code/getModule.typ | typst | ```ts
@Public()
@Get(':id')
findOne(@Req() request: Request, @Param('id') id: string) {
const language = (request.headers as any)['language'];
return this.moduleService.findOne(+id, language);
}
``` |
|
https://github.com/Myriad-Dreamin/shiroa | https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/packages/shiroa/supports-link.typ | typst | Apache License 2.0 |
#let link2page = state("shiroa-link2page", (:))
#let encode-url-component(s) = {
let prev = false
for (idx, c) in s.codepoints().enumerate() {
if c.starts-with(regex("[a-zA-Z]")) {
if prev {
prev = false
"-"
}
c
} else {
prev = true
if idx != 0 {
"-"
}
str(c.to-unicode())
}
}
}
#let cross-link-path-label(path) = {
assert(path.starts-with("/"), message: "absolute positioning required")
encode-url-component(path)
}
/// Cross link support
#let cross-link(path, reference: none, content) = {
let path-lbl = cross-link-path-label(path)
if reference != none {
assert(type(reference) == label, message: "invalid reference")
}
assert(content != none, message: "invalid label content")
context {
let link-result = link2page.final()
if path-lbl in link-result {
link((page: link-result.at(path-lbl), x: 0pt, y: 0pt), content)
return
}
if reference != none {
let result = query(reference)
// whether it is internal link
if result.len() > 0 {
link(reference, content)
return
}
}
// assert(read(path) != none, message: "no such file")
link(
{
"cross-link://jump?path-label="
path-lbl
if reference != none {
"&label="
encode-url-component(str(reference))
}
},
content,
)
}
}
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2006/WS-11.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (1 - 32)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[1], [ZHANG Yining], [CHN], [2997],
[2], [GUO Yan], [CHN], [2813],
[3], [WANG Nan], [CHN], [2721],
[4], [GUO Yue], [CHN], [2692],
[5], [TIE Yana], [HKG], [2588],
[6], [LI Jiawei], [SGP], [2585],
[7], [LI Xiaoxia], [CHN], [2579],
[8], [JIANG Huajun], [HKG], [2559],
[9], [NIU Jianfeng], [CHN], [2554],
[10], [WANG Yuegu], [SGP], [2515],
[11], [KIM Kyungah], [KOR], [2482],
[12], [FUKUHARA Ai], [JPN], [2464],
[13], [FUJII Hiroko], [JPN], [2443],
[14], [CAO Zhen], [CHN], [2439],
[15], [PARK Miyoung], [KOR], [2427],
[16], [BOROS Tamara], [CRO], [2404],
[17], [CHANG Chenchen], [CHN], [2386],
[18], [HIRANO Sayaka], [JPN], [2379],
[19], [LI Jiao], [NED], [2373],
[20], [TAN Wenling], [ITA], [2361],
[21], [PAVLOVICH Viktoria], [BLR], [2351],
[22], [GAO Jun], [USA], [2350],
[23], [WU Xue], [DOM], [2346],
[24], [STEFF Mihaela], [ROU], [2344],
[25], [CHEN Qing], [CHN], [2335],
[26], [TOTH Krisztina], [HUN], [2334],
[27], [FAN Ying], [CHN], [2333],
[28], [LIN Ling], [HKG], [2323],
[29], [FUKUOKA Haruna], [JPN], [2317],
[30], [KIM Mi Yong], [PRK], [2310],
[31], [GANINA Svetlana], [RUS], [2308],
[32], [WU Jiaduo], [GER], [2299],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (33 - 64)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[33], [SHEN Yanfei], [ESP], [2295],
[34], [KANAZAWA Saki], [JPN], [2280],
[35], [GRUNDISCH Carole], [FRA], [2269],
[36], [STEFANOVA Nikoleta], [ITA], [2268],
[37], [ODOROVA Eva], [SVK], [2261],
[38], [SUN Beibei], [SGP], [2258],
[39], [LIU Jia], [AUT], [2256],
[40], [FUJINUMA Ai], [JPN], [2254],
[41], [LIU Shiwen], [CHN], [2252],
[42], [LEE Eunhee], [KOR], [2243],
[43], [JEON Hyekyung], [KOR], [2242],
[44], [#text(gray, "KIM Bokrae")], [KOR], [2240],
[45], [LAU Sui Fei], [HKG], [2239],
[46], [KOMWONG Nanthana], [THA], [2238],
[47], [HIURA Reiko], [JPN], [2227],
[48], [KWAK Bangbang], [KOR], [2225],
[49], [<NAME>], [CHN], [2225],
[50], [XU Yan], [SGP], [2208],
[51], [<NAME> Sim], [HKG], [2206],
[52], [#text(gray, "RYOM Won Ok")], [PRK], [2205],
[53], [ZHANG Rui], [HKG], [2194],
[54], [ZHANG Xueling], [SGP], [2193],
[55], [XIAN Yifang], [FRA], [2191],
[56], [PAVLOVICH Veronika], [BLR], [2190],
[57], [LI Nan], [CHN], [2186],
[58], [MOON Hyunjung], [KOR], [2171],
[59], [DING Ning], [CHN], [2168],
[60], [IVANCAN Irene], [GER], [2164],
[61], [KOTIKHINA Irina], [RUS], [2164],
[62], [BILENKO Tetyana], [UKR], [2159],
[63], [STRBIKOVA Renata], [CZE], [2159],
[64], [ZAMFIR Adriana], [ROU], [2148],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (65 - 96)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[65], [WANG Chen], [CHN], [2148],
[66], [<NAME>bing], [AUT], [2148],
[67], [<NAME>], [GER], [2146],
[68], [KONISHI An], [JPN], [2141],
[69], [<NAME>], [ROU], [2135],
[70], [#text(gray, "LEE Eunsil")], [KOR], [2134],
[71], [POTA Georgina], [HUN], [2127],
[72], [<NAME>], [SGP], [2116],
[73], [UMEMURA Aya], [JPN], [2108],
[74], [LU Yun-Feng], [TPE], [2106],
[75], [DVORAK Galia], [ESP], [2101],
[76], [TASEI Mikie], [JPN], [2099],
[77], [SHIM Serom], [KOR], [2086],
[78], [TERUI Moemi], [JPN], [2086],
[79], [LOVAS Petra], [HUN], [2086],
[80], [STRUSE Nicole], [GER], [2078],
[81], [LAY Jian Fang], [AUS], [2076],
[82], [RAMIREZ Sara], [ESP], [2072],
[83], [MIROU Maria], [GRE], [2071],
[84], [MUANGSU<NAME>], [THA], [2071],
[85], [<NAME>], [GER], [2066],
[86], [<NAME>], [SWE], [2060],
[87], [<NAME>], [AUS], [2059],
[88], [<NAME>], [GER], [2058],
[89], [<NAME>], [CRO], [2055],
[90], [<NAME>], [CRO], [2054],
[91], [<NAME>], [LTU], [2053],
[92], [WANG Yu], [ITA], [2052],
[93], [<NAME>], [ISR], [2041],
[94], [<NAME>], [KOR], [2040],
[95], [<NAME>], [ROU], [2038],
[96], [XU Jie], [POL], [2038],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (97 - 128)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[97], [YOON Sunae], [KOR], [2031],
[98], [LANG Kristin], [GER], [2030],
[99], [KIM Jong], [PRK], [2030],
[100], [<NAME>ika], [AUT], [2022],
[101], [ONO Shiho], [JPN], [2021],
[102], [BADESCU Otilia], [ROU], [2019],
[103], [GATINSKA Katalina], [BUL], [2019],
[104], [<NAME>], [NZL], [2015],
[105], [#text(gray, "<NAME>")], [HUN], [1998],
[106], [<NAME>], [GER], [1997],
[107], [<NAME>], [GER], [1988],
[108], [#text(gray, "<NAME>")], [HUN], [1988],
[109], [<NAME>], [POR], [1985],
[110], [<NAME>], [BLR], [1980],
[111], [<NAME>], [GER], [1977],
[112], [<NAME>], [FRA], [1976],
[113], [<NAME>], [JPN], [1968],
[114], [<NAME>], [RUS], [1959],
[115], [<NAME>], [MDA], [1958],
[116], [<NAME>], [TPE], [1957],
[117], [<NAME>], [SLO], [1955],
[118], [<NAME>], [PRK], [1954],
[119], [<NAME>], [HUN], [1953],
[120], [<NAME>], [COL], [1951],
[121], [<NAME>], [POR], [1949],
[122], [#text(gray, "<NAME>")], [HUN], [1947],
[123], [<NAME>], [HUN], [1944],
[124], [<NAME>], [GRE], [1944],
[125], [<NAME>], [RUS], [1943],
[126], [#text(gray, "WIGOW Susanna")], [SWE], [1938],
[127], [<NAME>], [GER], [1938],
[128], [<NAME>], [JPN], [1935],
)
) |
|
https://github.com/Otto-AA/definitely-not-tuw-thesis | https://raw.githubusercontent.com/Otto-AA/definitely-not-tuw-thesis/main/src/styles/utils/state.typ | typst | MIT No Attribution | #let is-back-matter = state("is-back-matter", false) |
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/build-elevation/entry.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator, codetastic
#import notebookinator: *
#import codetastic: qrcode
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Build: Elevation",
type: "build",
date: datetime(year: 2023, month: 11, day: 3),
author: "<NAME>",
witness: "<NAME>",
)
#grid(
columns: (1fr, 1fr),
gutter: 20pt,
[
With a rough sketch of the design complete, we started building.
1. We cut two pieces of polycarbonate into shape. We didn't have CAD to go off of,
so we had to approximate.
2. We mounted the polycarbonate pieces two the catapult.
3. We placed the robot next to the match load bar, and then adjusted the
polycarbonate. We made it shorter as needed, and also adjusted the angle.
4. Once we were happy with our polycarbonate, we cut plate to reinforce it.
],
[
#figure(image("./IMG_5386.jpg"), caption: [
Our climbing mechanism approaching the elevation bar.
])
],
)
#admonition(
type: "warning",
)[
This design is super experimental and not very well tested. This is the bare
minimum we needed to get an elevation, without much refinement or planning. In
the future we'll need to actually CAD it out, and perform proper testing.
]
|
https://github.com/jneug/schule-typst | https://raw.githubusercontent.com/jneug/schule-typst/main/src/subjects/cs-docs.typ | typst | MIT License | #let _ab_highlight_doku = false
#let _state-docs = state("schule.cs.docs", yaml("./cs-docs.yaml"))
#let load(data) = {
_state-docs.update(data)
}
#let get() = _state-docs.get()
#let __content(string) = {
if type(string) == "string" {
return eval("[" + string + "]")
} else {
return string
}
}
#let __d_classheader(name, generic-type: none) = {
if generic-type != none [
=== Die generische Klasse #name
] else [
=== Die Klasse #name
]
}
#let __d_methodheader(name, generic-type: none, partial: false) = {
let prefix = "Dokumentation der Klasse"
if partial {
prefix = "Ausschnitt aus der " + prefix
}
if generic-type != none [
==== #prefix #name<#generic-type>
] else [
==== #prefix #name
]
}
#let methode(signature, body) = {
if type(signature) == "content" and signature.func() == raw {
signature = signature.text
}
block(
width: 100%,
fill: luma(85%),
breakable: false,
inset: 4pt,
below: 4pt,
)[
#set text(size: 0.85em)
#if not _ab_highlight_doku [#strong(signature)] else [#raw(signature, block: false, lang: "java")]
]
body
}
// {deprecated}
#let method = methode
#let klasse(name, generic-type: none, descr: none, partial: false, methods) = {
if descr != none {
__d_classheader(name, generic-type: generic-type)
__content(descr)
}
__d_methodheader(name, generic-type: generic-type, partial: partial)
for m in methods {
if type(m) == "array" {
method(m.at(0))[
#__content(m.at(1))
]
} else {
method(m.signature)[
#__content(m.descr)
]
}
}
}
// {deprecated}
#let class = klasse
#let display(key, descr: true) = {
context {
let doc-data = get()
if key not in doc-data {
panic("No docs for name " + key)
}
let scheme = doc-data.at(key)
class(
scheme.name,
generic-type: if scheme.generic {
scheme.generic-type
} else {
none
},
descr: if descr and "descr" in scheme {
scheme.descr
} else {
none
},
scheme.methods,
)
}
}
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/multiline_06.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test no trailing line break.
$
"abc" &= c
$
No trailing line break.
|
https://github.com/ticks-tan/wtu-typst | https://raw.githubusercontent.com/ticks-tan/wtu-typst/main/README.md | markdown | # wtu-typst
武汉纺织大学本科毕业设计typst模板,专注内容,格式什么的滚一边去。
> ## typst目前处于快速发展阶段,很多API不一定稳定,如果发现bug,欢迎提 [issue](https://github.com/ticks-tan/wtu-typst/issues) 。
## 使用须知:
学校官网最近没有发布更新的论文模板,
该模板使用的是很多年前的论文格式,
如果指导老师规定了格式,请慎用该模板。
## 如何使用
使用前建议先了解什么是 typst ,可以点击[链接](https://typst.app/docs/tutorial/)查看。
1. 下载该模板zip文件(clone)或者使用 git 克隆该仓库。
2. 修改demo.typ文件模板,然后开始创作
3. 到Github安装官方最新版本typst,[下载地址](https://github.com/typst/typst/releases/latest)
4. 编译为pdf文件
**推荐使用 vscode ,并安装插件使用,支持实时预览!** |
|
https://github.com/vEnhance/1802 | https://raw.githubusercontent.com/vEnhance/1802/main/src/eigen.typ | typst | MIT License | #import "@local/evan:1.0.0":*
= Eigenvalues and eigenvectors
== [TEXT] The problem of finding eigenvectors
Let's define the relevant term first:
#definition[
Suppose $T$ is a matrix or linear transformation, $lambda$ a scalar,
and $bf(v)$ is a vector such that
$ T(bf(v)) = lambda bf(v); $
that is, $T$ sends $bf(v)$ to a multiple of itself.
Then we call $lambda$ an *eigenvalue* and $bf(v)$ an *eigenvector*.
]
#typesig[
Eigenvalues $lambda$ are always scalars.
]
#example[
Let $T = mat(74,52;32,36)$ and consider the vector $bf(v) = vec(2,1)$. Then
$ T(bf(v)) = mat(74,52;32,36) vec(2,1) = vec(200,100) = 100 vec(2,1) = 100 bf(v). $
So we would say $bf(v)$ is an eigenvector with eigenvalue $100$.
Of course, if $bf(v)$ is an eigenvector, so are all its multiples, e.g.
$ mat(74,52;32,36) vec(20,10) = vec(2000,1000) = 100 vec(20,10) $
so $vec(20,10)$ is an eigenvector with the same eigenvalue $100$, etc.
]
#remark[
The stupid solution $bf(v) = bf(0)$ always satisfies the eigenvector equation for any $lambda$,
so we will pretty much ignore it and focus only on finding nonzero eigenvectors.
]
The goal of this section is to show:
#question[
Given an encoding of $T$ as a matrix, how can we find its eigenvectors (besides $bf(0)$)?
]
== [TEXT] How to come up with the recipe for eigenvalues
For this story, our protagonist will be the matrix
$ A = mat(5, -2; 3, 10). $
Phrased another way, the problem of finding eigenvectors is, by definition,
looking for $lambda$, $x$, $y$ such that
$
A vec(x,y) = lambda vec(x, y)
<==>
cases(
5 x - 2 y = lambda x,
3 x + 10 y = lambda y
).
$
Smart-alecks will say $x=y=0$ always works for every $lambda$.
_Are there other solutions?_
=== Why guessing the eigenvalues is ill-fated
As an example, let's see if there are any eigenvectors $vec(x,y)$ with eigenvalue $100$.
In other words, let's solve
$ mat(5, -2; 3, 10) vec(x, y) = 100 vec(x, y). $
If we solve the system of equations, we get
$
cases(
5 x - 2 y = 100 x,
3 x + 10 y = 100 y
)
==>
cases(
-95x - 2y = 0,
3x - 90y = 0,
)
==> x = y = 0.
$
Well, that's boring. In this system of equations, the only solution is $x = y = 0$.
We can try a different guess: maybe we use $1000$ instead of $100$.
An eigenvector with eigenvalue $1000$ ought to be correspond to
$ mat(5, -2; 3, 10) vec(x, y) = 1000 vec(x, y). $
If we solve the system of equations, we get
$
cases(
5 x - 2 y = 1000 x,
3 x + 10 y = 1000 y
)
==>
cases(
-995x - 2y = 0,
3x - 990y = 0,
)
==> x = y = 0
$
which... isn't any better. We still don't get any solutions besides $x = y = 0$.
At this point, you should be remembering something I told you in R04:
a "random" system of equations and variables usually only has a unique solution.
So if I keep picking numbers out of a hat like $100$, $1000$, etc.,
then I'm unlikely to find anything interesting.
In order to get a system that doesn't just solve to $x=y=0$,
I'm going to need to cherry-pick my number $lambda$.
=== Cherry-picking $lambda$
Let's try to figure out what value of $lambda$ would make the system more interesting.
If we copy what we did above, we see that the general process is:
$
cases(
5 x - 2 y = lambda x,
3 x + 10 y = lambda y
)
==>
cases(
(5-lambda)x - 2y = 0,
3x + (10-lambda)y = 0,
)
$
We need to cherry-pick $lambda$ to make sure that the system doesn't just
solve to $x = y = 0$ like the examples we tried with $100$ and $1000$.
But we learned how to do this in R04:
in order to get a degenerate system you need to make sure that
$
0 = det mat(5-lambda, -2; 3, 10-lambda).
$
#remark[
At this point, you might notice that this is secretly an explanation
of why $A - lambda I$ keeps showing up on your formula sheet.
Writing $A bf(v) = lambda bf(v)$
is the same as $(A - lambda I) bf(v) = 0$, just more opaquely.
]
Expanding the determinant on the left-hand side gives
$
0 = det mat(5-lambda, -2; 3, 10-lambda)
= (5-lambda)(10-lambda) + 6 = lambda^2 - 15 lambda + 56 = (lambda - 7)(lambda - 8).
$
Great! So we expect that if we choose either $lambda = 7$ and $lambda = 8$,
then we will get a degenerate system, and we won't just get $x = y = 0$.
Indeed, let's check this:
- When $lambda = 7$, our system is
$
cases(
5 x - 2 y = 7 x,
3 x + 10 y = 7 y
)
==>
cases(
-2x - 2y = 0,
3x + 3y = 0,
)
==> x = -y.
$
So for example, $vec(-13,13)$ and $vec(37,-37)$ will be eigenvectors with eigenvalue $7$:
$ A vec(-13, 13) = mat(5,-2;3,10) vec(-13, 13) = vec(-91, 91) = 7 vec(-13, 13). $
On exam, you probably answer
"the eigenvectors with eigenvalue $7$ are the multiples of $vec(-1,1)$",
or "the eigenvectors with eigenvalue $7$ are the multiples of $vec(1,-1)$" if you want;
these are the same thing.
Or if you want to mess with the grader,
"the eigenvectors with eigenvalue $7$ are the multiples of $vec(100,-100)$" is fine too.
- When $lambda = 8$, our system is
$
cases(
5 x - 2 y = 8 x,
3 x + 10 y = 8 y
)
==>
cases(
-3x - 2y = 0,
3x + 2y = 0,
)
==> x = -2/3 y.
$
So for example, $vec(-20, 30)$ is an eigenvector with eigenvalue $8$:
$ A vec(-20, 30) = mat(5,-2;3,10) vec(-20, 30) = vec(-160, 240) = 8vec(-20, 30). $
On exam, you should answer
"the eigenvectors with eigenvalue $8$ are the multiples of $vec(-2,3)$".
Or you can say
"the eigenvectors with eigenvalue $8$ are the multiples of $vec(2,-3)$" if you want;
these are the same thing.
You could even say
"the eigenvectors with eigenvalue $8$ are the multiples of $vec(200,-300)$"
and still get credit, but that's silly.
== [RECAP] Summary
To summarize the story above:
- We had the matrix $A = mat(5, -2; 3, 10)$ and wanted to find $lambda$'s for which
the equation
$ mat(5, -2; 3, 10) vec(x,y) = lambda vec(x,y) $
had solutions other than $x=y=0$.
- We realized that guessing $lambda$ was never going to fly,
so we went out of our way to cherry-pick $lambda$ to make sure the system was degenerate.
The buzzwords for this are "find the roots of the characteristic polynomial",
but I wanted to show that it flows naturally from the end goal.
- For the two values of $lambda$ we cherry-picked,
we know the system of equations is degenerate.
So we solve the two degenerate systems and see what happens.
In lectures and notes, the last two bullets are separated as two different steps,
to make it into a recipe.
But don't lose sight of how they're connected!
I would rather call it the following interlocked thing:
#align(center)[
We cherry-pick $lambda$ to make sure the system doesn't just solve to $x=y=0$.
To do the cherry-picking, ensure $det(A - lambda I) = 0$
so that our system is degenerate.
]
== [RECIPE] Calculating all the eigenvalues
To repeat the story:
#recipe(title: [Recipe for finding the eigenvectors and eigenvalues])[
Given a matrix $A$, to find its eigenvectors and eigenvalues:
1. Find all the values of $lambda$ such that, if you subtract $lambda$ from every diagonal
entry of $A$ (that is, look at $A - lambda I)$,
the resulting square matrix of coefficients has determinant $0$.
2. For each $lambda$, solve the degenerate system and output the solutions to it.
(You should find there is at least a one-dimensional space of solutions.)
]
#todo[Write example]
== [TEXT] Solving degenerate systems
When carrying out the recipe for finding eigenvectors and eigenvalues,
after cherry-picking $lambda$, you have to solve a degenerate system of equations.
Since most of the systems of equations you encounter in practice are nondegenerate,
here's a few words of advice on instincts for solving the degenerate ones.
=== Degenerate systems of two equations all look stupid
This is worth repeating:
*degenerate systems of two equations all look stupid*.
Earlier on, we saw the two systems
$
cases(
-2x - 2y = 0,
3x + 3y = 0,
)
#h(2em)
" and "
#h(2em)
cases(
-3x - 2y = 0,
3x + 2y = 0,
).
$
Both look moronic to the eye, because in each equation,
the two equations say the same thing.
This is by design: when you're solving the eigenvector problem,
_you're going out of your way to find degenerate systems_
so that there will actually be solutions besides $x = y = 0$.
In particular: if you do all the steps right,
*you should never wind up with $x = y = 0$ as your only solution*.
That means you either didn't do the cherry-picking step correctly,
or something went wrong when you were solving the system.
If that happens, check your work!
=== Degenerate systems of three equations may not look stupid, but they are
When you have three or more equations instead, they don't necessarily look as stupid.
To reuse the example I mentioned from R04, we have
$
x + 10 y - 9 z &= 0 \
3 x + y + 10 z &= 0 \
4 x + 11 y + z &= 0
$
which doesn't look stupid.
But again, if you check the determinant, you find out
$ det mat(1,10,-9;3,1,10;4,11,1) = 0. $
So you know _a priori_ that there will be solutions besides $x=y=z=0$.
I think 18.02 won't have too many situations where you need to solve a degenerate
three-variable system of equations, because it's generally annoying to do by hand.
But if it happens, you should fall back on your high school algebra
and solve the system however you learned it in 9th or 10th grade.
The good news is that at least one of the three equations is redundant,
so you can just throw one away and solve for the other two.
For example, in this case we would solve
$
x + 10 y &= 9z \
3 x + y &= -10z
$
for $x$ and $y$, as a function of $z$.
I think this particular example works out to $x = -109/29 z$, $y = 37/29 z$.
And it indeed fits the third equation too.
== [SIDENOTE] Complex eigenvectors
Even in the $2 times 2$ case, you'll find a lot of matrices $M$ with real coefficients
don't have eigenvectors.
Here's one example.
Let $ M = mat(cos(60 degree), -sin(60 degree); sin(60 degree), cos(60 degree))
= mat(1/2, -sqrt(3)/2; sqrt(3)/2, 1/2). $
be the matrix corresponding to rotation by $60$ degrees.
(Feel free to replace $60$ by a different number.)
I claim that $M$ has no real eigenvalues or eigenvectors.
Indeed, if $bf(v) in RR^2$ was an eigenvector,
then $M bf(v)$ needs to point in the same direction as $bf(v)$, by definition.
But that can never happen: $M$ is rotation by $60 degree$,
so $M bf(v)$ and $bf(v)$ necessarily point in different directions --- $60$ degrees apart.
#todo[what goes wrong?]
== [SIDENOTE] Application of eigenvectors: matrix powers
This is off-syllabus for 18.02, but I couldn't resist including it because
it shows you a good use of eigenvalues in a seemingly unrelated problem,
and also reinforces the idea that I keep axe-grinding:
#align(center)[
If you have a linear operator $T$,
and you know the outputs of $T$ on _any_ basis, that tells you all the outputs of $T$.
]
The problem is this:
#question[
Let $M$ be the matrix $mat(2,1;0,3)$.
Calculate $M^(100)$.
]
At first glance, you might thinks question is obviously impossible without a computer,
because raising a matrix to the $100$th power would require $100$ matrix multiplications.
But I'll show you how to do it with eigenvectors.
#soln[
First, we compute the eigenvectors and eigenvalues of $M$.
If you follow the recipe, you'll get the following results:
- The vector $vec(1,0)$ is an eigenvector with eigenvalue $2$ (as is any multiple of $vec(1,0)$),
because $M vec(1,0) = vec(2,0) = 2 vec(1,0)$.
- The vector $vec(1,1)$ is an eigenvector with eigenvalue $3$ (as is any multiple of $vec(1,1)$),
because $M vec(1,1) = vec(3,3) = 3 vec(1,1)$.
Now the trick is the following:
it's really easy to apply $M^(100)$ to the _eigenvectors_,
because it's just multiplication by a constant.
For example, the first few powers of $M$ on $vec(1,0)$
each double the vector, since they are all eigenvectors with eigenvalue $2$; that is:
$
M vec(1,0) &= vec(2,0) \
M^2 vec(1,0) &= M vec(2,0) = vec(4,0) \
M^3 vec(1,0) &= M vec(4,0) = vec(8,0)
&dots.v
$
and so on, until
$ M^(100) vec(1,0) = 2^(100) vec(1,0). $
By the same token:
$ M^(100) vec(1,1) = 3^(100) vec(1,1). $
So now we know the outputs of $M^(100)$ at two linearly independent vectors.
It would be sufficient, then, to use this information to
extract $M^(100) (bf(e)_1)$ and $M^100 (bf(e)_2)$.
We can now rewrite this as
$
M^(100) vec(1,0) = vec(2^(100), 0); #h(2em)
M^(100) vec(0,1) = M^(100) vec(1,1) - M^(100) vec(1,0) = vec(3^(100) - 2^(100), 3^(100)).
$
Thus encoding $M$ gives the answer:
$ M^(100) = mat(2^(100), 3^(100)-2^(100); 0, 3^(100)). #qedhere $
]
|
https://github.com/OverflowCat/BUAA-Data-and-Error-Analysis-Sp2024 | https://raw.githubusercontent.com/OverflowCat/BUAA-Data-and-Error-Analysis-Sp2024/neko/project-2/helper.typ | typst | #import "./vendor/lib.typ": round
#let hr = line(stroke: black.lighten(70%), length: 100%)
#let r0 = n => round(n, if str(n).starts-with("0.") {2} else {3})
#let r = n => round(n, 4)
#let rx = n => round(n, 5)
#let ry = n => round(n, 5)
#let rxy = n => round(n, 5)
#let c = x => calc.round(x, digits: 3)
#let c2 = x => calc.round(x, digits: 2)
#let average(arr) = {
let n = arr.len()
arr.sum() / n
}
#let stderr(arr) = {
let avg = average(arr)
let vs = arr.map(x => x - avg)
let n = arr.len()
let sigma2 = vs.map(x=>x*x).sum()/(n - 1)
calc.sqrt(sigma2)
} |
|
https://github.com/ustctug/ustc-thesis-typst | https://raw.githubusercontent.com/ustctug/ustc-thesis-typst/main/chapters/acknowledgements.typ | typst | MIT License | #block[
在研究学习期间,我有幸得到了三位老师的教导,
他们是:我的导师,中国科大XXX研究员,中科院X昆明动物所马老师以及美国犹他大学的XXX老师。
三位深厚的学术功底,严谨的工作态度和敏锐的科学洞察力使我受益良多。
衷心感谢他们多年来给予我的悉心教导和热情帮助。
感谢XXX老师在实验方面的指导以及教授的帮助。
科大的XXX同学和XXX同学参与了部分试验工作,在此深表谢意。
]
|
https://github.com/grnin/Zusammenfassungen | https://raw.githubusercontent.com/grnin/Zusammenfassungen/main/Bsys2/02_Dateisystem_API.typ | typst | // Compiled with Typst 0.11.1
#import "../template_zusammenf.typ": *
#import "@preview/wrap-it:0.1.0": wrap-content
/*#show: project.with(
authors: ("<NAME>", "<NAME>"),
fach: "BSys2",
fach-long: "Betriebssysteme 2",
semester: "FS24",
tableofcontents: (enabled: true),
language: "de"
)*/
= Dateisystem API
_Dateiendungen_ sind die Zeichen nach dem letzten Punkt. Dateiendungen haben für
File System (FS) und OS _(fast) keine Relevanz_. Bestimmte Programme deuten Dateiendung
als Typ. Häufig wird der Typ aber durch _Magic Numbers_ oder Strings innerhalb der Datei
gekennzeichnet.
=== Schutz gegen falsche Datentypen
Es liegt an der Applikation, den Dateityp richtig zu bestimmen.
Applikationen müssen sich gegen "Datenmüll" (bzw. Fehlinterpretation) schützen.
Sie dürfen _nie_ annehmen, dass Daten _gültig_ sind, sondern müssen diese _validieren_ und
auf Grenzverletzungen überprüfen.
=== Begriffe
- _Verzeichnis:_ Liste, die Dateien oder weitere Verzeichnisse enthalten kann.
Als Datei realisiert, die diese Liste enthält. Hat einen Dateinamen.
- _Verzeichnishierarchie:_ Gesamtheit aller Verzeichnisse im System.
Jedes Verzeichnis (ausser Wurzelverzeichnis) hat genau ein Elternverzeichnis
(Baum-Hierarchie).
- _Wurzelverzeichnis:_ Oberstes Verzeichnis in der Hierarchie. Hat keinen Namen, wird aber
oft mit `/` bezeichnet. #hinweis[(Windows: Root pro Partition, Unix: Root pro OS)]
=== Besondere Verzeichnisse
Jedes Verzeichnis enthält zwei implizite Referenzen auf Verzeichnisse:
- _`.`_ Referenz auf sich selbst
- _`..`_ Referenz auf das Elternverzeichnis
Jeder Prozess hat ein _Arbeitsverzeichnis (working directory)_, welches den Bezugspunkt
für relative Pfade darstellt. Dieses wird beim Prozessstart von aussen festgelegt.
Wird mit ```c getcwd()``` ermittelt und mit
```c chdir()``` #hinweis[(nimmt Pfad als String)] bzw
```c fchdir()``` #hinweis[(nimmt file descriptor)] geändert.
=== Pfade
Ein Pfad spezifiziert eine Datei oder ein Verzeichnis in der Verzeichnishierarchie.
Verzeichnisnamen werden durch `/` voneinander getrennt (Windows: `\`).
- _Absoluter Pfad_ beginnt mit `/` #hinweis[(vom Root-Verzeichnis aus)]
- _Relativer Pfad_ beginnt _nicht_ mit `/` #hinweis[(vom Arbeitsverzeichnis aus)]
- _Kanonische Pfade_ sind absolute Pfade ohne `"."` und `".."`.
Können mit ```c realpath()``` ermittelt werden.
==== Längster Pfadname
Verschiedene Implementierungen von POSIX dienen unterschiedlichen Zwecken.
Systeme können unterschiedliche Limits haben. Jedes POSIX-System definiert den
Header ```c <limits.h>```:
- _`NAME_MAX`:_ Maximale Länge eines Dateinamens (exklusive terminierender Null)
- _`PATH_MAX`:_ Maximale Länge eines Pfads (inklusive terminierender Null)
#hinweis[(beinhaltet Wert von `NAME_MAX`)]
- _`_POSIX_NAME_MAX`:_ Minimaler Wert von `NAME_MAX` nach POSIX #hinweis[(14)]
- _`_POSIX_PATH_MAX`:_ Minimaler Wert von `PATH_MAX` nach POSIX #hinweis[(256)]
_Beispiel - Arbeitsverzeichnis ausgeben:_
```c
int main (int argc, char ** argv) {
char *wd = malloc(PATH_MAX); // PATH_MAX = Maximale Länge des Pfades
getcwd(wd, PATH_MAX);
printf("Current WD is %s", wd);
free(wd);
return 0;
}
```
#pagebreak()
=== Zugriffsrechte (Unix)
Jeder Datei und jedem Verzeichnis sind Zugriffsrechte zugeordnet.
Gehört genau einem Benutzer (Owner) und genau einer Gruppe.
Hat je 3 Permission-Bits für _Owner_, _Gruppe_, und _andere Benutzer_.
- _Read-Bits:_ Darf lesen
- _Write-Bits:_ Darf schreiben
- _Execute/Search-Bits:_ Darf ausführen (Datei) bzw. durchsuchen (Verzeichnis)
Es gibt eine feste Reihenfolge der 9 Permission Bits: `owner rwx - group rwx - other rwx`.
Schreibweise: `r=4, w=2, x=1` `0740` oder `rwx r-- ---` bedeutet
owner hat alle Rechte, Gruppe kann nur lesen, andere haben keine Rechte.
==== POSIX
Die POSIX-API definiert die `STAT_INODE` Konstanten für die Zugriffsrechte in
```c <sys/stat.h>```. Beispiele:
- _`S_IRWXU`_ `= 0700 = rwx------` #hinweis[read, write & execute for user]
- _`S_IWUSR`_ `= 0200 = -w-------` #hinweis[write for user]
- _`S_IRGRP`_ `= 0040 = ---r-----` #hinweis[read for group]
- _`S_IXOTH`_ `= 0001 = --------x` #hinweis[execute for other]
Können mit `|` verknüpft werden, z.B. `S_IRWXU | S_IRGRP`
#wrap-content(
image("img/bsys_5.png"),
align: top + right,
columns: (62%, 38%),
)[
== Überblick APIs
- _POSIX-API:_ für direkten Zugriff, alle Dateien sind rohe Binärdaten
#hinweis[(so wie sie in der Datei gespeichert sind)]
- _C-API:_ für direkten Zugriff auf Streams #hinweis[(Textdateien)], Abstraktion
über Dateien, Pipes, etc. Für formatierte Ein- und Ausgabe, OS leitet alle
Zugriffe an Treiber weiter.
== POSIX File API
API für _direkten, unformatierten Zugriff_ auf Inhalt der Datei.
Sollte _nur für Binärdaten_ verwendet werden. Funktionen sind deklariert in
```c <unistd.h>``` #hinweis[(Unix Standard API)] und ```c <fcntl.h>```
#hinweis[(File Control)] und geben im Fehlerfall `-1` zurück.
Der Fehler-Code kann dann mit `errno` abgefragt werden.
]
=== `errno`
- _Makro oder globale Variable vom Typ `int`_
#hinweis[verhält sich immer wie eine globale Variable]
- Wird von vielen Funktionen gesetzt.
- Sollte _unmittelbar nach Auftreten eines Fehlers_ aufgerufen werden
#hinweis[damit Wert nicht von anderer Funktion überschrieben wird]
```c
if (chdir("docs") < 0) {
// hier nichts anderes machen damit Fehlercode nicht überschrieben wird
if (errno == EACCESS) {
printf("Error: Access denied");
}
}
```
==== `char * strerror (int code)`
`strerror` gibt die Adresse eines Strings zurück, der den Fehlercode `code` textuell
beschreibt.
```c
if (chdir("docs") < 0) {
printf("Error: %s\n", strerror (errno)); //e.g. Error: Permission denied
}
```
==== `void perror (const char *text)`
`perror` #hinweis[(präfix error)] schreibt `text` gefolgt von einem Doppelpunkt und vom
Ergebnis von `strerror(errno)` auf den Errorstream.
```c
if (chdir("docs") < 0) {
perror("chdir"); // chdir: No such file or directory
}
```
=== File-Descriptor
Files werden in der POSIX-API über _File-Deskriptoren (FD)_ repräsentiert.
Gilt immer nur innerhalb eines Prozesses. Ein neu erstellter FD returnt einen Index,
über welchen auf ihn zugegriffen werden kann.
- Index in eine _Tabelle aller geöffneten Dateien im Prozess_
- Tabelleneintrag enthält _Index in systemweite Tabelle_ aller geöffneten Dateien
- Die systemweite Tabelle enthält Daten, um physische Datei zu identifizieren.
Zustandsbehaftet: merkt sich aktuellen Offset (Offset des Bytes, das als nächstes
gelesen werden wird)
#wrap-content(
image("img/bsys_6.png"),
align: top + right,
columns: (70%, 30%),
)[
In jedem Prozess sind drei Standard File-Deskriptoren definiert:
- _`STDIN_FILENO = 0`:_ standard input
- _`STDOUT_FILENO = 1`:_ standard output
- _`STDERR_FILENO = 2`:_ standard error
]
=== Öffnen und Schliessen von Dateien: ```c int open (char *path, int flags, ...)```
erzeugt einen File-Deskriptor auf die Datei, die an `path` liegt.
`flags` gibt an, wie die Datei geöffnet werden soll.
#hinweis[(können über Pipe kombiniert werden. Sollen noch Berechtigungs-Flags verwendet
werden, werden diese als eigener Parameter angegeben)]
- _`O_RDONLY`:_ nur lesen
- _`O_RDWR`:_ lesen und schreiben
- _`O_CREAT`:_ Erzeuge Datei, wenn sie nicht existiert;
benötigt weiterer Parameter für Zugriffsrechte
- _`O_APPEND`:_ Setze Offset ans Ende der Datei vor jedem Schreibzugriff
#hinweis[(ohne dieses Flag wird bei jedem Schreiben der Inhalt von Anfang an überschrieben)]
- _`O_TRUNC`:_ Setze Länge der Datei auf 0 #hinweis[(Inhalt löschen)]
```c int close (int fd)``` _dealloziert_ den _File-Deskriptor `fd`_.
Dieser kann später von `open` für eine andere Datei verwendet werden
#hinweis[(gleiche File-Deskriptoren != gleiche Datei)].
Gibt `0` #hinweis[(OK)] oder `-1` #hinweis[(Fehler, z.B. FD existiert nicht)] zurück.
Wird die Datei _nicht geschlossen_, kann es sein, dass das _FD-Limit_ des Prozesses
erreicht wird und _keine weiteren Dateien_ mehr geöffnet werden können.
Es können auch _mehrere FDs diesselbe Datei öffnen_, da diese aber _verschiedene Offsets_
haben können, besteht die Gefahr, dass sie sich _gegenseitig Daten überschreiben_ -
nicht empfehlenswert.
```c
int fd = open("myfile.dat", O_RDONLY);
if (fd < 0) {
// error handling, -1 means error
}
// read data
close(fd); //gets written on the disc and the resources (and the file) can be used again
```
=== Lesen und Schreiben von Dateien: ```c ssize_t read(int fd, void * buffer, size_t n)```
#wrap-content(
image("img/bsys_7.png"),
align: top + right,
columns: (65%, 35%),
)[
versucht, die nächsten $n$ Byte am aktuellen Offset von `fd` in den `buffer` zu kopieren.
```c ssize_t write(int fd, void * buffer, size_t n)``` versucht, die nächsten $n$ Byte
vom `buffer` an den aktuellen Offset von `fd` zu kopieren.
Beide Funktionen geben die Anzahl der gelesenen / geschriebenen Bytes zurück oder -1 bei
Fehler #hinweis[(darum ist return type signed size)]. Blockieren normalerweise, bis $n$
Bytes kopiert wurden, ein Fehler auftritt oder das Ende der Datei erreicht wurde.
Erhöhen Offset von `fd` um Anzahl gelesener / geschriebener Bytes.
]
#pagebreak();
```c
#define N 32
char buf[N]
char spath[PATH_MAX]; // source path
char dpath[PATH_MAX]; // destination path
// ... gets paths from somewhere
int src = open(spath, O_RDONLY);
int dst = open(dpath, O_WRONLY | O_CREAT, S_IRWXU);
ssize_t read_bytes = read(src, buf, N);
write(dst, buf, read_bytes); //if file gets closed early, use return value of "read_bytes"
close(src);
close(dst);
```
=== Springen in einer Datei: ```c off_t lseek(int fd, off_t offset, int origin)```
#wrap-content(
image("img/bsys_8.png"),
align: top + right,
columns: (75%, 25%),
)[
setzt den Offset von `fd` auf `offset`. `origin` gibt an, wozu `offset` relativ ist:
- _`SEEK_SET`:_ Beginn der Datei #hinweis[(absoluter Offset)]
- _`SEEK_CUR`:_ Aktueller Offset #hinweis[(relativer Offset)]
- _`SEEK_END`:_ Ende der Datei #hinweis[(Offset über Datei hinaus)]
Gibt neuen Offset zurück oder -1 bei Fehler.\
Weitere Anwendungsmöglichkeiten:
- _`lseek(fd, 0, SEEK_CUR)`:_ gibt aktuellen Offset zurück
- _`lseek(fd, 0, SEEK_END)`:_ gibt die Grösse der Datei zurück
- _`lseek(fd, n, SEEK_END)`:_ hängt bei nachfolgendem `write` $n$ Nullen an Datei
#hinweis[(Padding um Datei auf bestimmte Grösse zu setzen)]
]
=== Lesen und Schreiben ohne Offsetänderung:
```c
ssize_t pread(int fd, void * buffer, size_t n, off_t offset)
ssize_t pwrite(int fd, void * buffer, size_t n, off_t offset)
```
Wie `read` bzw. `write`. Statt des Offsets von `fd` wird der zusätzliche Parameter
`offset` verwendet.\
#hinweis[(`off_t >= signed int`)] Der Offset von `fd` wird _nicht_ verändert.
=== Unterschiede Windows und POSIX
- Bestandteile von Pfaden werden durch _Backslash_ (`\`) getrennt.
#hinweis[(müssen darum in C-Strings doppelt geschrieben werden, da `\` Escape-Character ist)]
- Ein _Wurzelverzeichnis pro_ Datenträger/Partition
- Andere File-Handling-Funktionen #hinweis[CreateFile, ReadFile, WriteFile,
SetFilePointer, CloseHandle]
== C Stream API
- _Unabhängig vom Betriebssystem:_ für POSIX und Windows gleich
- _Stream-basiert:_ zeichen-orientiert #hinweis[Ist dafür da, mit Text zu arbeiten]
- Kann _gepuffert_ oder _ungepuffert_ sein. Für Dateien im Normalfall _gepuffert_.
Transferiert selbstständig grössere Daten-Blöcke zwischen Datei und Puffer.
- Hat einen eigenen _File-Position-Indicator_: Bei gepufferten Streams bestimmte Position
im Puffer, bei ungepufferten Streams entspricht dieser dem Offset des File-Descriptors.
=== Streams
Datenstruktur `FILE` enthält _Informationen über einen Stream_.
Soll _nicht direkt verwendet werden_, sondern nur über von C-API erzeugte Pointer
_`(FILE *)`_. Soll nicht kopiert werden, Pointer an sich kann von API als ID
verwendet werden.
Drei definierte Standard-Streams analog zu den Standard-FDs:\
```c FILE *stdin```, ```c FILE *stdout```, ```c FILE *stderr```
#pagebreak()
=== Öffnen einer Datei: ```c FILE * fopen(char const *path, char const *mode)```
erzeugt `FILE`-Objekt (und damit Stream) für Datei an `path`. `mode` gibt Flags analog zu
`open` als nullterminierten String an:
- _`"r"`:_ wie `O_RDONLY` #hinweis[(Datei lesen)]
- _`"w"`:_ wie `O_WRONLY | O_CREAT | O_TRUNC`
#hinweis[(in neue oder bestehende geleerte Datei schreiben)]
- _`"a"`:_ wie `O_WRONLY | O_CREAT | O_APPEND`
#hinweis[(in neue oder bestehende Datei anfügen)]
- _`"r+`:_ wie `O_RDWR` #hinweis[(Datei lesen & schreiben)]
- _`"w+"`:_ wie `O_RDWR | O_CREAT | O_TRUNC`
#hinweis[(neue oder geleerte bestehende Datei lesen & überschreiben)]
- _`"a+"`:_ wie `O_RDWR | O_CREAT | O_APPEND`
#hinweis[(neue oder bestehende Datei lesen & an Datei anfügen)]
Gibt Pointer auf erzeugtes `FILE`-Objekt zurück oder 0 bei Fehler.
```c FILE * fdopen(int fd, char const * mode)``` ist wie ```c fopen()```, aber statt Pfad
wird direkt der File-Deskriptor übergeben.
```c int fileno (FILE *stream)``` gibt File-Deskriptor zurück, auf den sich der Stream
bezieht, oder -1 bei Fehler.
Da die POSIX- & Stream-API _unterschiedliche Offsets_ haben, sollte man nach dem Umwandlen
mit den obigen Funktionen die "vorherige" API _nicht mehr verwenden_, da es wie bei
mehreren FDs auf diesselbe Datei zu _Konflikten_ kommen kann.
=== Schliessen einer Datei: ```c int fclose(FILE *file)```
ruft ```c fflush()``` auf, schliesst den durch `file` bezeichneten Stream, entfernt `file`
aus Speicher und gibt 0 zurück wenn OK, andernfalls `EOF`.
=== Flushen einer Datei: ```c int fflush(FILE *file)```
schreibt eventuell zu schreibenden Inhalt aus dem Hauptspeicher in die Datei.
Wird automatisch aufgerufen, wenn der Puffer voll ist oder die Datei geschlossen wird.
Gibt 0 zurück wenn OK, andernfalls `EOF`.
=== Lesen aus einer Datei: ```c int fgetc(FILE *stream)```
liest das nächste Byte vom `stream` als _unsigned char_ und gibt es als _int_ zurück
#hinweis[(weil man den nächstgrösseren Dateityp `int` benötigt, um Fehlercodes abzubilden)].
Erhöht den _File-Position-Indicator_ um 1.
```c char * fgets(char *buf, int n, FILE *stream)``` liest bis zu $n-1$ Zeichen aus
`stream`, bis Newline oder `EOF` auftritt. Hängt eine 0 an, und erzeugt damit
null-terminierten String. Gibt `buf` zurück, oder 0 wenn ein Fehler auftrat.
Erhöht den File-Position-Indicator entsprechend der gelesenen Zeichen.
==== Lesen rückgängig machen: ```c int ungetc(int c, FILE *stream)```
schiebt `c` zurück in den `stream` auf den _Unget-Stack_.
`fgetc` bevorzugt immer den Unget-Stack: `c` wird bei der nächsten Leseoperation so
zurückgegeben, als ob es an der Stelle gestanden hätte.
Die Datei selbst wird _nicht_ verändert.
Der Unget-Stack hat _mindestens Grösse 1: Funktioniert mindestens einmal_
Gibt `c` zurück, oder `EOF` im Fehlerfall.
=== Schreiben in eine Datei: ```c int fputc(int c, FILE *stream)```
konvertiert `c` in _unsigned char_ und schreibt diesen auf `stream`.
Gibt entweder `c` zurück oder `EOF`. Erhöht den File-Position-Indicator um 1.
```c int fputs(char *s, FILE *stream)``` schreibt die Zeichen vom String `s` bis
zur terminierenden 0 in `stream`. Die terminierende 0 wird _nicht_ mitgeschrieben.
Gibt im Fehlerfall `EOF` zurück.
#pagebreak()
=== Dateiende und Fehler:
- ```c int feof(FILE *stream)``` gibt 0 zurück, wenn Dateiende _noch nicht_ erreicht wurde
- ```c int ferror(FILE * stream)``` gibt 0 zurück, wenn _kein_ Fehler auftrat
```c
int return_value = fgetc (stream);
if (return_value == EOF) {
if (feof(stream) != 0) {
// EOF reached
} else if (ferror(stream) != 0) {
// Error Occured, check errno
} // feof and ferror need to be checked separately
}
```
=== Manipulation des File-Position-Indicator:
- *```c long ftell(FILE *stream)```*
gibt den gegenwärtigen FPI zurück.\
#hinweis[POSIX-Erweiterung von C: `ftello` mit Rückgabetyp `off_t`]
- *```c int fseek (FILE *stream, long offset, int origin)```*
setzt den FPI, analog zu `lseek`.\
#hinweis[POSIX-Erweiterung von C: `fseeko` mit `off_t` als Typ für `offset`]
- *```c int rewind (FILE *stream)```*
setzt den Stream zurück.
Äquivalent zu ```c fseek(stream, 0, SEEK_SET)``` und Löschen des Fehlerzustands.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/underover-00.typ | typst | Other | // Test braces.
$ x = underbrace(
1 + 2 + ... + 5,
underbrace("numbers", x + y)
) $
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/fauve-cdb/0.1.0/src/abstracts-bg.typ | typst | Apache License 2.0 | #import "@preview/cetz:0.2.2": canvas, draw
#let abstracts-bg(school-color) = canvas({
let page-w = 21
let page-h = 29.7
// TikZ very thick = 0.42mm
// top-left lines
for i in range(1, 35) {
draw.line(
(0, 4.428+i*4.128/35), (7, 6.4+i*4.128/35),
stroke: school-color.transparentize(75%) + 0.42mm
)
}
// top-left mask
draw.line(
(0, 8.556), (7.05, 6.4), (7.05, 10.8), (0, 10.8),
close: true, fill: white, stroke: 0pt
)
// bottom-right lines
let x = 14
let y = -24
for i in range(1, 35) {
draw.line(
(x+0.02, y+6.4+i*4.128/35), (x+7.02, y+4.428+i*4.128/35),
stroke: school-color.transparentize(85%) + 0.42mm
)
}
// bottom-right mask
draw.line(
(x -.03, y+6.4), (x+7.02, y+8.556), (x+7.02, y+10.8), (x -.03, y+10.8),
close: true, fill: white, stroke: 0pt
)
// top lines
let x = 7
let y = 4
for i in range(1, 35) {
draw.line(
(x, y+4.428+i*4.128/35), (x+7, y+6.4+i*4.128/35),
stroke: school-color.transparentize(75%) + 0.42mm
)
}
// top lines edge mask
draw.rect(
(x -.05, y+3), (x+.01, y+10),
fill: white, stroke: 0pt
)
// top fading mask
draw.rect(
(x, y+4.428), (x+7.05, y+10.8), stroke: 0pt,
fill: gradient.linear(dir: ttb, white, white, white, white.transparentize(100%))
)
}) |
https://github.com/jneug/typst-nassi | https://raw.githubusercontent.com/jneug/typst-nassi/main/src/nassi.typ | typst | MIT License | #import "@preview/cetz:0.3.0"
#import "elements.typ"
#import "draw.typ"
#let parse(content) = {
if content == none {
return ()
}
let code = content.split("\n")
let elems = ()
let i = 0
while i < code.len() {
let line = code.at(i).trim()
if line == "" {
i += 1
continue
}
if line.starts-with("if ") {
let (left, right) = ((), ())
let left-branch = true
let if-count = 0
i += 1
while if-count > 0 or code.at(i).trim() not in ("endif", "end if") {
let code-line = code.at(i).trim()
if code-line.starts-with("if") {
if-count += 1
} else if if-count > 0 and code-line in ("endif", "end if") {
if-count -= 1
}
if code.at(i).trim() == "else" and if-count == 0 {
left-branch = false
} else if left-branch {
left += (code.at(i),)
} else {
right += (code.at(i),)
}
i += 1
}
elems += elements.branch(
line.slice(3).trim(),
parse(left.join("\n")),
parse(right.join("\n")),
column-split: if left == () {
25%
} else if right == () {
75%
} else {
50%
},
)
} else if line.starts-with("switch ") {
let branches = (:)
let default = ()
let default-branch = false
let switch-count = 0
i += 1
while switch-count > 0 or code.at(i).trim() not in ("endswitch", "end switch") {
let code-line = code.at(i).trim()
if switch-count > 0 and code-line in ("endswitch", "end switch") {
switch-count -= 1
}
if code-line.starts-with("case ") and switch-count == 0 {
default-branch = false
let key = code-line.slice("case ".len())
branches.insert(key, ())
} else if code-line.starts-with("default") and switch-count == 0 {
default-branch = true
} else if branches.len() > 0 or default-branch {
if code-line.starts-with("switch") {
switch-count += 1
}
if default-branch {
default += (code.at(i),)
} else {
branches.at(branches.keys().at(-1)) += (code.at(i),)
}
}
i += 1
}
for (key, value) in branches {
branches.at(key) = parse(value.join("\n"))
}
branches.default = parse(default.join("\n"))
elems += elements.switch(
line.slice("switch ".len()).trim(),
branches,
)
} else if line.starts-with("while ") {
let children = ()
let while-count = 0
i += 1
while while-count > 0 or code.at(i).trim() not in ("endwhile", "end while") {
let code-line = code.at(i).trim()
if code-line.starts-with("while") {
while-count += 1
} else if while-count > 0 and code-line in ("endwhile", "end while") {
while-count -= 1
}
children += (code.at(i),)
i += 1
}
elems += elements.loop(
line.slice(6),
parse(children.join("\n")),
)
} else if line.starts-with("function ") {
let children = ()
i += 1
while code.at(i).trim() not in ("endfunction", "end function") {
children += (code.at(i),)
i += 1
}
elems += elements.function(
line.slice(9),
parse(children.join("\n")),
)
} else {
if line.starts-with("|") and line.ends-with("|") {
elems += elements.call(line.slice(1, -1).trim())
} else if line.contains("<-") {
let (a, b) = line.split("<-")
elems += elements.assign(a.trim(), b.trim())
} else {
elems += elements.process(line)
}
}
i += 1
}
return elems
}
#let themes = (
default: (
empty: rgb("#fffff3"),
process: rgb("#fceece"),
call: rgb("#fceece"),
branch: rgb("#fadad0"),
loop: rgb("#dcefe7"),
switch: rgb("#fadad0"),
parallel: rgb("#dcefe7"),
function: rgb("#ffffff"),
),
colorful: (
empty: color.map.rainbow.first(),
process: color.map.rainbow.at(int(color.map.turbo.len() / 4)),
call: color.map.rainbow.at(int(color.map.turbo.len() / 4)),
branch: color.map.rainbow.at(int(color.map.turbo.len() / 8)),
loop: color.map.rainbow.at(int(color.map.turbo.len() / 16)),
switch: color.map.rainbow.at(int(color.map.turbo.len() / 8)),
parallel: color.map.rainbow.at(int(color.map.turbo.len() / 16)),
function: rgb("#ffffff"),
),
nocolor: (
empty: white,
process: white,
call: white,
branch: white,
loop: white,
switch: white,
parallel: white,
function: white,
),
greyscale: (
empty: luma(100%),
process: luma(90%),
call: luma(90%),
branch: luma(75%),
loop: luma(75%),
switch: luma(50%),
parallel: luma(75%),
function: luma(100%),
),
)
#let diagram(
width: 100%,
font: ("Verdana", "Geneva"),
fontsize: 10pt,
inset: .5em,
theme: themes.default,
stroke: 1pt + black,
labels: (),
..cetz-args,
elements,
) = {
if type(elements) == content and elements.func() == raw {
elements = elements.text
}
if type(elements) != array {
elements = parse(elements)
}
layout(size => {
let width = width
if type(width) == ratio {
width *= size.width
}
set text(font: font, size: fontsize)
cetz.canvas(
..cetz-args,
{
draw.diagram((0, 0), elements, width: width, inset: inset, theme: theme, stroke: stroke, labels: labels)
},
)
})
}
#let shneiderman(..args) = (
body => {
show raw.where(block: true, lang: "nassi"): diagram.with(..args)
body
}
)
|
https://github.com/liuguangxi/erdos | https://raw.githubusercontent.com/liuguangxi/erdos/master/Problems/typstdoc/figures/p24_2.typ | typst | #import "@preview/cetz:0.2.1"
#cetz.canvas({
import cetz.draw: *
let a = 4.5
line((0, 0), (a, 0), (a/2, a/2*calc.sqrt(3)), close: true)
line((0, a/3*calc.sqrt(3)), (a, a/3*calc.sqrt(3)), (a/2, -a/6*calc.sqrt(3)), close: true)
line((a/6, a/6*calc.sqrt(3)), (a*5/6, a/6*calc.sqrt(3)))
line((a/3, a/3*calc.sqrt(3)), (a*2/3, 0))
line((a*2/3, a/3*calc.sqrt(3)), (a/3, 0))
content(
(a/2, -a*0.45),
box(stroke: gray, inset: 4pt)[Each triangle has LEVEL $n$]
)
})
|
|
https://github.com/schang412/typst-whalogen | https://raw.githubusercontent.com/schang412/typst-whalogen/master/lib.typ | typst | Apache License 2.0 | #import "@preview/xarrow:0.3.1": xarrow
#let _quote(t) = {
return "\"" + t + "\""
}
// reads a list of str or content, ignores content
// replaces the specified string with the content specified
#let _replace_with_content(l, replace: " ", content: []) = { // array(str|content) -> array(str|content)
let result = ()
for item in l {
if type(item) != "string" {
result.push(item)
continue
}
for item_split in item.split(replace) {
result.push(item_split)
result.push(content)
}
result.pop()
}
return result
}
#let sym_map = (
"<-->": sym.arrows.lr,
"<->": sym.arrow.l.r,
"->": sym.arrow.r,
"<-": sym.arrow.l,
"<=>": sym.harpoons.rtlb
)
// rewrites isotope statement as isotope, otherwise returns same thing
#let _parse_isotope(t) = { // str -> str
let res = t.match(regex("@([^,]*),([^,]*),([^,]*)@"))
if res != none {
return "attach(" + _quote(res.captures.at(0)) + ", tl: " + _quote(res.captures.at(1)) + ", bl: " + _quote(res.captures.at(2)) +")"
}
return _quote(t)
}
// describes what to write to the output when a certain state ends
// return result should be written to output. buffer should be cleared after running this function
#let _flush_ce_buffer(_state, _buffer) = { // (str, str) -> (str)
return (
"letter": _quote(_buffer),
"num_script": "_" + _quote(_buffer),
"": _buffer,
"num": _buffer,
"charge": "^" + _quote(_buffer.replace("-", sym.dash.en)),
"caret": "^" + _quote(_buffer.replace("^", "", count: 1).replace("-", sym.dash.en).replace(".", sym.bullet)),
"underscore": "_" + _quote(_buffer.replace("_", "", count: 1)),
"code": _buffer,
"punctuation": _buffer,
"leading_punctuation": _buffer,
"isotope?": _parse_isotope(_buffer),
).at(_state)
}
// lower level parser operates based off of current state
// adjusts the output according to current context
// primarily inserting math symbols as necessary
// Return: next_state(str), output(str), buffer(str)
#let _parse_ce(_state, _char_in, _buffer) = { // (str, str, str) -> (str, str, str)
let _out = ""
// end previous states on whitespace
if _char_in.contains(regex("\s")) {
_out = _flush_ce_buffer(_state, _buffer)
_buffer = ""
_state = ""
}
if _char_in == "#" {
_out = _flush_ce_buffer(_state, _buffer)
_buffer = ""
_state = "code"
}
// on letter flush buffer (unless already is letter)
if _char_in.contains(regex("[A-Za-z]")) {
(_state, _out, _buffer) = (
"letter": ("letter", _out, _buffer),
"isotope?": ("isotope?", _out, _buffer),
"code": ("code", _out, _buffer),
"caret": ("caret", _out, _buffer),
).at(_state, default: ("letter", _flush_ce_buffer(_state, _buffer), ""))
}
// on digit
if _char_in.contains(regex("\d")) {
(_state, _out, _buffer) = (
"letter": ("num_script", _flush_ce_buffer(_state, _buffer), ""),
"punctuation": ("num_script", _flush_ce_buffer(_state, _buffer), ""),
"num_script": ("num_script", _out, _buffer)
).at(_state, default: (_state, _out, _buffer))
}
// on plus/minus
if _char_in.contains(regex("[+-]")) {
(_state, _out, _buffer) = (
"letter": ("charge", _flush_ce_buffer(_state, _buffer), ""),
"punctuation": ("charge", _flush_ce_buffer(_state, _buffer), "")
).at(_state, default: (_state, _out, _buffer))
}
// on caret
if _char_in.contains("^") {
(_state, _out, _buffer) = (
"letter": ("caret", _flush_ce_buffer(_state, _buffer), ""),
"punctuation": ("caret", _flush_ce_buffer(_state, _buffer), ""),
"num_script": ("caret", _flush_ce_buffer(_state, _buffer), ""),
"underscore": ("caret", _flush_ce_buffer(_state, _buffer), "")
).at(_state, default: (_state, _out, _buffer))
}
// on underscore
if _char_in.contains("_") {
(_state, _out, _buffer) = (
"letter": ("underscore", _flush_ce_buffer(_state, _buffer), ""),
"punctuation": ("underscore", _flush_ce_buffer(_state, _buffer), ""),
"num_script": ("underscore", _flush_ce_buffer(_state, _buffer), ""),
"caret": ("underscore", _flush_ce_buffer(_state, _buffer), "")
).at(_state, default: (_state, _out, _buffer))
}
// on closing brackets...
if _char_in.contains(regex("[)}\]]")) {
(_state, _out, _buffer) = (
"_": ("", "", "")
).at(_state, default: ("punctuation", _flush_ce_buffer(_state, _buffer), ""))
}
// on opening brackets...
if _char_in.contains(regex("[\[({]")) {
(_state, _out, _buffer) = (
"_": ("", "", "")
).at(_state, default: ("leading_punctuation", _flush_ce_buffer(_state, _buffer), ""))
}
// isotope parsing
if _char_in.contains(regex("@")) {
(_state, _out, _buffer) = (
"isotope?": ("", _flush_ce_buffer(_state, _buffer + _char_in), "")
).at(_state, default: ("isotope?", _out, _buffer))
if _state != "isotope?" {
return (_state, _out, _buffer)
}
}
_buffer = _buffer + _char_in
return (_state, _out, _buffer)
}
// higher level parser which parses strings in a larger context
// replaces specific components with content that can be directly output
#let _fill_computed_ce_content(s) = { // (str) -> array(str | content)
let result = (s,)
for symbol in sym_map.values() {
// text over arrow with xarrow
let decorated_arrow_result = result
for r in result {
if type(r) != "string" {
continue
}
// match arrow with top and bottom text
let decorated_arrow_matches = r.matches(regex(symbol + "\[([^\]]+)\]\[([^\]]+)\]"))
for decorated_arrow_match in decorated_arrow_matches {
decorated_arrow_result = _replace_with_content(decorated_arrow_result, replace: decorated_arrow_match.text, content: [
#xarrow(sym: symbol, margin: 0.5em, [
$upright(#eval("$" + decorated_arrow_match.captures.at(0) + "$"))$
], opposite: [
$upright(#eval("$" + decorated_arrow_match.captures.at(1) + "$"))$
]
)
])
}
// match arrow with top only text
let decorated_arrow_matches = r.matches(regex(symbol + "\[([^\]]+)\]"))
for decorated_arrow_match in decorated_arrow_matches {
decorated_arrow_result = _replace_with_content(decorated_arrow_result, replace: decorated_arrow_match.text, content: [
#xarrow(sym: symbol, margin: 0.5em, [
$upright(#eval("$" + decorated_arrow_match.captures.at(0) + "$"))$
])
])
}
}
result = decorated_arrow_result
// lengthen arrow with xarrow
result = _replace_with_content(result, replace: symbol, content: [
#xarrow(sym: symbol, margin: 0.8em, [])
])
}
return result
}
// primary entrypoint for end user
// first runs through low level state machine parser, then applies higher level replacement
#let ce(t, debug: false) = { // (str, bool) -> content
assert(type(t) == "string", message: "ce: argument must be of type `string`")
let state = ""
for (pattern, result) in sym_map {
t = t.replace(regex(pattern), " " + result)
}
t = t + " " // append a space to ensure the state machine is reset and output buffer cleared
let buffer = ""
let out = ""
let result = ""
// iterate through the string
for c in t.codepoints() {
(state, out, buffer) = _parse_ce(state, c, buffer)
result += out
}
if debug {
return raw(result)
}
// convert string to content
for result_sub_str in _fill_computed_ce_content(result) {
if type(result_sub_str) == "string" {
result_sub_str = "$" + result_sub_str + "$"
$upright(#eval(result_sub_str))$
} else if type(result_sub_str) == "content" {
result_sub_str
}
}
}
|
https://github.com/Dioprz/Notes | https://raw.githubusercontent.com/Dioprz/Notes/main/Scala/Functional_Programming_in_Scala/README.md | markdown | Aviso:
He decidido dejar de trabajar en estas notas temporalmente. La industria no está solicitando muchos desarrolladores de Scala debido a la turbulencia que tiene el ecosistema. Posiblemente lo retome cuando tenga tiempo, ya que el libro es excelente y Scala, conceptualmente, ha sido un lenguaje muy interesante de explorar.
______________________________________________________________________
Las siguientes anotaciones son una compilación de los conceptos e ideas clave que capturaron mi interés durante la lectura del libro *Functional Programming in Scala*, escrito por *<NAME>* y *<NAME>*.
El lenguaje de marcado que usé para tomarlas se llama *Typst*, un [lenguaje nuevo](https://typst.app/docs/) que poco a poco adquiere la potencia de *LaTeX*, pero con una sintaxis tan cómoda y legible (o más) que la de Markdown. Debido a que GitHub no tiene renderización nativa para este formato, dejo como opción para leer las notas tanto el código como el pdf compilado.
También dejo un archivo `.scala` con las soluciones de algunos ejercicios de cada capítulo.
En caso de encontrar algún error en las notas, apreciaría mucho si crea un nuevo asunto para hacérmelo saber.
|
|
https://github.com/rem3-1415926/Typst_Thesis_Template | https://raw.githubusercontent.com/rem3-1415926/Typst_Thesis_Template/main/sec/acknowledgement.typ | typst | MIT License |
#let acknowledgement = [
= Acknowledgement
I would like to thank
- *Bill*, for being a supreme engineer
- *Bob*, for being an amazing scientist
] |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/lemmify/0.1.0/src/lib.typ | typst | Apache License 2.0 | #import "util.typ": *
#import "styles.typ": *
#import "translations.typ": *
// Transform theorem function into
// proof function. That is decrease
// the numbering by one.
#let use-proof-numbering(theorem-func) = {
let numb = n => numbering(theorem-func()[].numbering, n - 1)
return theorem-func.with(numbering: numb)
}
// Creates a selector for all theorems of
// the specified group. If subgroup is
// specified, only the theorems belonging to it
// will be selected.
#let thm-selector(group, subgroup: none) = {
if subgroup == none {
figure.where(kind: group)
} else {
figure.where(kind: group, supplement: [#subgroup])
}
}
// Reset theorem group counter to zero.
#let thm-reset-counter(group) = {
counter(thm-selector(group)).update(c => 0)
}
// Reset counter of specified theorem group
// on headings of the specified level
#let thm-reset-counter-heading-at(
group,
level,
content
) = {
show heading.where(level: level): it => {
thm-reset-counter(group)
it
}
content
}
// Reset counter of specified theorem group
// on headings with at most the specified level.
#let thm-reset-counter-heading(
group,
max-level,
content
) = {
let rules = range(1, max-level + 1).map(
k => thm-reset-counter-heading-at.with(group, k)
)
show: concat-fold(rules)
content
}
// Creates new theorem functions and
// a styling rule from a mapping (subgroup: args)
// and the style parameters.
// The args of each subgroup will be passed
// into thm-styling and ref-styling.
#let new-theorems(
group,
subgroup-map,
thm-styling: thm-style-simple,
thm-numbering: thm-numbering-heading,
ref-styling: thm-ref-style-simple,
ref-numbering: none
) = {
let helper-rule(subgroup, content) = {
show thm-selector(
group,
subgroup: subgroup
): thm-style.with(
thm-styling.with(subgroup-map.at(subgroup)),
thm-numbering
)
let numbering = if ref-numbering != none {
ref-numbering
} else {
thm-numbering
}
show: thm-ref-style.with(
group,
subgroups: subgroup,
ref-styling.with(subgroup-map.at(subgroup), numbering)
)
content
}
let rules(content) = {
show: concat-fold(subgroup-map.keys().map(sg => helper-rule.with(sg)))
content
}
let result = (:)
for (subgroup, _) in subgroup-map {
result.insert(subgroup, new-thm-func(group, subgroup))
}
result.insert("rules", rules)
return result
}
// Create a default set of theorems based
// on the language and given styling.
#let default-theorems(
group,
lang: "en",
thm-styling: thm-style-simple,
proof-styling: thm-style-proof,
thm-numbering: thm-numbering-heading,
ref-styling: thm-ref-style-simple,
max-reset-level: 2
) = {
let (proof, ..subgroup-map) = translations.at(lang)
let (rules: rules-theorems, ..theorems) = new-theorems(
group,
subgroup-map,
thm-styling: thm-styling,
thm-numbering: thm-numbering
)
let (rules: rules-proof, proof) = new-theorems(
group,
(proof: translations.at(lang).at("proof")),
thm-styling: proof-styling,
thm-numbering: thm-numbering-proof,
ref-numbering: thm-numbering
)
return (
..theorems,
proof: use-proof-numbering(proof),
rules: concat-fold((
thm-reset-counter-heading.with(group, max-reset-level),
rules-theorems,
rules-proof
))
)
}
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/matrix_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 13-14 expected array, found content
// $ mat(1, 2; 3, 4, delim: "[") $, |
https://github.com/eliapasquali/typst-thesis-template | https://raw.githubusercontent.com/eliapasquali/typst-thesis-template/main/preface/copyright.typ | typst | Other | #import "../config/variables.typ" : myName, myTitle, myDegree, myTime
#set page(numbering: none)
#align(left + bottom, [
#text(myName): #text(style: "italic", myTitle), #text(myDegree), #sym.copyright #text(myTime)
]) |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/enum-align-00.typ | typst | Other | // Alignment shouldn't affect number
#set align(horizon)
+ ABCDEF\ GHIJKL\ MNOPQR
+ INNER\ INNER\ INNER
+ BACK\ HERE
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/enum-04.typ | typst | Other | // In the line.
1.2 \
This is 0. \
See 0.3. \
|
https://github.com/ShapeLayer/ucpc-solutions__typst | https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/tests/utils_problem/test.typ | typst | Other | #import "/lib/lib.typ" as ucpc
#import ucpc.presets: difficulties as lv
#ucpc.utils.problem(
id: "A",
title: "Problem A",
tags: ("implementation", "graph_theory", ),
difficulty: lv.easy,
authors: ([Author a], ),
stat-open: (
submit-count: 10
),
i18n: ucpc.i18n.en-us.problem,
[
- Magna eu tempor sunt sint laboris nulla culpa labore et quis tempor ad labore ex eiusmod aliquip culpa et incididunt consectetur nostrud velit velit eu magna excepteur ut occaecat cillum aute mollit duis tempor ea officia ex reprehenderit anim eiusmod fugiat adipisicing anim ex do exercitation est anim aliqua irure ullamco tempor irure laboris elit deserunt esse laboris magna ullamco do culpa et ut cillum magna irure Lorem aute sit anim reprehenderit nostrud incididunt officia laborum sint sint adipisicing sint mollit labore excepteur est mollit culpa aliqua duis fugiat nostrud duis sint commodo aliqua proident est incididunt fugiat et irure.
]
)
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/note.md | markdown | ---
# title: "Markdown Style Guide"
# description: "Here is a sample of some basic Markdown syntax that can be used when writing Markdown content in Astro."
# pubDate: "Jul 01 2024"
# image: "/index.webp"
# categories:
# - tech
# tags:
# - Makrdown
# badge: Guide
---
- 很多笔记都是用 typst 写的而不是 md,由于 typst 是个比较新兴的标记语言,对 html 导出做得不够好(或者说官方压根还不支持)。使用社区自制方案以 svg 导出,会有明显的卡顿。
- 同时,目前也没有足够好的像 Mkdocs 之于 Markdown 那样的模板。
<!-- Here is a sample of some basic Markdown syntax that can be used when writing Markdown content in Astro.
## Headings
The following HTML `<h1>`—`<h6>` elements represent six levels of section headings. `<h1>` is the highest section level while `<h6>` is the lowest.
# H1
## H2
### H3
#### H4
##### H5
###### H6
## Paragraph -->
<!-- Xerum, quo qui aut unt expliquam qui dolut labo. Aque venitatiusda cum, voluptionse latur sitiae dolessi aut parist aut dollo enim qui voluptate ma dolestendit peritin re plis aut quas inctum laceat est volestemque commosa as cus endigna tectur, offic to cor sequas etum rerum idem sintibus eiur? Quianimin porecus evelectur, cum que nis nust voloribus ratem aut omnimi, sitatur? Quiatem. Nam, omnis sum am facea corem alique molestrunt et eos evelece arcillit ut aut eos eos nus, sin conecerem erum fuga. Ri oditatquam, ad quibus unda veliamenimin cusam et facea ipsamus es exerum sitate dolores editium rerore eost, temped molorro ratiae volorro te reribus dolorer sperchicium faceata tiustia prat.
Itatur? Quiatae cullecum rem ent aut odis in re eossequodi nonsequ idebis ne sapicia is sinveli squiatum, core et que aut hariosam ex eat.
## Images
#### Syntax
```markdown mockup-code

```
#### Output

## Blockquotes
The blockquote element represents content that is quoted from another source, optionally with a citation which must be within a `footer` or `cite` element, and optionally with in-line changes such as annotations and abbreviations.
### Blockquote without attribution
#### Syntax
```markdown
> Tiam, ad mint andaepu dandae nostion secatur sequo quae.
> **Note** that you can use _Markdown syntax_ within a blockquote.
```
#### Output
> Tiam, ad mint andaepu dandae nostion secatur sequo quae.
> **Note** that you can use _Markdown syntax_ within a blockquote.
### Blockquote with attribution
#### Syntax
```markdown
> Don't communicate by sharing memory, share memory by communicating.<br>
> — <cite><NAME>[^1]</cite>
```
#### Output
> Don't communicate by sharing memory, share memory by communicating.<br>
> — <cite><NAME>[^1]</cite>
[^1]: The above quote is excerpted from <NAME>'s [talk](https://www.youtube.com/watch?v=PAAkCSZUG1c) during Gopherfest, November 18, 2015.
## Tables
#### Syntax
```markdown
| Italics | Bold | Code |
| --------- | -------- | ------ |
| _italics_ | **bold** | `code` |
```
#### Output
| Italics | Bold | Code |
| --------- | -------- | ------ |
| _italics_ | **bold** | `code` |
## Code Blocks
#### Syntax
we can use 3 backticks ``` in new line and write snippet and close with 3 backticks on new line and to highlight language specific syntac, write one word of language name after first 3 backticks, for eg. html, javascript, css, markdown, typescript, txt, bash
````markdown
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n, k, a[N];
long long ans;
vector<int> v[N];
int main()
{
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
v[i % k].push_back(a[i]);
}
for (int i = 0; i < k; i++)
sort(v[i].rbegin(), v[i].rend());
for (int i = 0; i < k; i++)
{
for (int j = 0; j + 1 < v[i].size(); j += 2)
{
ans += v[i][j] + v[i][j + 1];
}
}
printf("%lld\n", ans);
return 0;
}
```
````
Output
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n, k, a[N];
long long ans;
vector<int> v[N];
int main()
{
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
v[i % k].push_back(a[i]);
}
for (int i = 0; i < k; i++)
sort(v[i].rbegin(), v[i].rend());
for (int i = 0; i < k; i++)
{
for (int j = 0; j + 1 < v[i].size(); j += 2)
{
ans += v[i][j] + v[i][j + 1];
}
}
printf("%lld\n", ans);
return 0;
}
```
## List Types
### Ordered List
#### Syntax
```markdown
1. First item
2. Second item
3. Third item
```
#### Output
1. First item
2. Second item
3. Third item
### Unordered List
#### Syntax
```markdown
- List item
- Another item
- And another item
```
#### Output
- List item
- Another item
- And another item
### Nested list
#### Syntax
```markdown
- Fruit
- Apple
- Orange
- Banana
- Dairy
- Milk
- Cheese
```
#### Output
- Fruit
- Apple
- Orange
- Banana
- Dairy
- Milk
- Cheese
## Other Elements — abbr, sub, sup, kbd, mark
#### Syntax
```markdown
<abbr title="Graphics Interchange Format">GIF</abbr> is a bitmap image format.
H<sub>2</sub>O
X<sup>n</sup> + Y<sup>n</sup> = Z<sup>n</sup>
Press <kbd><kbd>CTRL</kbd>+<kbd>ALT</kbd>+<kbd>Delete</kbd></kbd> to end the session.
Most <mark>salamanders</mark> are nocturnal, and hunt for insects, worms, and other small creatures.
```
#### Output
<abbr title="Graphics Interchange Format">GIF</abbr> is a bitmap image format.
H<sub>2</sub>O
X<sup>n</sup> + Y<sup>n</sup> = Z<sup>n</sup>
Press <kbd><kbd>CTRL</kbd>+<kbd>ALT</kbd>+<kbd>Delete</kbd></kbd> to end the session.
Most <mark>salamanders</mark> are nocturnal, and hunt for insects, worms, and other small creatures. -->
|
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/snippets/text/individual_lang_fonts.md | markdown | MIT License | # Individual language fonts
```typ
A cat แปลว่า แมว
#show regex("\p{Thai}+"): text.with(font: "Noto Serif Thai")
A cat แปลว่า แมว
```
|
https://github.com/Akida31/anki-typst | https://raw.githubusercontent.com/Akida31/anki-typst/main/typst/doc/example2.typ | typst | #import "../src/lib.typ" as anki
#set page(width: 16cm, height: auto, margin: 1cm)
// remove until here for doc
#import anki: anki_export
#anki_export(
id: "id 29579",
tags: ("Perfect", ),
deck: "beauty",
model: "simple",
question: "Are you beautiful?",
answer: "Yes!",
)
|
|
https://github.com/ammar-ahmed22/compile-typst-example | https://raw.githubusercontent.com/ammar-ahmed22/compile-typst-example/main/src/calculus.typ | typst | #set heading(numbering: "1.1.1")
= Calculus
== Derivatives
Derivatives are defined as the sensitivity to change in a functions output given a certain input. In other words, the value of the derivative at a given point in the domain of the function will be equal to the slope of tangent line at that point of the function. \
A more useful and understandble example would be in relation to speed and acceleration. Speed is how fast something is moving. Acceleration is how fast the thing is increasing or decreasing in speed. Therefore, acceleration is the derivative of speed. A higher acceleration would mean the speed is getting bigger, faster.
=== Power Rule
The power rule is used to find the derivative of a function, $f(x) = x^n$, where n is a real number. \
The power rule is defined as:
$
dif / (dif x) x^n = n x^(n-1)
$
The power rule can be used to differentiate polynomials as well. This is because polynomials are simply a linear combination of functions of the form, $f(x) = x^n$.
As an example, we can try differentiating the function:
$
p(x) = x^4 + 7x^3 - 3x^2 + 8x - 9 \
dif / (dif x) p(x) = 4x^3 + 21x^2 + 8
$
=== Product Rule
The chain rule is used to find derivatives in which there are two separable functions that are multiplied. As in, $f(x) = g(x)h(x)$. The rule states:
$
dif / (dif x) [g(x) dot h(x)] = g'(x) dot h(x) + g(x) dot h'(x)
$
_*NOTE*: $f'(x) = dif / (dif x) f(x)$_
For example, let's say we have the function, $f(x) = (3 - x^2)(x + 4)$. We can start off by separating these both into their own functions:
$
g(x) = 3 - x^2 \
h(x) = x + 4 \
f(x) = g(x) dot h(x)
$
Next, we can find both of their respective derivatives:
$
g'(x) = -2x \
h'(x) = 1 \
$
From this, we can apply the product rule:
$
f'(x) &= g'(x) dot h(x) + g(x) dot h'(x) \
&= -2x(x + 4) + (3 - x^2)(1) \
&= -2x^2 -8x + 3 - x^2 \
&= -3x^2 -8x + 3
$
== Integrals
The integral of a function is defined as the area under/above the curve for a function up to the x-axis. It is also the inverse operation of a derivative. \
Going back to our speed example, to find the speed given the acceleration, you would find the integral of the acceleration. \
There are 2 types of integrals; definite and indefinite. Definite integrals are for finding the area under/above the curve in between 2 specified values in the domain of the function, $a$ and $b$. Definite integrals are denoted as:
$
integral^a_b f(x)
$
Indefinite integrals are an expression for the general integration of the function. Indefinite integrals are the inverse of the derivative.
$
f(x) + C = integral f'(x)
$
where $C$ is a constant that is added because there may have been a constant term in the function that become zero when it was differentiated.
|
|
https://github.com/OpenCorvallis/osfc-checklists | https://raw.githubusercontent.com/OpenCorvallis/osfc-checklists/main/66083.typ | typst | Apache License 2.0 | // Copyright 2024 Oregon State Flying Club
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://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.
// 73146.typ is more extensively commented, check there first for design notes.
#import "common.typ": checklist, checklist_group
// -----------------------------------------------------------------------------
// Ground Checklists and Information page
// -----------------------------------------------------------------------------
#let ground_checklists_and_info = [
]
// -----------------------------------------------------------------------------
// Operating Checklists
// -----------------------------------------------------------------------------
#let operating_checklists = [
]
// -----------------------------------------------------------------------------
// Emergency Checklists (left side)
// -----------------------------------------------------------------------------
#let left_emergency_checklists = [
]
// -----------------------------------------------------------------------------
// Emergency Checklists (right side)
// -----------------------------------------------------------------------------
#let right_emergency_checklists = [
]
// -----------------------------------------------------------------------------
// Page definitions and formatting
// -----------------------------------------------------------------------------
#let margins = 6mm
#page(flipped: true, margin: margins, paper: "us-letter")[
#columns(2, gutter: 2*margins)[
= Ground Checklists and Information #h(1fr) N66083
#columns(2)[
#set text(6pt)
#ground_checklists_and_info
]
#v(1fr)
= Version 1 #h(1fr) #include "signature.typ"
#colbreak()
= Operating Checklists #h(1fr) N66083
#columns(2)[
#set text(9pt)
#operating_checklists
]
]
]
#page(flipped: true, margin: margins, paper: "us-letter")[
#columns(2, gutter: 2*margins)[
#box(fill: red, width: 100%,
align(center, box(fill: white, outset: 1em)[= Emergency Checklists]))
#v(-.5em)
#columns(2, gutter: 2mm)[
#set text(6pt)
#left_emergency_checklists
]
#colbreak()
#box(fill: red, width: 100%,
align(center, box(fill: white, outset: 1em)[= Emergency Checklists]))
#v(-.5em)
#columns(2, gutter: 2mm)[
#set text(6pt)
#right_emergency_checklists
]
]
]
|
https://github.com/KNnut/neoplot | https://raw.githubusercontent.com/KNnut/neoplot/main/pkg/neoplot.typ | typst | BSD 3-Clause "New" or "Revised" License | #let gp = plugin("neoplot.wasm")
#let get-text(it) = {
if type(it) == str {
it
} else if type(it) == content {
if it.has("text") {
it.text
} else {
panic("Content must contain field `text`")
}
} else {
panic("Invalid type `" + type(it) + "`")
}
}
#let get-svg-image(..args) = image.decode(format: "svg", ..args)
#let bridge(code, kind) = {
let arg = cbor.encode(
(
code: code,
type: kind,
)
)
let output = gp.exec(arg)
let (
print_output: print-output,
term_output: term-output,
) = cbor.decode(output)
(
print-output,
term-output,
)
}
#let term-format = ("image", "string", "bytes")
#let exec(
it,
kind: "script",
format: auto,
..args,
) = {
if kind not in ("script", "command") {
panic("Invalid code type `" + kind + "`")
}
if format == none {
return
}
let code = get-text(it)
if code.len() == 0 {
return
}
if format == auto {
return {
let (
print-output,
term-output,
) = bridge(code, kind)
if term-output != none {
get-svg-image(term-output.last(), ..args)
} else if print-output != none {
str(print-output)
}
}
}
format = (format,).flatten().map(fmt => {
if fmt == image {
"image"
} else if fmt in (str, "str") {
"string"
} else if fmt == bytes {
"bytes"
} else {
fmt
}
}).dedup()
for fmt in format {
if fmt not in ("print", ..term-format) {
panic("Invalid format `" + fmt + "`")
}
}
let result = (:)
for fmt in format {
let (
print-output,
term-output,
) = bridge(code, kind)
result.insert(fmt,
if fmt in term-format and term-output == none {
panic("No terminal output")
} else if fmt == "image" {
term-output.map(data => get-svg-image(data, ..args))
} else if fmt == "string" {
term-output.map(str)
} else if fmt == "bytes" {
term-output
} else if fmt == "print" {
if print-output == none {
panic("No print output")
}
str(print-output)
}
)
}
if result.len() == 1 {
result.values().first()
} else {
result
}
}
|
https://github.com/LDemetrios/Svart | https://raw.githubusercontent.com/LDemetrios/Svart/main/logo.typ | typst | #import "@preview/cetz:0.2.2"
#let logo(back:rgb("#08053f")) = cetz.canvas({
import cetz.draw: *
content(
(0, 0),
block(
radius: 50%,
width: 10cm,
height: 10cm,
clip: true,
image("gold.png", width: 10cm, height: 10cm),
),
)
let sh = .7
let letter = {
bezier((2.1, -0.3 + sh), (.25, 3.7), (13 / 20, 2))
line((-.7, 3.3), (.25, 3.7))
bezier((-.7, 3.3), (-.25, -.9 - sh - .2), (-6 / 20, 1 / 4))
bezier((-.25, -.9 - sh - .2), (-1.7, 0.7 - sh), (-0.8, -0.8))
line((-1.7, 0.7 - sh), (-2.1, 0.3 - sh))
bezier((-2.1, 0.3 - sh), (-.25, -3.7), (-13 / 20, -2))
line((-.25, -3.7), (.7, -3.3))
bezier((.7, -3.3), (.25, .9 + sh + .2), (6 / 20, -1 / 4))
bezier((.25, .9 + sh + .2), (1.7, -0.7 + sh), (0.8, 0.8))
line((1.7, -0.7 + sh), (2.1, -0.3 + sh))
}
merge-path(
letter + circle((0, 0), radius: 5, stroke: rgb("#2c2b1e") + .15cm),
fill: back,
stroke: none,
)
circle((0, 0), radius: 5, stroke: rgb("#2c2b1e") + .15cm)
merge-path(
letter,
stroke: (paint: rgb("#2c2b1e"), thickness: .1cm, cap: "round"),
)
})
#set page(height: auto, width: auto)
#logo()
|
|
https://github.com/eduardz1/Bachelor-Thesis | https://raw.githubusercontent.com/eduardz1/Bachelor-Thesis/main/utils/template.typ | typst | #let project(
title: "",
subtitle: "",
abstract: [],
keywords: [],
acknowledgments: none,
declaration-of-originality: none,
affiliation: (),
candidate: (),
supervisor: "",
cosupervisor: "",
date: none,
logo: none,
paper-size: "us-letter",
bibliography-file: none,
body,
) = {
// Set the document's basic properties.
set document(author: candidate.name, title: title)
set text(font: "New Computer Modern", lang: "en", size: 10pt)
set page(
paper: paper-size,
margin: (right: 3cm, left: 3.5cm, top: 3.5cm, bottom: 3.5cm),
)
// Outline customization
show outline.entry.where(level: 1): it => {
if it.body != [References] {
v(12pt, weak: true)
link(it.element.location(), strong({
it.body
h(1fr)
it.page
}))}
else {
text(size: 1em, it)
}
}
show outline.entry.where(level: 3): it => {
text(size: 0.8em, it)
}
// Configure equation numbering and spacing.
show math.equation: set block(spacing: 0.65em)
// Configure raw text/code blocks
show raw.where(block: true): set text(size: 0.8em, font: "FiraCode Nerd Font")
show raw.where(block: true): set par(justify: false)
set raw(syntaxes: (
"../resources/syntaxes/smol.sublime-syntax",
"../resources/syntaxes/sparql.sublime-syntax",
"../resources/syntaxes/turtle.sublime-syntax",
))
show raw.where(block: true): block.with(
fill: gradient.linear(luma(240), luma(245), angle: 270deg),
inset: 10pt,
radius: 4pt,
width: 100%,
)
show raw.where(block: false): box.with(
fill: gradient.linear(luma(240), luma(245), angle: 270deg),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// Figures
show figure.caption: set text(size: 0.8em)
// Configure lists and enumerations.
set enum(indent: 10pt, body-indent: 9pt)
set list(indent: 10pt, body-indent: 9pt, marker: ([•], [--]))
// Configure headings.
set heading(numbering: "1.a.I")
show heading.where(level: 1): it => {
if it.body != [References] {
block(width: 100%, height: 20%)[
#set align(center + horizon)
#set text(1.3em, weight: "bold")
#smallcaps(it)
]
} else {
block(width: 100%, height: 10%)[
#set align(center + horizon)
#set text(1.1em, weight: "bold")
#smallcaps(it)
]
}
}
show heading.where(level: 2): it => block(width: 100%)[
#set align(center)
#set text(1.1em, weight: "bold")
#smallcaps(it)
]
show heading.where(level: 3): it => block(width: 100%)[
#set align(left)
#set text(1em, weight: "bold")
#smallcaps(it)
]
// Title page
set align(center)
[
#text(1.5em, weight: "bold", affiliation.university) \
#text(1.2em, spacing: 182%, affiliation.school) \
#text(1.2em, spacing: 213%, affiliation.degree)
]
v(30pt)
image(logo, width: 40%)
v(30pt)
text(1.5em, subtitle)
v(1em, weak: true)
text(2em, weight: 700, title)
v(40pt)
grid(columns: 2, gutter: 14em, [
#set align(left)
#smallcaps("supervisor") \
*#supervisor* \ \
#smallcaps("co-supervisors") \
*#cosupervisor*
], [
#set align(left)
\ \ \
#smallcaps("candidate") \
*#candidate.name* \
#candidate.id
])
v(53pt)
text(1.2em, date)
set par(justify: true, first-line-indent: 1em)
pagebreak()
pagebreak()
set align(center + horizon)
// Declaration of originality
heading(
level: 2,
numbering: none,
outlined: false,
"Declaration of Originality",
)
text(style: "italic", [
“#declaration-of-originality”
])
pagebreak()
// acknowledgments
heading(level: 2, numbering: none, outlined: false, "Acknowledgments")
acknowledgments
pagebreak()
// Abstract
counter(page).update(0)
heading(level: 2, numbering: none, "Abstract")
abstract
heading(level: 2, numbering: none, outlined: false, "Keywords")
keywords
pagebreak()
pagebreak()
// Table of contents.
outline(depth: 3, indent: true)
pagebreak()
pagebreak()
// Main body
set page(numbering: "1")
set align(top + left)
body
pagebreak()
// Bibliography
if bibliography-file != none {
heading(level: 1, numbering: none, "References")
show bibliography: set text(0.9em)
bibliography(bibliography-file, title: none)
}
} |
|
https://github.com/SillyFreak/typst-packages-old | https://raw.githubusercontent.com/SillyFreak/typst-packages-old/main/pre-plantuml/gallery/test.typ | typst | MIT License | // make the PDF reproducible to ease version control
#set document(date: none)
#import "../src/lib.typ": plantuml-url, plantuml-source
#import "@preview/prequery:0.1.0"
// #import "@preview/pre-plantuml:0.0.1": plantuml-url, plantuml-source
// toggle this comment or pass `--input prequery-fallback=true` to enable fallback
// #prequery.fallback.update(true)
#let plantuml = plantuml-url.with("https://www.plantuml.com/plantuml/png/")
= Test
#plantuml("assets/uml.png", ```
@startuml
PUML -> RUST: HELLO
@enduml
```)
#plantuml-source("assets/uml.png", ```
@startuml
PUML -> RUST: HELLO
@enduml
```)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/packages/typst.ts/README.md | markdown | Apache License 2.0 | # Typst.ts
Usage:
```typescript
import { $typst } from '@myriaddreamin/typst.ts/dist/esm/contrib/snippet.mjs';
console.log(
(
await $typst.svg({
mainContent: 'Hello, typst!',
})
).length,
);
// :-> 7317
```
See [Typst.ts](https://github.com/Myriad-Dreamin/typst.ts) and documentation for details:
- [Get Started](https://myriad-dreamin.github.io/typst.ts/cookery/get-started.html)
- [Compiler interfaces](https://myriad-dreamin.github.io/typst.ts/cookery/guide/compilers.html)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/features_06.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test extra number stuff.
#set text(font: "IBM Plex Serif")
0 vs. #text(slashed-zero: true)[0] \
1/2 vs. #text(fractions: true)[1/2]
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/软件分析/hw/2100012990-郭子荀-软分第六次作业.typ | typst | #import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark
#import "../../template.typ": *
#show: note.with(
title: "作业5",
author: "YHTQ",
date: datetime.today().display(),
logo: none,
withOutlined : false,
withTitle : false,
withHeadingNumbering: false
)
= #empty
```c
x -= 1;
y += 1;
while(y < z){
x *= -100;
y += 1;
}
```
datalog 规则为:
```datalog
out(x, entry, negative)
out(y, entry, zero)
out(z, entry, positive)
out(x, exit, ?)
out(y, exit, ?)
out(z, exit, ?)
edge(entry, 1),
edge(1, 2),
edge(2, 3),
edge(3, 4),
edge(4, 5),
edge(5, 3),
edge(3, exit)
out(x, 1, positive) :- in(x, 1, positive)
out(x, 1, zero) :- in(x, 1, positive)
out(x, 1, negative) :- in(x, 1, negative)
out(x, 1, negative) :- in(x, 1, zero)
out(y, 1, s) :- in(y, 1, s)
out(z, 1, s) :- in(z, 1, s)
out(v, 3, s) :- in(v, 3, s)
out(y, 2, positive) :- in(y, 2, positive)
out(y, 2, positive) :- in(y, 2, zero)
out(y, 2, negative) :- in(y, 2, negative)
out(y, 2, zero) :- in(y, 2, negative)
out(x, 2, s) :- in(x, 2, s)
out(z, 2, s) :- in(z, 2, s)
out(x, 4, positive) :- in(x, 4, negative)
out(x, 4, negative) :- in(x, 4, positive)
out(x, 4, zero) :- in(x, 4, zero)
out(y, 4, s) :- in(y, 4, s)
out(z, 4, s) :- in(z, 4, s)
out(y, 5, positive) :- in(y, 5, positive)
out(y, 5, positive) :- in(y, 5, zero)
out(y, 5, negative) :- in(y, 5, negative)
out(y, 5, zero) :- in(y, 5, negative)
out(x, 5, s) :- in(x, 5, s)
out(z, 5, s) :- in(z, 5, s)
in(var, v, v1) :- edge(v1, v), out(var, v1, s)
```
这样的分析变得更精确了,例如在该例中,关于 $x$ 最终可以得到:
```datalog
out(x, exit, positive)
out(x, exit, negative)
```
也就是要么正要么负,但在通常的数据流分析中只能得到 $x$ 为槑
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/modern-sysu-thesis/0.1.0/README.md | markdown | Apache License 2.0 | # 基于 Typst 的中山大学学位论文模板
[](https://gitlab.com/sysu-gitlab/thesis-template/better-thesis)
[](https://github.com/sysu/better-thesis)
当前还未完全符合学位论文格式要求,欢迎同学们贡献代码!模板交流 QQ 群:797942860([点此直接加入](https://jq.qq.com/?_wv=1027&k=m58va1kd))
**Q:我不会 LaTeX,可以用这个模板写论文吗?**
**A:完全可以!Typst 是一个比 LaTeX 更简单的排版语言,同时安装更加方便,编译更加快速!**
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/attach-p3_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test default of limit attachments on relations at all sizes
#set page(width: auto)
$ a =^"def" b quad a lt.eq_"really" b quad a arrow.r.long.squiggly^"slowly" b $
$a =^"def" b quad a lt.eq_"really" b quad a arrow.r.long.squiggly^"slowly" b$
$a scripts(=)^"def" b quad a scripts(lt.eq)_"really" b quad a scripts(arrow.r.long.squiggly)^"slowly" b$
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/grid-3_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test a column that starts overflowing right after another row/column did
// that.
#set page(width: 5cm, height: 2cm)
#grid(
columns: 4 * (1fr,),
row-gutter: 10pt,
column-gutter: (0pt, 10%),
align(top, image("/assets/files/rhino.png")),
align(top, rect(inset: 0pt, fill: eastern, align(right)[LoL])),
[rofl],
[\ A] * 3,
[Ha!\ ] * 3,
)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/linebreak_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test two overlong words in a row.
Supercalifragilisticexpialidocious Expialigoricmetrioxidation.
|
https://github.com/cran/tinytable | https://raw.githubusercontent.com/cran/tinytable/master/inst/tinytest/_tinysnapshot/group_tt-3level.typ | typst | #show figure: set block(breakable: true)
#figure( // start figure preamble
kind: "tinytable",
supplement: "Table", // end figure preamble
block[ // start block
#let nhead = 4;
#let nrow = 3;
#let ncol = 5;
#let style-array = (
// tinytable cell style after
)
// tinytable align-default-array before
#let align-default-array = ( left, left, left, left, left, ) // tinytable align-default-array here
#show table.cell: it => {
let tmp = it
let data = style-array.find(data => data.x.contains(it.x) and data.y.contains(it.y))
if data != none {
if data.fontsize != none { tmp = text(size: data.fontsize, tmp) }
if data.color != none { tmp = text(fill: data.color, tmp) }
if data.indent != none { tmp = pad(left: data.indent, tmp) }
if data.underline != none { tmp = underline(tmp) }
if data.italic != none { tmp = emph(tmp) }
if data.bold != none { tmp = strong(tmp) }
if data.mono != none { tmp = math.mono(tmp) }
if data.strikeout != none { tmp = strike(tmp) }
tmp
} else {
tmp
}
}
#align(center, [
#table( // tinytable table start
column-gutter: 5pt,
columns: (auto, auto, auto, auto, auto),
stroke: none,
align: (x, y) => {
let data = style-array.find(data => data.x.contains(x) and data.y.contains(y))
if data != none and data.align != none {
data.align
} else {
left
}
},
fill: (x, y) => {
let data = style-array.find(data => data.x.contains(x) and data.y.contains(y))
if data != none and data.background != none {
data.background
}
},
table.hline(y: 4, start: 0, end: 5, stroke: 0.05em + black),
table.hline(y: 7, start: 0, end: 5, stroke: 0.1em + black),
table.hline(y: 0, start: 0, end: 5, stroke: 0.1em + black),
// tinytable lines before
table.header(
repeat: true,
table.cell(stroke: (bottom: .05em + black), colspan: 3, align: center)[e],table.cell(stroke: (bottom: .05em + black), colspan: 1, align: center)[f],[ ],
table.cell(stroke: (bottom: .05em + black), colspan: 2, align: center)[c],table.cell(stroke: (bottom: .05em + black), colspan: 3, align: center)[d],
[ ],table.cell(stroke: (bottom: .05em + black), colspan: 2, align: center)[a],table.cell(stroke: (bottom: .05em + black), colspan: 2, align: center)[b],
[mpg], [cyl], [disp], [hp], [drat],
),
// tinytable cell content after
[21.0], [6], [160], [110], [3.90],
[21.0], [6], [160], [110], [3.90],
[22.8], [4], [108], [ 93], [3.85],
// tinytable footer before
) // end table
]) // end align
] // end block
) // end figure
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/deco_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test a tighter highlight.
#set highlight(top-edge: "x-height", bottom-edge: "baseline")
#highlight[ace],
#highlight[base],
#highlight[super],
#highlight[phone #sym.integral]
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/repr-00.typ | typst | Other | // Literal values.
#auto \
#none (empty) \
#true \
#false
|
https://github.com/Entoryvekum/TypstTemplate | https://raw.githubusercontent.com/Entoryvekum/TypstTemplate/main/MathBasic/0.1.0/template.typ | typst | #let scr(body) = {
set text(
font: "STIX Two Math",
stylistic-set: 1
)
$cal(body)$
}
#let mbb(body) = {
$bb(#upper(body))$
}
#let ubold(body) = {
$upright(bold(body))$
}
#let boxed(body) = {
show math.equation: it => {
box(it,inset: (top: 0.5em, bottom: 0.5em))
}
body
}
#let envForMathEmphasis(type: "Theorem", name: none, num: true, fg: black, bg: white, headingColor: black, body) = locate(
location => {
let level = counter(heading).at(location)
let top = if level.len() > 0 { level.first() } else { 0 }
let counterName="CounterForMathEmphasisEnvironment"+str(top)
let counterForMath=counter(counterName)
show: block.with(spacing: 11pt)
stack(
dir: ttb,
rect(fill: fg, radius: (top: 2pt), stroke: fg)[
#strong(
text(headingColor)[
#type
#if num {
counterForMath.step()
[ #top.#counterForMath.display() ]
}
#if name != none and name!="" [#h(0.25em) #name ]
]
)
],
rect(
width: 100%,
fill: bg,
stroke: (fg)
)[
#emph(body)
]
)
}
)
#let thrm = envForMathEmphasis.with(
type: "Theorem",
fg: rgb("#84d7d7"),
bg: rgb("#f9fdff"),
)
#let def = envForMathEmphasis.with(
type: "Definition",
fg: rgb("#f8c486"),
bg: rgb("#fffcf9"),
)
#let lemma = envForMathEmphasis.with(
type: "Lemma",
fg: rgb("#f8ccf0"),
bg: rgb("#fefbff"),
)
#let corol = envForMathEmphasis.with(
type: "Corollary",
fg: rgb("#99dfa8"),
bg: rgb("#f9fffa"),
)
#let example = envForMathEmphasis.with(
type: "Example",
fg: rgb("#9db5f3"),
bg: rgb("#f8faff"),
)
#let caution = envForMathEmphasis.with(
type: "Caution",
fg: rgb("#ff9191"),
bg: rgb("#fff9fa"),
)
#let prop = envForMathEmphasis.with(
type: "Property",
fg: rgb("#f3e743"),
bg: rgb("#fffef1"),
)
#let idea = envForMathEmphasis.with(
type: "Idea",
fg: rgb("#b6b7d0"),
bg: rgb("#eeeeff"),
)
#let proof(body) = block(spacing: 11.5pt, {
set par(first-line-indent: 0pt)
emph[Proof.]
[\ ] + body
h(1fr)
$∎$
}) |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/columns_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test setting a column gutter and more than two columns.
#set page(height: 3.25cm, width: 7.05cm, columns: 3)
#set columns(gutter: 30pt)
#rect(width: 100%, height: 2.5cm, fill: conifer) #parbreak()
#rect(width: 100%, height: 2cm, fill: eastern) #parbreak()
#circle(fill: eastern)
|
https://github.com/chamik/gympl-skripta | https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-dila/_template.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/helper.typ": hrule
#counter(footnote).update(0)
#block(
fill: luma(230),
inset: 8pt,
radius: 4pt,
width: 100%,
[#columns(3, gutter: 5pt)[
#heading(level: 3, "Něco") <neco>
Autor: *Někdo* \
Překlad: _Někdo_
#colbreak()
Období: *Někdy* \
Země: *Někde*
#colbreak()
Rok vydání: *Někdy* \
L. druh: *něco* \
L. žánr: *něco*
]]
)
#columns(2, gutter: 1em)[
*Téma*\
*Motivy*\
*Časoprostor*\
*Postavy* \
*Kompozice*
*Vypravěč*
*Jazykové prostředky*\
*Obsah*\
*Literárně historický kontext*\
]
#pagebreak()
*Ukázka*
#pagebreak() |
https://github.com/Pablo-Gonzalez-Calderon/showybox-package | https://raw.githubusercontent.com/Pablo-Gonzalez-Calderon/showybox-package/main/lib/id.typ | typst | MIT License | /*
* ShowyBox - A package for Typst
* <NAME> and Showybox Contributors (c) 2023-2024
*
* lib/id.typ -- The package's file containing all the
* internal functions used to handle showybox id
*
* This file is under the MIT license. For more
* information see LICENSE on the package's main folder.
*/
#let _showy-id = counter("showybox-id") |
https://github.com/RaphGL/ElectronicsFromBasics | https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap8/6_ohmmeter_design.typ | typst | Other | #import "../../core/core.typ"
=== Ohmmeter design
Though mechanical ohmmeter (resistance meter) designs are rarely used
today, having largely been superseded by digital instruments, their
operation is nonetheless intriguing and worthy of study.
The purpose of an ohmmeter, of course, is to measure the resistance
placed between its leads. This resistance reading is indicated through a
mechanical meter movement which operates on electric current. The
ohmmeter must then have an internal source of voltage to create the
necessary current to operate the movement, and also have appropriate
ranging resistors to allow just the right amount of current through the
movement at any given resistance.
Starting with a simple movement and battery circuit, let's see how it
would function as an ohmmeter:
#image("static/00174.png")
When there is infinite resistance (no continuity between test leads),
there is zero current through the meter movement, and the needle points
toward the far left of the scale. In this regard, the ohmmeter
indication is "backwards" because maximum indication (infinity) is on
the left of the scale, while voltage and current meters have zero at the
left of their scales.
If the test leads of this ohmmeter are directly shorted together
(measuring zero $Omega$), the meter movement will have a maximum amount of
current through it, limited only by the battery voltage and the
movement's internal resistance:
#image("static/00175.png")
With 9 volts of battery potential and only 500 $Omega$ of movement resistance,
our circuit current will be 18 mA, which is far beyond the full-scale
rating of the movement. Such an excess of current will likely damage the
meter.
Not only that, but having such a condition limits the usefulness of the
device. If full left-of-scale on the meter face represents an infinite
amount of resistance, then full right-of-scale should represent zero.
Currently, our design "pegs" the meter movement hard to the right when
zero resistance is attached between the leads. We need a way to make it
so that the movement just registers full-scale when the test leads are
shorted together. This is accomplished by adding a series resistance to
the meter's circuit:
#image("static/00176.png")
To determine the proper value for R, we calculate the total circuit
resistance needed to limit current to 1 mA (full-scale deflection on
the movement) with 9 volts of potential from the battery, then subtract
the movement's internal resistance from that figure:
$
R_"total" &= E / I = (9 V) / (1 m A) \
R_"total" &= 9 k Omega \
R &= R_"total" - 500 Omega = 8.5 k Omega \
$
Now that the right value for R has been calculated, we're still left
with a problem of meter range. On the left side of the scale we have
"infinity" and on the right side we have zero. Besides being
"backwards" from the scales of voltmeters and ammeters, this scale is
strange because it goes from nothing to everything, rather than from
nothing to a finite value (such as 10 volts, 1 amp, etc.). One might
pause to wonder, "what does middle-of-scale represent? What figure lies
exactly between zero and infinity?" Infinity is more than just a
_very big_ amount: it is an incalculable quantity, larger than any
definite number ever could be. If half-scale indication on any other
type of meter represents 1/2 of the full-scale range value, then what is
half of infinity on an ohmmeter scale?
The answer to this paradox is a _logarithmic scale_. Simply put,
the scale of an ohmmeter does not smoothly progress from zero to
infinity as the needle sweeps from right to left. Rather, the scale
starts out "expanded" at the right-hand side, with the successive
resistance values growing closer and closer to each other toward the
left side of the scale:
#image("static/00177.png")
Infinity cannot be approached in a linear (even) fashion, because the
scale would _never_ get there! With a logarithmic scale, the amount
of resistance spanned for any given distance on the scale increases as
the scale progresses toward infinity, making infinity an attainable
goal.
We still have a question of range for our ohmmeter, though. What value
of resistance between the test leads will cause exactly 1/2 scale
deflection of the needle? If we know that the movement has a full-scale
rating of 1 mA, then 0.5 mA (500 µA) must be the value needed for
half-scale deflection. Following our design with the 9 volt battery as a
source we get:
$
R_"total" = E / I = (9 V) / (500 mu A) \
R_"total" = 18 k Omega
$
With an internal movement resistance of 500 $Omega$ and a series range
resistor of 8.5 k$Omega$, this leaves 9 k$Omega$ for an external (lead-to-lead)
test resistance at 1/2 scale. In other words, the test resistance giving
1/2 scale deflection in an ohmmeter is equal in value to the (internal)
series total resistance of the meter circuit.
Using Ohm's Law a few more times, we can determine the test resistance
value for 1/4 and 3/4 scale deflection as well:
1/4 scale deflection (0.25 mA of meter current):
$
R_"total" &= E / I = (9 V) / (250 mu A) \
R_"total" &= 36 k Omega
$
$
R_"test" &= R_"total" - R_"internal" \
R_"test" &= 36 k Omega - 9 k Omega \
R_"test" &= 27 k Omega \
$
3/4 scale deflection (0.75 mA of meter current):
$
R_"total" &= E / I = (9 V) / (750 mu A) \
R_"total" &= 12 k Omega \
$
$
R_"test" &= R_"total" - R_"internal" \
R_"test" &= 12k Omega - 9k Omega \
R_"test" &= 3 k Omega \
$
So, the scale for this ohmmeter looks something like this:
#image("static/00178.png")
One major problem with this design is its reliance upon a stable battery
voltage for accurate resistance reading. If the battery voltage
decreases (as all chemical batteries do with age and use), the ohmmeter
scale will lose accuracy. With the series range resistor at a constant
value of 8.5 k$Omega$ and the battery voltage decreasing, the meter will no
longer deflect full-scale to the right when the test leads are shorted
together (0 $Omega$). Likewise, a test resistance of 9 k$Omega$ will fail to
deflect the needle to exactly 1/2 scale with a lesser battery voltage.
There are design techniques used to compensate for varying battery
voltage, but they do not completely take care of the problem and are to
be considered approximations at best. For this reason, and for the fact
of the logarithmic scale, this type of ohmmeter is never considered to
be a precision instrument.
One final caveat needs to be mentioned with regard to ohmmeters: they
only function correctly when measuring resistance that is not being
powered by a voltage or current source. In other words, you cannot
measure resistance with an ohmmeter on a "live" circuit! The reason
for this is simple: the ohmmeter's accurate indication depends on the
only source of voltage being its internal battery. The presence of any
voltage across the component to be measured will interfere with the
ohmmeter's operation. If the voltage is large enough, it may even
damage the ohmmeter.
#core.review[
- Ohmmeters contain internal sources of voltage to supply power in
taking resistance measurements.
- An analog ohmmeter scale is "backwards" from that of a voltmeter or
ammeter, the movement needle reading zero resistance at full-scale and
infinite resistance at rest.
- Analog ohmmeters also have logarithmic scales, "expanded" at the low
end of the scale and "compressed" at the high end to be able to span
from zero to infinite resistance.
- Analog ohmmeters are not precision instruments.
- Ohmmeters should _never_ be connected to an energized circuit
(that is, a circuit with its own source of voltage). Any voltage
applied to the test leads of an ohmmeter will invalidate its reading.
]
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compute/calc.typ | typst | Apache License 2.0 | // Test math functions.
// Ref: false
---
// Test conversion to numbers.
#test(int(false), 0)
#test(int(true), 1)
#test(int(10), 10)
#test(int("150"), 150)
#test(int("-834"), -834)
#test(int("\u{2212}79"), -79)
#test(int(10 / 3), 3)
#test(float(10), 10.0)
#test(float(50% * 30%), 0.15)
#test(float("31.4e-1"), 3.14)
#test(float("31.4e\u{2212}1"), 3.14)
#test(float("3.1415"), 3.1415)
#test(float("-7654.321"), -7654.321)
#test(float("\u{2212}7654.321"), -7654.321)
#test(type(float(10)), float)
---
#test(calc.round(calc.e, digits: 2), 2.72)
#test(calc.round(calc.pi, digits: 2), 3.14)
---
// Error: 6-10 expected boolean, float, string, or integer, found length
#int(10pt)
---
// Error: 8-13 expected boolean, integer, ratio, string, or float, found type
#float(float)
---
// Error: 6-12 invalid integer: nope
#int("nope")
---
// Error: 8-15 invalid float: 1.2.3
#float("1.2.3")
---
// Test the `abs` function.
#test(calc.abs(-3), 3)
#test(calc.abs(3), 3)
#test(calc.abs(-0.0), 0.0)
#test(calc.abs(0.0), -0.0)
#test(calc.abs(-3.14), 3.14)
#test(calc.abs(50%), 50%)
#test(calc.abs(-25%), 25%)
---
// Error: 11-22 expected integer, float, length, angle, ratio, or fraction, found string
#calc.abs("no number")
---
// Test the `even` and `odd` functions.
#test(calc.even(2), true)
#test(calc.odd(2), false)
#test(calc.odd(-1), true)
#test(calc.even(-11), false)
---
// Test the `rem` function.
#test(calc.rem(1, 1), 0)
#test(calc.rem(5, 3), 2)
#test(calc.rem(5, -3), 2)
#test(calc.rem(22.5, 10), 2.5)
#test(calc.rem(9, 4.5), 0)
---
// Error: 14-15 divisor must not be zero
#calc.rem(5, 0)
---
// Error: 16-19 divisor must not be zero
#calc.rem(3.0, 0.0)
---
// Test the `quo` function.
#test(calc.quo(1, 1), 1)
#test(calc.quo(5, 3), 1)
#test(calc.quo(5, -3), -1)
#test(calc.quo(22.5, 10), 2)
#test(calc.quo(9, 4.5), 2)
---
// Error: 14-15 divisor must not be zero
#calc.quo(5, 0)
---
// Error: 16-19 divisor must not be zero
#calc.quo(3.0, 0.0)
---
// Test the `min` and `max` functions.
#test(calc.min(2, -4), -4)
#test(calc.min(3.5, 1e2, -0.1, 3), -0.1)
#test(calc.max(-3, 11), 11)
#test(calc.min("hi"), "hi")
---
// Test the `pow`, `log`, `exp`, and `ln` functions.
#test(calc.pow(10, 0), 1)
#test(calc.pow(2, 4), 16)
#test(calc.exp(2), calc.pow(calc.e, 2))
#test(calc.ln(10), calc.log(10, base: calc.e))
---
// Error: 10-16 zero to the power of zero is undefined
#calc.pow(0, 0)
---
// Error: 14-31 exponent is too large
#calc.pow(2, 10000000000000000)
---
// Error: 10-25 the result is too large
#calc.pow(2, 2147483647)
---
// Error: 14-36 exponent may not be infinite, subnormal, or NaN
#calc.pow(2, calc.pow(2.0, 10000.0))
---
// Error: 10-19 the result is not a real number
#calc.pow(-1, 0.5)
---
// Error: 12-14 cannot take square root of negative number
#calc.sqrt(-1)
---
// Error: 11-13 value must be strictly positive
#calc.log(-1)
---
// Error: 20-21 base may not be zero, NaN, infinite, or subnormal
#calc.log(1, base: 0)
---
// Error: 10-24 the result is not a real number
#calc.log(10, base: -1)
---
// Test the `fact` function.
#test(calc.fact(0), 1)
#test(calc.fact(5), 120)
---
// Error: 11-15 the result is too large
#calc.fact(21)
---
// Test the `perm` function.
#test(calc.perm(0, 0), 1)
#test(calc.perm(5, 3), 60)
#test(calc.perm(5, 5), 120)
#test(calc.perm(5, 6), 0)
---
// Error: 11-19 the result is too large
#calc.perm(21, 21)
---
// Test the `binom` function.
#test(calc.binom(0, 0), 1)
#test(calc.binom(5, 3), 10)
#test(calc.binom(5, 5), 1)
#test(calc.binom(5, 6), 0)
#test(calc.binom(6, 2), 15)
---
// Test the `gcd` function.
#test(calc.gcd(112, 77), 7)
#test(calc.gcd(12, 96), 12)
#test(calc.gcd(13, 9), 1)
#test(calc.gcd(13, -9), 1)
#test(calc.gcd(272557, 272557), 272557)
#test(calc.gcd(0, 0), 0)
#test(calc.gcd(7, 0), 7)
---
// Test the `lcm` function.
#test(calc.lcm(112, 77), 1232)
#test(calc.lcm(12, 96), 96)
#test(calc.lcm(13, 9), 117)
#test(calc.lcm(13, -9), 117)
#test(calc.lcm(272557, 272557), 272557)
#test(calc.lcm(0, 0), 0)
#test(calc.lcm(8, 0), 0)
---
// Error: 10-41 the return value is too large
#calc.lcm(15486487489457, 4874879896543)
---
// Error: 10-12 expected at least one value
#calc.min()
---
// Error: 14-18 cannot compare string and integer
#calc.min(1, "hi")
---
// Error: 16-19 cannot compare 1pt with 1em
#calc.max(1em, 1pt)
---
// Test the `range` function.
#test(range(4), (0, 1, 2, 3))
#test(range(1, 4), (1, 2, 3))
#test(range(-4, 2), (-4, -3, -2, -1, 0, 1))
#test(range(10, 5), ())
#test(range(10, step: 3), (0, 3, 6, 9))
#test(range(1, 4, step: 1), (1, 2, 3))
#test(range(1, 8, step: 2), (1, 3, 5, 7))
#test(range(5, 2, step: -1), (5, 4, 3))
#test(range(10, 0, step: -3), (10, 7, 4, 1))
---
// Error: 7-9 missing argument: end
#range()
---
// Error: 11-14 expected integer, found float
#range(1, 2.0)
---
// Error: 17-22 expected integer, found string
#range(4, step: "one")
---
// Error: 18-19 number must not be zero
#range(10, step: 0)
|
https://github.com/Myriad-Dreamin/arch-media-box-typst | https://raw.githubusercontent.com/Myriad-Dreamin/arch-media-box-typst/main/README.md | markdown | # Arch Linux 盒装安装媒介
这是一个由 [Debian 小药盒](https://github.com/moesoha/debian-media-box) 启发的 Arch Linux 盒装安装介质的平面设计。所使用的素材基于[Arch Linux 盒装安装媒介](https://github.com/Isoheptane/arch-media-box),并使用 typst 重写。

| 包装盒 | 说明书 |
| --------------- | --------------------------------------- |
|  |  |
尽管 Arch Linux 的 Logo 与某药品并无太多相似之处,但既然已经存在了 Debian 盒装安装介质的梗,那整一个 Arch Linux 盒装安装介质似乎也没问题吧。
## 使用
下载 `box.pdf` 文件后打印即可。
## 源文件
该项目使用的外部字体有:
- Noto Sans CJK SC
## Todo
- 完全移植`background.svg`:
- [ ] Arch Big Logo
- [ ] CC Logos
- [ ] Barcode
- [ ] Linear Gradient Background
- [ ] Box profile
- 设置 CMYK 色彩模式:
> 在这里,由于 InkScape 无法使用 CMYK 色彩模式,因此需要先导入 RGB 色彩模式的 PDF 文件,然后再导入到 Scribus 中转换为 CMYK 色彩模式。
- 移植`Instruction.tex`:
> `Instruction.tex` 需要使用 `xelatex` 编译,或者直接去 action 下载。
## 许可
本作品采用 [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/) 许可协议进行许可。
|
|
https://github.com/jxpeng98/Typst-CV-Resume | https://raw.githubusercontent.com/jxpeng98/Typst-CV-Resume/main/README.md | markdown | MIT License | # Typst-CV-Resume
This Typst CV template is inspired by the Latex template [Deedy-Resume](https://github.com/deedy/Deedy-Resume). You can use it for both industry and academia.
If you want to find a cover letter template, you can check out [modernpro-coverletter](https://github.com/jxpeng98/typst-coverletter).
## How to start
### Use Typst CLI
If you use Typst CLI, you can use the following command to create a new project:
```bash
typst init modernpro-cv
```
It will create a folder named `modernpro-cv` with the following structure:
```plain
modernpro-cv
├── bib.bib
├── cv_double.typ
└── cv_single.typ
```
If you want to use the single-column version, you can modify the template `cv-single.typ`. If you prefer the two-column version, you can use the `cv-double.typ`.
**Note:** The `bib.bib` is the bibliography file. You can modify it to add your publications.
### Manual Download
If you want to manually download the template, you can download `modernpro-cv-{version}.zip` from the [release page](https://github.com/jxpeng98/Typst-CV-Resume/releases)
### Typst website
If you want to use the template via [Typst](https://typst.app), You can `start from template` and search for `modernpro-cv`.
## How to use the template
### The arguments
The template has the following arguments:
| Argument | Description | Default |
| --- | --- | --- |
| `font-type` | The font type. You can choose any supported font in your system. | `Times New Roman` |
| `continue-header` | Whether to continue the header on the follwing pages. | `false` |
| `name` | Your name. | `""` |
| `address` | Your address. | `""` |
| `lastupdated` | Whether to show the last updated date. | `true` |
| `pagecount` | Whether to show the page count. | `true` |
| `date` | The date of the CV. | `today` |
| `contacts` | contact details, e.g phone number, email, etc. | `(text: "", link: "")` |
### Start single column version
If you want to use the single column version, you create a new `.typ` file and copy the following code:
```Typst
#import "@preview/modernpro-cv:1.0.2": *
#import "@preview/fontawesome:0.5.0": *
#show: cv-single.with(
font-type: "PT Serif",
continue-header: "false",
name: [],
address: [],
lastupdated: "true",
pagecount: "true",
date: "2024-07-03",
contacts: (
(text: [#fa-icon("location-dot") UK]),
(text: [#fa-icon("mobile") 123-456-789], link: "tel:123-456-789"),
(text: [#fa-icon("link") example.com], link: "https://www.example.com"),
)
)
```
### Start double column version
The double column version is similar to the single column version. However, you need to add contents to the specific `left` and `right` sections.
```Typst
#import "@preview/modernpro-cv:1.0.2": *
#import "@preview/fontawesome:0.5.0": *
#show: cv-double(
font-type: "PT Sans",
continue-header: "true",
name: [#lorem(2)],
address: [#lorem(4)],
lastupdated: "true",
pagecount: "true",
date: "2024-07-03",
contacts: (
(text: [#fa-icon("location-dot") UK]),
(text: [#fa-icon("mobile") 123-456-789], link: "tel:123-456-789"),
(text: [#fa-icon("link") example.com], link: "https://www.example.com"),
),
left: [
// contents for the left column
],
right:[
// contents for the right column
]
)
```
### Start the CV
Once you set up the arguments, you can start to add details to your CV / Resume.
I preset the following functions for you to create different parts:
| Function | Description |
| --- | --- |
| `#section("Section Name")` | Start a new section |
| `#sectionsep` | End the section |
|`#oneline-title-item(title: "", content: "")`| Add a one-line item (**Title:** content)|
|`#oneline-two(entry1: "", entry2: "")`| Add a one-line item with two entries, aligned left and right|
|`#descript("descriptions")`| Add a description for self-introduction|
|`#award(award: "", date: "", institution: "")`| Add an award (**award**, *institution* *date*)|
|`#education(institution: "", major: "", date: "", institution: "", core-modules: "")`| Add an education experience|
|`#job(position: "", institution: "", location: "", date: "", description: [])`| Add a job experience (description is optional)|
|`#twoline-item(entry1: "", entry2: "", entry3: "", entry4: "")`| Two line items, similar to education and job experiences|
|`#references(references:())`| Add a reference list. In the `()`, you can add multi reference entries with the following format `(name: "", position: "", department: "", institution: "", address: "", email: "",),`|
|`#show bibliography: none #bibliography("bib.bib")`| Add a bibliography. You can modify the `bib.bib` file to add your publications. **Note:** Keep this at the end of your CV|
**Note:** Use `+ @ref` to display your publications. For example,
```Typst
#section("Publications")
// numbering list
+ @quenouille1949approximate
+ @quenouille1949approximate
// Keep this at the end
#show bibliography: none
#bibliography("bib.bib")
```
## Preview
### Single Column

### Double Column

## Legacy Version
I redesigned the template and submitted the new version to Typst Universe. However, you can find the legacy version in the `legacy` folder if you prefer to use the multi-font setting. You can also download the `modernpro-cv-legacy.zip` from the [release page](https://github.com/jxpeng98/Typst-CV-Resume/releases).
**Note:** The legacy version also has a cover letter template. You can use it with the CV template.
## Cover Letter
If you used the previous version of this template, you might know that I also provided a cover letter template.
If you want to use a consistent cover letter with the new version of the CV template, you can find it from another repository [typst-coverletter](https://github.com/jxpeng98/typst-coverletter).
you can also use the following code in the command line:
```bash
typst init modernpro-coverletter
```
## License
The template is released under the MIT License. For more information, please refer to the [LICENSE](https://github.com/jxpeng98/Typst-CV-Resume/blob/main/LICENSE) file.
|
https://github.com/lucifer1004/leetcode.typ | https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/README.md | markdown | # leetcode.typ - Solving Leetcode problems in Typst

To compile the document, you need to install [`typst`](https://github.com/typst/typst) first, then run
```bash
typst watch leetcode.typ
```
to get a dynamically updated PDF file `leetcode.pdf`.
Example output is [here](./build/leetcode.pdf).
|
|
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/project_documentation/content/meeting_minutes/week_10.typ | typst | = Project Meeting 21.11.2023 08:15 - 09:00 (MS Teams)
== Participants
- Prof. Dr. <NAME>
- <NAME>
- <NAME>
== Agenda
- Presentation of first draft of PoC UI & Inference
- Next steps: combine UI & inference
Input from Advisor:
- FRP: Take a look at the chapter on reactive animations in "The Haskell School of Expression"
- Think about how textual representation of a composed function could look like (e.g. in an ML type language) |
|
https://github.com/lebinyu/typst-thesis-template | https://raw.githubusercontent.com/lebinyu/typst-thesis-template/main/thesis/chapter1.typ | typst | Apache License 2.0 | #let title = [
Title of Chapter 1
]
#let chaptnumber = 1
#let introduction = [
// = this is a chapter <aaa>
#lorem(20)
]
#let mainbody = [
== subsetion test
#lorem(50) #cite("bruegge2004object")
$ 1+1 = alpha $
#lorem(400) #cite("allen1983theory")
== subsection testtest
$ 2+1 = beta $
#lorem(500)
// == Bibliography
// #bibliography(title: none, "reference.bib")
]
// #let reference = [
// == Bibliography
// #bibliography(title: none, "reference.bib")
// ]
|
https://github.com/Myriad-Dreamin/shiroa | https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/github-pages/docs/format/supports/embed-html.typ | typst | Apache License 2.0 | #import "/github-pages/docs/book.typ": book-page
#show: book-page.with(title: "Typst Supports - Embed Sanitized HTML Elements")
|
https://github.com/lphoogenboom/typstThesisDCSC | https://raw.githubusercontent.com/lphoogenboom/typstThesisDCSC/master/projectInfo.typ | typst | #let student = (
name: "<NAME>",
email: "<EMAIL>"
)
#let report = (
type: "Literature Survey", // Choose: (Literature Survey | Thesis)
title: "Thesis Titcle",
subtitle: "Optional Subtitle",
coverImage: "../graphics/template/COVER.jpg"
) |
|
https://github.com/jrihon/multi-bibs | https://raw.githubusercontent.com/jrihon/multi-bibs/main/chapters/00_title/titlepage.typ | typst | MIT License | #v(50%)
#align(left)[
= INSERT THESIS TITLE HERE: FOO BAR BAZ ]
My thesis is about how I can be the very best, that no one ever was!
#pagebreak()
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/crates/reflexo/README.md | markdown | Apache License 2.0 | # reflexo
A portable format to show (typst) document in web browser.
See [Typst.ts](https://github.com/Myriad-Dreamin/typst.ts)
|
https://github.com/Slyde-R/not-jku-thesis-template | https://raw.githubusercontent.com/Slyde-R/not-jku-thesis-template/main/template/content/Tutorial.typ | typst | MIT No Attribution | #import "../utils.typ": todo, silentheading, flex-caption
#import "@preview/wrap-it:0.1.0": wrap-content
= Tutorial <Tutorial>
#todo[Exclude this chapter!]
This template uses the Arial font with size 11pt, a spacing of 1em with a side margin of 2.5cm with a 1cm single sided bounding correction, which is _*intended*_ to follow the guidelines of the @jku. This can be edited in the `thesis.typ` file#footnote[This is a footnote.]. If you are looking for how to cite, this sentence is what your are looking for @Bradshaw2012. This is an abbreviation that is explained in the glossary, which is the @goat.
== Drafting and Inwriting
Set the boolean variables `inwriting` and `draft` inside `utils.typ`.
The `draft` variable is used to show DRAFT in the header and the title. This should be true until the final version is handed-in.
The `inwriting` is used to change the appearance of the document for easier writing. Set to `true` for yourself but `false` for handing in a draft or so.
== Example for figures
=== Normal Figure
#lorem(30)
And this is a reference to this @tag.
#figure(
image("../images/MissMoneypenny.jpg", width: 60%), caption: flex-caption([This is a #strike[caption] beautiful cat named Miss Moneypenny ],[Picture of Miss Moneypenny (short description of the image for the list of figures)])
)<tag>
=== Wrap-Content
#wrap-content([#figure(image("../images/JamesBond.jpg", width:150pt,), caption: [another caption])],
[
#lorem(100)
], align: right)
=== Sub-Figures
#figure(grid(columns: 2, row-gutter: 2mm, column-gutter: 1mm,
image("../images/Calcipher.jpg", height: 200pt), image("../images/Mei.jpg", height: 200pt),
"a) test 1", "b) test2"),
caption: "Caption"
)<label>
== Math
This is how you define inline math: $a^2 + b^2 = c^2$. For bigger equations you can use a math block, as you can see in @eq1.
$
integral_(-oo)^(oo) f(x) d x = 1\
1 = 1
$<eq1>
== Tables
=== Normal Table
#align(center)[
#table(
columns: 3,
align: center,
table.header(
[Substance],
[Subcritical °C],
[Supercritical °C],
),
[Hydrochloric Acid],
[12.0], [92.1],
[Sodium Myreth Sulfate],
[16.6], [104],
[Potassium Hydroxide],
table.cell(colspan: 2)[24.7],
)]
=== Referenceable Table
#figure(
table(
columns: 3,
align: center,
table.header(
[Substance],
[Subcritical °C],
[Supercritical °C],
),
[Hydrochloric Acid],
[12.0], [92.1],
[Sodium Myreth Sulfate],
[16.6], [104],
[Potassium Hydroxide],
table.cell(colspan: 2)[24.7],
),
caption: "This is a caption"
)
#silentheading(4)[This is a silent level 4 heading]
This won't show up in the overview.
== Code
Some python code:
```py
print("Hello World")
```
Some C++ code:
```cpp
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
``` |
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/themes/science-slam.typ | typst | #import "../../../polylux.typ": *
// ANCHOR: init
#let science-slam-theme(aspect-ratio: "16-9", darkness: "dark", body) = {
let background-color = if darkness == "dark" {
navy
} else if darkness == "very dark" {
navy.darken(50%)
} else if darkness == "ultra dark" {
black
} else {
panic("illegal darkness, must be one of dark, very dark, ultra dark")
}
set page(
paper: "presentation-" + aspect-ratio,
fill: background-color,
)
set text(fill: white.darken(10%), size: 40pt, font: "Fira Sans")
body
}
// ANCHOR_END: init
// ANCHOR: title-slide
#let title-slide(title: [], author: []) = {
polylux-slide({
set align(center + horizon)
smallcaps(strong(title))
parbreak()
text(size: .7em, author)
})
}
// ANCHOR_END: title-slide
// ANCHOR: slide
#let slide(title: [], body) = {
polylux-slide({
strong(title)
set align(horizon)
body
})
}
// ANCHOR_END: slide
// ANCHOR: use-init
#show: science-slam-theme.with(darkness: "very dark")
// ANCHOR_END: use-init
// ANCHOR: use-title-slide
#title-slide(title: [My awesome topic], author: [A really funny guy])
// ANCHOR_END: use-title-slide
// ANCHOR: use-slide
#slide(title: "A hilarious slide")[
You didn't expect that!
]
// ANCHOR_END: use-slide
|
|
https://github.com/bigskysoftware/hypermedia-systems-book | https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/ch01-hypermedia-a-reintroduction.typ | typst | Other | #import "lib/definitions.typ": *
== Hypermedia: A Reintroduction
Hypermedia is a universal technology today, almost as common as electricity.
Billions of people use hypermedia-based systems every day, mainly by interacting
with the _Hypertext Markup Language (HTML)_ being exchanged via the _Hypertext Transfer Protocol (HTTP)_ by
using a web browser connected to the World Wide Web.
People use these systems to get their news, check in on friends, buy things
online, play games, send emails and so forth: the variety and sheer number of
online services being delivered by hypermedia is truly astonishing.
And yet, despite this ubiquity, the topic of hypermedia itself is a strangely
under-explored concept today, left mainly to specialists. Yes, you can find a
lot of tutorials on how to author HTML, create links and forms, etc. But it is
rare to see a discussion of HTML _as a hypermedia_ and, more broadly, on how an
entire hypermedia _system_
fits together.
This is in contrast with the early web development era when concepts like _Representational State Transfer (REST)_ and _Hypermedia As The Engine of Application State (HATEOAS)_ were
discussed frequently, refined and debated among web developers.
In a sad turn of events, today, the world’s most popular hypermedia, HTML, is
often viewed resentfully: it is an awkward, legacy markup language that must be
grudgingly used to build user interfaces in what are increasingly entirely
JavaScript-based web applications.
HTML happens to be there, in the browser, and so we have to use it.
This is a shame and we hope to convince you that hypermedia is
_not_ simply a piece of legacy technology that we have to accept and deal with.
Instead, we aim to show you that hypermedia is a tremendously innovative, simple
and _flexible_ way to build robust applications: _Hypermedia-Driven Applications_.
We hope that by the end of this book you will feel, as we do, that the
hypermedia approach deserves a seat at the table when you, a web developer, are
considering the architecture of your next application. Creating a
Hypermedia-Driven Application on top of a _hypermedia system_ like the web is a
viable and, indeed, often excellent choice for
_modern_ web applications.
(And, as the section on Hyperview will show, not just web applications.)
=== What Is Hypermedia? <_what_is_hypermedia>
#blockquote(
attribution: [<NAME>, https:\/\/archive.org/details/SelectedPapers1977/page/n7/mode/2up],
)[
Hypertexts: new forms of writing, appearing on computer screens, that will
branch or perform at the reader’s command. A hypertext is a non-sequential piece
of writing; only the computer display makes it practical.
]
Let us begin at the beginning: what is hypermedia?
#index[hypermedia]
Hypermedia is a media, for example a text, that includes
_non-linear branching_ from one location in the media to another, via, for
example, hyperlinks embedded in the media. The prefix "hyper-" derives from the
Greek prefix "ὑπερ-" which means "beyond" or "over", indicating that hypermedia _goes beyond_ normal,
passively consumed media like magazines and newspapers.
Hyperlinks are a canonical example of what is called a _#indexed[hypermedia control]_:
/ Hypermedia Control: #[
A #indexed[hypermedia control] is an element in a hypermedia that describes (or
controls) some sort of interaction, often with a remote server, by encoding
information about that interaction directly and completely within itself.
]
Hypermedia controls are what differentiate hypermedia from other sorts of media.
You may be more familiar with the term _#indexed[hypertext]_, from whose
Wikipedia page the above quote is taken. Hypertext is a sub-category of
hypermedia and much of this book is going to discuss how to build modern
applications using hypertexts such as HTML, the Hypertext Markup Language, or
HXML, a hypertext used by the Hyperview mobile hypermedia system.
Hypertexts like HTML function alongside other technologies crucial for making an
entire hypermedia system work: network protocols like HTTP, other media types
such as images and videos, hypermedia servers (i.e., servers providing
hypermedia APIs), sophisticated hypermedia clients (e.g., web browsers), and so
on.
Because of this, we prefer the broader term _#indexed[hypermedia system]s_
when describing the underlying architecture of applications built using
hypertext, to emphasize the system architecture over the particular hypermedia
being used.
It is the entire hypermedia _system architecture_ that is underappreciated and
ignored by many modern web developers.
=== A Brief History of Hypermedia <_a_brief_history_of_hypermedia>
Where did the idea of hypermedia come from?
#index[Bush, Vannevar]
#index[Memex]
While there were many precursors to the modern idea of hypertext and the more
general hypermedia, many people point to the 1945 article _As We May Think_ written
by <NAME> in _The Atlantic_ as a starting point for looking at what has
become modern hypermedia.
In this article Bush described a device called a #indexed[Memex], which, using a
complex mechanical system of reels and microfilm, along with an encoding system,
would allow users to jump between related frames of content. The Memex was never
actually implemented, but it was an inspiration for later work on the idea of
hypermedia.
#index[Nelson, Ted]
The terms "hypertext" and "hypermedia" were coined in 1963 by <NAME>, who
would go on to work on the _Hypertext Editing System_
at Brown University and who later created the _File Retrieval and Editing System (#indexed[FRESS])_,
a shockingly advanced hypermedia system for its time. (This was perhaps the
first digital system to have a notion of
"undo".)
#index[Engelbart, Douglas]
While Nelson was working on his ideas, <NAME> was busy at work at the
Stanford Research Institute, explicitly attempting to make <NAME>’s Memex
a reality. In 1968, Englebart gave "The Mother of All Demos" in San Francisco,
California.
Englebart demonstrated an unbelievable amount of technology:
- Remote, collaborative text editing with his peers in Menlo Park
- Video and audio chat
- An integrated windowing system, with window resizing, etc
- A recognizable hypertext, whereby clicking on underlined text navigated to new
content.
Despite receiving a standing ovation from a shocked audience after his talk, it
was decades before the technologies Englebart demonstrated became mainstream.
==== Modern Implementation <_modern_implementation>
#index[Berners-Lee, Tim]
#index[World Wide Web][creation]
In 1990, <NAME>, working at CERN, published the first website. He had
been working on the idea of hypertext for a decade and had finally, out of
desperation at the fact it was so hard for researchers to share their research,
found the right moment and institutional support to create the World Wide Web:
#blockquote(
attribution: [<NAME>,
https:\/\/britishheritage.org/tim-berners-lee-the-world-wide-web],
)[
Creating the web was really an act of desperation, because the situation without
it was very difficult when I was working at CERN later. Most of the technology
involved in the web, like the hypertext, like the Internet, multifont text
objects, had all been designed already. I just had to put them together. It was
a step of generalising, going to a higher level of abstraction, thinking about
all the documentation systems out there as being possibly part of a larger
imaginary documentation system.
]
By 1994 his creation was taking off so quickly that Berners-Lee founded the W3C,
a working group of companies and researchers tasked with improving the web. All
standards created by the W3C were royalty-free and could be adopted and
implemented by anyone, cementing the open, collaborative nature of the web.
#index[Fielding, Roy]
In 2000, Roy Fielding, then at U.<NAME>, published a seminal PhD dissertation
on the web: "Architectural Styles and the Design of Network-based Software
Architectures." Fielding had been working on the open source Apache HTTP Server
and his thesis was a description of what he felt was a _new and distinct networking architecture_ that
had emerged in the early web. Fielding had worked on the initial HTTP
specifications and, in the paper, defined the web’s hypermedia network model
using the term _REpresentational State Transfer (#indexed[REST])_.
Fielding’s work became a major touchstone for early web developers, giving them
a language to discuss the new technical medium they were building applications
in.
We will discuss Fielding’s key ideas in depth in Chapter 2, and try to correct
the record with respect to REST, HATEOAS and hypermedia.
=== The World’s Most Successful Hypertext: HTML <_the_worlds_most_successful_hypertext_html>
#blockquote(
attribution: [Rescuing REST From the API Winter,
https:\/\/intercoolerjs.org/2016/01/18/rescuing-rest.html],
)[
In the beginning was the hyperlink, and the hyperlink was with the web, and the
hyperlink was the web. And it was good.
]
#index[HTML][history]
The system that Berners-Lee, Fielding and many others had created revolved
around a hypermedia: HTML. HTML started as a read-only hypermedia, used to
publish (at first) academic documents. These documents were linked together via
anchor tags which created
_hyperlinks_ between them, allowing users to quickly navigate between documents.
When #index[HTML][2.0] HTML 2.0 was released, it introduced the notion of the `form` tag,
joining the anchor tag (i.e., hyperlink) as a second hypermedia control. The
introduction of the form tag made building _applications_ on the web viable by
providing a mechanism for _updating_ resources, rather than just reading them.
It was at this point that the web transitioned from an interesting
document-oriented system to a compelling _application architecture_.
Today HTML is the most widely used hypermedia in existence and this book
naturally assumes that the reader has a reasonable familiarity with it. You do
not need to be an HTML (or CSS) expert to understand the code in this book, but
the better you understand the core tags and concepts of HTML, the more you will
get out of it.
==== The Essence of HTML as a Hypermedia <_the_essence_of_html_as_a_hypermedia>
Let us consider these two defining hypermedia elements (that is the two defining _hypermedia controls_)
of HTML, the anchor tag and the form tag, in a bit of detail.
===== Anchor tags <_anchor_tags>
#index[hyperlink]
#index[anchor tag]
Anchor tags are so familiar as to be boring but, as the original hypermedia
control, it is worth reviewing the mechanics of hyperlinks to get our minds in
the right place for developing a deeper understanding of hypermedia.
Consider a simple anchor tag, embedded within a larger HTML document:
#figure(caption: [A simple hyperlink],
```html
<a href="https://hypermedia.systems/">
Hypermedia Systems
</a>
```)
An anchor tag consists of the tag itself, `<a></a>`, as well as the attributes
and content within the tag. Of particular interest is the
`href` attribute, which specifies a _hypertext reference_ to another document or
document fragment. It is this attribute that makes the anchor tag a hypermedia
control.
In a typical web browser, this anchor tag would be interpreted to mean:
- Show the text "Hypermedia Systems" in a manner indicating that it is clickable
- When the user clicks on that text, issue an HTTP `GET` request to the URL
`https://hypermedia.systems/`
- Take the HTML content in the body of the HTTP response to this request and
replace the entire screen in the browser as a new document, updating the
navigation bar to this new URL.
Anchors provide the main mechanism we use to navigate around the web today, by
selecting links to navigate from document to document, or from resource to
resource. @fig-get-in-action shows what a user interaction with an anchor tag/hyperlink looks like in
visual form.
#asciiart(
read("images/diagram/http-get-in-action.txt"), caption: [An HTTP GET In Action],
)<fig-get-in-action>
#index[GET request]
When the link is clicked the browser (or, as we sometimes refer to it, the _hypermedia client_)
initiates an HTTP `GET` request to the URL encoded in the link’s `href` attribute.
Note that the HTTP request includes additional data (i.e.,
_metadata_) on what, exactly, the browser wants from the server, in the form of
headers. We will discuss these headers, and HTTP in more depth in Chapter 2.
The _hypermedia server_ then responds to this request with a
_hypermedia response_ --- the HTML --- for the new page. This may seem like a
small and obvious point, but it is an absolutely crucial aspect of a truly
RESTful _hypermedia system_: the client and server must communicate via
hypermedia!
===== Form tags <_form_tags>
Anchor tags provide _navigation_ between documents or resources, but don’t allow
you to update those resources. That functionality falls to the #indexed[form tag].
Here is a simple example of a form in HTML:
#figure(caption: [A simple form],
```html
<form action="/signup" method="post">
<input type="text" name="email" placeholder="Enter Email To Sign Up">
<button>Sign Up</button>
</form>
```)
Like an anchor tag, a form tag consists of the tag itself,
`<form></form>`, combined with the attributes and content within the tag. Note
that the form tag does not have an `href` attribute, but rather has an `action` attribute
that specifies where to issue an HTTP request.
#index[POST request]
Furthermore, it also has a `method` attribute, which specifies exactly which
HTTP "method" to use. In this example the form is asking the browser to issue a `POST` request.
In contrast with anchor tags, the content and tags _within_ a form can have an
effect on the hypermedia interaction that the form makes with a server. The _values_ of `input` tags
and other tags such as
`select` tags will be included with the HTTP request when the form is submitted,
as URL parameters in the case of a `GET` and as part of the request body in the
case of a `POST`. This allows a form to include an arbitrary amount of
information collected from a user in a request, unlike the anchor tag.
In a typical browser this form tag and its contents would be interpreted by the
browser roughly as follows:
- Show a text input and a "Sign Up" button to the user
- When the user submits the form by clicking the "Sign Up" button or by hitting
the enter key while the input element is focused, issue an HTTP `POST` request
to the path `/signup` on the "current" server
- Take the HTML content in the body of the HTTP response body and replace the
entire screen in the browser as a new document, updating the navigation bar to
this new URL.
This mechanism allows the user to issue requests to _update the state_ of
resources on the server. Note that despite this new type of request the
communication between client and server is still done entirely with _hypermedia_.
It is the form tag that makes Hypermedia-Driven Applications possible.
If you are an experienced web developer you probably recognize that we are
omitting a few details and complications here. For example, the response to a
form submission often _redirects_ the client to a different URL.
This is true, and we will get down into the muck with forms in more detail in
later chapters but, for now, this simple example suffices to demonstrate the
core mechanism for updating system state purely within hypermedia. @fig-post-in-action is a diagram of the interaction.
#asciiart(
read("images/diagram/http-post-in-action.txt"), caption: [An HTTP POST In Action],
)<fig-post-in-action>
===== Web 1.0 applications <_web_1_0_applications>
As someone interested in web development, the above diagrams and discussion are
probably very familiar to you. You may even find this content boring. But take a
step back and consider the fact that these two hypermedia controls, anchors and
forms, are the _only_ native ways for a user to interact with a server in plain
HTML.
Only two tags!
And yet, armed with only these two tags, the early web was able to grow
exponentially and offer a staggeringly large amount of online, dynamic
functionality to billions of people.
This is strong evidence of the power of hypermedia. Even today, in a web
development world increasingly dominated by large JavaScript-centric front end
frameworks, many people choose to use simple vanilla HTML to achieve their
application goals and are often perfectly happy with the results.
These two tags give a tremendous amount of expressive power to HTML.
==== So What Isn’t Hypermedia? <_so_what_isnt_hypermedia>
So links and forms are the two main hypermedia-based mechanisms for interacting
with a server available in HTML.
#index[Fetch API]
Now let’s consider a different approach: let’s interact with a server by issuing
an HTTP request via #index[JavaScript] JavaScript. To do this, we will use the
#link(
"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API",
)[`fetch()`]
API, a popular API for issuing an "Asynchronous JavaScript and XML," or AJAX #index[AJAX] request,
available in all modern web browsers:
#figure(caption: [JavaScript],
```html
<button onclick="fetch('/api/v1/contacts/1') <1>
.then(response => response.json()) <2>
.then(data => updateUI(data)) "> <3>
Fetch Contact
</button>
```)
1. Issue the request.
2. Convert the response to a JavaScript object.
3. Invoke the `updateUI()` function with the object.
This button has an `onclick` attribute that specifies some JavaScript to run
when the button is clicked.
The JavaScript will issue an AJAX HTTP `GET` request to
`/api/v1/contacts/1` using `fetch()`. An AJAX request is like a "normal" HTTP
request, but it is issued "behind the scenes" by the browser. The user does not
see a request indicator from the browser as they would with normal links and
forms. Additionally, unlike requests issued by those hypermedia controls, it is
up to the JavaScript code to handle the response from the server.
Despite AJAX having XML as part of its acronym, today the HTTP response to this
request would almost certainly be in the JavaScript Object Notation (JSON) #index[JSON] format
rather than XML.
An HTTP response to this request might look something like this:
#figure(caption: [JSON],
```json
{ <1>
"id": 42, <2>
"email" : "<EMAIL>" <3>
}
```)
1. The start of a JSON object.
2. A property, in this case with the name `id` and the value `42`.
3. Another property, the email of the contact with this id.
The JavaScript code above converts the JSON text received from the server into a
JavaScript object by calling the `json()` method on it. This new JavaScript
object is then handed off to the #index[updateUI method] `updateUI()`
method.
The `updateUI()` method is responsible for updating the UI based on the data
encoded in the JavaScript Object, perhaps by displaying the contact in a bit of
HTML generated via a client-side template in the JavaScript application.
The details of exactly what the `updateUI()` function does aren’t important for
our discussion.
What _is_ important, what is the _crucial_ aspect of this JSON-based server
interaction is that it is _not_ using hypermedia. The #indexed[JSON API] being
used here does not return a hypermedia response. There are no _hyperlinks_ or
other hypermedia-style controls in it.
This JSON API is, rather, a _#indexed[Data API]_.
Because the response is in JSON and is _not_ hypermedia, the JavaScript `updateUI()` method
must understand how to turn this contact data into HTML.
In particular, the code in `updateUI()` needs to know about the
_internal structure_ and meaning of the data.
It needs to know:
- Exactly how the fields in the JSON data object are structured and named.
- How they relate to one another.
- How to update the local data this new data corresponds with.
- How to render this data to the browser.
- What additional actions/API end points can be called with this data.
In short, the logic in `updateUI()` needs to have intimate knowledge of the API
endpoint at `/api/v1/contact/1`, knowledge provided via some side-channel beyond
the response itself. As a result, the `updateUI()`
code and the API have a strong relationship, known as _#indexed[tight coupling]_:
if the format of the JSON response changes, then the code for
`updateUI()` will almost certainly also need to be changed as well.
===== Single Page Applications <_single_page_applications>
This bit of JavaScript, while very modest, is the organic beginnings of a much
larger conceptual approach to building web applications. This is the beginning
of a _#indexed[Single Page Application (SPA)]_. The web application is no longer
navigating _between_ pages using hypermedia controls as was the case with links
and forms.
Instead, the application is exchanging _plain data_ with the server and then
updating the content _within_ a single page.
When this strategy or architecture is adopted for an entire application,
everything happens on a "Single Page" and, thus the application becomes a "Single
Page Application."
The Single Page Application architecture is extremely popular today and has been
the dominant approach to building web applications for the last decade. This can
be observed by the high level of mind-share and discussion it has received in
the industry.
Today the vast majority of Single Page Applications adopt far more sophisticated
frameworks for managing their user interface than this simple example shows.
Popular libraries such as #indexed[React], #indexed[Angular], #indexed[Vue.js],
etc. are now the common --- indeed, the standard --- way to build web
applications.
With these more complex frameworks developers typically work with an elaborate
client-side model --- that is, with JavaScript objects stored locally in the
browser’s memory that represent the "model" or "domain" of your application.
These JavaScript objects are updated via JavaScript code and the framework then "reacts"
to these changes, updating the user interface.
When the user interface is updated by a user these changes also flow
_into_ the model objects, establishing a "two-way" binding mechanism: the model
can update the UI, and the UI can update the model.
This is a much more sophisticated approach to a web client than hypermedia, and
it typically does away almost entirely with the underlying hypermedia
infrastructure available in the browser.
HTML is still used to build user interfaces, but the _hypermedia_
aspect of the two major hypermedia controls, anchors and forms, are unused.
Neither tag interacts with a server via their native
_hypermedia_ mechanism. Rather, they become user interface elements that drive
local interactions with the in-memory domain model via JavaScript, which is then
synchronized with the server using plain data JSON APIs.
So, as with our simple button above, the Single Page Application approach
foregoes the hypermedia architecture. It leaves aside the advantages of the
existing RESTful architecture of the web and the built-in functionality found in
HTML’s native hypermedia controls in favor of JavaScript driven behaviors.
SPAs are much more like _#indexed[thick client application]s_, that is, like the
client-server applications of the 1980s --- an architecture popular
_before_ the web came along and that the web was, in many ways, a reaction to.
This approach isn’t necessarily wrong, of course: there are times when a thick
client approach is the appropriate choice for an application. But it is worth
thinking about _why_ web developers so frequently make this choice without
considering other alternatives, and if there are reasons _not_ to go down this
path.
=== Why Use Hypermedia? <_why_use_hypermedia>
#blockquote(
attribution: [<NAME>, https://macwright.com/2020/05/10/spa-fatigue.html],
)[
#index[MacWright, Tom]
The emerging norm for web development is to build a React single-page
application, with server rendering. The two key elements of this architecture
are something like:
1. The main UI is built & updated in JavaScript using React or something similar.
2. The backend is an API that that application makes requests against.
This idea has really swept the internet. It started with a few major popular
websites and has crept into corners like marketing sites and blogs.
]
The JavaScript-based Single Page Application approach has taken the web
development world by storm, and if there was one single reason for its wild
success it was this: The Single Page Application offers a far more interactive
and immersive experience than the old, gronky, Web 1.0 hypermedia-based
applications could. SPAs had the ability to smoothly update elements inline on a
page without a dramatic reload of the entire document, they had the ability to
use CSS transitions to create nice visual effects, and the ability to hook into
arbitrary events like mouse movements.
All of these abilities give JavaScript-based applications a huge advantage in
building sophisticated user experiences.
Given the popularity, power and success of this modern approach to building web
applications, why on earth would you consider an older, clunkier and less
popular approach like hypermedia?
==== JavaScript Fatigue <_javascript_fatigue>
We are glad you asked!
#index[hypermedia][advantages]
It turns out that the hypermedia architecture, even in its original Web 1.0
form, has a number of advantages when compared with the Single Page Application + JSON Data API approach. Three of the biggest are:
- It is an extremely _simple_ approach to building web applications.
- It is extremely tolerant of content and API changes. In fact, it thrives on
them!
- It leverages tried and true features of web browsers, such as caching.
#index[JavaScript Fatigue]
#index[JSON][API churn]
The first two advantages, in particular, address major pain points in modern web
development:
- Single Page Application infrastructure has become extremely complex, often
requiring an entire team to manage.
- JSON API churn --- constant changes made to JSON APIs to support application
needs --- has become a major pain point for many application teams.
The combination of these two problems, along with other issues such as
JavaScript library churn, has led to a phenomenon known as "JavaScript Fatigue."
This refers to a general sense of exhaustion with all the hoops that are
necessary to jump through to get anything done in modern-day web applications.
We believe that a hypermedia architecture can help cure JavaScript Fatigue for
many developers and teams.
But if hypermedia is so great, and if it addresses so many of the problems that
beset the web development industry, why was it set aside in the first place?
After all, hypermedia was there first. Why didn’t web developers just stick with
it?
There are two major reasons hypermedia hasn’t made a comeback in web
development.
The first is this: the expressiveness of HTML _as a hypermedia_
hasn’t changed much, if at all, since HTML 2.0, which was released
_in the mid 1990s_. Many new _features_ have been added to HTML, of course, but
there haven’t been _any_ major new ways to interact with a server in HTML in
almost three decades.
HTML developers still only have anchor tags and forms available as hypermedia
controls, and those hypermedia controls can still only issue
`GET` and `POST` requests.
This baffling lack of progress by HTML leads immediately to the second, and
perhaps more practical reason that HTML-as-hypermedia has fallen on hard times:
as the interactivity and expressiveness of HTML has remained frozen, the demands
of web users have continued to increase, calling for more and more interactive
web applications.
JavaScript-based applications coupled to data-oriented JSON APIs have stepped in
as a way to provide these more sophisticated user interfaces. It was the _user experience_ that
you could achieve in JavaScript, and that you couldn’t achieve in plain HTML,
that drove the web development community to the JavaScript-based Single Page
Application approach. The shift was not driven by any inherent superiority of
the Single Page Application as a system architecture.
It didn’t have to be this way. There is nothing _intrinsic_ to the idea of
hypermedia that prevents it from having a richer, more expressive interactivity
model than vanilla HTML. Rather than moving away from a hypermedia-based
approach, the industry could have demanded more interactivity from HTML.
Instead, building thick-client style applications within web browsers became the
standard, in an understandable move to a more familiar model for building rich
applications.
Not everyone set aside hypermedia, of course. There have been heroic efforts to
continue to advance hypermedia outside of HTML, efforts like
#indexed[HyTime], #indexed[VoiceXML], and #indexed[HAL].
But HTML, the most widely used hypermedia in the world, stopped making progress
as a hypermedia. The web development world moved on, solving the interactivity
problems with HTML by adopting JavaScript-based SPAs and, mostly inadvertently,
a completely different system architecture.
=== A Hypermedia Resurgence? <_a_hypermedia_resurgence>
It is interesting to think about how HTML _could_ have advanced. Instead of
stalling as a hypermedia, how could HTML have continued to develop? Could it
have kept adding new hypermedia controls and increasing the expressiveness of
existing ones? Would it have been possible to build modern web applications
within this original, hypermedia-oriented and RESTful model that made the early
web so powerful, so flexible, so much fun?
This might seem like idle speculation, but we have some good news on this score:
in the last decade a few idiosyncratic, alternative front end libraries have
arisen that attempt to get HTML moving again. Ironically, these libraries are
written in JavaScript, the technology that supplanted HTML as the center of web
development.
However, these libraries use JavaScript not as a _replacement_ for the
fundamental hypermedia system of the web.
Instead, they use JavaScript to augment HTML itself _as a hypermedia_.
These _hypermedia-oriented_ libraries re-center hypermedia as the core
technology in web applications.
==== Hypermedia-Oriented JavaScript Libraries <_hypermedia_oriented_javascript_libraries>
#index[Multi-Page Application (MPA)]
In the web development world there is an ongoing debate between the Single Page
Application (SPA) approach and what is now being called the
"Multi-Page Application" (MPA) approach. MPA is a modern name for the old, Web
1.0 way of building web applications, using links and forms located on multiple
web pages, submitting HTTP requests and getting HTML responses.
MPA applications, by their nature, are Hypermedia-Driven Applications: after
all, they are exactly what Roy Fielding was describing in his dissertation.
These applications tend to be clunky, but they work reasonably well. Many web
developers and teams choose to accept the limitations of plain HTML in the
interest of simplicity and reliability.
<NAME>, creator of Svelte.js, a popular SPA library, and a thought-leader
on the SPA side of the debate, has proposed a mix of this older MPA style and
the newer SPA style. Harris calls this approach to building web applications "transitional,"
in that it attempts to blend the MPA approach and the newer SPA approach into a
coherent whole. (This is somewhat similar to the "transitional" trend in
architecture, which combines traditional and modern architectural styles.)
"Transitional" is a fitting term for mixed-style applications, and it offers a
reasonable compromise between the two approaches, using either one as
appropriate on a case-by-case basis.
But this compromise still feels unsatisfactory.
Must we default to having these two very different architectural models in our
applications?
Recall that the crux of the trade-off between SPAs and MPAs is the
_user experience_, or interactivity of the application. This typically drives
the decision to choose one approach versus the other for an application or ---
in the case of a "transitional" application --- for a particular feature.
It turns out that by adopting a hypermedia-oriented library, the interactivity
gap between the MPA and the SPA approach closes dramatically. You can use the
MPA approach, that is, the hypermedia approach, for much more of your
application without compromising your user interface. You might even be able to
use the hypermedia approach for _all_ your application needs.
Rather than having an SPA with a bit of hypermedia around the edges, or some mix
of the two approaches, you can often create a web application that is _primarily_ or _entirely_ hypermedia-driven,
and that still satisfies the interactivity that your users require.
This can _tremendously_ simplify your web application and produce a much more
coherent and understandable piece of software. While there are still times and
places for the more complex SPA approach, which we will discuss later in the
book, by adopting a hypermedia-first approach and using a hypermedia-oriented
library to push HTML as far as possible, your web application can be powerful,
interactive _and_ simple.
One such hypermedia oriented library is #link("https://htmx.org")[htmx]. Htmx
will be the focus of Part Two of this book. We show that you can, in fact,
create many common "modern" UI features found in sophisticated Single Page
Applications by instead using the hypermedia model.
And, it is refreshingly fun and simple to do so.
==== Hypermedia-Driven Applications <_hypermedia_driven_applications>
When building a web application with htmx the term Multi-Page Application
applies _roughly_, but it doesn’t fully characterize the core of the application
architecture. As you will see, htmx doesn’t
_need_ to replace entire pages, and, in fact, an htmx-based application can
reside entirely within a single page. We don’t recommend this practice, but it
is possible!
So it isn’t quite right to call web applications built with htmx
"Multi-Page Applications." What the older Web 1.0 MPA approach and the newer
hypermedia-oriented library powered applications have in common is their use of _hypermedia_ as
their core technology and architecture.
Therefore, we use the term _Hypermedia-Driven Applications (HDAs)_
to describe both.
This clarifies that the core distinction between these two approaches and the
SPA approach _isn’t_ the number of pages in the application, but rather the
underlying _system_ architecture.
/ Hypermedia-Driven Application (HDA): #[
A web application that uses _hypermedia_ and _hypermedia exchanges_ as its
primary mechanism for communicating with a server.
]
So, what does an HDA look like up close?
Let’s look at an htmx-powered implementation of the simple JavaScript-powered
button above:
#figure(caption: [An htmx implementation],
```html
<button hx-get="/contacts/1" hx-target="#contact-ui"> <1>
Fetch Contact
</button>
```)
1. issues a `GET` request to `/contacts/1`, replacing the `contact-ui`.
As with the JavaScript powered button, this button has been annotated with some
attributes. However, in this case we do not have any (explicit) JavaScript
scripting.
Instead, we have _declarative_ attributes much like the `href`
attribute on anchor tags and the `action` attribute on form tags. The
`hx-get` attribute tells htmx: "When the user clicks this button, issue a `GET` request
to `/contacts/1`." The `hx-target` attribute tells htmx:
"When the response returns, take the resulting HTML and place it into the
element with the id `contact-ui`."
Here we get to the crux of htmx and how it allows you to build Hypermedia-Driven
Applications:
_The HTTP response from the server is expected to be in HTML format, not JSON_.
An HTTP response to this htmx-driven request might look something like this:
#figure(caption: [HTML],
```html
<details>
<div>
Contact: HTML Example
</div>
<div>
<a href="mailto:<EMAIL>">Email</a>
</div>
</details>
```)
This small bit of HTML would be placed into the element in the DOM with the id `contact-ui`.
Thus, this htmx-powered button is exchanging _hypermedia_ with the server, just
like an anchor tag or form might, and thus the interaction is still using the
basic hypermedia model of the web. Htmx _is_
adding functionality to this button (via JavaScript), but that functionality is _augmenting_ HTML
as a hypermedia. Htmx extends the hypermedia system of the web, rather than _replacing_ that
hypermedia system with a totally different architecture.
Despite looking superficially similar to one another it turns out that this
htmx-powered button and the JavaScript-based button are using extremely
different system architectures and, thus, approaches to web development.
As we walk through building a Hypermedia-Driven Application in this book, the
differences between the two approaches will become more and more apparent.
=== When Should You Use Hypermedia? <_when_should_you_use_hypermedia>
#index[hypermedia][when to use]
Hypermedia is often, though _not always_, a great choice for a web application.
Perhaps you are building a website or application that simply doesn’t
_need_ a huge amount of user-interactivity. There are many useful web
applications like this, and there is no shame in it! Applications like Amazon,
eBay, any number of news sites, shopping sites, message boards and so on don’t
need a massive amount of interactivity to be effective: they are mainly text and
images, which is exactly what the web was designed for.
Perhaps your application adds most of its value on the _server side_, by
coordinating users or by applying sophisticated data analysis and then
presenting it to a user. Perhaps your application adds value by simply sitting
in front of a well-designed database, with simple Create-Read-Update-Delete
(CRUD) operations. Again, there is no shame in this!
In any of these cases, using a hypermedia approach would likely be a great
choice: the interactivity needs of these applications are not dramatic, and much
of the value of these applications lives on the server side, rather than on the
client side.
All of these applications are amenable to what Roy Fielding called
"large-grain hypermedia data transfers": you can simply use anchor tags and
forms, with responses that return entire HTML documents from requests, and
things will work just fine. This is exactly what the web was designed to do!
By adopting the hypermedia approach for these applications, you will save
yourself a huge amount of client-side complexity that comes with adopting the
Single Page Application approach: there is no need for client-side routing, for
managing a client-side model, for hand-wiring in JavaScript logic, and so forth.
The back button will "just work." Deep linking will "just work." You will be
able to focus your efforts on your server, where your application is actually
adding value.
And, by layering htmx or another hypermedia-oriented library on top of this
approach, you can address many of the usability issues that come with vanilla
HTML and take advantage of finer-grained hypermedia transfers. This opens up a
whole slew of new user interface and experience possibilities, making the set of
applications that can be built using hypermedia _much_ larger.
But more on that later.
=== When Shouldn’t You Use Hypermedia? <_when_shouldnt_you_use_hypermedia>
#index[hypermedia][limitations]
So, what about that _not always_? When isn’t hypermedia going to work well for
an application?
One example that springs immediately to mind is an online spreadsheet
application. In the case of a spreadsheet, updating one cell could have a large
number of cascading changes that need to be made across the entire sheet. Worse,
this might need to happen _on every keystroke_.
In this case we have a highly dynamic user interface without clear boundaries as
to what might need to be updated given a particular change. Introducing a
hypermedia-style server round-trip on every cell change would hurt performance
tremendously.
This is simply not a situation amenable to the "large-grain hypermedia data
transfer" approach of the web. For an application like this we would certainly
recommend looking into using a sophisticated client-side JavaScript approach.
_However_ even in the case of an online spreadsheet there are likely areas where
the hypermedia approach might help.
The spreadsheet application likely also has a settings page. And perhaps that
settings page _is_ amenable to the hypermedia approach. If it is simply a set of
relatively straight-forward forms that need to be persisted to the server, the
chances are good that hypermedia would, in fact, work great for this part of the
app.
And, by adopting hypermedia for that part of your application, you might be able
to simplify that part of the application quite a bit. You could then save more
of your application’s _complexity budget_ for the core, complicated spreadsheet
logic, keeping the simple stuff simple.
Why waste all the complexity associated with a heavy JavaScript framework on
something as simple as a settings page?
#sidebar[A Complexity Budget][
Any software project has a complexity budget, explicit or not: there is only so
much complexity a given development team can tolerate and every new feature and
implementation choice adds at least a bit more to the overall complexity of the
system.
#index[complexity budget]
What is particularly nasty about complexity is that it tends to grow
exponentially: one day you can keep the entire system in your head and
understand the ramifications of a particular change, and a week later the whole
system seems intractable. Even worse, efforts to help control complexity, such
as introducing abstractions or infrastructure to manage the complexity, often
end up making things even more complex. Truly, the job of the good software
engineer is to keep complexity under control.
The sure-fire way to keep complexity down is also the hardest: say no. Pushing
back on feature requests is an art and, if you can learn to do it well, making
people feel like _they_ said no, you will go far.
Sadly this is not always possible: some features will need to be built. At this
point the question becomes: "what is the simplest thing that could possibly
work?" Understanding the possibilities available in the hypermedia approach will
give you another tool in your "simplest thing" tool chest.
]
=== Hypermedia: A Sophisticated, Modern System Architecture <_hypermedia_a_sophisticated_modern_system_architecture>
Hypermedia is often regarded as an old and antiquated technology in web
development circles, useful perhaps for static websites but certainly not a
realistic choice for modern, sophisticated web applications.
Seriously? Are we claiming that modern web applications can be built using it?
Yes, seriously.
Contrary to current popular opinion, hypermedia is an _innovative_
and _modern_ system architecture for building applications, in some ways _more modern_ than
the prevailing Single Page Application approaches. In the remainder of this book
we will reintroduce you to the core, practical concepts of hypermedia and then
demonstrate exactly how you can take advantage of this system architecture in
your own software.
In the coming chapters you will develop a firm understanding of all the benefits
and techniques enabled by this approach. We hope that, in addition, you will
also become as passionate about it as we are. <_html_notes_div_soup>
#html-note[\<div\> Soup][
The best-known kind of messy HTML is `<div>` soup.
When developers fall back on the generic `<div>` and `<span>` elements instead
of more meaningful tags, we either degrade the quality of our websites or create
more work for ourselves --- probably both.
For example, instead of adding a button using the dedicated `<button>`
element, a `<div>` element might have a `click` event listener added to it.
#figure(
```html
<div class="bg-accent padding-4 rounded-2" onclick="doStuff()">
Do stuff
</div>
```)
There are two main issues with this button:
- It’s not focusable --- the Tab key won’t get you to it.
- There’s no way for assistive tools to tell that it’s a button.
Yes, we can fix that by adding `role="button"` and
`tabindex="0"`:
#figure(
```html
<div class="bg-accent padding-4 rounded-2"
role="button"
tabindex="0"
onclick="doStuff()">Do stuff</div>
```)
These are easy fixes, but they’re things you have to _remember_. It’s also not
obvious from the HTML source that this is a button, making the source harder to
read and the absence of these attributes harder to spot. The source code of
pages with div soup is difficult to edit and debug.
To avoid div soup, become friendly with the HTML spec of available tags, and
consider each tag another tool in your tool chest. There might be things there
you don’t remember from before! (With the 113 elements currently defined in the
spec, it’s more of a tool _shed_).
Of course, not every UI pattern has a designated HTML element. We often need to
compose elements and augment them with attributes. Before you do, though,
rummage through the HTML tool chest. Sometimes you might be surprised by how
much is available. ]
|
https://github.com/EGmux/TheoryOfComputation | https://raw.githubusercontent.com/EGmux/TheoryOfComputation/master/final/prova1.typ | typst | #set heading(numbering: "1.")
=== 1 Seja *$L = {w in {a,b}^* | "w termina com ab"$}*
==== i) Dê uma AFD que reconheça L
#figure(image("../assets/afd.png", width: 50%), caption: []) <fig-afd>
==== ii) Prove por indução sobre w que para toda *$w in {a,b}^* "o AFD aceita sse" w in L$*
*$=> "ida"$*
*O AFD aceitar implica em $w in L$*\
Para o caso base temos que *$w = "ab"$* e de fato partindo do estado inicial
após duas transições a palavra é aceita.
Para a hipótese indutiva suponha que *$w = Sigma^n"ab"$* é aceito pelo AFD.
Devemos provar que para *$w = Sigma^(n+1)"ab"$* tambem deverá ser aceito.
note que podemos separar a cadeia *$w$* em
#math.equation(block: true, $ w = Sigma Sigma^n"ab" $)
tal que *$w_1 = Sigma$* e *$w_2 = Sigma^n"ab"$*
*$w_1 = b$*
nesse casos temos que se encontra no estado inicial e portanto a segunda cadeia
será aceita visto que *$Sigma^n "ab"$* é aceita partindo do estado inicial.
*$w_1 = a$*
Logo há 3 possíveis estados para *$Sigma^(n+1)$* , analisemo-os
- Se for o primeiro estado então pelo caso base temos que será aceita
- Se for o segundo caso estado então ocorerrá uma transição para o mesmo estado e
outra para o estado de aceitação, logo será aceita
- Se for o terceiro estado então ocorrerá uma transição para o segundo estado e
depois para o estado de aceitação, loge será aceita
como para todos estados será aceita então *$"a"Sigma^n"ab"$* será aceito
e como *$Sigma^(n+1)"ab"$* será aceito então está provada a hipotése indutiva e
para *$Sigma^m"ab", m in NN$* é aceita a palavra que pertence a linguagem de
*$L$* logo o AFD aceitar implica em *$w in L$*
*$<== "volta"$*
Se *$w in L$* então o AFD aceita
Suponha que *$w$* esteja em *$L$* logo tem a forma *$Sigma^m"ab", m in NN$* pela
definição de *$L$* .
após ler $Sigma^m$ caracteres o AFD só pode estar em 3 possíves estados,
analisemo-os
- Se o primeiro então ocorre uma função de transição para o segundo estado e
depois uma outra para estado de aceitação, logo AFD aceita
- Se o segundo então ocorre uma função de transição que faz o AFD permanecer no
mesmo estado e uma segunda função de transição para chegar no estado de
aceitação, logo AFD aceita
- Se o terceiro então ocorre uma função de transição para o segundo estado e uma
segunda transição para estado de aceitação, logo AFD aceita w
como AFD aceita toda cadeia da forma $Sigma^m"ab"$ então se $w in L => "w será aceita pelo AFD"$
como provamos a ida e a volta para tal proposição então é um caso de se e
somente se ⬚
=== iii) Dê uma gramatica regular que gera L
#math.equation(block: true, $ &= S -> A a b && \
&= A -> A a | A b | ϵ && \ $)
=== A derivada de uma linguagem $L subset.eq Sigma^*$ com respeito a um símbolo $a in Sigma$ é definida da seguinte forma
#math.equation(block: true, $ (cal(d) L)/(cal(d) a) = { w in Sigma^* | a w in L} $)
a derivada contem todas as cadeias que podem ser obtidas tomando uma cadeia em L
que começa com um $a$ e remove-se a(Cadeias que não começam com a são
completamente removidas) Mostre que se $L$ for regular então a operação de
derivada tambem será regular.
=== 4. Seja $G$ a graática livre de contexto $G$ com as seguintes produções
#math.equation(block: true, $ S -> a S | S b | a | b $)
==== a) Dê um autômato com pilha que reconheça L.
#figure(image("../assets/ap.png", width: 50%), caption: []) <fig-ap>
==== b) G é ambígua? Em caso positivo dê exemplo de uma cadeia que tenha duas derivações mais à esquerda (ou mais à direita) distintas.
Não é ambígua note que ambiguidade implica em $|w_1| = |w_2|$ via indução temos
que
para o caso base $|W_1|=1$ então $W= a, W= b$ e só há uma maneira de produzir
essas cadeias logo para $|W| =1$ é não ambigua
considerando agora hipótese indutiva $|W| =n $ é não ambígua provemos que $|W+1|$ tambem
não será ambigua.
sabemos que $|W|$ por hipótese é não ambígua a adição de um novo símbolo
possibilita que tenhamos apenas uma única regra de produção sendo aplicada $S -> a$ ou $S -> b$
- Como não há nenhuma outra sequência de aplicação de regras de produção então
essas são as únicas maneiras de gerar uma sequência de caracteres de tamanho 1
- Logo como as cadeias geradas de tamanho 1 são distintas então $|W+1|$ deverá ser
gerado de maneira não ambígua visto que a aplicação das $N$ primeiras regras de
produção resulta numa cadeia não ambígua.
==== c) Diga se G é linear, regular , linear á direita ou linear á esquerda, justificado suas respostas
não pode ser linear à direita visto que $S -> a S$ contradiz a condição de todas
regras de produção terem um único não terminal a direita. não pode ser linear à
esquerda visto que $S -> S b$ contradiz a condição de todas as regras de
produção terem um único não terminal a esquerda. deverá ser linear visto que
todas as regras apresentam um único terminal ou nenhum.
=== 5 Use o lema do bombeamento para mostra que :
==== i) $L_1 = {w w w | w in {a,b}^*}$ não é regular
Suponha que $L_1$ seja regular então
- $(forall n>=0) , x y^n z in L$
- $|x y| <= p$ onde p é o tamanho máximo que a cadeia $x y$ possa atingir e ser
ainda bombeada
- $|y| >= 1$ isto é $y$ não pode ser cadeia vazia
Suponha a seguinte estrutura
$x = w, y = w, z = w$
aplicando o lema do bombeamento teríamos para $p = 2|w|$
e que a cadeia $w w^2 w$ deveria ser aceita, visto que as três condições
anteriores foram satisfeitas, no entanto claramente não pertence a $w$ visto que $|x y^2 z| = 4|w|$ e $y in L => |y| = 3 |w|$
logo a linguagem não é regular.
==== ii) *$L_2 = {0^n\#0^(2n)\#0^(3n)|n >= 0}$* não é livre do contexto
Se *$L_2$* é livre de contexto, então
*$|v y| >= 0$ *\
*$ forall i >= 0 , u v^i x y^i z in L_2$*\
*$|v x y| <= p$*
considere a seguinte estrutura
$u = 0^n, v = \#, x = 0^(2n), y = \#, z = 0^(3n) $
de acordo com o lema do bombeamento para linguagems livres de contexto temos que
a seguinte cadeia deverá pertencer a $L_2$
$0^n\#^p 0^(2n) \#^p 0^(3n)$
mas notamos que não é o caso visto que há excesso do símbolo $\#$ e portanto a
linguagem não deverá ser livre de contexto por falhar a condição 2.
=== 3 Suponha que já tenha sido demonstrado que a linguagem $L_1 = {0^n^3 1^n | n>= 0}$ não é regular. Usando as propriedados de fechamento da classe de linguagens regulares
*mostre que a seguinte linguagem tambem não será regular*
#math.equation(block: true, $ L_2 = {a^k b c^l | k,l >= 0 and k != l^3} $)
se é regular então deverá ser fechada para complemento, mas note que
#math.equation(block: true, $ overline(L_2) = {a^k b c^l | k,l < 0 or k = l^3} $) para
que essa linguagem seja aceita então $k ,l <0 $ ou $k = l^3$ consideramos a
segunda possibilidade
gora considere a seguinte palavra aceita por $L_1 = 0^l^3 1^l$ e considere agora
que o alfabeto de $L_2 = {0,1}$ assim teríamos que
$0^l^3 1^l in overline(L_2) $ com $b = ϵ$ então $overline(L_2)$ é não regular
visto que contem uma cadeia que não pode ser reconhecida por AFD's e
consequentemente como o complemento é não regular e esperava-se ser regular, via
propriedade de fechamento das linguages regulares, deduzimos que $L_2$ é não
regular.
|
|
https://github.com/MattiaOldani/Informatica-Teorica | https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/complessità/13_richiami_matematici.typ | typst | = Richiami matematici: teoria dei linguaggi formali
Dato un problema $P$, finora ci siamo chiesti _"*esiste* un programma per la sua soluzione automatica?"_ Tramite questa domanda abbiamo potuto indagare la *teoria della calcolabilità*, il cui oggetto di studio è l'esistenza (_o meno_) di un programma per un dato problema.
In questa parte del corso studieremo la *teoria della complessità*, in cui entra in gioco una seconda investigazione: _"*come* funzionano i programmi per P?"_
Per rispondere a questa domanda, vogliamo sapere quante *risorse computazionali* utilizziamo durante la sua esecuzione. Vediamo altre domande a cui la teoria della complessità cerca di rispondere:
- dato un programma per il problema $P$, quanto tempo impiega il programma nella sua soluzione? Quanto spazio di memoria occupa?
- dato un problema $P$, qual è il minimo tempo impiegato dai programmi per $P$? Quanto spazio in memoria al minimo posso occupare per programmi per $P$?
- in che senso possiamo dire che un programma è *efficiente* in termini di tempo e/o spazio?
- quali problemi possono essere efficientemente risolti per via automatica?
Prima di iniziare, diamo una breve introduzione alla *teoria dei linguaggi formali*.
== Alfabeto, stringhe e linguaggi
Un *alfabeto* è un insieme finito di simboli $Sigma = {sigma_1, dots, sigma_k}$. Un alfabeto binario è un qualsiasi alfabeto composto da due soli simboli.
Una *stringa* su $Sigma$ è una sequenza di simboli di $Sigma$ nella forma $x = x_1 space dots space x_n$, con $x_i in Sigma$.
La *lunghezza* di una stringa $x$ indica il numero di simboli che la costituiscono e si indica con $|x|$. Una stringa particolare è la *stringa nulla*, che si indica con $epsilon$ ed è tale che $|epsilon| = 0$.
Indichiamo con $Sigma^*$ l'insieme delle stringhe che si possono costruire sull'alfabeto $Sigma$, compresa la stringa nulla. L'insieme delle stringhe formate da almeno un carattere è definito da $Sigma^+ = Sigma^* slash {epsilon}$.
Un *linguaggio* $L$ su un alfabeto $Sigma$ è un sottoinsieme $L subset.eq Sigma^*$, che può essere finito o infinito.
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion-pkgs/touying-utils-current-heading.typ | typst | Apache License 2.0 | // path: lib.typ
// - level (auto, int): The level
#let current-heading(level: auto, hierachical: true, depth: 9999) = {
let current-page = here().page()
if not hierachical and level != auto {
let headings = query(heading).filter(h => (
h.location().page() <= current-page and h.level <= depth and h.level == level
))
return headings.at(-1, default: none)
}
let headings = query(heading).filter(h => h.location().page() <= current-page and h.level <= depth)
if headings == () {
return
}
if level == auto {
return headings.last()
}
let current-level = headings.last().level
let current-heading = headings.pop()
while headings.len() > 0 and level < current-level {
current-level = headings.last().level
current-heading = headings.pop()
}
if level == current-level {
return current-heading
}
}
-----
// contains: level, hierachical, depth
#import "lib.typ": *
#current-heading(/* range 0..1 */)[];
-----
// contains: "body"
#import "lib.typ": *
#current-heading(level: /* range 0..1 */)[];
-----
// contains: false, true
#import "lib.typ": *
#current-heading(hierachical: /* range 0..1 */)[];
-----
// contains: 9999, 1
#import "lib.typ": *
#current-heading(depth: /* range 0..1 */)[];
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-0530.typ | typst | Apache License 2.0 | #let data = (
(),
("ARMENIAN CAPITAL LETTER AYB", "Lu", 0),
("ARMENIAN CAPITAL LETTER BEN", "Lu", 0),
("ARMENIAN CAPITAL LETTER GIM", "Lu", 0),
("ARMENIAN CAPITAL LETTER DA", "Lu", 0),
("ARMENIAN CAPITAL LETTER ECH", "Lu", 0),
("ARMENIAN CAPITAL LETTER ZA", "Lu", 0),
("ARMENIAN CAPITAL LETTER EH", "Lu", 0),
("ARMENIAN CAPITAL LETTER ET", "Lu", 0),
("ARMENIAN CAPITAL LETTER TO", "Lu", 0),
("ARMENIAN CAPITAL LETTER ZHE", "Lu", 0),
("ARMENIAN CAPITAL LETTER INI", "Lu", 0),
("ARMENIAN CAPITAL LETTER LIWN", "Lu", 0),
("ARMENIAN CAPITAL LETTER XEH", "Lu", 0),
("ARMENIAN CAPITAL LETTER CA", "Lu", 0),
("ARMENIAN CAPITAL LETTER KEN", "Lu", 0),
("ARMENIAN CAPITAL LETTER HO", "Lu", 0),
("ARMENIAN CAPITAL LETTER JA", "Lu", 0),
("ARMENIAN CAPITAL LETTER GHAD", "Lu", 0),
("ARMENIAN CAPITAL LETTER CHEH", "Lu", 0),
("ARMENIAN CAPITAL LETTER MEN", "Lu", 0),
("ARMENIAN CAPITAL LETTER YI", "Lu", 0),
("ARMENIAN CAPITAL LETTER NOW", "Lu", 0),
("ARMENIAN CAPITAL LETTER SHA", "Lu", 0),
("ARMENIAN CAPITAL LETTER VO", "Lu", 0),
("ARMENIAN CAPITAL LETTER CHA", "Lu", 0),
("ARMENIAN CAPITAL LETTER PEH", "Lu", 0),
("ARMENIAN CAPITAL LETTER JHEH", "Lu", 0),
("ARMENIAN CAPITAL LETTER RA", "Lu", 0),
("ARMENIAN CAPITAL LETTER SEH", "Lu", 0),
("ARMENIAN CAPITAL LETTER VEW", "Lu", 0),
("ARMENIAN CAPITAL LETTER TIWN", "Lu", 0),
("ARMENIAN CAPITAL LETTER REH", "Lu", 0),
("ARMENIAN CAPITAL LETTER CO", "Lu", 0),
("ARMENIAN CAPITAL LETTER YIWN", "Lu", 0),
("ARMENIAN CAPITAL LETTER PIWR", "Lu", 0),
("ARMENIAN CAPITAL LETTER KEH", "Lu", 0),
("ARMENIAN CAPITAL LETTER OH", "Lu", 0),
("ARMENIAN CAPITAL LETTER FEH", "Lu", 0),
(),
(),
("ARMENIAN MODIFIER LETTER LEFT HALF RING", "Lm", 0),
("ARMENIAN APOSTROPHE", "Po", 0),
("ARMENIAN EMPHASIS MARK", "Po", 0),
("ARMENIAN EXCLAMATION MARK", "Po", 0),
("ARMENIAN COMMA", "Po", 0),
("ARMENIAN QUESTION MARK", "Po", 0),
("ARMENIAN ABBREVIATION MARK", "Po", 0),
("ARMENIAN SMALL LETTER TURNED AYB", "Ll", 0),
("ARMENIAN SMALL LETTER AYB", "Ll", 0),
("ARMENIAN SMALL LETTER BEN", "Ll", 0),
("ARMENIAN SMALL LETTER GIM", "Ll", 0),
("ARMENIAN SMALL LETTER DA", "Ll", 0),
("ARMENIAN SMALL LETTER ECH", "Ll", 0),
("ARMENIAN SMALL LETTER ZA", "Ll", 0),
("ARMENIAN SMALL LETTER EH", "Ll", 0),
("ARMENIAN SMALL LETTER ET", "Ll", 0),
("ARMENIAN SMALL LETTER TO", "Ll", 0),
("ARMENIAN SMALL LETTER ZHE", "Ll", 0),
("ARMENIAN SMALL LETTER INI", "Ll", 0),
("ARMENIAN SMALL LETTER LIWN", "Ll", 0),
("ARMENIAN SMALL LETTER XEH", "Ll", 0),
("ARMENIAN SMALL LETTER CA", "Ll", 0),
("ARMENIAN SMALL LETTER KEN", "Ll", 0),
("ARMENIAN SMALL LETTER HO", "Ll", 0),
("ARMENIAN SMALL LETTER JA", "Ll", 0),
("ARMENIAN SMALL LETTER GHAD", "Ll", 0),
("ARMENIAN SMALL LETTER CHEH", "Ll", 0),
("ARMENIAN SMALL LETTER MEN", "Ll", 0),
("ARMENIAN SMALL LETTER YI", "Ll", 0),
("ARMENIAN SMALL LETTER NOW", "Ll", 0),
("ARMENIAN SMALL LETTER SHA", "Ll", 0),
("ARMENIAN SMALL LETTER VO", "Ll", 0),
("ARMENIAN SMALL LETTER CHA", "Ll", 0),
("ARMENIAN SMALL LETTER PEH", "Ll", 0),
("ARMENIAN SMALL LETTER JHEH", "Ll", 0),
("ARMENIAN SMALL LETTER RA", "Ll", 0),
("ARMENIAN SMALL LETTER SEH", "Ll", 0),
("ARMENIAN SMALL LETTER VEW", "Ll", 0),
("ARMENIAN SMALL LETTER TIWN", "Ll", 0),
("ARMENIAN SMALL LETTER REH", "Ll", 0),
("ARMENIAN SMALL LETTER CO", "Ll", 0),
("ARMENIAN SMALL LETTER YIWN", "Ll", 0),
("ARMENIAN SMALL LETTER PIWR", "Ll", 0),
("ARMENIAN SMALL LETTER KEH", "Ll", 0),
("ARMENIAN SMALL LETTER OH", "Ll", 0),
("ARMENIAN SMALL LETTER FEH", "Ll", 0),
("ARMENIAN SMALL LIGATURE ECH YIWN", "Ll", 0),
("ARMENIAN SMALL LETTER YI WITH STROKE", "Ll", 0),
("ARMENIAN FULL STOP", "Po", 0),
("ARMENIAN HYPHEN", "Pd", 0),
(),
(),
("RIGHT-FACING ARMENIAN ETERNITY SIGN", "So", 0),
("LEFT-FACING ARMENIAN ETERNITY SIGN", "So", 0),
("ARMENIAN DRAM SIGN", "Sc", 0),
)
|
https://github.com/zenor0/simple-neat-typst-cv | https://raw.githubusercontent.com/zenor0/simple-neat-typst-cv/master/cv/utils/icons.typ | typst | MIT License |
#let show-icon-text(icon, name, size: 0.7em, reverse: false) = {
box[
#if reverse {
name
}
#box(
image(icon, height: size)
)
#if not reverse {
name
}
]
}
#let set-up-icon(doc) = {
show "Python" : name => show-icon-text("../assets/icons/python.svg", name)
show "C++" : name => show-icon-text("../assets/icons/cplusplus.svg", name)
show "Vue" : name => show-icon-text("../assets/icons/vuedotjs.svg", name)
show "TypeScript" : name => show-icon-text("../assets/icons/typescript.svg", name)
show "Git" : name => show-icon-text("../assets/icons/git.svg", name)
show "Docker" : name => show-icon-text("../assets/icons/docker.svg", name)
show "Golang": name => show-icon-text("../assets/icons/go.svg", name)
show "MySQL" : name => show-icon-text("../assets/icons/mysql.svg", name)
show "RabbitMQ" : name => show-icon-text("../assets/icons/rabbitmq.svg", name)
show "Redis" : name => show-icon-text("../assets/icons/redis.svg", name)
show "Pandas" : name => show-icon-text("../assets/icons/pandas.svg", name)
show "Flask" : name => show-icon-text("../assets/icons/flask.svg", name)
show "Socket.io" : name => show-icon-text("../assets/icons/socketdotio.svg", name)
show "Typst" : name => show-icon-text("../assets/icons/typst.svg", name)
show "Word" : name => show-icon-text("../assets/icons/microsoftword.svg", name)
show "Excel" : name => show-icon-text("../assets/icons/microsoftexcel.svg", name)
show "Powerpoint" : name => show-icon-text("../assets/icons/microsoftpowerpoint.svg", name)
show "Davinci Resolve" : name => show-icon-text("../assets/icons/davinciresolve.svg", name)
show "Premiere Pro" : name => show-icon-text("../assets/icons/adobepremierepro.svg", name)
show "Photoshop" : name => show-icon-text("../assets/icons/adobephotoshop.svg", name)
show "Illustrator" : name => show-icon-text("../assets/icons/adobeillustrator.svg", name)
show "After Effects" : name => show-icon-text("../assets/icons/adobeaftereffects.svg", name)
show "Google" : name => show-icon-text("../assets/icons/google.svg", name)
show "Stackoverflow" : name => show-icon-text("../assets/icons/stackoverflow.svg", name)
show "LLMs" : name => show-icon-text("../assets/icons/openai.svg", name)
show "字节跳动" : name => show-icon-text("../assets/icons/bytedance.svg", name)
show "哔哩哔哩" : name => show-icon-text("../assets/icons/bilibili.svg", name)
doc
} |
https://github.com/maxhves/maxhves-cv | https://raw.githubusercontent.com/maxhves/maxhves-cv/main/README.md | markdown | ## Maxhves resume
This CV/resume template is created using [Typst](https://typst.app), and this repository serves both as an evolving record of my personal resume and as a template for anyone who wants to create a similar document.
As a newcomer to Typst, I cannot guarantee that this template is a perfect example of best practices, but I am pleased with the current result. Over time, I will continue to refine the codebase and enhance the overall appearance of the resume.
## Preview
| Page 1 | Page 2 |
| ------ | ------ |
|  |  |
|
|
https://github.com/Mouwrice/thesis-typst | https://raw.githubusercontent.com/Mouwrice/thesis-typst/main/README.md | markdown | This repository contains the complete typst project used to write my thesis.
The compiled pdf is hosted on GitHub Pages at https://mouwrice.github.io/thesis-typst/thesis.pdf
|
|
https://github.com/Maso03/Bachelor | https://raw.githubusercontent.com/Maso03/Bachelor/main/template.typ | typst | MIT License | #let template(
/// the title of your thesis
/// type: str
title: "Thesis Title",
/// single author name or list of author names
/// type: str | array<str>
author: "<NAME>",
/// date of submission
/// type: datetime
date: datetime(year: 1970, month: 1, day: 1),
/// formatting template for the date
/// type: str
date-format: "[day].[month].[year]",
/// List of logos to show at the top of the titlepage
/// type: array<image>
logos: (),
/// Additional details to show at the bottom of the titlepage
/// type: dictionary<str, str>
details: (:),
/// Your abstract
/// type: content
abstract: lorem(100),
/// Dictionary of acronyms
/// type: dictionary<str, str>
acronyms: (:),
/// Rest of the document
/// type: content
body,
) = {
let author = if type(author) != array { (author,) } else { author }
set document(title: title, author: author, date: date)
set page(paper: "a4", margin: 2.5cm, numbering: "I")
set pagebreak(weak: true)
set text(size: 12pt, font: "CMU Sans Serif")
set par(leading: 1em, justify: true)
set list(indent: 0.75em)
set enum(indent: 0.75em)
set math.equation(numbering: "1")
set bibliography(title: "References")
set outline(indent: auto, depth: 2, fill: repeat(" . "))
show par: set block(spacing: 1.5em)
show heading.where(level: 1): set block(above: 2em, below: 2em)
show heading.where(level: 2): set block(above: 2em, below: 1.5em)
show heading.where(level: 3): set block(above: 1.5em, below: 1em)
show heading.where(level: 1): set text(size: 24pt)
show heading.where(level: 2): set text(size: 20pt)
show heading.where(level: 3): set text(size: 16pt)
show heading: it => {
if it.level == 1 { pagebreak() }
if it.numbering == none { it } else {
grid(
columns: (auto, auto),
box(width: 48pt, counter(heading).display()),
it.body,
)
}
}
show outline.entry.where(level: 1): it => [
#if it.element.func() != heading { return it }
#show ".": ""
#v(8pt) #strong(it)
]
show raw.where(block: true): set align(left)
show raw.where(block: true): set par(justify: false)
show raw.where(block: true): set text(size: 8pt)
show raw.where(block: true): set block(
radius: 2pt, inset: 8pt, width: 100%,
stroke: luma(128), fill: luma(240),
)
show raw.where(block: false): box.with(
radius: 2pt, inset: (x: 3pt), outset: (y: 3pt),
stroke: luma(128), fill: luma(240),
)
{
set align(center)
set page(numbering: none)
set par(justify: false)
let author = author.join(" & ")
let date = date.display(date-format)
stack(
spacing: 1fr,
stack(dir: ltr, spacing: 1fr, ..logos),
text(size: 20pt, strong(title)),
[
#show strong: set text(size: 14pt)
#show strong: it => [#linebreak() #it #parbreak()]
präsentiert dem *Fachbereich Informatik* für den *
Bachelor of Science* an der *DHBW Stuttgart* von #strong(author) eingereicht am #strong(date)
],
table(
columns: (auto, 1fr, auto), align: left, stroke: none,
..details.keys().map(it => (strong(it), none)).zip(details.values()).flatten(),
),
)
}
counter(page).update(1)
align(horizon + center, {
heading(outlined: false, level: 2, [Abstract])
abstract
pagebreak()
})
align(horizon, [
#heading(outlined: false, level: 2, [Selbstständigkeitserklärung])
Hiermit erkläre ich ausdrücklich:
+ dass die vorliegende Arbeit mit dem Titel #emph(title) vollständig von mir selbst verfasst wurde, sofern im Text oder in den Quellenangaben nichts anderes vermerkt ist, oder dass sie im Folgenden anerkannt wird;
+ dass ich die direkt oder indirekt aus anderen Quellen übernommenen Gedanken an den entsprechenden Stellen des Dokuments angegeben habe;
+ Diese Arbeit wurde weder ganz noch teilweise für einen Abschluss an dieser oder einer anderen Universität oder Einrichtung eingereicht;
+ Ich habe diese Arbeit in der Vergangenheit nicht veröffentlicht;
+ die gedruckte Fassung, falls es eine solche gibt, der eingereichten Fassung entspricht.
Ich bin mir bewusst, dass eine unehrliche Erklärung rechtliche Konsequenzen nach sich ziehen wird.
#v(32pt)
Stuttgart, #date.display(date-format)
#v(32pt)
#line(length: 256pt)
#author.join(", ")
])
outline()
heading(level: 1, [Acronyms])
table(
columns: (auto, auto), inset: (left: 0em, right: 1em), stroke: none,
..acronyms.keys().map(strong).zip(acronyms.values()).flatten(),
)
set heading(numbering: "1.1")
set page(numbering: "1 / 1")
counter(page).update(1)
body
}
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/experiment/weeks/week3.typ | typst | #import "../../utils.typ": *
#section("Data")
#subsection("Data-Mining")
This is *random collection of data*, which will later be processed.
- advertising
- predictive analysis
- statistical process needed
#subsection("Data-Farming")
This is *targeted collection of data*, which will later be processed.
- detection of weaknesses
- adherence to norms
- evaluation of median and variance values.
#subsection("Data matters")
- which data do we use?
- is the data neutral, or is there a clear bias?
- do we collect targeted data or random data?
- note that targeted data will always include our own biases!
- do we collect small samples or massive amounts of data?
#section("Terms")
*these terms will be in german since I will have to complete the exam in that ""great""
language, sorry.*
#subsection("Merkmalsträger")
This is the object with the attribute of interest.\
For example: We would like to measure failure rate for cars, hence a car is our
object of interest -> Merkmalsträger.
#subsection("Grundgesamtheit")
The amount of all objects of interest together
#subsubsection("Abgrenzungsmerkmal")
This determines the category of which each object of interest must be in, in
order to get considered for the amount of all objects of interest.\
These attributes have 3 different categories:\
- space/raum : all objects(ex. machines) within a room
- time/zeit : all measured data within a measurement interval
- object/sachlich : all objects(ex. machines) of a brand
#subsection("Merkmal / Attribute")
The attribute of interest during a statistical investigation. For example, the
failure rate of something is an attribute.
#subsection("Merkmalswerte / Attribute Value")
This is the value of the attribute, note that each attribute might have their
own unit -> percentage, hours, etc.
#section("Scala")
#subsection("Nominal Scala")
these are named attributes that have no specific value, e.g. they are all of the
same value, trying to calculate with these is stupid. Measurable Values:\
- #text(purple)[Difference(non scalar)/Verschiedenartigkeit]
#grid(
rows: (auto, auto, auto),
columns: (auto, auto),
gutter: 8pt,
[Attribute],
[Attribute value],
[gender],
[attack helicopter, pony, penguin],
[cat],
[globi, grief],
)
#subsection("Ordinal Scala")
This is essentially the same with names, or rather categories as values, but,
this time the categories are ranked, e.g. *not equal*.\
*Note the ranking is from best to worst*\
Measurable Values:
- #text(purple)[Difference(non scalar)/Verschiedenartigkeit]
- #text(purple)[rank]
#grid(
rows: (auto, auto, auto),
columns: (auto, auto),
gutter: 8pt,
[Attribute],
[Attribute value],
[Operating Sytem],
[Linux , BSD , Winshit],
[Editor],
[Neovim, helix, vscode],
)
#subsection(" Metric Scala / Kardinal/Cardinal Scala")
This is an overall term for the 2 sub scales.\
- real numbers
- ordered depending on the value of the attribute
- quantitative values
- depending on the starting point -> either interval or context scala
- is the representation of an experiment
#subsubsection("Interval Scala")
On this scale, the *0 point is chosen*, this means that you will have to check
how the value relates to other values on that scale. E.g. *you can't just assume
that double scalar value means double the real world
value!* For example, 20db is not double the value of 10db, sound is a
logarithmic value!\
Measurable Values:
- #text(purple)[Difference(non scalar)/Verschiedenartigkeit]
- #text(purple)[rank]
- #text(purple)[scalar differences -> distance]
#grid(
rows: (auto, auto, auto),
columns: (auto, auto),
gutter: 8pt,
[Attribute],
[Attribute value],
[Sound],
[10db , 20db , 30db],
[Temperature (Celsius!)],
[-10C, 0C, 20C],
)
#text(
teal,
)[The reason we can't assume double the scalar value means double the real world
value is in the 0 point. As soon as you change the 0 point, you can no longer
compare values with each other. A good example is weight, if you randomly place
the 0 value at 20kg, you will influence your evaluation of the average weight.]
#subsubsection("Verhältniss Skala/Context Scala")
In this scale, *the 0 point is exactly 0*. For this scale, *double the scalar
value is double the real world value*, aka 20kg is double the weight of 10kg.\
Measurable Values:
- #text(purple)[Difference(non scalar)/Verschiedenartigkeit]
- #text(purple)[rank]
- #text(purple)[scalar differences -> distance]
- #text(
purple,
)[relatives > a person in group x is 2 times as heavy as one in group y]
#grid(
rows: (auto, auto, auto),
columns: (auto, auto),
gutter: 8pt,
[Attribute],
[Attribute value],
[Weight],
[10kg , 20kg , 40kg],
[Temperature (Kelvin!)],
[0K, 10K, 200K],
)
#align(
center,
[#image("../../Screenshots/2023_10_05_09_05_15.png", width: 80%)],
)
#section("Statistical Investigation")
#subsection("Planning")
- choose attributes
- choose techniques
- choose visualization for data
- choose analysis technique
#subsection("Collecting data")
- choose Abgrenzunsgmerkmale/attribute categories
- choose attributes to investigate
- choose data spectrum -> has an effect on tolerable error
- specify what the expected result should be, what are the objectives?
#subsubsection("Primary statistics")
This means collecting data for this specific usecase, this means that the data
is specifically collected for our attributes, increasing our potential accuracy.
#columns(2, [
#text(green)[Benefits]
- accuracy
#colbreak()
#text(red)[Downsides]
- more work
- more time needed
- more expensive
])
#subsubsection("Secondary statistics")
This means using existing data, which is then converted for our experiment.
#columns(2, [
#text(green)[Benefits]
- less work
- less time needed
- cheaper
#colbreak()
#text(red)[Downsides]
- accuracy
])
#subsubsection("Teil/VollErhebung")
This is just *sampling* or the full dataset.
#subsubsection("Urliste")
#align(center, [#image("../../Screenshots/2023_10_05_09_38_48.png", width: 80%)])
#subsubsection("Häufigkeitsverteilung / Frequencyspread")
- defines how many times $x_i$ appears)
- can either be *absolute* or *relative* values
- $h_i$ = *absolute* frequency (amount of measurements with value x)
- $f_i$ = *relative* frequency (all measurements with value x divided by all measurements)
- n = amount of all measurements
- v = amount of different attributes
#align(center, [#image("../../Screenshots/2023_10_05_09_43_29.png", width: 60%)])
#subsubsection("kumulierte Häufigkeitsverteilung / Accumulated Frequencyspread")
- $H_i$ = absolute accumulated frequency
- $F_i$ = relative accumulated frequency
- n = amount of all measurements
- v = amount of different attributes
#align(center, [#image("../../Screenshots/2023_10_05_09_44_41.png", width: 60%)])
#subsubsection("Last tipps")
If you have too many attributes, then the table is no longer clear, in this case you should group these attributes:
#align(center, [#image("../../Screenshots/2023_10_05_09_48_42.png", width: 60%)])
|
|
https://github.com/Akida31/anki-typst | https://raw.githubusercontent.com/Akida31/anki-typst/main/typst/examples/simple.typ | typst | #import "../src/lib.typ" as anki
#import anki.theorems: item
#show: anki.setup.with(enable_theorems: true)
#set heading(numbering: "1.")
#let theorem = item("Theorem", initial_tags: ("proof",))
#let example = item("Example", initial_tags: ("example",))
= Heading1
== Subheading1
=== SubSubheading1
= Heading
== Subheading
// update the item counter manually
// #anki.theorems.set_thmcounter(items: (3, 5, 7))
#theorem("Euclid")[
Theorem-content
][
This is a proof
]
#example("Pythagoras")[
Did you know?
$ a^2 + b^2 = c^2 $
]
// run typst query examples/simple.typ '<anki-export>' --input export=true --root=.
// to get something like this (the format isn't stable):
/*
[
{
"func": "metadata",
"value": {
"id": "Euclid",
"deck": "Heading::Subheading",
"model": "",
"fields": {
"front": {
"plain": "Euclid"
},
"back": {
"plain": {
"func": "text",
"text": "Theorem-content"
}
},
"proof": {
"plain": {
"func": "text",
"text": "This is a proof"
}
}
},
"tags": [
"proof"
]
},
"label": "<anki-export>"
},
{
"func": "metadata",
"value": {
"id": "Pythagoras",
"deck": "Heading::Subheading",
"model": "",
"fields": {
"front": {
"plain": "Pythagoras"
},
"back": {
"content": " Did you know? + = ",
"page_start": 2,
"page_end": 2
}
},
"tags": [
"example"
]
},
"label": "<anki-export>"
}
]
*/
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/place-background.typ | typst | Apache License 2.0 | // Test placing a background image on a page.
---
#set page(paper: "a10", flipped: true)
#set text(fill: white)
#place(
dx: -10pt,
dy: -10pt,
image(
"/files/tiger.jpg",
fit: "cover",
width: 100% + 20pt,
height: 100% + 20pt,
)
)
#align(bottom + right)[
_Welcome to_ #underline[*Tigerland*]
]
|
https://github.com/indicatelovelace/typstTemplates | https://raw.githubusercontent.com/indicatelovelace/typstTemplates/main/themes/dhbw-thesis/config.typ | typst | MIT License | #import "@preview/drafting:0.1.1": *
#import "@preview/hydra:0.5.0": hydra
#import "./utils.typ": authorMetadata, flattenAuthorMetadata
#let conf(
title: none,
authors: (), /*
author is an array of dicts. The only key that is necessary is "name".
Any other property supplied is printed at the bottom end of the page, as per the guidelines, in the format "#key: #value", in the given order. For multiple authors, this data is collected, deduplicated, and either displayed as per usual or, if possible, listed as line seperated values.
*/
courseName: none,
submissionDate: datetime.today().display(), // expects content, not a datetime, so use .display()
submissionPlace: "Musterort",
thesisType: none, // e.g Bachelor Thesis
companyLogo: [], // expects any content, e.g. an image
universityLogo: [],
university: none, // e.g. DHBW Ravensburg
abstractTitle: none, // No abstract if none
abstract: none,
appendix: none, // no appendix if none
glossary: none, // the user is expected to create their own glossarium, with a package of their choice, or by hand. This can of course also include an list of symbols etc. No glossarium is printed if none
bibliographyTitle: none, // No bibliography if none
bibliographyFiles: (),
bibliographyStyle: "ieee",
declarationOnHonour: true,
storageDeclaration: true,
draft: true,
language: "de", // enable language-specific quotes with ISO 639-1/2/3 language code
font: "IBM Plex Serif",
fontSize: 12pt,
smallcapsFont: "Linux Libertine",
mathFont: "IBM Plex Serif",
outlines: ((none, none),), // e.g. (table, "List of Tables") in the submitted order
equationTitle: none, // no equation table if none, equations are not a regular figure, only block equations are listed
equationSupplement: none, // no eqution supplement if none
doc,
) = {
let author = authorMetadata(authors)
let name = author.remove("name").join(", ")
set page(
paper: "a4",
number-align: right,
margin: (rest: 2.5cm),
)
set text(
lang: language,
region: language,
font: font,
size: fontSize,
)
// Add some spacing between figures and caption
set figure(gap: 1.2em)
show outline: it => {
set par(first-line-indent: 0em, leading: 1em, justify: false, linebreaks: "simple")
show ref: x => none
it
}
show figure: set block(above: 2.0em, below: 2.0em, breakable: false)
show figure.where(kind: image): it => {
set align(center)
set text(font: "IBM Plex Sans")
set par(leading: 0.5em)
block[#it.body #text(font: font)[#it.caption] + v(0em)]
}
show math.equation: set text(font: mathFont)
// Add numbering to equations
if equationSupplement != none {
set math.equation(numbering: "(1)", supplement: equationSupplement)
} else {
set math.equation(numbering: none, supplement: none)
}
// leading is line spacing
set par(first-line-indent: 1em, leading: 1.5em, justify: true, linebreaks: "optimized")
show raw.where(block: true): it => {
set block(above: 1em, below: 1em)
it
}
show raw: it => {
set figure(supplement: [Command Line Output])
it
}
show table: it => {
set par(first-line-indent: 0em, hanging-indent: 0em, justify: false, leading: 0.7em)
it
}
set table.header(repeat: true)
// Configure headings.
set heading(numbering: "1.1")
show heading: it => {
let first = true
// Don't indent headings
set par(first-line-indent: 0em)
// Set some defaults
set text(weight: "bold")
let size = 1em
let style = "normal"
// Set size and style based on the heading level
if (it.level == 1) {
size = 1.5em
locate(loc => {
let levels = counter(heading).at(loc)
if levels != (1,) {
pagebreak(weak: true)
}
})
} else if (it.level == 2) {
size = 1.3em
} else if (it.level == 3) {
size = 1.2em
} else {
style = "italic"
}
// Apply styling defined in the condition above
set text(size: size, style: style)
// Some spacing above the heading
v(size / 2, weak: false)
// Display heading numbers until level four, if numbering is enabled
// Shouldn't really use more than three heading levels, so no more from level four onwards!
if it.numbering != none and it.level < 4 {
counter(heading).display()
h(0.75em, weak: true)
}
// Print the heading itself
it.body
// Some spacing below the heading
v(size / 2, weak: false)
}
if draft == true {
set-page-properties(margin-left: 2.5cm, margin-right: 2.5cm)
}
// Print company and / or university logo, if given
grid(
columns: (30%, 40%, 30%),
//rows: (), TODO
if companyLogo != none {
companyLogo
},
[],
if universityLogo != none {
universityLogo
}
)
// Print author and university information
text(hyphenate: false)[
#align(
center,
[
//#v(2%)
#v(3em)
#text(size: 14pt, title)
#v(4em)
#text(weight: "bold", upper(thesisType)) \
#v(11em)
#if courseName != none [#if language == "de" [des Studiengangs] else [of the degree programm] #text(
courseName,
weight: "bold",
)]
#if language == "de" [an der ] else [at the] #university
#v(4em)
#if language == "de" [von] else [by]
#v(1em)
#text(name, weight: "bold")
#v(4em)
#submissionDate
],
)
#align(
bottom + left,
[
#table(
columns: (50%, 50%),
align: (x, y) => (left, left).at(x),
stroke: none,
..flattenAuthorMetadata(dict: author)
)
],
)]
// Enable page numbers starting by declatation on honour, with roman numbering
counter(page).update(0)
set page(numbering: "I")
if storageDeclaration {
heading(level: 1, outlined: false, numbering: none)[
#text(lang: "de")[Erklärung zur unbegrenzten Aufbewahrung]
]
par(
first-line-indent: 0em,
text(lang: "de")[
Hiermit genehmigen die Autoren der Arbeit eine unbefristete Aufbewahrung durch den Studiengang #courseName und durch die Betreuenden.
],
)
v(8em)
for n in name.split(",") {
grid(
columns: (auto, auto),
column-gutter: 1fr,
row-gutter: 20pt,
[#submissionPlace, #submissionDate], [],
[_Ort, Datum_], emph[#n],
) + v(40pt)
}
}
if declarationOnHonour {
heading(level: 1, outlined: false, numbering: none)[
Ehrenwörtliche Erklärung
]
par(
first-line-indent: 0em,
text(lang: "de")[
Ich versichere hiermit, dass ich die vorliegende Arbeit mit dem Titel
\ #strong(title) \
selbstständig verfasst und keine anderen als die angegebenen Quellen und Hilfsmittel benutzt habe.
],
)
v(8em)
for n in name.split(",") {
grid(
columns: (auto, auto),
column-gutter: 1fr,
row-gutter: 20pt,
[#submissionPlace, #submissionDate], [],
[_Ort, Datum_], emph[#n],
) + v(40pt)
}
}
// Prints the outline for figures with given name only if at least one item of that kind exists
let printOutlineIfContentExists(title, kind) = {
context {
let elems = query(figure.where(kind: kind))
let count = elems.len()
if count > 0 {
par(first-line-indent: 0em, leading: 1em)[
#heading(level: 1, numbering: none)[#title]
#outline(
title: none,
target: figure.where(kind: kind),
)
]
}
}
}
// Outlines for equations
let printOutlineIfEquationExists(title) = {
context {
let elems = query(math.equation.where(block: true))
let count = elems.len()
if count > 0 and title != none {
par(first-line-indent: 0em, leading: 1em)[
title#heading(level: 1, numbering: none)[#title]
#outline(
title: none,
target: math.equation.where(block: true),
)
]
}
}
}
show par: set block(spacing: 1.8em, breakable: true)
if abstractTitle != none {
par(first-line-indent: 0em)[
#heading(level: 1, outlined: false, numbering: none)[#abstractTitle]
#abstract
]
}
// Outline / Table of contents
par(first-line-indent: 0em, leading: 1em)[
#outline(depth: 3, indent: true)
]
for (name, kind) in outlines {
printOutlineIfContentExists(name, kind)
}
printOutlineIfEquationExists(equationTitle)
{
show par: set block(spacing: 1em)
set par(leading: 1em)
glossary
}
set page(header: context {
set align(right)
set text(font: smallcapsFont)
smallcaps[#hydra(1)]
})
/* set page(header: [
#context {
let head = query(selector(heading).after(loc)).find(h => {
h.location().page() == loc.page() and h.level == 1
})
if (head != none) { } else {
let l1h = query(selector(heading).before(loc)).filter(headIt => {
headIt.level == 1
})
let oldHead = if l1h != () {
l1h.last().body
} else {
[]
}
let count = counter(heading.where(level: 1)).display()
set align(right)
set text(font: "Linux Libertine")
smallcaps[#count #oldHead]
}
}
])
*/
// Use arabic numbering for content
set page(numbering: "1")
counter(page).update(1)
// Display paper content
doc
set page(header: none)
pagebreak(weak: true)
if bibliographyFiles.len() > 0 and bibliographyTitle != none {
par(justify: false)[#bibliography(bibliographyFiles, title: bibliographyTitle, full: false)]
}
if appendix != none {
counter(heading).update(1)
counter(figure).update(1)
for it in outlines {
let k = it.at(1)
counter(figure.where(kind: k)).update(0)
}
set heading(numbering: "A.1")
set figure(numbering: "A")
show heading: it => {
if it.level > 1 {
set heading(outlined: false, supplement: none)
}
it
}
appendix
}
}
|
https://github.com/AntoniosBarotsis/typst-assignment-template | https://raw.githubusercontent.com/AntoniosBarotsis/typst-assignment-template/master/README.md | markdown | # Typst Assignment Template
A simple assignment template for [Typst](https://typst.app/).
## Example Usage
You can find an example [here](./example.typ) as well as its render [here](./example.pdf).
## Status
I haven't used this extensively *yet* so I don't know what weird behaviors might be lying around,
I'm quite new to this. Feel free to use it and let me know if you find any issues!
Any feature requests or ideas to improve this/make it more configurable are welcome!
Not sure if I'll introduce some form of versioning even before package management makes an
appearance in Typst but it is something I'll keep in mind if I keep making frequent (breaking)
changes.
|
|
https://github.com/jomaway/typst-teacher-templates | https://raw.githubusercontent.com/jomaway/typst-teacher-templates/main/ttt-exam/lib/points.typ | typst | MIT License | #import "@preview/ttt-utils:0.1.2": grading
#import "i18n.typ": ling
#let total_points = context grading.get_points().sum()
// Show a box with the total_points
#let point-sum-box = {
box(stroke: 1pt, inset: 0.8em, radius: 3pt)[
#set align(bottom)
#stack(
dir:ltr,
spacing: 0.5em,
box[#text(1.4em, sym.sum) :],
line(stroke: 0.5pt), "/",
[#total_points #smallcaps[PTs]]
)
]
}
// Show a table with point distribution
#let point-table = {
context {
let points = grading.get_points()
box(radius: 5pt, clip: true, stroke: 1pt,
table(
align: (col, _) => if (col == 0) { end } else { center },
inset: (x: 1em, y:0.6em),
fill: (x,y) => if (x == 0 or y == 0) { luma(230) },
rows: (auto, auto, 1cm),
columns: (auto, ..((1cm,) * points.len()), auto),
ling("assignment"), ..points.enumerate().map(((i,_)) => [#{i+1}]), ling("total"),
ling("points"), ..points.map(str), total_points,
ling("awarded"),
)
)
}
}
#let small-grading-table(grading-scale, dist) = {
if grading.validate-scale(grading-scale) {
table(
columns: (1fr,) * grading-scale.len(),
inset: 0.5em,
align: center,
table.header(..grading-scale.rev().map(g => [#g.grade])),
..grading-scale.rev().map(g => ([ #g.upper-limit - #g.lower-limit]) ).flatten(),
..dist.values().map(v => [#v x])
)
}
}
|
https://github.com/Dav1com/wasm-random-plugin | https://raw.githubusercontent.com/Dav1com/wasm-random-plugin/master/README.md | markdown | MIT License | # wasm-random-plugin
Wasm plugin for generating predictable and protable random numbers. Meant as a Typst plugin
|
https://github.com/liuguangxi/suiji | https://raw.githubusercontent.com/liuguangxi/suiji/main/examples/random-bitmap.typ | typst | MIT License | #set document(date: none)
#import "/src/lib.typ": *
#set page(width: auto, height: auto, margin: 0pt)
#{
let seed = 0
let unit = 1mm
let (width, height) = (200,) * 2
let rng = gen-rng(seed)
let data = ()
(rng, data) = integers(rng, low: 0, high: 256, size: width * height * 3)
grid(columns: (unit,)*width, rows: unit,
..data.chunks(3).map(((r,g,b)) => grid.cell(fill: rgb(r,g,b))[])
)
}
|
https://github.com/sarahzeller/tud | https://raw.githubusercontent.com/sarahzeller/tud/main/_extensions/sarahzeller/tud/typst-template.typ | typst | MIT License | #let slides(
title: none,
subtitle: none,
author: none,
date: datetime.today(),
beamer-format: (16, 9),
theme-background: rgb("#00305D"),
theme-text: white,
font: "Open Sans",
has-section-slides: true,
doc
) = {
// Variables for configuration.
let scale = 2cm
let width = beamer-format.at(0) * scale
let height = beamer-format.at(1) * scale
let theme-muted = theme-background.lighten(75%)
let margin = (x: 2em, y: 4em);
let background(color: theme-background) = (
place(top + left, dx: - margin.x, dy: - margin.y)[
#rect(
width: 100% + 2 * margin.x, height: 100% + 2 * margin.y,
fill: gradient.radial(color.lighten(50%).saturate(75%), color.lighten(20%)),
),
<background>
]
)
let hasBackground(selector, loc) = query(selector, loc)
.filter(l => l.location().page() == loc.page())
.len() > 0
// Setup.
set document(
title: title,
author: author,
)
set text(
font: font,
size: 22pt,
)
set page(
width: width,
height: height,
margin: margin,
header: [
#locate(loc => {
let sections = query(heading.where(level: 1), loc)
let offset = if (has-section-slides) { 1 } else { 0 }
let link-offset = if (has-section-slides) { 0 } else { 1 }
let sectionsWithPages = sections
.enumerate(start: 1)
.map(((i, s)) => {(
let start = counter(page).at(s.location()).first() + offset,
let stop = if (i < sections.len()) {
counter(page).at(sections.at(i).location()).first()
} else {
counter(page).final(loc).first() + offset
},
return (pageRange: range(start, stop), label: s.body)
)})
if hasBackground(selector(<background>).after(loc), loc) == false {
set text(
size: 0.4em,
)
grid(
columns: range(sections.len()).map(_ => 1fr),
gutter: 1em,
rows: 1,
..sectionsWithPages.map(((pageRange, label)) => [
#let is-active = pageRange.contains(loc.page()-1)
#let color = if (is-active == true) {theme-background} else { theme-muted}
#show link: set text(fill: color)
#if pageRange.len() > 0 [
#link((page: pageRange.first() + link-offset, x: 0em, y:0em), label)
]
#set align(horizon)
#stack(
dir: ltr,
spacing: .5em,
..pageRange.map(i => {
let radius = if (loc.page() == i+1) {
.3em
} else {
.15em
}
return box(height: .6em,
link((page: i+1, x: 0em, y: 0em),
circle(radius: radius, fill: color)
)
)
})
)
])
)
}
})
],
footer-descent: 2em,
footer: [
#locate(loc => {
if hasBackground(selector(<background>).before(loc), loc) == false {
set text(
size: 0.4em,
fill: theme-background
)
set align(horizon)
grid(columns: (auto, auto, 1fr), rows: 2.5em, gutter: 1em, ..(
box(image("_extensions/sarahzeller/tud/TU_Dresden_Logo_blau.svg", height: 2.5em)),
[ #author #sym.dot.op #title],
counter(page).display(
"1 · 1",
both: true,
)
))
}
})
]
)
show link: l => {
if type(l.dest) == "string" and l.dest.starts-with("http") {
underline(l)
} else {
l
}
}
show figure.caption: set text(size: 0.6em)
show "->": sym.arrow
//format code blocks
show raw.where(block: true): set text(size: 0.8em)
show heading.where(level: 1): title => {
if has-section-slides == true {
pagebreak()
block(width: 100%, height: 100%)[
#set align(horizon)
#background()
#text(
fill: theme-text,
title
)
]
} else {
pagebreak(weak: true)
}
}
show heading.where(level: 2): title => {
pagebreak(weak: true)
title
}
// Title page.
background()
rect(width: 100%, height: 100%, stroke: none)[
#image("_extensions/sarahzeller/tud/TU_Dresden_Logo_weiss.svg", width: 15%)
#set text(fill: theme-text)
#set align(horizon)
#text(size: 50pt, weight: "bold", title)
#linebreak()
#text(size: 30pt, subtitle)
#v(2em)
#text(size: 25pt, author)
#linebreak()
#text(size: 15pt, date.display("[day].[month].[year]"))
]
pagebreak(weak: true)
counter(page).update(1)
// Actual content.
doc
} |
https://github.com/RandomcodeDev/FalseKing-Design | https://raw.githubusercontent.com/RandomcodeDev/FalseKing-Design/main/engine/platforms.typ | typst | = Platforms
The engine will support at least Windows and Linux. All desktop platforms will use Steam, all others will use the platform's official store.
#table(
columns: 3,
[*Platform*], [*Toolchain*], [*Graphics API(s)*],
[Windows], [MSVC, GDK], [DirectX 12, Vulkan, OpenGL],
[Linux], [LLVM], [Vulkan, OpenGL],
[Xbox Series X|S], [MSVC, GDKX], [DirectX 12],
[PlayStation 5], [LLVM, PS5 SDK], [GNM],
[Nintendo Switch/Switch 2], [LLVM, Switch SDK], [Vulkan]
)
These platforms may be supported purely out of personal interest:
#table(
columns: 4,
[*Platform*], [*Toolchain*], [*Graphics API(s)*], [*Notes*],
[Xbox 360], [Ancient MSVC], [DirectX 9], [Some dependencies will need to be ported, and this will be extremely difficult.
If LLVM could be modified to target PowerPC Windows, this would become far easier.],
[PlayStation 3], [Ancient GCC, possibly LLVM], [GCM, OpenGL], [Haven't tried this very hard yet, it's probably possible],
[PlayStation Portable], [GCC], [OpenGL], [Crashes in homebrew startup code],
[Bare metal x86], [LLVM], [Software renderer], [This will take a lot of engineering and probably not be worth it]
)
|
|
https://github.com/0x1B05/algorithm-journey | https://raw.githubusercontent.com/0x1B05/algorithm-journey/main/practice/note/content/预备知识.typ | typst | #import "../template.typ": *
= 算法预备知识
== acm风格算法笔试中处理输入和输出
=== 读写 api
1. 规定数据量(`BufferedReader`、`StreamTokenizer`、`PrintWriter`),其他语言有对等的写法
2. 按行读(`BufferedReader`、`PrintWriter`),其他语言有对等的写法
3. 不要用 `Scanner`、`System.out`,`IO` 效率慢
#code(
caption: [acm风格测试方式],
)[
```java
// 子矩阵的最大累加和问题,不要求会解题思路,后面的课会讲
// 每一组测试都给定数据规模
// 需要任何空间都动态生成,在大厂笔试或者比赛中,这种方式并不推荐
// 测试链接 : https://www.nowcoder.com/practice/cb82a97dcd0d48a7b1f4ee917e2c0409?
// 请同学们务必参考如下代码中关于输入、输出的处理
// 这是输入输出处理效率很高的写法
// 提交以下的code,提交时请把类名改成"Main",可以直接通过
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class Code02_SpecifyAmount{
public static void main(String[] args) throws IOException {
// 把文件里的内容,load进来,保存在内存里,很高效,很经济,托管的很好
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 一个一个读数字
StreamTokenizer in = new StreamTokenizer(br);
// 提交答案的时候用的,也是一个内存托管区
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
while (in.nextToken() != StreamTokenizer.TT_EOF) { // 文件没有结束就继续
// n,二维数组的行
int n = (int) in.nval;
in.nextToken();
// m,二维数组的列
int m = (int) in.nval;
// 装数字的矩阵,临时动态生成
int[][] mat = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
in.nextToken();
mat[i][j] = (int) in.nval;
}
}
out.println(maxSumSubmatrix(mat, n, m));
}
out.flush();
br.close();
out.close();
}
// 求子矩阵的最大累加和,后面的课会讲
public static int maxSumSubmatrix(int[][] mat, int n, int m) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
// 需要的辅助数组,临时动态生成
int[] arr = new int[m];
for (int j = i; j < n; j++) {
for (int k = 0; k < m; k++) {
arr[k] += mat[j][k];
}
max = Math.max(max, maxSumSubarray(arr, m));
}
}
return max;
}
// 求子数组的最大累加和,后面的课会讲
public static int maxSumSubarray(int[] arr, int m) {
int max = Integer.MIN_VALUE;
int cur = 0;
for (int i = 0; i < m; i++) {
cur += arr[i];
max = Math.max(max, cur);
cur = cur < 0 ? 0 : cur;
}
return max;
}
}
```
]
=== 动态空间 vs 静态空间
- 不推荐:临时动态空间
- 推荐:全局静态空间
#code(
caption: [静态空间],
)[
```java
// 展示acm风格的测试方式
// 子矩阵的最大累加和问题,不要求会解题思路,后面的课会讲
// 每一组测试都给定数据规模
// 任何空间都提前生成好,一律都是静态空间,然后自己去复用,推荐这种方式
// 测试链接 : https://www.nowcoder.com/practice/cb82a97dcd0d48a7b1f4ee917e2c0409?
// 请同学们务必参考如下代码中关于输入、输出的处理
// 这是输入输出处理效率很高的写法
// 提交以下的code,提交时请把类名改成"Main",可以直接通过
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
public class Code03_StaticSpace {
// 题目给定的行的最大数据量
public static int MAXN = 201;
// 题目给定的列的最大数据量
public static int MAXM = 201;
// 申请这么大的矩阵空间,一定够用了
// 静态的空间,不停复用
public static int[][] mat = new int[MAXN][MAXM];
// 需要的所有辅助空间也提前生成
// 静态的空间,不停复用
public static int[] arr = new int[MAXM];
// 当前测试数据行的数量是n
// 当前测试数据列的数量是m
// 这两个变量可以把代码运行的边界规定下来
public static int n, m;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer in = new StreamTokenizer(br);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
while (in.nextToken() != StreamTokenizer.TT_EOF) {
n = (int) in.nval;
in.nextToken();
m = (int) in.nval;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
in.nextToken();
mat[i][j] = (int) in.nval;
}
}
out.println(maxSumSubmatrix());
}
out.flush();
br.close();
out.close();
}
// 求子矩阵的最大累加和,后面的课会讲
public static int maxSumSubmatrix() {
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
// 因为之前的过程可能用过辅助数组
// 为了让之前结果不干扰到这次运行,需要自己清空辅助数组需要用到的部分
Arrays.fill(arr, 0, m, 0);
for (int j = i; j < n; j++) {
for (int k = 0; k < m; k++) {
arr[k] += mat[j][k];
}
max = Math.max(max, maxSumSubarray());
}
}
return max;
}
// 求子数组的最大累加和,后面的课会讲
public static int maxSumSubarray() {
int max = Integer.MIN_VALUE;
int cur = 0;
for (int i = 0; i < m; i++) {
cur += arr[i];
max = Math.max(max, cur);
cur = cur < 0 ? 0 : cur;
}
return max;
}
}
```
]
=== 按行读取
#code(
caption: [按行读取],
)[
```java
// 展示acm风格的测试方式
// 测试链接 : https://www.nowcoder.com/exam/test/70070648/detail?pid=27976983
// 其中,7.A+B(7),就是一个没有给定数据规模,只能按行读数据的例子
// 此时需要自己切分出数据来计算
// 请同学们务必参考如下代码中关于输入、输出的处理
// 这是输入输出处理效率很高的写法
// 提交以下的code,提交时请把类名改成"Main",可以直接通过
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Code04_ReadByLine {
public static String line;
public static String[] parts;
public static int sum;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
while ((line = in.readLine()) != null) {
parts = line.split(" ");
sum = 0;
for (String num : parts) {
sum += Integer.valueOf(num);
}
out.println(sum);
}
out.flush();
in.close();
out.close();
}
}
```
]
== 对数器
- 有一个想要测的方法 a, 一个暴力尝试的方法 b(不追求时间复杂度,好想好写的).
- 生成一个随机样本发生器, 可以产生随机样本.
- 在方法 a 跑一遍,得到结果 a; 在方法 b 跑一遍,得到结果 b.
- 把两个结果进行比较, 如果发现两个结果不一样,要么方法 a 错了;要么方法 b
错了;要么两个方法都错.
- 给一个小样本, 通过瞪眼法看看 a 结果和 b 的结果, 就可以知道方法 a 和 方法 b
正确性.
- 把方法 a 和方法 b 都改对, 然后把随机样本产生数的长度设置大些, 值也更随机些.
跑个几千万次, 如果没有错误出现, 就可以确定方法 a 对了, 这个比 oj 更加可靠.
=== 举例
例如把冒泡排序和插入排序 2 个作对数器,方法 b 是系统自带的排序方法
#code(caption: [系统自带的排序方法])[
```java
public static void comparator(int[]arr){
Arrays.sort(arr);
}
```
]
`generateRandomArray` 方法如下:
#code(
caption: [generateRandomArray],
)[
```java
public static int[] generateRandomArray(int maxSize, int maxValue) {
// Math.random()->[0,1)所有的小数,等概率返回一个
// Math.random()*N->[0,N)所有小数,等概率返回一个
// (int)(Math.random()*N)->[0,N-1]所有的整数,等概率返回一个
int[] arr = new int[(int) ((maxSize + 1) * Math.random())];// 长度随机
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
}
return arr;
}
```
]
主函数如下:
#code(caption: [主函数])[
```java
public static void main(String[] args) {
int testTime = 500000;
int maxSize = 100;
int maxValue = 100;
boolean succeed = true;
for (int i = 0; i < testTime; i++) {
int[] arr1 = generateRandomArray(maxSize, maxValue);
int[] arr2 = copyArray(arr1);
insertionSort(arr1);
comparator(arr2);
if (!isEqual(arr1, arr2)) {// 打印arr1打印arr2
succeed = false;
break;
}
}
System.out.println(succeed ? "Nice!" : "Fucking fucked!");
if(!succeed){
int[] arr = generateRandomArray(maxSize, maxValue);
printArray(arr);
insertionSort(arr);
printArray(arr);
}
}
```
]
=== 对数器模板
#code(caption: [对数器模板])[
```java
public static OutputType destMethod(InputType input) {
.....
}
public static OutputType comparator(InputType input) {
.....
}
public static InputType randGen(int maxSize, int maxValue) {
.....
}
public static void main(String[] args){
int testTime = 500000;
int maxSize = 100;
int maxValue = 100;
boolean succeed = true;
for(int i = 0; i <testTime; i++){
InputType input = randGen(maxSize, maxValue);
OutputType res1 = destMethod(input);
OutputType res2 = comparator(input);
if(!isEqual(res1,res2)){
succeed = false;
break;
}
if (i % 1000 == 0) {
System.out.println(i + "round pass!!");
}
}
System.out.println(succeed ? "Nice!" : "Oops!");
if(!succeed){
InputType input = randGen(maxSize, maxValue);
print("input:"+input);
OutputType res1 = destMethod(input);
print("dest method output:"+output);
OutputType res2 = comparator(input);
print("comparator output:"+output);
}
}
```
]
== 比较器
1. 比较器的实质就是重载比较运算符
2. 比较器可以很好地应用在特殊标准地排序上
3. 比较器可以很好地应用在根据特殊标准排序的结构上
#code(
caption: [比较器],
)[
```java
// 以学生类为例子
public static class Student {
public String name;
public int id;
public int age;
public Student(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
}
public static void main(String[] args) {
Student student1 = new Student("A", 2, 20);
Student student2 = new Student("B", 3, 22);
Student student3 = new Student("C", 1, 21);
Student[] students = new Student[] { student1, student2, student3 };
// 这个排序方法默认为升序,传入比较器,根据id的降序来排序
Arrays.sort(students, new IdDescendingComparator());
}
// 编写比较器,实现Comparator接口
public static class IdDescendingComparator implements Comparator<Student> {
// 返回负数的时候,第一个参数排在前面
// 返回正数的时候,第二个参数排在前面
// 返回0的时候,谁在前面都无所谓
@Override
public int compare(Student o1, Student o2) {
// 后减前是降序
// 前减后是升序
return o2.id - o1.id;
}
}
```
]
== master 公式
master 公式:也叫主定理.它提供了一种通过渐近符号表示递推关系式的方法. 应用 Master
定理可以很简便的求解递归方程.(递归就是系统帮做压栈和出栈的过程)
$T [n] = a*T[n/b] + O (n^d)$
#tip("Tip")[
- $T[n]$->母问题的规模
- $T[n/b]$代表递归的子问题的规模
- $a$是调用次数
- $O(n^d)$除去递归之外的额外操作的复杂度
]
+ 当`d<log(b,a)`时,时间复杂度为`O(n^(logb a))`
+ 当`d=log(b,a)`时,时间复杂度为`O((n^d)*logn)`
+ 当`d>log(b,a)`时,时间复杂度为`O(n^d)`
=== 递归求数组的最大值
```java
public static int getMax(int[] arr) {
return process(arr, 0, arr.length-1);
}
// 在[L,R]上求最大值
public static int process(int[] arr, int L, int R) {
if (L == R) {
return arr[L];
}
int mid = L + ((R - L) >> 1);//中点
int leftMax = process(arr, L, mid);
int rightMax = process(arr, mid+1, R);
return Math.max(leftMax, rightMax);
}
```
=== master 公式说明
将整个数组分为两部分,则左部分为`n/2`,右部分也为`n/2`,两者相加,返回操作为`O(1)`
则得到的式子如下:
`a=2,b=2,d=0`、`T [n] = 2*T[n/2] + O (1)` 、`d<log(b,a)`则时间复杂度为`O(n)`
== 根据数据量猜解法
一个基本事实
- C/C++运行时间1s,java/python/go等其他语言运行时间1s\~2s,
- 对应的常数指令操作量是 10^7 \~ 10^8,不管什么测试平台,不管什么cpu,都是这个数量级
所以可以根据这个基本事实,来猜测自己设计的算法最终有没有可能在规定时间内通过
运用 *根据数据量猜解法技巧* 的必要条件:
+ 题目要给定各个入参的范围最大值,正式笔试、比赛的题目一定都会给,面试中要和面试官确认
+ 对于自己设计的算法,时间复杂度要有准确的估计
问题规模和可用算法
#three-line-table[
| \ |logn |n| n\*logn| n\*根号n| n^2| 2^n| n!|
| - | - | - | - | - | - | - | - |
|n <= 11 |Yes| Yes| Yes| Yes| Yes| Yes| Yes|
|n <= 25 |Yes| Yes| Yes| Yes| Yes| Yes| No |
|n <= 5000 |Yes| Yes| Yes| Yes| Yes| No | No|
|n <= 10^5 |Yes| Yes| Yes| Yes| No | No | No|
|n <= 10^6 |Yes| Yes| Yes| No |No | No | No|
|n <= 10^7 |Yes| Yes| No | No |No | No | No|
|n >= 10^8 |Yes| No | No| No |No | No | No|
]
=== 题目1 : 最优的技能释放顺序
现在有一个打怪类型的游戏,这个游戏是这样的,你有n个技能,每一个技能会有一个伤害,同时若怪物低于一定的血量,则该技能可能造成双倍伤害,每一个技能最多只能释放一次,已知怪物有m点血量,现在想问你最少用几个技能能消灭掉他(血量小于等于00)。
输入描述:
第一行输入一个整数T,代表有T组测试数据。对于每一组测试数据,一行输入2个整数`n`和`m`,代表有`n`个技能,怪物有`m`点血量。接下来`n`行,每一行输入两个数`A`和`x`,代表该技能造成的伤害和怪物血量小于等于`x`的时候该技能会造成双倍伤害
输出描述:
对于每一组数据,输出一行,代表使用的最少技能数量,若无法消灭输出`-1`。
#tip("Tip")[
```
1≤T≤100
1≤n≤10
0≤m≤10^6
1≤A,x≤m
```
]
#example("Example")[
输入:
```
3
3 100
10 20
45 89
5 40
3 100
10 20
45 90
5 40
3 100
10 20
45 84
5 40
```
输出:
```
3
2
-1
```
说明:
总共3组数据
- 对于第一组:我们首先用技能1,此时怪物血量剩余90,然后使用技能3,此时怪物剩余血量为85,最后用技能2,由于技能2在怪物血量小于89的时候双倍伤害,故此时怪物已经消灭,答案为3
- 对于第二组:我们首先用技能1,此时怪物血量剩余90,然后用技能2,由于技能2在怪物血量小于90的时候双倍伤害,故此时怪物已经消灭,答案为2
- 对于第三组:我们首先用技能1,此时怪物血量剩余90,然后使用技能3,此时怪物剩余血量为85,最后用技能2,由于技能2在怪物血量小于84的时候双倍伤害,故此时怪物无法消灭,输出-1
]
==== 解答
注意到技能的数据小,直接全排列。
#code(caption: [解答])[
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
/**
* Code01_KillMonsterEverySkillUseOnce
*/
public class Code01_KillMonsterEverySkillUseOnce {
public static int MAXN = 11;
public static int[] kill = new int[MAXN];
public static int[] blood = new int[MAXN];
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer in = new StreamTokenizer(br);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
while (in.nextToken() != StreamTokenizer.TT_EOF) {
int T = (int) in.nval;
for (int i = 0; i < T; i++) {
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int m = (int) in.nval;
for (int j = 0; j < n; j++) {
in.nextToken();
kill[j] = (int)in.nval;
in.nextToken();
blood[j] = (int)in.nval;
}
int ans = compute(n, m, 0);
out.println(ans==Integer.MAX_VALUE ? -1:ans);
}
}
out.flush();
out.close();
br.close();
}
// n->技能数量,hp->怪物血量,cur->当前来到第几个技能
public static int compute(int n, int hp, int cur) {
if (hp <= 0) {
return cur;
}
if (cur == n) {
return Integer.MAX_VALUE;
}
int ans = Integer.MAX_VALUE;
for (int j = cur; j < n; j++) {
swap(cur, j);
ans = Math.min(ans, compute(n, hp-(hp>blood[cur]?kill[cur]:kill[cur]*2), cur+1));
swap(cur, j);
}
return ans;
}
public static void swap(int i, int j){
int tmp = blood[i];
blood[i] = blood[j];
blood[j] = tmp;
int tmp2 = kill[i];
kill[i] = kill[j];
kill[j] = tmp2;
}
}
```
]
#tip("Tip")[
当怪物不死的时候不能返回-1(结果只会返回-1了),要返回`Integer.MAX_VALUE`作标记.
]
=== #link("https://leetcode.cn/problems/super-palindromes/")[题目2 : 超级回文数的数目]
如果一个正整数自身是回文数,而且它也是一个回文数的平方,那么我们称这个数为超级回文数。
现在,给定两个正整数 L 和 R (以字符串形式表示),返回包含在范围 [L, R] 中的超级回文数的数目。
```
1 <= len(L) <= 18
1 <= len(R) <= 18
```
`L` 和 `R` 是表示 `[1, 10^18)` 范围的整数的字符串
==== 解答
10^18 -> 枚举根号 -> 枚举前一半 故
前一半(1-10^5) -> (奇/偶)回文(10^9) ->10^18
|
|
https://github.com/yoshiatsu163/typst-test | https://raw.githubusercontent.com/yoshiatsu163/typst-test/master/test.typ | typst | // 脚注とフッター
// ヘッダー
// 色設定
#let dark = true
#let colorset = if dark {
(
text: rgb("ADBAC7"),
inverse_text: rgb("404040"),
background: rgb("22272e"),
caution: rgb("6CB6FF"),
cautionpale: rgb("353747"),
alert: rgb("F47067"),
alertpale: rgb("7a594e")
)
} else {
(
text: rgb("#404040"),
inverse_text: rgb("fafafa"),
background: rgb("fafafa"),
caution: rgb("005CC5"),
cautionpale: rgb("a6c7ed"),
alert: rgb("D73A49"),
alertpale: rgb("f0c7cb")
)
}
#let conf(
title: none,
author: (),
abstract: [],
titlesize: 17pt, //タイトルのフォントサイズ
authorsize: 12pt, //著者名のフォントサイズ
textsize: 13.5pt, // 本文フォントサイズ
abstract_title_size: 17pt, //アブストタイトルのサイズ
abstract_text_size: 10pt, //アブスト本文サイズ
dark: false, // ダークモード設定
doc,
) = {
// ページ設定
set page(
width: 390pt,
height: 590pt,
margin: (x: 1.0cm, y: 1.0cm),
number-align: center,
fill: colorset.at("background")
)
// パラグラフデフォルト設定
set par(
leading: 0.8em, //行送り
first-line-indent: 1em, //一行目インデント
justify: true,
)
// 見出し
show heading: it => {
set align(left)
let fontsize = if it.level == 1 {
textsize * 1.1
} else {
textsize * 1.1
}
set text(fontsize, weight: "regular")
counter("heading").step(level: it.level)
block(strong(
counter("heading").display() + " " + it.body
))
}
//本文のフォントと色
set text(
font: "UD Digi Kyokasho NP-R",
// font: "Noto Sans JP",
lang: "ja",
size: textsize,
fill: colorset.at("text")
)
// 強調表示
show strong: set text(font: "IBM Plex Sans JP Smbld")
//show strong: set text(font: "Noto Sans JP Mdm")
// 箇条書きと別行立て数式の設定
set list(indent: 1em)
set enum(
indent: 1em,
numbering: "(1)"
)
set math.equation(numbering: "(1)")
align(center, text(titlesize)[
*#title*
])
align(center, text(authorsize)[
#author
])
par(justify: false)[
//#v(16pt)
#align(center, text(abstract_title_size)[*Abstract*]) \
#v(-30pt)
#align(center, text(abstract_text_size)[
#abstract
])
]
v(8pt)
columns(1, doc)
}
// theorem 用カウンタの定義
#let theorem-number = counter("theorem-number")
// theorem 関数の定義。コマンドみたいに使える
#let theorem(title: none, kind: "定理", body) = {
let title-text = {
if title == none {
emph[#kind 2.#theorem-number.display()]
} else {
emph[#kind 2.#theorem-number.display() 【#title】]
}
}
box(stroke: (left: 1pt), inset: (left: 5pt, top: 2pt, bottom: 5pt))[
#title-text #h(0.5em)
#body
]
theorem-number.step()
}
#let dualblock(
densecolor: none,
palecolor: none,
upper_text_color: none,
lower_text_color: none,
upper_text: [],
lower_text: [],
) = {
set align(center)
block(
width: 390pt - 2.0cm,
fill: densecolor,
inset: 4pt,
below: 0pt
)[
#align(
left,
text(fill: upper_text_color)[#upper_text]
)
]
block(
width: 390pt - 2.0cm,
fill: palecolor,
inset: 8pt,
above: 0pt
)[#text(fill: lower_text_color)[#lower_text]]
}
#let note_num = counter("note_num")
#let note(
title: none,
content: []
) = {
note_num.step()
dualblock(
densecolor: colorset.at("caution"),
palecolor: colorset.at("cautionpale"),
upper_text_color: colorset.at("inverse_text"),
lower_text_color: colorset.at("text"),
upper_text: strong([Note #note_num.display() 【#title】]),
lower_text: content
)
}
#let imp_num = counter("imp_num")
#let imp(
title: none,
content: []
) = {
imp_num.step()
dualblock(
densecolor: colorset.at("alert"),
palecolor: colorset.at("alertpale"),
upper_text_color: colorset.at("inverse_text"),
lower_text_color: colorset.at("text"),
upper_text: strong([重要 #imp_num.display() 【#title】]),
lower_text: content
)
}
#show: doc => conf(
title: [
*日本国憲法前文*
],
author: [
吉田敦司 \
研究第一部 材料グループ
],
abstract: lorem(80),
dark: true,
doc
)
= *緒言*
#strong("日本国民")は正当に選挙された国会における代表者を通じて行動し、われらとわれらの子孫のために、諸国民と協和による成果と、わが国全土にわたって自由のもたらす恵沢を確保し、政府の行為によって再び戦争の惨禍が起こることのないようにすることを決意し、ここに主権が国民に存することを宣言し、この憲法を確定する#cite("electronic")。
#note(title: "テスト", content: "そもそも国政は国民の厳粛な信託によるものであって、その権威は国民に由来し、その権力は国民の代表者がこれを行使し、その福利は国民がこれを享受する。これは人類普遍の原理であり、この憲法は、かかる原理に基づくものである。われらはこれに反する一切の憲法、法令及び詔勅を排除する。")
== test
日本国民は、恒久の平和を念願し、人間相互の関係を支配する崇高な理想を深く自覚するのであって、平和を愛する諸国民の公正と信義を信頼して、われらの安全と生存を保持しようと決意した。われらは平和を維持し、専制と隷従、圧迫と偏狭を地上から永遠に除去しようと努めている国際社会において、名誉ある地位を占めたいと思う。われらは全世界の国民が、ひとしく恐怖と欠乏から免れ、平和の内に生存する権利を有することを確認する。
われらは、いずれの国家も、自国のことのみに専念して他国を無視してはならないのであって、政治道徳の法則は、普遍的なものであり、この法則に従うことは、自国の主権を維持し、他国と対等関係に立とうとする各国の責務であると信ずる。
日本国民は、国家の名誉にかけて、全力をあげて崇高な理想と目的を達成することを誓う。
#strong("日本国民")は正当に選挙された国会における代表者を通じて行動し、われらとわれらの子孫のために、諸国民と協和による成果と、わが国全土にわたって自由のもたらす恵沢を確保し、政府の行為によって再び戦争の惨禍が起こることのないようにすることを決意し、ここに主権が国民に存することを宣言し、この憲法を確定する。そもそも国政は国民の厳粛な信託によるものであって、その権威は国民に由来し、その権力は国民の代表者がこれを行使し、その福利は国民がこれを享受する。これは人類普遍の原理であり、この憲法は、かかる原理に基づくものである。われらはこれに反する一切の憲法、法令及び詔勅を排除する。
日本国民は、恒久の平和を念願し、人間相互の関係を支配する崇高な理想を深く自覚するのであって、平和を愛する諸国民の公正と信義を信頼して、われらの安全と生存を保持しようと決意した。われらは平和を維持し、専制と隷従、圧迫と偏狭を地上から永遠に除去しようと努めている国際社会において、名誉ある地位を占めたいと思う。われらは全世界の国民が、ひとしく恐怖と欠乏から免れ、平和の内に生存する権利を有することを確認する。
われらは、いずれの国家も、自国のことのみに専念して他国を無視してはならないのであって、政治道徳の法則は、普遍的なものであり、この法則に従うことは、自国の主権を維持し、他国と対等関係に立とうとする各国の責務であると信ずる。
日本国民は、国家の名誉にかけて、全力をあげて崇高な理想と目的を達成することを誓う。
#strong("日本国民")は正当に選挙された国会における代表者を通じて行動し、われらとわれらの子孫のために、諸国民と協和による成果と、わが国全土にわたって自由のもたらす恵沢を確保し、政府の行為によって再び戦争の惨禍が起こることのないようにすることを決意し、ここに主権が国民に存することを宣言し、この憲法を確定する。そもそも国政は国民の厳粛な信託によるものであって、その権威は国民に由来し、その権力は国民の代表者がこれを行使し、その福利は国民がこれを享受する。これは人類普遍の原理であり、この憲法は、かかる原理に基づくものである。われらはこれに反する一切の憲法、法令及び詔勅を排除する。
日本国民は、恒久の平和を念願し、人間相互の関係を支配する崇高な理想を深く自覚するのであって、平和を愛する諸国民の公正と信義を信頼して、われらの安全と生存を保持しようと決意した。われらは平和を維持し、専制と隷従、圧迫と偏狭を地上から永遠に除去しようと努めている国際社会において、名誉ある地位を占めたいと思う。われらは全世界の国民が、ひとしく恐怖と欠乏から免れ、平和の内に生存する権利を有することを確認する。
われらは、いずれの国家も、自国のことのみに専念して他国を無視してはならないのであって、政治道徳の法則は、普遍的なものであり、この法則に従うことは、自国の主権を維持し、他国と対等関係に立とうとする各国の責務であると信ずる。
日本国民は、国家の名誉にかけて、全力をあげて崇高な理想と目的を達成することを誓う。
#strong("日本国民")は正当に選挙された国会における代表者を通じて行動し、われらとわれらの子孫のために、諸国民と協和による成果と、わが国全土にわたって自由のもたらす恵沢を確保し、政府の行為によって再び戦争の惨禍が起こることのないようにすることを決意し、ここに主権が国民に存することを宣言し、この憲法を確定する。そもそも国政は国民の厳粛な信託によるものであって、その権威は国民に由来し、その権力は国民の代表者がこれを行使し、その福利は国民がこれを享受する。これは人類普遍の原理であり、この憲法は、かかる原理に基づくものである。われらはこれに反する一切の憲法、法令及び詔勅を排除する。
日本国民は、恒久の平和を念願し、人間相互の関係を支配する崇高な理想を深く自覚するのであって、平和を愛する諸国民の公正と信義を信頼して、われらの安全と生存を保持しようと決意した。われらは平和を維持し、専制と隷従、圧迫と偏狭を地上から永遠に除去しようと努めている国際社会において、名誉ある地位を占めたいと思う。われらは全世界の国民が、ひとしく恐怖と欠乏から免れ、平和の内に生存する権利を有することを確認する。
われらは、いずれの国家も、自国のことのみに専念して他国を無視してはならないのであって、政治道徳の法則は、普遍的なものであり、この法則に従うことは、自国の主権を維持し、他国と対等関係に立とうとする各国の責務であると信ずる。
日本国民は、国家の名誉にかけて、全力をあげて崇高な理想と目的を達成することを誓う。
#bibliography("works.yml")
|
|
https://github.com/George-Miao/typst-common | https://raw.githubusercontent.com/George-Miao/typst-common/main/0.2.0/src/lib.typ | typst | MIT License | #import "math.typ": *
#import "util.typ": *
#let jp(body) = {
set text(
font: (
"Noto Serif CJK JP",
"XCharter",
),
lang: "ja",
size: 11pt,
)
body
}
#let a(body) = {
set text(fill: red)
body
}
#let book(
title: "",
subtitle: "",
authors: (),
logo: none,
toc: true,
body,
) = {
// Set the document's basic properties.
set document(author: authors.map(a => a.name), title: title)
set page(
"us-letter",
numbering: (page, ..nums) => {
// Skip the cover page
if page > 1 {
text(str(page - 1))
}
},
number-align: end,
header: locate(loc => {
let current = loc.position().page
// Skip title page
if current == 1 {
return
}
// Find the first heading on or before the current page
let ele = query(
selector(heading.where(level: 1)),
loc,
).rev().find(elem => elem.location().page() <= current)
if ele == none {
return
}
if ele.location().page() == current {
return
}
text(0.9em, weight: 300, style: "italic", ele.body)
}),
)
set math.mat(delim: "[")
set text(
font: "XCharter",
lang: "en",
size: 11pt,
)
/* Title page. */
// The page can contain a logo if you pass one with `logo: "logo.png"`.
v(0.6fr)
// if_then_ln(logo, x => align(right, image(x, width: 26%)))
v(8.6fr)
text(2em, weight: 700, title)
v(0.2fr)
text(1em, style: "italic", weight: 500, subtitle)
v(1fr)
// Author information.
pad(
top: 0.7em,
right: 20%,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(start)[
*#author.name* \
#author.email
]),
),
)
v(2.4fr)
pb
/* Table of contents */
if toc {
show heading: x => block(below: 3em, text(size: 1.3em, x))
show outline.entry.where(level: 1): it => text(1.1em, weight: 800, it)
outline(target: heading.where(outlined: true))
}
pagebreak(weak: true)
set heading(numbering: "1.")
// Chapter heading
show heading.where(level: 1): head => {
let (chapter, ..) = counter(heading).get()
pagebreak(weak: true)
// Chapter number
v(3.5em)
text(.8em, weight: 800, font: "Charter", fill: rgb("#525252"), [Chapter #chapter])
v(-1em)
// Chapter title
text(
size: 27pt,
weight: 800,
par(
leading: .4em,
justify: false,
head.body,
),
)
v(3em)
}
show heading.where(level: 2): head => {
let num = text(fill: rgb("#525252"), counter(heading).get().map(str).join("."))
block(above: 1.4em, below: 2em)[
#num #h(.5em) #text(size: 1.3em, [#head.body])
]
}
set par(justify: true)
body
}
#let sheet(
title: "",
subtitle: "",
author: "",
course: "",
date: today(),
height: auto,
logo: none,
body,
) = {
// If it's in single sheet mode (height = auto), don't number the pages.
let numbering = if (height == auto) {
none
} else {
"1"
}
// Set the document's basic properties.
set page(
"us-letter",
numbering: numbering,
height: height,
number-align: end,
margin: 1in,
)
set document(author: author, title: title)
set text(
font: "XCharter",
lang: "en",
size: 11pt,
)
set block(breakable: true)
set math.mat(delim: "[")
if subtitle == "" {
subtitle = course
}
// Header
stack[
#set block(spacing: .7em);
#if_then(author, x => text(1.1em, weight: 800, x))
#h(1fr)
#if_then(title, x => text(1.1em, weight: 800, x))\
#if_then(date, x => text(0.8em, style: "italic", x))
#h(1fr)
#if_then(subtitle, x => text(0.8em, style: "italic", x))\
#v(1em)
]
// Body
set par(justify: true)
set text(hyphenate: true)
body
}
#let problem(name, body) = {
v(1em)
text(1em, weight: 700, [#name.])
h(.5em)
body
}
#let thm_color = (15%, 0%, 50%)
#let definition = new_theorem("Definition", cmy: (30%, 0%, 20%))
#let theorem = new_theorem("Theorem", cmy: thm_color)
#let fact = new_theorem("Fact", cmy: thm_color)
#let proposition = new_theorem("Proposition", cmy: thm_color)
#let corollary = new_theorem("Corollary", cmy: thm_color)
#let lemma = new_theorem("Lemma", cmy: thm_color)
#let example = new_theorem("Example")
#let question = new_theorem("Question")
#let answer = new_theorem("Answer")
#let remark = new_theorem("Remark")
#let note = new_theorem("Note")
#let recall = new_theorem("Recall")
#let caution = new_theorem("Caution")
#let claim = new_theorem("Claim")
#let proof(newline: false, body) = {
if newline {
linebreak()
}
block(inset: (left: 1em))[
_proof_.
#h(.5em)
#body
#h(1fr)
$square$
]
}
#let proof_ln = proof.with(newline: true)
#let sub = text.with(fill: rgb("#737373")) |
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/docs/community.md | markdown | Apache License 2.0 | ---
description: |
Join the Typst community, get help from other users and have a say in the
future of Typst.
---
# Community
Hey and welcome to the Community page! We're so glad you're here. Typst is
developed by an early-stage startup and is still in its infancy, but it would be
pointless without people like you who are interested in it.
We would love to not only hear from you but to also provide spaces where you can
discuss any topic around Typst, typesetting, writing, the sciences, and
typography with other likeminded people.
For the time being, **we would like to invite you to our [Discord
server](https://discord.gg/2uDybryKPe).** The server is open for everyone.
Of course, you are also very welcome to connect with us on social media
([Twitter](https://twitter.com/typstapp/),
[Instagram](https://instagram.com/typstapp/),
[LinkedIn](https://linkedin.com/company/typst), and
[GitHub](https://github.com/typst)).
## What to share?
For our community, we want to foster versatility and inclusivity. You are
welcome to post about any topic that you think would interest other community
members, but if you need a little inspiration, here are a few ideas:
- Share and discuss your thoughts and ideas for new features or improvements
you'd like to see in Typst
- Showcase documents you've created with Typst, or share any unique or creative
ways you've used the platform
- Share importable files or templates that you use to style your documents
- Alert us of bugs you encounter while using Typst
## Beta test
We are starting a public beta test of our product on March 21st, 2023. The Typst
compiler is still under active development and breaking changes can occur at any
point. The compiler is developed in the open on
[GitHub](https://github.com/typst/typst).
We will update the members of our Discord server and our social media followers
when new features become available. We'll also update you on the development
progress of large features.
## How to support Typst { #support-typst }
If you want to support Typst, there are multiple ways to do that! You can
[contribute to the code](https://github.com/typst/typst) or
[translate the strings in Typst](https://github.com/search?q=repo%3Atypst%2Ftypst+impl+LocalName+for&type=code)
to your native language if it's not supported yet. You can also help us by
[sponsoring us!](https://github.com/sponsors/typst) Multiple recurring
sponsorship tiers are available and all of them come with a set of goodies.
No matter how you contribute, thank you for your support!
## Community Rules { #rules }
We want to make our community a safe and inclusive space for everyone.
Therefore, we will not tolerate any sexual harassment, sexism, political
attacks, derogatory language or personal insults, racism, doxing, and other
inappropriate behavior. We pledge to remove members that are in violation of
these rules. [Contact us](https://typst.app/contact/) if you think another
community member acted inappropriately towards you. All complaints will be
reviewed and investigated promptly and fairly.
In addition, our [privacy policy](https://typst.app/privacy/) applies on all
community spaces operated by us, such as the Discord server. Please also note
that the terms of service and privacy policies of the respective services apply.
## See you soon! { #see-you }
Thanks again for learning more about Typst. We would be delighted to meet you on
our [Discord server](https://discord.gg/2uDybryKPe)!
|
https://github.com/YouXam/bupt-network-resources-guide | https://raw.githubusercontent.com/YouXam/bupt-network-resources-guide/main/main.typ | typst | MIT License | #import "template.typ": project, chineseoutline
#import "@preview/fontawesome:0.4.0": fa-icon
#let vpn = box(baseline: 0.2em, stroke: 0.3pt + black, inset: (right: 0.3em, rest: 0.2em), radius: 5pt, fill: green.lighten(90%))[
#box(height: 0.8em, baseline: 0.1em, inset: (left: 0.1em, right: 0.1em, top: 0.05em))[
#fa-icon("shield-halved", fill: green.darken(20%), size: 0.8em)
]#text([校园网/VPN], size: 0.8em, font: "Source Han Sans")
]
#let http = box(baseline: 0.3em, stroke: 0.3pt + black, inset: (right: 0.3em, rest: 0.2em), radius: 5pt, fill: red.lighten(90%))[
#box(height: 0.8em, baseline: 0.1em, inset: (left: 0.1em, right: 0.1em))[
#image("icons/unsafe-icon.svg")
]#text([不支持 HTTPS], size: 0.8em, font: "Source Han Sans")
]
#let plink(name, https: true, suffix: "") = {
link(
(if https {"https://" } else { "http://" }) + name + ".bupt.edu.cn" + suffix,
)[#{
text(
if https
[https:\/\/]
else
[http:\/\/],
fill: blue.lighten(50%),
weight: "extralight"
)
text(
[#name],
fill: blue.lighten(10%),
weight: "extrabold"
)
[\.bupt.edu.cn]
if suffix != "" {
[#suffix]
}
}]
if not https {
h(0.2em)
http
}
}
#show: project.with(title: "北邮网络资源手册", author: "YouXam")
#heading(outlined: false, numbering: none)[前言]
亲爱的北邮学弟学妹们:
首先我诚挚欢迎各位加入北京邮电大学这个大家庭。作为北邮的新成员,你们将开启人生的新篇章,在这片充满机遇与挑战的热土上追求独特的大学梦想。
进入大学,我们需要熟练运用各种网络资源和工具,借助线上平台来学习、生活、交流。而北邮的的网络资源繁多,既有学校的各种网站、平台,也有学长学姐们开发的各类工具。对于新生来说,这些资源可能并不是那么容易找到,也缺乏一个统一的指引。
有鉴于此,我汇集了校内外各类优质网站,编撰了这份“北邮网络资源手册”,希望能为你们提供一个获取有用资讯的指引。这个手册囊括了校园生活、学习资源、实用工具等多个维度,我真诚地希望它能在求学路上助你们一臂之力。
此手册内容源于我个人的经验和了解,不代表北邮官方和任何其他组织的观点和立场。由于我知识面有限,手册难免有疏漏之处,非常欢迎大家继续补充和完善,让它更加贴近同学们的实际需求。
你可以在 #fa-icon("github") #link("https://github.com/YouXam/bupt-network-resources-guide")[YouXam/bupt-network-resources-guide] 上找到这份手册的源代码,也欢迎提出 issue 和 pull request。
最后,衷心祝愿各位学弟学妹在北邮取得圆满成就,未来都能在梦寐以求的事业领域施展才华,成就非凡!
#align(right)[
YouXam\
#link("mailto:<EMAIL>")[<EMAIL>] \
2024 年 8 月 8 日
]
#pagebreak()
#chineseoutline()
#pagebreak()
= 北邮官方资源
#h(2em)本章主要介绍北邮学校的各类官方网站、平台。
== 北邮认证系统介绍
#h(2em)新生可以在 @welcome 查询学号,然后就可以激活或注册北邮的各类账号了。大体而言,在北邮常使用的账号有以下五类,其中账号为你的学号,*密码则相互独立*:
+ #link("https://netaccount.bupt.edu.cn")[校园网]账号;
+ #link("https://jwgl.bupt.edu.cn")[本科教务管理系统]账号;
+ #link("https://mail.bupt.edu.cn")[北邮教育邮箱]账号;
+ 学生卡账号;
+ #link("https://auth.bupt.edu.cn")[统一身份认证系统]账号。
#h(2em)其中校园网账号用于在学校内连接校园网和使用电子资源统一访问系统,本科教务管理系统账号用于查询课表、成绩、选课等,北邮教育邮箱账号用于登录北邮教育邮箱(腾讯企业邮),其他系统则大都使用统一身份认证系统账号登录。当然也有一些较不常用的不使用统一身份认证系统的系统,例如#link("https://win.bupt.edu.cn/")[大学生创新创业计划训练平台]。
== 学生卡
在校园内,学生卡的主要作用有以下三点:
+ 作为门禁卡,进出校园、图书馆等;
进出校园一般使用人脸识别,而图书馆的闸机和其他某些区域的门禁可以在完美校园 App / 钥匙串中直接控制。
+ 借阅图书;
+ 在食堂、超市消费,在澡堂、水房用水。
需使用完美校园 App/微信小程序充值、查询余额、消费记录等。其中食堂和超市使用的刷卡机同时也支持微信和支付宝扫码支付(第一次使用需要绑定校园卡)。若单日消费超过一定金额,需要输入校园卡密码,初始密码为身份证号后 6 位,若末位为 “X” 则用 “0” 代替。
== VPN <vpn>
在校外环境,如果需要访问某些只有校园网环境才能访问的网站和资源,你需要使用 VPN 连接到校园网。北邮官方提供的方式有以下三种:
+ #link("https://vpn.bupt.edu.cn")[Atrust VPN]。这是推荐使用的方式。需要下载客户端、并使用北邮企业微信/校园网自服务(或在微信中访问 #plink("netaccount")) 查看 OTP 动态口令。登录时,用户名为学号,密码为 OTP 动态口令。
+ #link("https://webvpn.bupt.edu.cn")[WebVPN]。这是网页版的 VPN,不需要下载客户端。需要使用微信扫码登录。
+ #link("https://libcon.bupt.edu.cn")[电子资源统一访问系统]。此系统虽然是用于在非校园网环境访问数据库,但也可以访问校园网环境下的普通资源。需要使用校园网账号登录。
== 网站
#h(2em)本节中的网站可使用浏览器直接访问,域名均为 bupt.edu.cn 结尾。需要使用校园网环境或者 VPN(见 @vpn) 连接的会使用 #vpn 标识,不支持 HTTPS 的会使用 #http #h(0.2em)#footnote[必须使用形如 *http:\/\/*xxx.bupt.edu.cn 的网址而不能使用 *http#text(fill: red)[s]:\/\/*xxx.bupt.edu.cn 的网址访问。] 标识。
=== #link("https://welcome.bupt.edu.cn/")[北京邮电大学迎新网] <welcome>
#h(2em)#plink("welcome")
这是北邮的迎新网站,是新生首先需要使用的第一个网站。你应当首先阅读#link("https://welcome.bupt.edu.cn/info/1002/1011.htm")[迎新系统说明],按照指引完成各项任务。其中最重要的一项是#link("https://stu.bupt.edu.cn/xsfw/sys/xhcxappcqjtu/*default/index.do?xhcx#/xhcx")[查询学号]。详细的迎新流程在随录取通知书中的新生手册中应当有详细说明。
=== #link("https://netaccount.bupt.edu.cn")[校园网自服务系统] <netaccount>
#h(2em)#plink("netaccount")
在这里你可以修改校园网账号的密码。初始密码为证件号后 6 位,最后一位如为 “X” 用 “0” 代替。
你同样可以通过“北邮企业微信/校园网”(或在微信中访问 #plink("netaccount"))修改校园网账号的密码。
=== #link("https://jwgl.bupt.edu.cn/")[本科教务管理系统]
#h(2em)#plink("jwgl") #vpn
本科教务管理系统是北邮学生查询课表、成绩、选课等信息的主要平台。初始密码为 <PASSWORD>,登录后请及时修改密码。
在抢课的时候,突发的高并发可能导致本科教务管理系统负载均衡出现问题,此时你可以尝试直接访问源站:http:\/\/10.3.58.1$x$:1808$x$/jsxsd,其中 $x in [0, 7]$。
=== #link("https://mail.bupt.edu.cn/")[北邮教育邮箱]
#h(2em)#plink("mail")
新用户请先#link("https://register.bupt.cn/")[注册账号] #vpn。注册完成后,你就可以使用形如 <EMAIL> (其中 foo 为注册时指定)和 <EMAIL> (校友邮箱,其中 2024210001 为学号示例)的邮箱地址了。
若需要修改邮箱地址,请使用当前邮箱发邮件到 #link("mailto:<EMAIL>")[<EMAIL>] 说明情况,注销后重新注册。
=== #link("https://auth.bupt.edu.cn")[统一身份认证系统] <auth>
#h(2em)#plink("auth")
北邮的大部分系统均使用统一身份认证系统登录,可以使用学号和统一身份认证系统的密码登录,也可以使用微信/企业微信认证(例如扫码或者直接在微信中访问)。
新用户请先 #link("https://uc.bupt.edu.cn/#/register/index")[激活账号]。
=== #link("http://my.bupt.edu.cn/")[信息服务门户]
#h(2em)#plink("my", https: false) #vpn
信息服务门户主要的作用是查看校内通知和新闻,同时也通过“系统直通车”、“服务导航”等分区提供北邮各网络资源的跳转渠道,如教务系统、学工系统、正版软件等。
=== #link("https://ucloud.bupt.edu.cn/uclass")[云邮教学空间]
#h(2em)#plink("ucloud", suffix: "/uclass")
云邮教学空间是北邮的在线教学平台,用于发布课程资料、作业等。大部分作业和实验报告等都需要在这里提交。
注:可以使用第三方 Telegram 机器人 #link("https://t.me/bupt_ucloud_bot")[\@bupt_ucloud_bot] 来订阅作业提醒和提交作业。
=== #link("https://lib.bupt.edu.cn")[图书馆]
#h(2em)#plink("lib")
北邮图书馆的网站,可以查询图书馆馆藏书目、使用各类信息资源(例如学校购买的各类科研数据库)。
=== #link("https://libcon.bupt.edu.cn")[电子资源统一访问系统]
#h(2em)#plink("libcon")
你可以使用电子资源统一访问系统访问学校购买的各类数据库,例如知网、维普、IEL 等。该系统本是用于在非校园网环境访问数据库,但由于学校网络出口的限制,校园网环境下可能也需要使用此系统才能访问各类数据库。
登录账号为校园网账号。
=== #link("https://order.bupt.edu.cn/")[北京邮电大学图书馆/教三楼空间预约管理系统]
#h(2em)#plink("order") #vpn
该系统一般用于预约沙河图书馆研讨间。
=== #link("https://service.bupt.edu.cn")[网上服务大厅] <service>
#h(2em)#plink("service")
网上服务大厅可用于填报和提交各类申请表,例如校外人员入校申请、请假申请等。
=== #link("https://software.bupt.edu.cn")[软件正版化平台]
#h(2em)#plink("software") #vpn
你可以在软件正版化平台下载和安装正版 Windows, Office, Visual Studio 等。
=== #link("https://3039.bupt.edu.cn")[信息化报修系统] <3039>
#h(2em)#plink("3039")
若遇到校园网、官方网站故障或使用问题,可以在此系统中提交报修。
也可以直接拨打电话 010-62283039(周一至周五的 9:00-17:00)。
=== #link("https://dekt.bupt.edu.cn")[第二课堂(管理端)]
#h(2em)#plink("dekt")
第二课堂是北邮的活动报名、签到平台。
此网页版用于教师、学生干部或社团负责人发布和管理活动,使用统一认证账户登录。报名和签到需要使用微信小程序“北邮第二课堂”。
第二课堂使用教程见#link("https://mp.weixin.qq.com/s/KaXWdPVSi5likW4P2B4YYg")[ 你好,新同学!第二课堂新手任务已发布!
]。
== 企业微信
=== 使用方式
#h(2em)需要通过导员发送的二维码扫描绑定企业微信帐号。
=== 应用介绍
#h(2em)北邮企业微信中包含很多应用,因为相对而言较为集中,并且有应用目录,所以这里只介绍几个较为重要的,其他应用你可以在企业微信中查看。
+ 网上服务大厅:同 @service;
+ 校园网自服务:查看用于连接 VPN 的 OTP;
+ 体育馆预约:预约健身房、羽毛球场、游泳馆等;
+ 宿舍用电:缴纳宿舍电费;
+ 北邮接诉即办:提供维修服务(如宿舍电器报修)、服务监管(可于此投诉校园生活中遇到的各类问题);
+ 信息帮:同 @3039;
+ 微教学:查看课程表、考试安排、成绩等。某些课程签到时,可在常用功能/云平台/我的课程/当前课程中签到。
== 杂项
=== 校历
#h(2em)https://www.bupt.edu.cn/ggfw/xl.htm
=== 办公电话
#h(2em)https://www.bupt.edu.cn/ggfw/bgdh.htm
=== 校园地图
#h(2em)https://www.bupt.edu.cn/bygk/zjby/xydt.htm
#pagebreak()
= 北邮其他资源
#h(2em)本章中的资源大多由北邮学长学姐们开发和维护,但其中部分同样受到北邮官方的监督和支持(例如北邮人论坛)。
== #link("https://bbs.byr.cn")[北邮人论坛]
#h(2em)北邮人论坛是北京邮电大学官方网络论坛,面向全部在校生与校友开放,是国内最活跃的高校论坛之一。论坛内版块全面,信息丰富,能够解答北邮人方方面面的问题,无论你是想咨询选课、发表论文、奖学金、考研保研出国校招的各类攻略,还是想谈天说地、恋爱征友、寻找出游攻略,你都能在这里找到一起讨论的人,共同寻求答案。
北邮人论坛有以下四种访问方式:
+ 电脑网页版:https://bbs.byr.cn;
+ 手机网页版(通过直链查看帖子无需登录,但不能发帖):https://bbs.byr.cn/n
+ 客户端
- App Store:https://apps.apple.com/cn/app/id1115232927
- Android 下载:https://github.com/BYR-App-Dev/BYR_App_Android_Release/releases/latest/download/release.apk
- Android 加速镜像:https://bbs.byr.cn/files/apk/byrbbs-android-app/latest/release.apk
- Github Org:https://github.com/BYR-App-Dev
+ telnet(支持更多高级功能):#link("telnet://bbs.byr.cn")[telnet:\/\/bbs.byr.cn]
#h(2em)新生必须先访问#link("https://bbs.byr.cn")[电脑网页版],使用*网关账户(校园网账户,见 @netaccount)*认证身份并注册账户,然后#link("https://bbs.byr.cn/#!user/passwd")[通过手机号验证]。
注:北邮人论坛是北邮人独有的精神家园,禁止外借账号使用,违者面临封禁风险。
详细使用方式可见#link("https://mp.weixin.qq.com/s/cC7LivGeex88aO4a_mJrBg")[21 年版新生论坛指南]。
北邮人论坛由#link("https://team.byrio.work/")[北邮人团队]维护和运营。
== #link("https://overleaf.byrio.work")[Overleaf]
#h(2em)https://overleaf.byrio.work #vpn
Overleaf 是一个在线 LaTeX 编辑器,支持多人协作。北邮人团队提供了一个 Overleaf 实例,具有 Overleaf 官方的专业版功能。必须使用结尾为 \@bupt.edu.cn 或者 \@bupt.cn 的邮箱注册。
== #link("https://bitwarden.byrio.work")[Bitwarden]
#h(2em)https://bitwarden.byrio.work
Bitwarden 是一个密码管理器,支持多平台。北邮人团队提供了一个 Bitwarden (Vaultwarden) 实例,具有 Bitwarden 官方服务器的专业版功能。必须使用结尾为 \@bupt.edu.cn 或者 \@bupt.cn 的邮箱注册。
== 开源镜像
#h(2em)由北邮人团队维护的北邮开源镜像站提供了大量的开源软件镜像,包括:
+ pypi
+ npm
+ golang
+ cargo
+ linux 相关软件源
#h(2em)镜像站地址:https://mirrors.byr.ink/ #vpn
== #link("https://git.byr.moe")[GitLab]
#h(2em)https://git.byr.moe
北邮人团队维护的 GitLab 实例。可以用于托管代码、协作开发等。
== “巴普特今天网炸了吗” QQ 群聊
#h(2em)北邮人团队负责的*非北邮官方*校园网帮助群,如果你遇到了校园网网络问题,可以加入群聊咨询:835973564。
== #link("https://wiki.buptnet.icu")[北邮校园网指南]
#h(2em)https://wiki.buptnet.icu
北邮人团队维护的北邮校园网使用指南,详细介绍了北邮校园网的使用方法和常见问题等。
== #link("https://byr.pt/")[北邮人 PT]
#h(2em)https://byr.pt
可用于下载和分享各类资源(例如电影、剧集、游戏、软件等)。必须使用非三大运营商的 IPv6 网络访问(例如教育网 IPv6 网络或国外 IPv6 网络),可以使用校园网访问。
== #link("https://byrdocs.org")[BYR Docs]
#h(2em)https://byrdocs.org
BYR Docs 是一个资料分享平台,旨在使北邮学生更方便地获取与北邮课程有关的教育资源,包括电子书籍、考试题目和复习资料等。
可使用北邮教育网 IPv6 免登录访问。若在校外,需使用统一身份认证系统登录。
= 公共资源
#h(2em)本章中的资源与北邮无关。
== zlibrary
#h(2em)https://zh.singlelogin.re/
常用电子书下载网站。注意,zlibrary 有许多*假冒*网站(例如 #text(fill: red)[z-lib.io, z-lib.id, zlibrary.to]),请注意链接的正确性。zlibrary 官方并不强制要求收费下载电子书,凡要求付费下载电子资源的,一律为假冒网站。
zlibrary Telegram 频道:https://t.me/zlibrary_official
zlibrary Telegram 中文频道:https://t.me/zlib_china_official
== 教育认证
#h(2em)当你注册了北邮教育邮箱后,你可以使用北邮教育邮箱注册一些教育认证服务,例如:
+ GitHub Education Pack:https://education.github.com/pack
+ JetBrains 学生许可证:https://www.jetbrains.com/zh-cn/community/education/#students
#h(2em)由于网上可以找到很多教程,故不再赘述。 |
https://github.com/davawen/Cours | https://raw.githubusercontent.com/davawen/Cours/main/Physique/Optique/3-Lentilles-Spheriques-Mince/lentilles-spheriques.typ | typst | #import "@local/physique:0.1.0": *
#import optique: *
#show: doc => template(doc)
#titleb[Lentilles sphériques minces dans l'approximation de Gauss]
= Définitions
== Lentille
Une lentille est composée de deux dioptres formant un volume d'indice $n$ placés dans un milieu d'indice $n'$
#figure(caption: [Une lentille d'indice $n'$], canvas({
import draw: *
lentil(0)
content((-1, 0), $n$)
content((1, 0), $n$)
content((0, 0), $n'$)
content((-1, -1), [Dioptre 1])
content((1, -1), [Dioptre 2])
}))
== Lentille sphérique
Dans une lentille sphérique, les deux dioptres sont des sphères.
== Lentille sphérique mince
#figure(caption: [Lentille sphérique], canvas({
import draw: *
line((-5, 0), (5, 0), mark: (end: "straight"))
let dash_a = 40deg
let lentil_a = 20deg
point((-3, 0), value: $c_2$, name: "c2")
point((3, 0), value: $c_1$, name: "c1")
// circle("c1", radius: 3, stroke: (dash: "dashed"))
arc("c1", start: 180deg - dash_a, delta: 2*dash_a, radius: 3.3, anchor: "origin", stroke: (dash: "dashed"), name: "c1dash")
arc("c1", start: 180deg - lentil_a, delta: 2*lentil_a, radius: 3.3, anchor: "origin")
arc("c2", start: -dash_a, delta: 2*dash_a, radius: 3, anchor: "origin", stroke: (dash: "dashed"), name: "c2dash")
arc("c2", start: -lentil_a, delta: 2*lentil_a, radius: 3, anchor: "origin")
line("c2", "c2dash.10%")
content(("c2", 50%, "c2dash.10%"), angle: "c2dash.10%", $R_2$, anchor: "south", padding: .2)
line("c1", "c1dash.90%")
content(("c1", 50%, "c1dash.90%"), angle: "c1", $R_1$, anchor: "south", padding: .2)
}))
On doit définir deux points, $S_1$ et $S_2$, les sommets du dioptre sphérique.
L'épaisseur de la lentille $S_1 S_2$, qu'on note habituellement $e$ doit être faible devant $R_1$ et devant $R_2$
Pour des lentilles très fines, on a $e ~~> 0$, donc $S_1 approx S_2$.
== Centre
Comme $S_1 approx S_2$, on va les considérer comme un unique point $O$, le centre de la lentille.
== Différentes formes de lentille - Représentation
=== Lentilles sphérique à bord mince
#figure(image("fig1.png", width: 80%))
=== Lentilles sphériques à bord épaix
#figure(image("fig2.png", width: 80%))
=== Représentations
#figure(image("fig3.png", width: 80%))
#pagebreak()
= Lentilles et conditions de Gauss
== Stigmatisme des lentilles
#figure(caption: [Absence de stigmatisme pour une lentille mince sphérique en ne limitant pas le faisceau et stigmatisme approché d’une lentille mince sphérique en limitant le faisceau aux rayons arrivant au voisinage du centre], image("fig_stigmatisme.png"))
Le caractère de stigmatique rigoureux de la lentille n'est pas vérifié.
Si on pose les conditions de Gauss pour la lentille (en utilisaant un diaphragme), on observe un stigmatisme approché.
== Aplanétisme des lentilles
#figure(caption: [Absence d’aplanétisme pour une lentille mince sphérique lorsque les rayons arrivent trop inclinés sur la lentille], image("fig_aplanetisme.png"))
En déplaçant le point objet perpendiculairement, on voit que tant qu'on reste dans de conditions de Gausse (point pas trop éloigné de l'axe optique), l'aplanétisme approché est vérifié
== Stigmatisme et aplanétisme des conditions de Gauss
Les conditions de Gauss assurent le stigmatisme et l'aplanétisme peut importe la lentille (tant qu'elle est centrée).
== Caractère focal d'une lentille
#figure(caption: [Caractère focal d'une lentille mince sphérique], image("fig_focal.png", width: 80%))
== Foyers principaux, foyers secondaires
#def[Foyer principal]: Foyer sur l'axe optique \
#def[Foyer secondaire]: Autre foyer pas sur l'axe optique
Voir: _Chapitre 2. 2.4) Foyers secondaires - Plan focal_
== Distance focale et vergence
La distance focale est la distance algébrique du centre de la lentille ($O$) au foyer image.
$f' = ov(O F') = -ov(O F) = ov(F O)$
La vergence est l'inverse de la distance focale:
$ V = 1 / f' $
#tip[La vergence garde toujours le même signe que la distance focale.]
== Signe de la distance focale et caractère de la lentille
On aura:
- $f' > 0$ si la lentille est convergente
- $f' < 0$ si la lentille est divergente
= Construction d'une image
== Règles de construction
- #stack(dir: ltr, [Le rayon passant par le centre de la lentille est non dévié (], line(start: (0em, 0.3em)), [)])
- #stack(dir: ltr, [Le rayon arrivant $parallel$ à l'axe optique passe par $F'$ (], line(start: (0em, 0.3em), stroke: blue), [)])
- #stack(dir: ltr, [Le rayon passant par $F$ ressort $parallel$ à l'axe optique (], line(start: (0em, 0.3em), stroke: red), [)])
Ces règles de constructions ne sont valables que dans les conditions de Gauss, car "centre de la lentille" = sommet du premier dioptre + sommet du deuxième dioptre dans le cadre d'une lentille mince.
== Cas d'une lentille convergente
#figure(caption: [Conjugaison des objets et des images dans ne lentille divergente], image("fig_tab_convergente.png"))
#figure_lentille_convergente
== Cas d'une lentille divergente
#figure_lentille_divergente
#figure(caption: [Conjugaison des objets et des images dans une lentille divergente], image("fig_tab_divergente.png"))
= Relations de conjugaisons
== Formule de conjugaison avec origine au centre
Les relations qu'on va écrire ne dépendent pas d'un positionnement spécifique. On peut les utiliser pour n'importe quel type de lentille et de positionnement.
#figure(caption: [Relation de conjugaison par construction], image("fig_conjugaison_construction.png", width: 60%))
Dans le triangle $O F_1' A'$:
$ alpha + (pi - beta) + (-alpha') = pi $
#resultb($ alpha - alpha' = beta $)
On se place dans les conditions de Gauss, on peut donc travailler avec des petits angles.
$ alpha approx tan alpha $
$ alpha' approx tan alpha' $
On place le point $K$, on a:
$ beta = beta_1 + beta_2 $
$ beta_1 approx tan beta_1 &= ov(K I)/ov(K F'_1) "(dans le triangle " K I F'_ 1")" \
&= ov(K I)/ov(O F') $
$ beta_2 approx tan beta_2 = ov(O K)/ov(K F'_1) = ov(O K)/ov(O F') $
On donc:
$ beta = ov(K I)/ov(O F') + ov(O K)/ov(O F') = ov(O I)/ov(O F') $
De plus:
$ alpha approx tan alpha = ov(O I)/ov(A O) "(dans le triangle AOI)" $
$ alpha' approx tan alpha' = ov(O I)/ov(A' O) "(dans le triangle A'OI)" $
On remplace dans l'équation $alpha - alpha' = beta$:
$ ov(O I) / ov(A O) - ov(O I)/ov(A' O) = ov(O I)/ov(O F') $
On a donc bien:
#resultb($ 1 / ov(O A') - 1 / ov(O A) = 1 / ov(O F') = 1/f' $)
== Formule de conjugaison avec origines aux foyers dits de Newton
#figure(caption: [Formule de conjugaison <NAME>], image("fig_conjugaison_newton.png", width: 60%))
On place l'angle $alpha$.
On se place dans les conditions de Gauss, donc:
$ alpha approx tan alpha &= ov(A B)/ov(A F) "(dans le triangle ABF)" \
&= ov(O I)/ov(A F) \
&= ov(O J) / ov(O F) "(dans le triangle OJF)" \
&= ov(A' B')/ov(O F)
$
On a donc:
$ ov(A B)/ov(A F) = ov(A'B')/ov(O F) <=> ov(A'B')/ov(A B) = ov(O F)/ov(A F) $
On place l'angle $beta$:
$ beta approx tan beta &= ov(O I)/ov(O F') = ov(A B)/ov(O F) "(dans le triangle OIF')" \
&= ov(A' B')/ov(A'F') = ov(O J)/ov(A' F') "(dans le triangle F'A'B')" $
On a donc que:
$ ov(A B)/ov(O F') = ov(A' B')/ov(A'F') <=> ov(A'B')/ov(A B) = ov(A'F')/ov(O F') $
Ce qui implique:
$ ov(O F)/ov(A F) = ov(A' F')/o(O F') \
<=> ov(O F) dot ov(O F') = ov(A F) dot ov(A' F') = ov(F A) dot ov(F' A') $
#resultb($ ov(F' A') dot ov(F A) = ov(O F) dot ov(O F') = -f'^2 $)
== Grandissement
Le grandissmenet $gamma$ est $gamma = ov(A'B')/ov(A B)$ par définition. \
On a l'expression du grandissement avec origines aux foyers:
#resultb($ gamma = ov(O F)/ov(A F) = ov(A F')/ov(O F') $)
Expression avec origines aux centre:
$ delta approx tan delta $
$ tan delta = ov(A B)/ov(A O) "(dans le triangle OAB)" $
Et
$ tan delta = ov(A'B')/ov(A'O) "(dans le triangle OA'B')" $
On a donc:
$ ov(A B)/ov(A O) = ov(A'B')/ov(A' O) $
$ <=> ov(A'B')/ov(A B) = ov(A' O)/ov(A O) = ov(O A')/ov(O A) $
Donc:
#resultb($ gamma = ov(O A')/ov(O A) $)
= Reconnaissance de la nature d'une lentille
Observation d'un objet lointain:
- Image renversée avec une lentille convergente
- Image virtuelle droite avec une lentille divergente
Observation d'un objet proche:
- Effet "loupe" avec une lentille convergente
- Image plus petite avec une lentille divergente
= Construction d'un rayon transmis ou d'un rayon incident - Utilisation des foyers secondaires
#figure(caption: [Obtention du rayon transmis par une lentille convergente], image("fig_rayon_transmis.png", width: 80%))
#figure(caption: [Obtention du rayon transmis par une lentille divergente], image("fig_rayon_transmis_div.png", width: 80%))
Pour construire un rayon transmis quelconque, on trace le rayon parallèle à celui-ci qui passe par le centre de la lentille.
Le rayon étudié passe forcément par l'intersection du rayon parallèle et du plan focal image.
On peut utiliser la même méthode avec le foyer objet. On place l'intersection du plan focal objet et du rayon incident, et on trace le rayon qui passe par cette intersection et par le centre de la lentille. Le rayon transmis est parallèle avec ce rayon.
= Projection d'une image à l'aide d'une lentille
Le problème posé est: «on a un objet, et l'objet en question, ça peut-être une observation, et vous voulez par exemple le projeter sur un écran, imaginez par exemple un petit objet et je veux vous la montrer et que tout le monde la voie»
On veut faire une projection pour récuperer une image réelle plus grande (ou plus petite) que l'objet utilisé.
On a un objet réel, on veut en faire une image réelle, avec des critères de grandissement qui peuvent changer (entre plus petit et plus grand).
== Choix du type de lentille
#grid(columns: (1fr, 1fr), gutter: 4em,
figure_lentille_convergente,
figure_lentille_divergente
)
On va utiliser une lentille convergente (seul moyen de faire réel $->$ réel). On aura donc une image renversée.
== Condition de projection d'un objet réel
On a la relation de conjugaison:
$ 1/ov(O A') - 1/ov(O A) = 1/f' $
On pose: $D = ov(A A')$ et $x = ov(O A')$.
On a une image réelle si et seulement si $x > 0$.
Où faut-il mettre la lentille entre les deux pour pouvoir conjuguer l'objet $A$ avec son image $A'$
#figure(canvas({
import draw: *
line((-4, 0), (4, 0), mark: (end: "straight"))
line((0, -2), (0, 2), mark: (start: "straight", end: "straight"))
point((-3, 0), value: $A$)
point((2, 0), value: $A'$)
line((-3, -0.5), (2, -0.5), mark: (start: "straight", end: "straight"), name: "D")
line((0, 1), (2, 1), mark: (start: "straight", end: "straight"), name: "x")
content("D.50%", $D$, anchor: "north", padding: 5pt)
content("x.50%", $x$, anchor: "south", padding: 5pt)
}))
On a $ov(O A) = ov(O A') + ov(A' A) = x - D$
On veut déterminer la position de la lentille, donc on veut déterminer les
On a donc:
$ 1/x - 1/(x - D) = 1/f' $
$ ((x - D) - x)/(x(x - D)) = 1/f' $
$ (x(x - D))/((x - D) - x) = f' $
$ x(x - D) = f'((x - D) - x) $
$ x(x - D) = f'(x - D) - f'x $
D'où:
$ f'(x - D) - x f' = x(x - D) $
$ f'x - f' D - x f' = x^2 - D x $
$ -f' D = x^2 - D x $
#resultb($ x^2 - D x + f' D = 0 $)
En résolvant l'équation pour $x$:
$ Delta = D^2 - 4f' D $
On aura des solutions réelles que si $Delta >= 0$.
Interprétation physique: $x$ est une distance, donc $x in RR^+$.
$ D (D - 4f') >= 0 $
On veut $A$ objet réel et $A'$ image réelle, donc $ov(A A') > 0$, donc $D > 0$. Pour que l'équation ait une solution réelle, il faut que $D >= 4f'$.
== Condition sur le grandissement <condition>
On suppose que la condition précédente est vérifiée ($D >= 4f'$), et que par conséquent $x$ est positif.
On a:
#box(height: 5em)[
#columns[
$ x_1 = (D + sqrt(D(D - 4f')))/2 $
$ x_2 = (D - sqrt(D(D - 4f')))/2 $
]]
On a $D >= 0$, donc $sqrt(D(D - 4f')) >= 0$, donc $x_1 > x_2$. \
$x_1$ est trivialement positif. \
$sqrt(D(D - 4f')) = sqrt(D^2 - 4D f') < sqrt(D^2)$, donc $x_2$ est positif.
On a donc deux positions valides.
On définit le grandissement:
$ gamma = ov(O A')/ov(O A) $
On connait déjà $ov(O A')$ (c'est $x$), mais il faut encore définir $ov(O A)$:
$ ov(O A) = ov(O A') + ov(A' A) = x - D $
On pose:
$ y_1 = ov(O A) = x_1 - D = (-D + sqrt(D(D - 4f')))/2 $
$ y_2 = ov(O A) = x_2 - D = (-D - sqrt(D(D - 4f')))/2 $
On a $y_2$ trivialement négatif, et par la même méthode qu'avant, $y_1$ est négatif aussi.
On a donc:
$ gamma = x/y $
Soit:
$ gamma_1 = x_1/y_1 = (D + sqrt(D (D - 4f')))/(-D + sqrt(D (D - 4f'))) $
$ gamma_2 = x_2/y_2 = (D - sqrt(D (D - 4f')))/(-D - sqrt(D (D - 4f'))) $
Dans les deux cas, on a un numérateur positif et un dénominateur négatif, donc on a toujours un grandissement négatif (image renversée).
On prend la valeur absolue (on prend l'opposé pour avoir une fraction positive):
$ abs(gamma_1) = (D + sqrt(D (D - 4f')))/(D - sqrt(D (D - 4f'))) $
$ abs(gamma_2) = (D - sqrt(D (D - 4f')))/(D + sqrt(D (D - 4f'))) $
On a donc: $abs(gamma_1) > 1$ et $abs(gamma_2) < 1$.
Quand on a besoin d'aggrandir un objet, on utilisera donc la solution $x_1$, et quand on a besoin de réduire (téléscope), on utilisera $x_2$.
== Choix de la lentille
On a besoin de $D >= 4f'$, donc ne pas choisir une lentille avec une distance focale trop grande (sinon, le système optique ne rentrera pas sur le rail)
== Problème de luminosité
Dû aux conditions de Gauss (et donc à la faible surface et taille de lentille utilisables), on risque de perdre beaucoup de lumière.
On utilisera éventuellement un condenseur.
= Focométrie des lentilles
#def[Focométrie]: Détermination de la distance focale d'une lentille
Toutes les méthodes que l'on va énoncer ne fonctionnent que pour les lentilles convergentes.
== Méthode des points conjugués
On prend un objet, on forme son image, on détermine donc $ov(O A)$ et $ov(O A')$, et on utilise la relation de conjugaison pour récuperer la valeure de $f'$. On a:
$ f' = (ov(O A) times ov(O A'))/(ov(O A) - ov(O A')) $
== Méthode de Silbermann
La méthode de Silbermann a pour but de former une image de même taille que l'objet.
On pose un objet et une lentille sur notre axe optique, ainsi qu'un écran qu'on va bouger jusqu'a trouver une image de la même taille que l'objet.
#figure(caption: [Méthode de Silbermann], canvas({
import draw: *
line((-4, 0), (4, 0), mark: (end: "straight"))
line((0, -2), (0, 2), mark: (start: "straight", end: "straight"))
point((-3, 0), value: $A$, anchor: "north")
point((-3, 1), value: $B$)
line((-3, 0), (-3, 1))
line((2.5, -1.5), (2.5, 1.5), name: "ecran")
content("ecran.end", [écran], anchor: "south-west")
line((2, -1.6), (3, -1.6), mark: (start: "straight", end: "straight"))
}))
On aura donc:
$ gamma = ov(O A')/ov(O A) = -1 $
$ <=> ov(O A') = ov(-O A) $
$ 1/ov(O A') - 1/ov(O A) = 1/f' \
<=> -1/ov(O A) - 1/ov(O A) = 1/f' \
<=> -2/ov(O A) = 1/f' \
<=> f' = -ov(O A)/2 = ov(O A')/2 $
#resultb($ f' = ov(A A')/4 $)
== Méthode de Bessel
On utilise les formules de projection d'un objet réel vers une image réelle qu'on a démontré en @condition.
#figure(caption: [Méthode de Bessel], canvas({
import draw: *
line((-5, 0), (5, 0), mark: (end: "straight"))
point((-3, 0), value: $A$, anchor: "north", name: "A")
point((-3, 1), value: $B$, name: "B")
line((-3, 0), (-3, 1), name: "AB")
line((0, 2), (0, -2), stroke: blue, mark: (start: "straight", end: "straight"), name: "lentil1")
line((2, 2), (2, -2), stroke: blue, mark: (start: "straight", end: "straight"), name: "lentil2")
line((4, 1.5), (4, -1.5), name: "ecran")
line("lentil1.0.5", "lentil2.0.5", mark: (start: "straight", end: "straight"), name: "d")
content("d.50%", $d$, anchor: "south", padding: 2pt)
}))
On place la lentille dans une des deux positions valides.
On utilise la distance entre l'objet et son image pour calculer la distance focale.
On a donc:
$ x_1 = (D + sqrt(D(D - 4f')))/2 $
$ x_2 = (D - sqrt(D(D - 4f')))/2 $
Ainsi:
$ d &= x_1 - x_2 \
&= sqrt(D(D - 4f')) $
$ d^2 = D^2 - 4D f' $
$ 4D f' = D^2 - d^2 $
#resultb($ f' = (D^2 - d^2)/(4D) $)
== Méthode d'autocollimation
#figure(caption: [Méthode de Bessel], canvas({
import draw: *
line((-4, 0), (2, 0), mark: (end: "straight"))
line((0, 2), (0, -2), mark: (start: "straight", end: "straight"), name: "lentil")
line((0.5, 2), (0.5, -2), name: "miroir")
for i in range(11) {
line((0.55, -2 + i*0.4), (0.9, -1.8 + i *0.4))
}
point((-3, 0), value: $A$, anchor: "north", name: "A")
point((-3, 1), value: $B$, name: "B")
line((-3, 0), (-3, 1))
line("A", "lentil.0.7", mark: half_mark)
line("lentil.0.7", "miroir.0.7", mark: half_mark)
line("miroir.0.9", "lentil.0.9", mark: half_mark)
line("lentil.0.9", "A", mark: half_mark)
line((-2.8, -1), (-0.2, -1), mark: (start: "straight", end: "straight"), name: "focal")
content("focal.50%", $f'$, anchor: "north", padding: 2pt)
}))
Méthode très pratique qui ne nécessite pas de faire des calculs numériques poussés. Elle présente aussi l'avantage d'être pratique en terme de réalisation. Elle nécéssite cependant un miroir plan.
On place un miroir plan derrière la lentille, et on va décaler les deux simultanéments. On va essayer d'obtenir la distance focale comme la distance entre l'objet et la lentille.
On a:
$ A -> cal(L) -> A_1 -> m -> A'_1 -> cal(L) ("dans le sens inverse") -> A' $
On veut que $A$ soit posé au foyer objet de la lentille, ce qui nous donnera donc:
$ F -> cal(L) -> oo -> m -> oo -> cal(L) ("dans le sens inverse") -> F'_"retour" $
On regarde sur le plan de l'objet si l'image s'est bien formée "à l'identique". Il suffit de mesurer la distance entre l'objet et la lentille pour obtenir la distance focale.
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/gradient-math_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test on root
#show math.equation: set text(fill: gradient.linear(..color.map.rainbow))
#show math.equation: box
$ x_"1,2" = frac(-b +- sqrt(b^2 - 4 a c), 2 a) $
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/features-10.typ | typst | Other | // Error: 24-25 expected "lining", "old-style", or auto, found integer
#set text(number-type: 2)
|
https://github.com/bennyhandball/PA1_LoB_Finance | https://raw.githubusercontent.com/bennyhandball/PA1_LoB_Finance/main/PA/supercharged-dhbw/2.1.0/declaration-of-authorship.typ | typst | #let declaration-of-authorship(authors, title, date, language, many-authors, at-university, city, date-format) = {
pagebreak()
v(2em)
text(size: 20pt, weight: "bold", if (language == "de") {
"Selbstständigkeitserklärung"
} else {
"Declaration of Authorship"
})
v(1em)
if (authors.len() == 1) {
par(justify: true, leading: 18pt, [
<NAME> 1.1.13 der Anlage 1 zu §§ 3, 4 und 5 der Studien- und Prüfungsordnung für die Bachelorstudiengänge im Studienbereich Technik der Dualen Hochschule Baden- Württemberg vom 29.09.2017. Ich versichere hiermit, dass ich meine Arbeit mit dem Thema:
])
v(1em)
align(center,
text(weight: "bold", title)
)
v(1em)
par(justify: true, leading: 18pt, [
selbstständig verfasst und keine anderen als die angegebenen Quellen und Hilfsmittel benutzt habe. Ich versichere zudem, dass die eingereichte elektronische Fassung mit der gedruckten Fassung übereinstimmt.
])
} else {
par(justify: true, leading: 18pt, [
<NAME> 1.1.13 der Anlage 1 zu §§ 3, 4 und 5 der Studien- und Prüfungsordnung für die Bachelorstudiengänge im Studienbereich Technik der Dualen Hochschule Baden- Württemberg vom 29.09.2017. Wir versichern hiermit, dass wir unsere Arbeit mit dem Thema:
])
v(1em)
align(center,
text(weight: "bold", title)
)
v(1em)
par(justify: true, leading: 18pt, [
selbstständig verfasst und keine anderen als die angegebenen Quellen und Hilfsmittel benutzt haben. Wir versichern zudem, dass die eingereichte elektronische Fassung mit der gedruckten Fassung übereinstimmt.
])
}
let end-date = if (type(date) == datetime) {
date
} else {
date.at(1)
}
v(2em)
if (at-university) {
text([#city, #end-date.display(date-format)])
} else {
let connection-string
if (language == "de") {
connection-string = " und "
} else {
connection-string = " and "
}
text([#authors.map(author => author.company.city).dedup().join(", ", last: connection-string), #end-date.display(date-format)])
}
v(1em)
if (many-authors) {
grid(
columns: (1fr, 1fr),
gutter: 20pt,
..authors.map(author => {
v(3.5em)
line(length: 80%)
author.name
})
)
} else {
for author in authors {
v(4em)
line(length: 40%)
author.name
}
}
} |
|
https://github.com/kdog3682/typkit | https://raw.githubusercontent.com/kdog3682/typkit/main/0.1.0/src/index.typ | typst | // #import "pages.typ"
#import "types.typ": *
#import "validation.typ": *
#import "assertion.typ": *
#import "resolve.typ": *
#import "typography.typ": *
#import "misc.typ": *
#import "ao.typ": *
#import "layout.typ": *
#import "str-utils.typ": *
#import "eval.typ": *
#import "strokes.typ"
#import "sizes.typ"
#import "alignments.typ"
#import "lines.typ"
#import "ink.typ"
#import "patterns.typ"
#import "marks.typ"
#import "typst.typ"
#let dashbreak(style: "gentle") = {
if style == "tilde" {
centered(text(sym.tilde, size: 20pt),)
}
else if style == "dots" {
let a = line(stroke: strokes.soft)
let b = sym.diamond.filled
centered(tflex(a, b, a, inset: 2pt))
}
else if style == "gentle" {
v(5pt)
line(length: 100%, stroke: strokes.gentle-dots)
}
else if style == "topbar" {
v(-5pt)
line(length: 100%, stroke: strokes.soft)
v(20pt)
}
else if style == "spacebar" {
v(-5pt)
line(length: 100%, stroke: strokes.soft)
}
}
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion/bug_cite_function_infer.typ | typst | Apache License 2.0 | // path: references.bib
@article{Russell:1908,
Author = {<NAME>},
Journal = {American Journal of Mathematics},
Pages = {222--262},
Title = {Mathematical logic based on the theory of types},
Volume = 30,
Year = 1908}
@article{Rus,
Author = {<NAME>},
Journal = {American Journal of Mathematics},
Pages = {222--262},
Title = {Mathematical logic based on the theory of types},
Volume = 30,
Year = 1908}
-----
// contains:Russell:1908,Mathematical logic based on the theory of types
// compile:true
#set heading(numbering: "1.1")
#let cite_prose(labl) = cite(labl)
#let cite_prose_different_name(labl) = cite(labl)
#bibliography("references.bib")
#cite_prose(<Rus> /* range -2..-1 */)
|
https://github.com/howz97/howz97.github.io | https://raw.githubusercontent.com/howz97/howz97.github.io/main/cv.typ | typst | #show heading: set text(font: "Linux Biolinum")
#show link: underline
// Uncomment the following lines to adjust the size of text
// The recommend resume text size is from `10pt` to `12pt`
// #set text(
// size: 12pt,
// )
// Feel free to change the margin below to best fit your own CV
#set page(
margin: (x: 0.9cm, y: 1.3cm),
)
// For more customizable options, please refer to official reference: https://typst.app/docs/reference/
#set par(justify: true)
#let chiline() = {v(-3pt); line(length: 100%); v(-5pt)}
= <NAME> (张豪)
<EMAIL> |
#link("https://github.com/howz97")[github.com/howz97] | #link("https://www.yuque.com/ha0zhang")[yuque]
== Education
#chiline()
#link("https://net.ncepu.edu.cn/")[*NCEPU*] #h(1fr) 2016/09 -- 2020/07 \
Bachelor of software engineering #h(1fr) Baoding, Hebei \
== Work Experience
#chiline()
*EloqData* #h(1fr) Since 2022/11 \
Software Engineer #h(1fr) Beijing \
- [C++] Develop #link("https://www.eloqdata.com/docs/monosql-mysql-diff")[MonoSQL] which encapsulate DynamoDB to be used as a storage engine for MariaDB
- [C++] Develop CDC for #link("https://www.eloqdata.com/eloqsql/introduction")[EloqSQL] to replicate incremental data
- [C++] Develop the EloqLoad. A tool used for importing data at TB scale to EloqSQL
- [Rust] Develop the command line tool #link("https://www.eloqdata.com/downloadeloqctl")[eloqctl] for deploying and controlling EloqSQL and EloqKV clusters
- [Golang] #link("https://github.com/monographdb/tidb")[github.com/monographdb/tidb] Develop EloqDM which is a fork from TiDB-DM, make it compatible with EloqSQL
- [Golang] #link("https://github.com/monographdb/codis")[github.com/monographdb/codis] Develop Codis to make it compatible with EloqKV
- [Golang] #link("https://github.com/monographdb/juicefs")[github.com/monographdb/juicefs] Develop JuiceFS to use EloqKV as it's metadata engine
- [Shell] Build the release workflow of EloqSQL and EloqKV based on concourse
#link("https://www.tap4fun.com/")[*Tap4fun*] #h(1fr) 2020/07 -- 2021/12 \
Golang Developer #h(1fr) Chengdu \
Participated in the development of "Age of Apes" and "Invasion"
== Network courses
#chiline()
*TinyKV* #link("https://github.com/howz97/tinykv")[github.com/howz97/tinykv] \
Distributed scalable key/value storage which data is sharded into multiple raft groups. Cluster scaling is happen with raft configuration change and won't block data access. Transaction is implemented based on MVCC and thus have snapshot isolation level.
*MIT6.824* #link("https://github.com/howz97/mit6.824")[github.com/howz97/mit6.824] (private repo) \
Distributed scalable key/value storage which data is sharded into multiple raft groups. Cluster scaling is triggered by a HA master cluster and migrate shard in a blocking way.
*CMU15-445* #link("https://github.com/howz97/bustub")[github.com/howz97/bustub] \
A lab-level relational DBMS.
*CMU15-721* #link("https://github.com/howz97/postgres/tree/2023-S721-P1")[github.com/howz97/postgres/tree/2023-S721-P1] \
Implement a foreign data wrapper for PostgreSQL to support columnar storage.
*ToyOS* #link("https://github.com/howz97/toyos")[github.com/howz97/toyos] \
A toy os kernel implemented by following the guidance of #link("https://os.phil-opp.com/")["Writing an OS in Rust"] blog series.
== Personal Projects
#chiline()
*Algorithm Library* #link("https://github.com/howz97/algorithm")[github.com/howz97/algorithm] #h(1fr) Since 2019/07 \
A algorithm library written in golang, covering all contents of "Algorithms" by <NAME>. This library includes sorting, balanced tree, graph, string sorting/search/matching/compression, priority queue.
*LSM-Tree* #link("https://github.com/howz97/lsm-tree")[github.com/howz97/lsm-tree] \
Lightweight key/value storage engine based on lsm-tree. Implemented basic compaction, WAL, MVCC based transaction, optional serializable snapshot isolation.
*Bitcask* #link("https://github.com/howz97/bitcask")[github.com/howz97/bitcask] \
Lightweight key/value storage engine based on bitcask, written in async rust.
*Time-wheel* #link("https://github.com/howz97/time_wheel")[github.com/howz97/time_wheel] \
A timer written in rust.
*Open-Source Contributions* \
- #link("https://github.com/etcd-io/etcd/pull/13870")[github.com/etcd-io/etcd/pull/13870]
- #link("https://github.com/MariaDB/server/pull/2813")[github.com/MariaDB/server/pull/2813]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.